From b5ebcd0b865d5fd650f1d99b02c5c42a49a8192d Mon Sep 17 00:00:00 2001 From: urieljareth Date: Sat, 28 Nov 2026 09:20:55 -0600 Subject: [PATCH] feat: migrar backend unificado a Go 1.27 + SPA Vite embebido --- .claude/skills/cotizador-cli/SKILL.md | 18 +- .dockerignore | 11 +- .env.example | 43 +- .gitignore | 80 +- AGENTS.md | 232 +- Dockerfile | 74 +- README.md | 120 +- api/.dockerignore | 9 - api/.env.example | 16 - api/COTIZADOR_API_SKILL.md | 52 - api/Dockerfile | 19 - api/app/__init__.py | 0 api/app/auth.py | 346 - api/app/config.py | 20 - api/app/database.py | 33 - api/app/dependencies.py | 37 - api/app/models/__init__.py | 0 api/app/models/catalogo.py | 81 - api/app/models/cliente.py | 35 - api/app/models/common.py | 57 - api/app/models/configuracion.py | 41 - api/app/models/cotizacion.py | 130 - api/app/models/export_.py | 73 - api/app/models/paquete.py | 55 - api/app/routers/__init__.py | 0 api/app/routers/auth.py | 71 - api/app/routers/bonos.py | 14 - api/app/routers/catalogo.py | 308 - api/app/routers/categorias.py | 192 - api/app/routers/clientes.py | 214 - api/app/routers/cobros.py | 158 - api/app/routers/configuracion.py | 49 - api/app/routers/cotizaciones.py | 1003 -- api/app/routers/export_.py | 368 - api/app/routers/financiamiento.py | 122 - api/app/routers/health.py | 42 - api/app/routers/import_.py | 113 - api/app/routers/paquetes.py | 442 - api/app/services/__init__.py | 0 api/app/services/calculators.py | 208 - api/app/services/excel_generator.py | 531 - api/app/services/pdf_generator.py | 552 - api/main.py | 123 - api/requirements.txt | 30 - cazar-tmp.ts | 113 - cli/cotizador.mjs | 1450 --- cmd/cotizador/main.go | 171 + docker-compose.coolify.yml | 68 +- docker-compose.yaml | 68 +- docker-compose.yml | 24 +- .../specs/2026-11-28-migracion-go-design.md | 63 + eslint.config.mjs | 18 - go.mod | 31 + go.sum | 125 + internal/audit/audit.go | 87 + internal/auth/auth.go | 601 + internal/auth/auth_test.go | 79 + internal/cli/cli.go | 1131 ++ internal/cli/cli_test.go | 399 + internal/cli/commands.go | 1744 +++ internal/config/config.go | 145 + internal/db/db.go | 115 + internal/db/migrations/001_initial_schema.sql | 478 + internal/domain/aprobacion_core.go | 146 + internal/domain/calculators.go | 540 + internal/domain/cobros_fechas.go | 239 + internal/domain/domain_test.go | 187 + internal/domain/solo_admin_core.go | 71 + internal/excel/catalogo_csv.go | 253 + internal/excel/cotizacion.go | 769 ++ internal/excel/excel_test.go | 276 + internal/httpapi/admin_control_handlers.go | 497 + internal/httpapi/auth_handlers.go | 540 + internal/httpapi/catalogo_handlers.go | 979 ++ internal/httpapi/cliente_portal_handlers.go | 438 + internal/httpapi/clientes_handlers.go | 418 + internal/httpapi/cobros_handlers.go | 701 ++ internal/httpapi/cotizaciones_handlers.go | 1742 +++ internal/httpapi/export_propuesta_handlers.go | 649 + internal/httpapi/httpapi_test.go | 266 + internal/httpapi/server.go | 343 + internal/idempotency/idempotency.go | 108 + internal/notify/notify.go | 694 ++ internal/pdf/cotizacion.go | 582 + internal/pdf/helpers.go | 429 + internal/pdf/nota_horas.go | 394 + internal/pdf/pdf_test.go | 454 + internal/pdf/propuesta.go | 739 ++ internal/propuesta/cliente_ia.go | 476 + internal/propuesta/economia.go | 224 + internal/propuesta/pipeline.go | 230 + internal/propuesta/prompts.go | 1043 ++ internal/propuesta/propuesta_test.go | 876 ++ internal/propuesta/validacion.go | 476 + internal/scheduler/scheduler.go | 143 + internal/seed/data.go | 1883 +++ internal/seed/provision.go | 376 + internal/seed/seed.go | 348 + internal/seed/seed_test.go | 218 + internal/spa/dist/index.html | 1 + internal/spa/spa.go | 55 + internal/webhooks/webhooks.go | 349 + internal/webhooks/webhooks_test.go | 74 + next.config.ts | 10 - package-lock.json | 10362 ---------------- package.json | 60 - postcss.config.mjs | 7 - prisma.config.ts | 27 - .../20260427090524_init/migration.sql | 161 - .../migration.sql | 69 - .../migration.sql | 2 - .../migration.sql | 6 - .../migration.sql | 10 - .../migration.sql | 2 - .../migration.sql | 6 - .../migration.sql | 32 - .../migration.sql | 46 - .../migration.sql | 10 - .../migration.sql | 20 - .../migration.sql | 26 - .../migration.sql | 3 - .../migration.sql | 109 - .../migration.sql | 3 - .../migration.sql | 5 - .../migration.sql | 139 - .../migration.sql | 23 - .../migration.sql | 3 - prisma/migrations/migration_lock.toml | 3 - prisma/schema.prisma | 505 - prisma/seed.ts | 2046 --- public/file.svg | 1 - public/globe.svg | 1 - public/next.svg | 1 - public/vercel.svg | 1 - public/window.svg | 1 - scripts/provision-agent-keys.ts | 248 - scripts/verificar-propuesta-cliente.ts | 70 - scripts/verificar-propuesta-economia.ts | 26 - scripts/verificar-propuesta-pdf.ts | 232 - scripts/verificar-propuesta-prompts.ts | 76 - scripts/verificar-propuesta-schemas.ts | 94 - scripts/verificar-propuesta-validacion.ts | 123 - src/app/(app)/catalogo/loading.tsx | 7 - src/app/(app)/catalogo/page.tsx | 61 - src/app/(app)/clientes/loading.tsx | 7 - src/app/(app)/clientes/page.tsx | 33 - src/app/(app)/cobros/page.tsx | 154 - src/app/(app)/configuracion/loading.tsx | 7 - src/app/(app)/configuracion/page.tsx | 12 - .../(app)/cotizaciones/[id]/editar/page.tsx | 83 - src/app/(app)/cotizaciones/[id]/loading.tsx | 7 - src/app/(app)/cotizaciones/loading.tsx | 7 - src/app/(app)/cotizaciones/nueva/page.tsx | 66 - src/app/(app)/layout.tsx | 17 - src/app/(app)/loading.tsx | 7 - src/app/api/agent-keys/[id]/revoke/route.ts | 54 - src/app/api/agent-keys/[id]/rotate/route.ts | 60 - src/app/api/agent-keys/route.ts | 110 - src/app/api/aprobar/[token]/route.ts | 120 - src/app/api/audit-logs/route.ts | 46 - src/app/api/auth/login/route.ts | 59 - src/app/api/auth/logout/route.ts | 8 - src/app/api/auth/me/route.ts | 10 - src/app/api/catalogo/[id]/route.ts | 130 - src/app/api/catalogo/route.ts | 107 - src/app/api/categorias/[id]/route.ts | 47 - src/app/api/categorias/route.ts | 40 - .../api/cliente/cotizaciones/[id]/route.ts | 71 - src/app/api/cliente/cotizaciones/route.ts | 73 - .../cliente/pagos/[id]/comprobante/route.ts | 118 - src/app/api/cliente/pagos/route.ts | 36 - src/app/api/cliente/push/config/route.ts | 24 - src/app/api/cliente/push/suscribir/route.ts | 77 - src/app/api/cliente/resumen/route.ts | 33 - src/app/api/clientes/[id]/acceso/route.ts | 124 - src/app/api/clientes/[id]/archivar/route.ts | 82 - src/app/api/clientes/[id]/route.ts | 74 - src/app/api/clientes/route.ts | 95 - src/app/api/cobros/generar/route.ts | 48 - src/app/api/cobros/pagos/[id]/anular/route.ts | 56 - .../api/cobros/pagos/[id]/aprobar/route.ts | 79 - .../api/cobros/pagos/[id]/reabrir/route.ts | 46 - .../api/cobros/pagos/[id]/rechazar/route.ts | 57 - .../api/cobros/pagos/[id]/registrar/route.ts | 115 - src/app/api/cobros/pagos/route.ts | 53 - src/app/api/cobros/programas/[id]/route.ts | 77 - src/app/api/cobros/programas/route.ts | 81 - src/app/api/cobros/recordatorios/route.ts | 46 - src/app/api/comprobantes/[pagoId]/route.ts | 75 - src/app/api/configuracion/route.ts | 58 - .../api/cotizaciones/[id]/aprobar/route.ts | 121 - src/app/api/cotizaciones/[id]/enviar/route.ts | 401 - src/app/api/cotizaciones/[id]/estado/route.ts | 154 - .../[id]/horas/[registroId]/route.ts | 116 - src/app/api/cotizaciones/[id]/horas/route.ts | 104 - .../api/cotizaciones/[id]/nota-horas/route.ts | 168 - src/app/api/cotizaciones/[id]/precio/route.ts | 102 - src/app/api/cotizaciones/[id]/route.ts | 571 - .../[id]/solicitar-aprobacion/route.ts | 76 - src/app/api/cotizaciones/route.ts | 441 - .../api/export/catalogo/plantilla/route.ts | 40 - src/app/api/export/catalogo/route.ts | 50 - src/app/api/export/excel/[id]/route.ts | 91 - src/app/api/export/excel/route.ts | 97 - src/app/api/export/pdf/[id]/route.ts | 87 - src/app/api/export/pdf/route.ts | 91 - src/app/api/health/route.ts | 28 - src/app/api/import/catalogo/route.ts | 171 - src/app/api/openapi.json/route.ts | 351 - src/app/api/paquetes/[id]/manage/route.ts | 61 - src/app/api/paquetes/[id]/route.ts | 83 - src/app/api/paquetes/route.ts | 69 - src/app/api/propuesta-ia/[id]/pdf/route.ts | 78 - src/app/api/propuesta-ia/[id]/route.ts | 154 - src/app/api/webhooks/[id]/route.ts | 41 - src/app/api/webhooks/deliveries/route.ts | 29 - src/app/api/webhooks/route.ts | 103 - src/app/aprobar/[token]/page.tsx | 85 - src/app/cliente/cotizaciones/page.tsx | 85 - src/app/cliente/layout.tsx | 34 - src/app/cliente/loading.tsx | 26 - src/app/cliente/resumen-data.ts | 140 - src/app/layout.tsx | 42 - src/app/login/page.tsx | 10 - src/instrumentation.ts | 17 - src/lib/agent-auth-core.ts | 164 - src/lib/agent-auth.ts | 296 - src/lib/aprobacion-core.ts | 140 - src/lib/aprobacion.ts | 291 - src/lib/audit.ts | 69 - src/lib/auth.ts | 86 - src/lib/catalogo.ts | 108 - src/lib/clientes.ts | 39 - src/lib/cobros.ts | 114 - src/lib/config-helpers.ts | 62 - src/lib/cotizacion-pdf.ts | 72 - src/lib/cotizaciones.ts | 28 - src/lib/db.ts | 22 - src/lib/email.ts | 164 - src/lib/excel-builder.ts | 564 - src/lib/idempotency.ts | 94 - src/lib/nota-horas-pdf.ts | 272 - src/lib/notificaciones.ts | 475 - src/lib/pago-vencido-core.ts | 125 - src/lib/pdf-generator.ts | 555 - src/lib/propuesta/cliente-ia.ts | 234 - src/lib/propuesta/economia.ts | 113 - src/lib/propuesta/pdf.ts | 551 - src/lib/propuesta/pipeline.ts | 99 - src/lib/propuesta/prompts.ts | 244 - src/lib/propuesta/schemas.ts | 231 - src/lib/propuesta/validacion.ts | 252 - src/lib/push.ts | 85 - src/lib/scheduler.ts | 76 - src/lib/schemas.ts | 326 - src/lib/solo-admin-core.ts | 67 - src/lib/uploads.ts | 138 - src/lib/webhooks-core.ts | 38 - src/lib/webhooks.ts | 250 - src/middleware.ts | 124 - start.bat | 25 +- stop.bat | 8 +- tests/approval-guard.test.ts | 182 - tests/auth-scopes.test.ts | 147 - tests/calculators-parity.test.ts | 122 - tests/pago-vencido-idempotency.test.ts | 207 - tests/solo-admin-and-defaults.test.ts | 81 - tests/webhooks-hmac.test.ts | 51 - tsconfig.json | 34 - web/index.html | 23 + web/package-lock.json | 2710 ++++ web/package.json | 29 + {src/app => web/public}/favicon.ico | Bin {public => web/public}/sw.js | 0 web/src/App.tsx | 93 + .../src}/components/CotizacionForm.tsx | 10 +- {src => web/src}/components/EstadoBadge.tsx | 0 {src => web/src}/components/ExportButtons.tsx | 0 .../src}/components/PropuestaIAPanel.tsx | 0 .../src}/components/ServicioFormModal.tsx | 0 .../src}/components/layout/Sidebar.tsx | 23 +- .../src}/components/ui/DialogProvider.tsx | 0 web/src/components/ui/LoadingScreen.tsx | 44 + {src => web/src}/components/ui/Modal.tsx | 0 src/app/globals.css => web/src/index.css | 3 + web/src/lib/api.ts | 90 + web/src/lib/auth.tsx | 67 + {src => web/src}/lib/calculators.ts | 0 {src => web/src}/lib/cobros-fechas.ts | 40 +- {src => web/src}/lib/store.ts | 0 web/src/main.tsx | 13 + .../src/pages/AprobarTokenPage.tsx | 130 +- .../src/pages/LoginPage.tsx | 38 +- .../src/pages/app}/CatalogoClient.tsx | 27 +- web/src/pages/app/CatalogoPage.tsx | 63 + .../src/pages/app}/ClienteDialog.tsx | 5 - .../src/pages/app}/ClientesList.tsx | 20 +- web/src/pages/app/ClientesPage.tsx | 46 + .../src/pages/app}/ConfiguracionClient.tsx | 3 - web/src/pages/app/ConfiguracionPage.tsx | 32 + .../src/pages/app/DashboardPage.tsx | 91 +- .../app}/NuevaCotizacionClienteButton.tsx | 8 +- .../src/pages/app}/cobros/CobrosClient.tsx | 47 +- web/src/pages/app/cobros/CobrosPage.tsx | 60 + .../src/pages/app}/cobros/EstadoPagoBadge.tsx | 5 - .../src/pages/app}/cobros/PagosTabla.tsx | 3 - .../src/pages/app}/cobros/PorCobrarTabla.tsx | 7 - .../src/pages/app}/cobros/ProgramasTabla.tsx | 13 +- .../pages/app}/cobros/RegistrarPagoDialog.tsx | 4 - .../src/pages/app}/cobros/types.ts | 10 - .../cotizaciones}/CambiarEstadoButtons.tsx | 12 +- .../app/cotizaciones/CotizacionDetailPage.tsx | 210 +- .../app}/cotizaciones/CotizacionesList.tsx | 20 +- .../app/cotizaciones/CotizacionesPage.tsx | 54 +- .../pages/app/cotizaciones}/DeleteButton.tsx | 8 +- .../app/cotizaciones/EditarCotizacionPage.tsx | 180 + .../app}/cotizaciones/ListDeleteButton.tsx | 14 +- .../app/cotizaciones/NuevaCotizacionPage.tsx | 75 + .../app/cotizaciones}/PreciosEditables.tsx | 15 +- .../app/cotizaciones}/RegistroHorasPanel.tsx | 52 +- .../cliente/ClienteCotizacionDetallePage.tsx | 132 +- .../pages/cliente/ClienteCotizacionesPage.tsx | 111 + .../src/pages/cliente/ClienteInicioPage.tsx | 115 +- .../src/pages/cliente/ClientePagosPage.tsx | 101 +- .../src/pages}/cliente/ClienteShell.tsx | 25 +- .../src/pages/cliente}/CopiarDato.tsx | 4 - .../src/pages}/cliente/FilaCotizacion.tsx | 13 +- .../src/pages/cliente}/SubirComprobante.tsx | 12 +- web/tsconfig.app.json | 25 + web/tsconfig.json | 7 + web/tsconfig.node.json | 16 + web/vite.config.ts | 26 + 332 files changed, 29135 insertions(+), 37275 deletions(-) delete mode 100644 api/.dockerignore delete mode 100644 api/.env.example delete mode 100644 api/COTIZADOR_API_SKILL.md delete mode 100644 api/Dockerfile delete mode 100644 api/app/__init__.py delete mode 100644 api/app/auth.py delete mode 100644 api/app/config.py delete mode 100644 api/app/database.py delete mode 100644 api/app/dependencies.py delete mode 100644 api/app/models/__init__.py delete mode 100644 api/app/models/catalogo.py delete mode 100644 api/app/models/cliente.py delete mode 100644 api/app/models/common.py delete mode 100644 api/app/models/configuracion.py delete mode 100644 api/app/models/cotizacion.py delete mode 100644 api/app/models/export_.py delete mode 100644 api/app/models/paquete.py delete mode 100644 api/app/routers/__init__.py delete mode 100644 api/app/routers/auth.py delete mode 100644 api/app/routers/bonos.py delete mode 100644 api/app/routers/catalogo.py delete mode 100644 api/app/routers/categorias.py delete mode 100644 api/app/routers/clientes.py delete mode 100644 api/app/routers/cobros.py delete mode 100644 api/app/routers/configuracion.py delete mode 100644 api/app/routers/cotizaciones.py delete mode 100644 api/app/routers/export_.py delete mode 100644 api/app/routers/financiamiento.py delete mode 100644 api/app/routers/health.py delete mode 100644 api/app/routers/import_.py delete mode 100644 api/app/routers/paquetes.py delete mode 100644 api/app/services/__init__.py delete mode 100644 api/app/services/calculators.py delete mode 100644 api/app/services/excel_generator.py delete mode 100644 api/app/services/pdf_generator.py delete mode 100644 api/main.py delete mode 100644 api/requirements.txt delete mode 100644 cazar-tmp.ts delete mode 100644 cli/cotizador.mjs create mode 100644 cmd/cotizador/main.go create mode 100644 docs/superpowers/specs/2026-11-28-migracion-go-design.md delete mode 100644 eslint.config.mjs create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/audit/audit.go create mode 100644 internal/auth/auth.go create mode 100644 internal/auth/auth_test.go create mode 100644 internal/cli/cli.go create mode 100644 internal/cli/cli_test.go create mode 100644 internal/cli/commands.go create mode 100644 internal/config/config.go create mode 100644 internal/db/db.go create mode 100644 internal/db/migrations/001_initial_schema.sql create mode 100644 internal/domain/aprobacion_core.go create mode 100644 internal/domain/calculators.go create mode 100644 internal/domain/cobros_fechas.go create mode 100644 internal/domain/domain_test.go create mode 100644 internal/domain/solo_admin_core.go create mode 100644 internal/excel/catalogo_csv.go create mode 100644 internal/excel/cotizacion.go create mode 100644 internal/excel/excel_test.go create mode 100644 internal/httpapi/admin_control_handlers.go create mode 100644 internal/httpapi/auth_handlers.go create mode 100644 internal/httpapi/catalogo_handlers.go create mode 100644 internal/httpapi/cliente_portal_handlers.go create mode 100644 internal/httpapi/clientes_handlers.go create mode 100644 internal/httpapi/cobros_handlers.go create mode 100644 internal/httpapi/cotizaciones_handlers.go create mode 100644 internal/httpapi/export_propuesta_handlers.go create mode 100644 internal/httpapi/httpapi_test.go create mode 100644 internal/httpapi/server.go create mode 100644 internal/idempotency/idempotency.go create mode 100644 internal/notify/notify.go create mode 100644 internal/pdf/cotizacion.go create mode 100644 internal/pdf/helpers.go create mode 100644 internal/pdf/nota_horas.go create mode 100644 internal/pdf/pdf_test.go create mode 100644 internal/pdf/propuesta.go create mode 100644 internal/propuesta/cliente_ia.go create mode 100644 internal/propuesta/economia.go create mode 100644 internal/propuesta/pipeline.go create mode 100644 internal/propuesta/prompts.go create mode 100644 internal/propuesta/propuesta_test.go create mode 100644 internal/propuesta/validacion.go create mode 100644 internal/scheduler/scheduler.go create mode 100644 internal/seed/data.go create mode 100644 internal/seed/provision.go create mode 100644 internal/seed/seed.go create mode 100644 internal/seed/seed_test.go create mode 100644 internal/spa/dist/index.html create mode 100644 internal/spa/spa.go create mode 100644 internal/webhooks/webhooks.go create mode 100644 internal/webhooks/webhooks_test.go delete mode 100644 next.config.ts delete mode 100644 package-lock.json delete mode 100644 package.json delete mode 100644 postcss.config.mjs delete mode 100644 prisma.config.ts delete mode 100644 prisma/migrations/20260427090524_init/migration.sql delete mode 100644 prisma/migrations/20260430154327_add_packages_categories/migration.sql delete mode 100644 prisma/migrations/20260430180000_remove_categoria_string/migration.sql delete mode 100644 prisma/migrations/20260601000000_add_servicio_personalizado_horas/migration.sql delete mode 100644 prisma/migrations/20260603085717_add_modelo_cobro_retainer/migration.sql delete mode 100644 prisma/migrations/20260603090526_add_nivel_servicio/migration.sql delete mode 100644 prisma/migrations/20260609224848_doble_propuesta/migration.sql delete mode 100644 prisma/migrations/20260610012632_add_performance_indexes/migration.sql delete mode 100644 prisma/migrations/20260630000000_add_registro_horas_incluir_iva/migration.sql delete mode 100644 prisma/migrations/20260708000000_registro_horas_estado_pago/migration.sql delete mode 100644 prisma/migrations/20260728000000_add_observaciones_internas/migration.sql delete mode 100644 prisma/migrations/20260729000000_add_propuesta_ia/migration.sql delete mode 100644 prisma/migrations/20260729010000_propuesta_ia_transcripcion/migration.sql delete mode 100644 prisma/migrations/20261020000000_pagos_recurrentes_panel_cliente/migration.sql delete mode 100644 prisma/migrations/20261026201926_recordatorios_pagos_pendientes/migration.sql delete mode 100644 prisma/migrations/20261027001210_clientes_puesto_y_nota_de_pago/migration.sql delete mode 100644 prisma/migrations/20261125000000_agent_api_approval_webhooks/migration.sql delete mode 100644 prisma/migrations/20261125120000_solo_admin_and_archiving/migration.sql delete mode 100644 prisma/migrations/20261125160000_pago_vencido_notificado_at/migration.sql delete mode 100644 prisma/migrations/migration_lock.toml delete mode 100644 prisma/schema.prisma delete mode 100644 prisma/seed.ts delete mode 100644 public/file.svg delete mode 100644 public/globe.svg delete mode 100644 public/next.svg delete mode 100644 public/vercel.svg delete mode 100644 public/window.svg delete mode 100644 scripts/provision-agent-keys.ts delete mode 100644 scripts/verificar-propuesta-cliente.ts delete mode 100644 scripts/verificar-propuesta-economia.ts delete mode 100644 scripts/verificar-propuesta-pdf.ts delete mode 100644 scripts/verificar-propuesta-prompts.ts delete mode 100644 scripts/verificar-propuesta-schemas.ts delete mode 100644 scripts/verificar-propuesta-validacion.ts delete mode 100644 src/app/(app)/catalogo/loading.tsx delete mode 100644 src/app/(app)/catalogo/page.tsx delete mode 100644 src/app/(app)/clientes/loading.tsx delete mode 100644 src/app/(app)/clientes/page.tsx delete mode 100644 src/app/(app)/cobros/page.tsx delete mode 100644 src/app/(app)/configuracion/loading.tsx delete mode 100644 src/app/(app)/configuracion/page.tsx delete mode 100644 src/app/(app)/cotizaciones/[id]/editar/page.tsx delete mode 100644 src/app/(app)/cotizaciones/[id]/loading.tsx delete mode 100644 src/app/(app)/cotizaciones/loading.tsx delete mode 100644 src/app/(app)/cotizaciones/nueva/page.tsx delete mode 100644 src/app/(app)/layout.tsx delete mode 100644 src/app/(app)/loading.tsx delete mode 100644 src/app/api/agent-keys/[id]/revoke/route.ts delete mode 100644 src/app/api/agent-keys/[id]/rotate/route.ts delete mode 100644 src/app/api/agent-keys/route.ts delete mode 100644 src/app/api/aprobar/[token]/route.ts delete mode 100644 src/app/api/audit-logs/route.ts delete mode 100644 src/app/api/auth/login/route.ts delete mode 100644 src/app/api/auth/logout/route.ts delete mode 100644 src/app/api/auth/me/route.ts delete mode 100644 src/app/api/catalogo/[id]/route.ts delete mode 100644 src/app/api/catalogo/route.ts delete mode 100644 src/app/api/categorias/[id]/route.ts delete mode 100644 src/app/api/categorias/route.ts delete mode 100644 src/app/api/cliente/cotizaciones/[id]/route.ts delete mode 100644 src/app/api/cliente/cotizaciones/route.ts delete mode 100644 src/app/api/cliente/pagos/[id]/comprobante/route.ts delete mode 100644 src/app/api/cliente/pagos/route.ts delete mode 100644 src/app/api/cliente/push/config/route.ts delete mode 100644 src/app/api/cliente/push/suscribir/route.ts delete mode 100644 src/app/api/cliente/resumen/route.ts delete mode 100644 src/app/api/clientes/[id]/acceso/route.ts delete mode 100644 src/app/api/clientes/[id]/archivar/route.ts delete mode 100644 src/app/api/clientes/[id]/route.ts delete mode 100644 src/app/api/clientes/route.ts delete mode 100644 src/app/api/cobros/generar/route.ts delete mode 100644 src/app/api/cobros/pagos/[id]/anular/route.ts delete mode 100644 src/app/api/cobros/pagos/[id]/aprobar/route.ts delete mode 100644 src/app/api/cobros/pagos/[id]/reabrir/route.ts delete mode 100644 src/app/api/cobros/pagos/[id]/rechazar/route.ts delete mode 100644 src/app/api/cobros/pagos/[id]/registrar/route.ts delete mode 100644 src/app/api/cobros/pagos/route.ts delete mode 100644 src/app/api/cobros/programas/[id]/route.ts delete mode 100644 src/app/api/cobros/programas/route.ts delete mode 100644 src/app/api/cobros/recordatorios/route.ts delete mode 100644 src/app/api/comprobantes/[pagoId]/route.ts delete mode 100644 src/app/api/configuracion/route.ts delete mode 100644 src/app/api/cotizaciones/[id]/aprobar/route.ts delete mode 100644 src/app/api/cotizaciones/[id]/enviar/route.ts delete mode 100644 src/app/api/cotizaciones/[id]/estado/route.ts delete mode 100644 src/app/api/cotizaciones/[id]/horas/[registroId]/route.ts delete mode 100644 src/app/api/cotizaciones/[id]/horas/route.ts delete mode 100644 src/app/api/cotizaciones/[id]/nota-horas/route.ts delete mode 100644 src/app/api/cotizaciones/[id]/precio/route.ts delete mode 100644 src/app/api/cotizaciones/[id]/route.ts delete mode 100644 src/app/api/cotizaciones/[id]/solicitar-aprobacion/route.ts delete mode 100644 src/app/api/cotizaciones/route.ts delete mode 100644 src/app/api/export/catalogo/plantilla/route.ts delete mode 100644 src/app/api/export/catalogo/route.ts delete mode 100644 src/app/api/export/excel/[id]/route.ts delete mode 100644 src/app/api/export/excel/route.ts delete mode 100644 src/app/api/export/pdf/[id]/route.ts delete mode 100644 src/app/api/export/pdf/route.ts delete mode 100644 src/app/api/health/route.ts delete mode 100644 src/app/api/import/catalogo/route.ts delete mode 100644 src/app/api/openapi.json/route.ts delete mode 100644 src/app/api/paquetes/[id]/manage/route.ts delete mode 100644 src/app/api/paquetes/[id]/route.ts delete mode 100644 src/app/api/paquetes/route.ts delete mode 100644 src/app/api/propuesta-ia/[id]/pdf/route.ts delete mode 100644 src/app/api/propuesta-ia/[id]/route.ts delete mode 100644 src/app/api/webhooks/[id]/route.ts delete mode 100644 src/app/api/webhooks/deliveries/route.ts delete mode 100644 src/app/api/webhooks/route.ts delete mode 100644 src/app/aprobar/[token]/page.tsx delete mode 100644 src/app/cliente/cotizaciones/page.tsx delete mode 100644 src/app/cliente/layout.tsx delete mode 100644 src/app/cliente/loading.tsx delete mode 100644 src/app/cliente/resumen-data.ts delete mode 100644 src/app/layout.tsx delete mode 100644 src/app/login/page.tsx delete mode 100644 src/instrumentation.ts delete mode 100644 src/lib/agent-auth-core.ts delete mode 100644 src/lib/agent-auth.ts delete mode 100644 src/lib/aprobacion-core.ts delete mode 100644 src/lib/aprobacion.ts delete mode 100644 src/lib/audit.ts delete mode 100644 src/lib/auth.ts delete mode 100644 src/lib/catalogo.ts delete mode 100644 src/lib/clientes.ts delete mode 100644 src/lib/cobros.ts delete mode 100644 src/lib/config-helpers.ts delete mode 100644 src/lib/cotizacion-pdf.ts delete mode 100644 src/lib/cotizaciones.ts delete mode 100644 src/lib/db.ts delete mode 100644 src/lib/email.ts delete mode 100644 src/lib/excel-builder.ts delete mode 100644 src/lib/idempotency.ts delete mode 100644 src/lib/nota-horas-pdf.ts delete mode 100644 src/lib/notificaciones.ts delete mode 100644 src/lib/pago-vencido-core.ts delete mode 100644 src/lib/pdf-generator.ts delete mode 100644 src/lib/propuesta/cliente-ia.ts delete mode 100644 src/lib/propuesta/economia.ts delete mode 100644 src/lib/propuesta/pdf.ts delete mode 100644 src/lib/propuesta/pipeline.ts delete mode 100644 src/lib/propuesta/prompts.ts delete mode 100644 src/lib/propuesta/schemas.ts delete mode 100644 src/lib/propuesta/validacion.ts delete mode 100644 src/lib/push.ts delete mode 100644 src/lib/scheduler.ts delete mode 100644 src/lib/schemas.ts delete mode 100644 src/lib/solo-admin-core.ts delete mode 100644 src/lib/uploads.ts delete mode 100644 src/lib/webhooks-core.ts delete mode 100644 src/lib/webhooks.ts delete mode 100644 src/middleware.ts delete mode 100644 tests/approval-guard.test.ts delete mode 100644 tests/auth-scopes.test.ts delete mode 100644 tests/calculators-parity.test.ts delete mode 100644 tests/pago-vencido-idempotency.test.ts delete mode 100644 tests/solo-admin-and-defaults.test.ts delete mode 100644 tests/webhooks-hmac.test.ts delete mode 100644 tsconfig.json create mode 100644 web/index.html create mode 100644 web/package-lock.json create mode 100644 web/package.json rename {src/app => web/public}/favicon.ico (100%) rename {public => web/public}/sw.js (100%) create mode 100644 web/src/App.tsx rename {src => web/src}/components/CotizacionForm.tsx (99%) rename {src => web/src}/components/EstadoBadge.tsx (100%) rename {src => web/src}/components/ExportButtons.tsx (100%) rename {src => web/src}/components/PropuestaIAPanel.tsx (100%) rename {src => web/src}/components/ServicioFormModal.tsx (100%) rename {src => web/src}/components/layout/Sidebar.tsx (87%) rename {src => web/src}/components/ui/DialogProvider.tsx (100%) create mode 100644 web/src/components/ui/LoadingScreen.tsx rename {src => web/src}/components/ui/Modal.tsx (100%) rename src/app/globals.css => web/src/index.css (93%) create mode 100644 web/src/lib/api.ts create mode 100644 web/src/lib/auth.tsx rename {src => web/src}/lib/calculators.ts (100%) rename {src => web/src}/lib/cobros-fechas.ts (90%) rename {src => web/src}/lib/store.ts (100%) create mode 100644 web/src/main.tsx rename src/app/aprobar/[token]/AprobarClient.tsx => web/src/pages/AprobarTokenPage.tsx (65%) rename src/app/login/LoginForm.tsx => web/src/pages/LoginPage.tsx (78%) rename {src/app/(app)/catalogo => web/src/pages/app}/CatalogoClient.tsx (97%) create mode 100644 web/src/pages/app/CatalogoPage.tsx rename {src/app/(app)/clientes => web/src/pages/app}/ClienteDialog.tsx (95%) rename {src/app/(app)/clientes => web/src/pages/app}/ClientesList.tsx (95%) create mode 100644 web/src/pages/app/ClientesPage.tsx rename {src/app/(app)/configuracion => web/src/pages/app}/ConfiguracionClient.tsx (98%) create mode 100644 web/src/pages/app/ConfiguracionPage.tsx rename src/app/(app)/page.tsx => web/src/pages/app/DashboardPage.tsx (74%) rename {src/app/(app)/clientes => web/src/pages/app}/NuevaCotizacionClienteButton.tsx (87%) rename {src/app/(app) => web/src/pages/app}/cobros/CobrosClient.tsx (94%) create mode 100644 web/src/pages/app/cobros/CobrosPage.tsx rename {src/app/(app) => web/src/pages/app}/cobros/EstadoPagoBadge.tsx (81%) rename {src/app/(app) => web/src/pages/app}/cobros/PagosTabla.tsx (98%) rename {src/app/(app) => web/src/pages/app}/cobros/PorCobrarTabla.tsx (94%) rename {src/app/(app) => web/src/pages/app}/cobros/ProgramasTabla.tsx (97%) rename {src/app/(app) => web/src/pages/app}/cobros/RegistrarPagoDialog.tsx (94%) rename {src/app/(app) => web/src/pages/app}/cobros/types.ts (67%) rename {src/app/(app)/cotizaciones/[id] => web/src/pages/app/cotizaciones}/CambiarEstadoButtons.tsx (98%) rename src/app/(app)/cotizaciones/[id]/page.tsx => web/src/pages/app/cotizaciones/CotizacionDetailPage.tsx (63%) rename {src/app/(app) => web/src/pages/app}/cotizaciones/CotizacionesList.tsx (93%) rename src/app/(app)/cotizaciones/page.tsx => web/src/pages/app/cotizaciones/CotizacionesPage.tsx (51%) rename {src/app/(app)/cotizaciones/[id] => web/src/pages/app/cotizaciones}/DeleteButton.tsx (93%) create mode 100644 web/src/pages/app/cotizaciones/EditarCotizacionPage.tsx rename {src/app/(app) => web/src/pages/app}/cotizaciones/ListDeleteButton.tsx (83%) create mode 100644 web/src/pages/app/cotizaciones/NuevaCotizacionPage.tsx rename {src/app/(app)/cotizaciones/[id] => web/src/pages/app/cotizaciones}/PreciosEditables.tsx (94%) rename {src/app/(app)/cotizaciones/[id] => web/src/pages/app/cotizaciones}/RegistroHorasPanel.tsx (91%) rename src/app/cliente/cotizaciones/[id]/page.tsx => web/src/pages/cliente/ClienteCotizacionDetallePage.tsx (79%) create mode 100644 web/src/pages/cliente/ClienteCotizacionesPage.tsx rename src/app/cliente/page.tsx => web/src/pages/cliente/ClienteInicioPage.tsx (69%) rename src/app/cliente/pagos/page.tsx => web/src/pages/cliente/ClientePagosPage.tsx (84%) rename {src/app => web/src/pages}/cliente/ClienteShell.tsx (91%) rename {src/app/cliente/pagos => web/src/pages/cliente}/CopiarDato.tsx (89%) rename {src/app => web/src/pages}/cliente/FilaCotizacion.tsx (85%) rename {src/app/cliente/pagos => web/src/pages/cliente}/SubirComprobante.tsx (82%) create mode 100644 web/tsconfig.app.json create mode 100644 web/tsconfig.json create mode 100644 web/tsconfig.node.json create mode 100644 web/vite.config.ts diff --git a/.claude/skills/cotizador-cli/SKILL.md b/.claude/skills/cotizador-cli/SKILL.md index a4c3c36..12c52cc 100644 --- a/.claude/skills/cotizador-cli/SKILL.md +++ b/.claude/skills/cotizador-cli/SKILL.md @@ -5,12 +5,12 @@ description: Usa el CLI `cotizador` para operar el Cotizador — Uriel Jareth Co # Operar el Cotizador — Uriel Jareth Consulting por CLI -El CLI vive en `cli/cotizador.mjs` (Node 18+, sin dependencias). Ejecútalo desde la raíz del repo con `node cli/cotizador.mjs `. +El CLI vive integrado en el binario Go (`cmd/cotizador`). Ejecútalo desde la raíz del repo con `go run ./cmd/cotizador cli ` (o `./cotizador cli `). ## Antes de nada -1. Descubre los comandos con `node cli/cotizador.mjs esquema`. Devuelve en JSON cada comando con sus flags, tipos, valores válidos, ejemplos y endpoint, más el dominio (fases, tipos de pago, estados). No adivines flags. -2. Sesión: `node cli/cotizador.mjs whoami`. Si sale código 3, pide al usuario sus credenciales o que defina `COTIZADOR_EMAIL` / `COTIZADOR_PASSWORD`. Nunca escribas una contraseña en un archivo del repo ni la repitas en el chat. +1. Descubre los comandos con `go run ./cmd/cotizador cli esquema`. Devuelve en JSON cada comando con sus flags, tipos, valores válidos, ejemplos y endpoint, más el dominio (fases, tipos de pago, estados). No adivines flags. +2. Sesión: `go run ./cmd/cotizador cli whoami`. Si sale código 3, pide al usuario sus credenciales o que defina `COTIZADOR_EMAIL` / `COTIZADOR_PASSWORD`. Nunca escribas una contraseña en un archivo del repo ni la repitas en el chat. 3. Destino: `COTIZADOR_URL` (default `http://localhost:3000`). Producción es `https://cotizador.urieljareth.org`. **Confirma con el usuario antes de escribir en producción.** ## Reglas @@ -25,12 +25,12 @@ El CLI vive en `cli/cotizador.mjs` (Node 18+, sin dependencias). Ejecútalo desd ## Recetas ```bash -node cli/cotizador.mjs servicios listar --q "seo" --campos id,nombre,precioBase,fase -node cli/cotizador.mjs servicios crear --nombre "..." --fase 1 --tipo-pago unico --precio 5000 --categoria "Desarrollo Web" -node cli/cotizador.mjs servicios editar "" --precio 5500 -node cli/cotizador.mjs cotizaciones crear --cliente "..." --empresa "..." --servicio "" --servicio "=4500" -node cli/cotizador.mjs cotizaciones estado UJ2611AD001 enviada -node cli/cotizador.mjs cotizaciones pdf UJ2611AD001 --salida ./cotizacion.pdf +go run ./cmd/cotizador cli servicios listar --q "seo" --campos id,nombre,precioBase,fase +go run ./cmd/cotizador cli servicios crear --nombre "..." --fase 1 --tipo-pago unico --precio 5000 --categoria "Desarrollo Web" +go run ./cmd/cotizador cli servicios editar "" --precio 5500 +go run ./cmd/cotizador cli cotizaciones crear --cliente "..." --empresa "..." --servicio "" --servicio "=4500" +go run ./cmd/cotizador cli cotizaciones estado UJ2611AD001 enviada +go run ./cmd/cotizador cli cotizaciones pdf UJ2611AD001 --salida ./cotizacion.pdf ``` Guía completa: `docs/CLI.md`. diff --git a/.dockerignore b/.dockerignore index 73d9aec..2084ecb 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,19 +1,20 @@ -node_modules -.next .git .claude -api +.opencode docs +uploads +web/node_modules +web/dist cotizador +cotizador.exe *.xlsx *.bat .env* !.env.example -*.tsbuildinfo *.tmp.* Dockerfile docker-compose*.yml +docker-compose*.yaml README.md AGENTS.md CLAUDE.md -src/generated diff --git a/.env.example b/.env.example index e956fc0..17aa580 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,10 @@ -# Cotizador — Uriel Jareth Consulting — variables de entorno +# Cotizador — Uriel Jareth Consulting — variables de entorno (Go + SPA) # Copia este archivo a .env (local) o configúralas en Coolify (producción). -# ── Base de datos (compartida por Next.js y el API Python) ── +# ── Servidor ── +PORT=3000 + +# ── Base de datos PostgreSQL ── # Se conserva el nombre físico de BD (cotizador_e3) en producción para no romper el volumen postgres_data. DB_HOST=localhost DB_PORT=5432 @@ -9,17 +12,10 @@ DB_USER=postgres DB_PASSWORD=postgres DB_NAME=cotizador_e3 -# Opcional: solo la usa el CLI de Prisma (migraciones). Si no la defines, -# se construye automáticamente desde las DB_* (ver prisma.config.ts). -DATABASE_URL="postgresql://postgres:postgres@localhost:5432/cotizador_e3" - # ── Auth ── # OBLIGATORIA. Genera una con: openssl rand -base64 32 JWT_SECRET= -# ── API Python (api/) — clave para agentes de IA / n8n ── -API_KEY= - # ── Seed (catálogo + usuarios). En producción: RUN_SEED=true solo el primer despliegue ── RUN_SEED=false SEED_ADMIN_EMAIL=admin@urieljareth.com @@ -30,24 +26,20 @@ SEED_ASESOR_EMAIL= SEED_ASESOR_PASSWORD= SEED_ASESOR_NAME= -# --- Propuesta consultiva con IA (MiniMax) --- -# Clave del panel de MiniMax. NUNCA se commitea: .env está en .gitignore. -# Ojo con el prefijo: NO uses ANTHROPIC_API_KEY. El SDK la lee por su cuenta y -# mandaría la clave de MiniMax a api.anthropic.com. +# ── Propuesta consultiva con IA (MiniMax) ── +# Sin MINIMAX_API_KEY el botón de generar devuelve un error claro; el resto funciona igual. MINIMAX_API_KEY= MINIMAX_BASE_URL=https://api.minimax.io/anthropic MINIMAX_MODEL=MiniMax-M3 -# --- Notificaciones (panel de cliente) --- -# Web Push. Genera el par con: node -e "console.log(require('web-push').generateVAPIDKeys())" -# Sin claves la app funciona: solo se omiten las notificaciones push (aviso en log). +# ── Notificaciones (panel de cliente y aprobación) ── +# Web Push (VAPID). Sin claves se omiten las notificaciones push con aviso en log. VAPID_PUBLIC_KEY= VAPID_PRIVATE_KEY= -# URL pública (links de correo y notificaciones). En Coolify: el dominio del servicio web. -# Variable de servidor: un NEXT_PUBLIC_* quedaría fijo en el bundle al compilar. +# URL pública para links de correo, aprobación y notificaciones push. APP_URL=http://localhost:3000 -# SMTP de correos (opcionales: sin SMTP_HOST no se envía correo, solo avisa en log) +# SMTP de correos (opcional: sin SMTP_HOST se omite el envío con aviso en log) SMTP_HOST= SMTP_PORT=587 SMTP_USER= @@ -55,22 +47,17 @@ SMTP_PASS= SMTP_FROM= SMTP_FROM_NAME=Uriel Jareth Consulting -# Recordatorio de pagos pendientes: cada cuántos días se reenvía al cliente su -# estado de cuenta mientras siga debiendo cobros (desde las 9:00 hora de México). -# 0 apaga el automático; el botón "Enviar recordatorio" de /cobros sigue sirviendo. +# Recordatorio automático de pagos pendientes (días desde las 9:00 hora de México; 0 = apagado) COBROS_RECORDATORIO_DIAS=3 -# Directorio de comprobantes. Local: vacío = /uploads. -# En Coolify ya va montado como volumen en /app/uploads (docker-compose.coolify.yml). +# Directorio de comprobantes. Local: vacío = /uploads. En Coolify: /app/uploads. UPLOAD_DIR= -# --- API de agentes, aprobación humana y webhooks HMAC-SHA256 --- -# Correo al que llegan las solicitudes de aprobación de borradores (fallback: primer usuario admin) +# ── API de agentes, aprobación humana y webhooks HMAC-SHA256 ── +# Correo para solicitudes de aprobación de borradores (fallback: primer usuario admin) ADMIN_NOTIFY_EMAIL= # Webhook saliente por defecto hacia n8n (firmado con X-Cotizador-Signature: sha256=...) WEBHOOK_N8N_URL= WEBHOOK_N8N_SECRET= # Webhook de n8n para envío de cotizaciones aprobadas por WhatsApp/Chatwoot WEBHOOK_WHATSAPP_SEND_URL= -# Backend Python (api/): solo aceptar la vieja API_KEY sin alcances si se habilita explícitamente -ALLOW_LEGACY_API_KEY=false diff --git a/.gitignore b/.gitignore index 64c9ad9..ed028f7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,65 +1,33 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. +# Frontend dependencies & build output +web/node_modules/ +web/dist/ -# dependencies -/node_modules -/.pnp -.pnp.* -.yarn/* -!.yarn/patches -!.yarn/plugins -!.yarn/releases -!.yarn/versions +# Embedded SPA build output (keep placeholder index.html so `go test` / `go build` works from fresh clone) +internal/spa/dist/* +!internal/spa/dist/index.html -# testing -/coverage +# Compiled Go binaries +/cotizador +/cotizador.exe +*.exe +*.test +*.out -# next.js -/.next/ -/out/ - -# production -/build - -# misc -.DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* -.pnpm-debug.log* - -# env files (can opt-in for committing if needed) +# Environment files .env* !.env.example -# vercel -.vercel - -# python api (api/) -__pycache__/ -*.py[cod] -*.egg-info/ -.venv/ -venv/ -.pytest_cache/ -.ruff_cache/ - -# typescript -*.tsbuildinfo -next-env.d.ts - -/src/generated/prisma - -# business files (never commit quotation spreadsheets) +# Business files (never commit quotation spreadsheets) *.xlsx -# editor temp files -*.tmp.* - -# claude local settings -.claude/settings.local.json - -# Comprobantes de pago subidos por los clientes (nunca se commitean) +# Uploaded payment receipts uploads/ + +# OS / editor / local agent artifacts +.DS_Store +*.pem +*.tmp.* +npm-debug.log* +.claude/settings.local.json +.opencode/ +.mimocode/ diff --git a/AGENTS.md b/AGENTS.md index 0908ebf..58633b2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,173 +1,117 @@ -# AGENTS.md — Cotizador — Uriel Jareth Consulting +# AGENTS.md — Cotizador — Uriel Jareth Consulting (Go + Vite SPA) ## Quick Reference | Command | Purpose | |---------|---------| -| `npm run dev` | Start Next.js dev server on port 3000 | -| `npm run build` | Production build (runs TypeScript check) | -| `npm run lint` | ESLint (flat config, eslint-config-next) | -| `npm run db:seed` | Run seed (upserts all data, idempotent) | -| `npm run db:migrate` | Create/apply migration (`prisma migrate dev`) | -| `npm run db:generate` | Regenerate Prisma client | -| `npm run db:studio` | Prisma Studio GUI | -| `npm run cli -- ` | CLI `cotizador` (servicios, clientes, cotizaciones, horas). `node cli/cotizador.mjs esquema` lo describe en JSON. See `docs/CLI.md` | +| `go run ./cmd/cotizador serve` | Start unified Go server (API + embedded SPA) on port 3000 (runs auto-migrations on boot) | +| `go test -count=1 ./...` | Run all Go unit & HTTP API security tests | +| `go vet ./...` | Static analysis across all Go packages | +| `go build -o cotizador ./cmd/cotizador` | Compile unified static binary (`serve`, `migrate`, `seed`, `provision-keys`, `cli`) | +| `go run ./cmd/cotizador migrate` | Apply idempotent SQL migrations (`_go_migrations`) | +| `go run ./cmd/cotizador seed` | Run idempotent catalog/config/user seed | +| `go run ./cmd/cotizador provision-keys --preset` | Provision scoped `AgentApiKey` credentials in PostgreSQL | +| `go run ./cmd/cotizador cli ` | CLI `cotizador` (servicios, clientes, cotizaciones, horas). `cotizador cli esquema` lo describe en JSON | +| `cd web && npm run dev` | Start Vite dev server (proxies `/api` to `http://localhost:3000`) | +| `cd web && npm run build` | Build production React 19 + Tailwind CSS v4 SPA into `web/dist/` | -**There is no test suite** — no runner, no test files, in either backend. Verification is `npm run build` (typechecks) + `npm run lint`. Don't claim a change is verified on the strength of a build alone; exercise the affected route or page. +**Windows environment.** Use `start.bat` / `stop.bat` to manage Docker PostgreSQL + SPA build + Go server together. PowerShell is the shell. -**Windows environment.** Use `start.bat` / `stop.bat` to manage Docker PostgreSQL + Next.js together. PowerShell is the shell. Paths with brackets (e.g. `[id]`) require `-LiteralPath` in PowerShell, not `-Path`. +**Single Go backend + embedded SPA.** A single Go 1.27 binary (`cmd/cotizador`) serves: +- All REST API routes under `/api/*` (OpenAPI 3.1 at `/api/openapi.json`) +- The compiled Vite React 19 + Tailwind CSS v4 SPA (`web/` → embedded via `//go:embed all:dist` in `internal/spa/`) +- Background recurring payment & reminder scheduler (`internal/scheduler`) +- Server-side PDF (`fpdf`) and Excel/CSV (`excelize`) generation +- Consultative AI proposal pipeline via MiniMax (`internal/propuesta`) +- Built-in CLI (`cotizador cli ...`) and key provisioning (`cotizador provision-keys`) -**Two backends, one database.** The Next.js app (`src/`, port 3000) and a standalone Python FastAPI service (`api/`, port 8000) both talk to the same PostgreSQL DB. Prisma owns the schema/migrations; the Python API reads/writes the same tables independently. `docker-compose.yml` runs `postgres` + the `api` service; Next.js is run separately via `npm run dev` / `start.bat`. +**Compose files:** `docker-compose.yaml` is a byte-identical copy of `docker-compose.coolify.yml` — Coolify reads `/docker-compose.yaml`. **Whenever you edit the Coolify stack, update both `docker-compose.coolify.yml` and `docker-compose.yaml` identically.** Local dev uses `docker-compose.yml` (PostgreSQL 16 on port 5432). Pass `-f docker-compose.yml` explicitly in local dev. -**Three compose files, and two of them are the same file.** `docker-compose.yaml` is a byte-identical copy of `docker-compose.coolify.yml` — it exists only so Coolify's default detection finds the production stack. Local dev is `docker-compose.yml` (postgres with port 5432 published + api). Because `.yml` and `.yaml` both exist, a bare `docker compose` warns about ambiguity before resolving to `docker-compose.yml`; pass `-f docker-compose.yml` explicitly, as `start.bat` does. **When you edit the Coolify stack, edit both `docker-compose.coolify.yml` and `docker-compose.yaml`** or Coolify deploys the stale copy. +## PostgreSQL & Migrations -## Prisma 7 — Critical Gotchas +- **Direct `pgx/v5` pool** (`internal/db/db.go`) using individual `DB_HOST`, `DB_PORT`, `DB_USER`, `DB_PASSWORD`, `DB_NAME` params (never a raw connection string, avoiding SCRAM encoding issues). +- **Schema compatibility:** All 25 tables preserve exact quoted PascalCase table names (`"Cotizacion"`, `"PagoRecurrente"`, etc.) and quoted camelCase columns (`"tipoPago"`, `"vencidoNotificadoAt"`, etc.) from the live production database `cotizador_e3`. +- **Migrations:** Idempotent SQL files in `internal/db/migrations/*.sql`, tracked in `"_go_migrations"`, executed automatically on `cotizador serve` startup (safe on both empty DBs and live production DBs). +- **IDs:** `db.NewID()` generates CUID-like URL-safe IDs. Seed service IDs are slugs (e.g. `auditoria-en-sitio-web-2`); never validate IDs by format. -- **Prisma client is NOT at `@prisma/client`.** It's generated to `src/generated/prisma/` and imported as `@/generated/prisma/client`. -- **Uses `PrismaPg` driver adapter** (from `@prisma/adapter-pg`) with individual connection params (host/port/user/password/database), NOT a connection string. The `connectionString` approach causes SCRAM auth errors with postgres:postgres. -- **`prisma.config.ts`** has no `seed` property (unsupported by PrismaConfig type). Run seed manually with `npx tsx prisma/seed.ts`. -- After changing `schema.prisma`: run `npx prisma migrate dev`, then `npx prisma generate`. -- The `globalForPrisma` singleton pattern in `src/lib/db.ts` prevents hot-reload connection leaks in dev. +## Domain & Business Rules (`internal/domain/`) -## PDFKit — Server-Side PDF +- **`internal/domain/calculators.go`** is the single source of truth for totals, charge models, phases, financing, Bucéfalo CRM prices, hours ranges, and formatting (mirrored for UI previews in `web/src/lib/calculators.ts`). +- Cotización number format: `UJ{YY}{MM}{AsesorInitials}{seq}` (3-digit zero-padded sequence). +- Vigencia = 15 business days from `fecha` (excludes Sat/Sun). `IVA_RATE = 0.16` (16%). +- **Bucéfalo CRM plan prices:** basico=\$1,000, estandar=\$3,500, premium=\$4,500, empresarial=\$7,500 (monthly). +- **Financing (`FinanciamientoPlan` 3/6/9/12 months):** `comisionTotal = monto × comision%`, `pagoMensual = (monto + comisionTotal) × (1 + tasa) / meses`, then +16% IVA. +- **Charge models (`ServicioCotizado.modeloCobro`):** `fijo` (default), `horas`, `retainer`, `demanda`. `TARIFA_HORA_DEFAULT = 700`. **`precio` is always the authoritative total** — never re-derive totals from `horas × tarifaHora` for retainer/demanda lines. +- **Doble propuesta (`Cotizacion.esDoble`):** `ServicioCotizado.opcion` is `"1"`, `"2"`, or `"ambas"`. `CalcularTotalesOpcion` sums lines matching the option **plus** `"ambas"`. +- **Registro de horas (`RegistroHoras`):** `estadoPago` is `"por_pagar"` or `"pagada"` (`fechaPago` stamped on transition). Pending and paid totals stay separated (`ResumenPagoHoras`). Dates use `FechaRegistroDesdeISO` to avoid UTC off-by-one. Grouping modes: `detalle | dia | semana | mes`. +- **`Configuracion`:** Key-value store (`clave`/`valor`), including branding (`color_primario`, `color_secundario`, `logo_base64`) and bank transfer info. +- **Internal notes:** `observacionesInternas` must NEVER leak into PDFs, Excel exports, client portal responses, or `soloAceptadas` agent responses. -- `pdfkit` is excluded from Next.js bundling via `serverExternalPackages` in `next.config.ts`. Without this, font metric files (`.afm`) can't be resolved at runtime. -- **Footer auto-page-break bug:** `doc.text()` at `y > page.height - margins.bottom` triggers pdfkit's automatic page addition. To write footers in the bottom margin, temporarily set `doc.page.margins.bottom = 0`, write, then restore. Use `bufferPages: true` + `switchToPage()` to add footers after all content. -- Returns `Promise` — convert to `Uint8Array` for `NextResponse` body. +## Auth, Panel Isolation & Iron-Clad Rules (`internal/auth/`) -## Next.js 16 Conventions +- **JWT sessions** signed with HS256 (`golang-jwt/jwt/v5`, 7-day expiry) in httpOnly cookie `cotizador-session`. `JWT_SECRET` is required at server startup. Passwords hashed with `bcrypt` (cost 10). +- **Roles:** `admin`, `asesor` (staff) and `cliente` (client portal). + - Staff routes call `Auth.RequireActor(...)` inside every handler; client portal routes (`/api/cliente/*`) call `Auth.RequireCliente(...)`. + - Shared routes (`/api/comprobantes/{pagoId}`, `/api/export/pdf/{id}`) explicitly validate ownership when `role == "cliente"`. +- **Agent API Keys (`AgentApiKey`):** Prefixed `ujc_live_*`, SHA-256 hashed in PostgreSQL, 60s sliding-window in-memory rate limit, exact **9 scopes** (`catalogo:leer`, `clientes:leer`, `clientes:escribir`, `cotizaciones:leer`, `cotizaciones:leer_aceptadas`, `cotizaciones:borrador`, `cotizaciones:enviar`, `cobros:leer`, `cobros:registrar`). +- **Iron-clad approval rule:** No agent can ever approve quotes (never add an approval scope). States: `borrador → aprobada → enviada → aceptada | rechazada | vencida`. Approval requires human `role="admin"` (`POST /api/cotizaciones/{id}/aprobar`) or one-time signed link (`/aprobar/{token}` + `POST { confirmar: true }`). Sending (`POST /api/cotizaciones/{id}/enviar`) requires `estado == "aprobada" && aprobadaAt != nil`. +- **`soloAdmin` items:** Catalog services marked `soloAdmin = true` (e.g. Bucéfalo CRM items) and quotes containing them are hidden/blocked from agents (`internal/domain/solo_admin_core.go`). +- **Idempotency & Audit:** `internal/idempotency/` guards `POST /api/cotizaciones`, `POST /api/cotizaciones/{id}/enviar`, `POST /api/clientes`, and `POST /api/cobros/pagos/{id}/registrar`. Security-relevant events and blocked attempts are written to `AuditLog` (`internal/audit/`). +- **Webhooks (`internal/webhooks/`):** HMAC-SHA256 (`X-Cotizador-Signature: sha256=...`), 3 retries, 8s timeout, `WebhookDelivery` log, automatic `WEBHOOK_N8N_URL`/`WEBHOOK_N8N_SECRET` fan-out. -- **Async params:** Dynamic route params are `Promise<{ id: string }>` — must `await params` before use. -- **All pages are `force-dynamic`** — no static generation or ISR. -- **Tailwind CSS v4** — no `tailwind.config.*` file. Config is in `postcss.config.mjs` (using `@tailwindcss/postcss`) and CSS custom properties via `@theme inline` in `src/app/globals.css`. +## Cobros recurrentes, Notificaciones & Subidas -## Data Model Notes +- **Dates (`internal/domain/cobros_fechas.go`):** Calendar dates in `America/Mexico_City` persisted as UTC midnight (`ParseFechaCalendario`, `FormatFechaCobro`, `InstanteDePago`). Never parse `YYYY-MM-DD` with local timezone blindly. +- **Anular vs delete:** Cancelling a charge marks `estado = "anulado"` (never deletes the row, otherwise `GenerarCobros` recreates it as `pendiente`). +- **Scheduler (`internal/scheduler/`):** Runs 20s after boot and every 60 min — runs overdue reminders first (from 9:00 MX when `COBROS_RECORDATORIO_DIAS > 0`), then `GenerarCobros` + `NotificarCobrosNuevos`, plus idempotent `pago.vencido` webhook emission. +- **Uploads (`internal/uploads/`):** Stored in `UPLOAD_DIR/comprobantes//.` (max 10 MB, path-traversal guarded). Pure-Go image resize (max 1920 px) + WebP encoding (`nativewebp`); PDFs saved as-is. +- **Notifications (`internal/notify/`):** Best-effort SMTP MIME (HTML + text + PDF attachments) and Web Push VAPID (`webpush-go`). Missing SMTP/VAPID config logs a warning and never breaks the flow. -- **Configuracion** is a key-value store (`clave`/`valor`), not a traditional settings model. New config keys: `color_primario`, `color_secundario`, `logo_base64` (branding for PDF export). -- **Cascading deletes:** Cotizacion → ServicioCotizado, PlanBucefaloCotizacion use `onDelete: Cascade`. -- Cotización number format: `UJ{YY}{MM}{AsesorInitials}{seq}` (e.g. `UJ2605AG001`) — see `generarNumeroCotizacion` in `src/lib/calculators.ts`. Sequence is 3 digits, zero-padded. -- Vigencia = 15 business days from fecha (excludes Sat/Sun) — `calcularVigencia`. -- IVA_RATE = 0.16 (16%). -- **Bucéfalo CRM plan prices** (in `calculators.ts`, NOT the DB): basico=$1,000, estandar=$3,500, premium=$4,500, empresarial=$7,500 (monthly). -- **Financing** lives in the `FinanciamientoPlan` table (3/6/9/12 months). Formula: `comisionTotal = monto × comision%`, `pagoMensual = (monto + comisionTotal) × (1 + tasa) / meses`, then add 16% IVA. Both backends must keep this formula identical. +## PDF, Excel & Propuesta IA -### Catálogo de servicios (alta y edición) +- **PDFs (`internal/pdf/`):** Pure Go (`codeberg.org/go-pdf/fpdf`) with embedded UTF-8 Go fonts and PNG/JPEG/WebP logo support: quote PDF, hours payment note PDF, consultative proposal PDF, and separate red-banner internal annex PDF. +- **Excel & CSV (`internal/excel/`):** `excelize/v2` for quote workbooks (`HOJA RESUMEN` + per-service tabs, never leaking `observacionesInternas` or `domicilioFiscal`) and catalog CSV export/template/import. +- **Propuesta IA (`internal/propuesta/`):** MiniMax Anthropic-compatible API (`MINIMAX_API_KEY`, `MINIMAX_BASE_URL`, `MINIMAX_MODEL`) with deterministic economic ratio calculation, validation, and auto-reparation. -- API: `GET|POST /api/catalogo` (GET filtra `?q=&fase=&tipoPago=&categoriaId=&activo=true|false`; sin `activo` devuelve activos y archivados) y `GET|PATCH|PUT|DELETE /api/catalogo/[id]`. **PATCH y PUT son parciales**: solo tocan los campos enviados (`servicioCatalogoPatchSchema`). DELETE archiva (`activo=false`) si alguna cotización usa el servicio; si no, lo borra. -- Las respuestas salen de `serializarServicio` (`src/lib/catalogo.ts`): forma plana con `categoriaNombre`, `categoriaColor` y `enCotizaciones`. Los 400 de estas rutas usan `errorValidacion` (`{ error, detalles: [{ campo, mensaje }] }`). -- En `servicioCatalogoSchema` solo `nombre`, `fase`, `tipoPago` y `precioBase` son obligatorios; `categoriaId` es opcional y, sin `orden`, el servicio queda al final de su fase (`siguienteOrden`). En esos esquemas el `.optional()` va **por fuera** del transform de texto: si va por dentro, una clave ausente se vuelve `null` y un PATCH borra el dato. -- UI: `src/components/ServicioFormModal.tsx` hace el POST/PATCH y muestra el error de la API sin cerrarse. Lo usan `/catalogo` y `CotizacionForm`: en el cotizador, "Nuevo servicio" (general o por fase) lo crea y lo deja seleccionado, y el lápiz de cada servicio lo edita. Si la cotización usa ese servicio, su partida toma el nombre, fase, tipo de pago, tiempo y entregables nuevos; el precio solo si la partida tenía el precio base anterior. -- Los ids de los servicios del seed son slugs (`auditoria-en-sitio-web-2`), no cuids: no valides ids por formato. +## Frontend SPA (`web/`) & UI Conventions -### Charge models (`ServicioCotizado.modeloCobro`) - -A quoted line item is `fijo` (default), `horas`, `retainer`, or `demanda` — see `MODELOS_COBRO` in `calculators.ts`. The time-based three are `MODELOS_COBRO_TIEMPO`. Supporting fields: `esPersonalizado`, `horas`, `tarifaHora`, `montoMinimo`, `horasIncluidas`. `TARIFA_HORA_DEFAULT = 700`. - -**`precio` is always the authoritative total.** For retainer and demanda lines, `horas × tarifaHora` is display/comparison metadata only — never re-derive a total from it. `calcularTotalesOpcion` and the PDF/Excel builders all sum `precio`. - -### Doble propuesta (two-option quotes) - -`Cotizacion.esDoble` turns one quote into two comparable proposals. Each `ServicioCotizado.opcion` is `"1"`, `"2"`, or `"ambas"` (shared by both). `opcionesMetadata` (Json) holds per-option `titulo` / `descripcion` / `noIncluye` (`MetaOpcion`). `calcularTotalesOpcion(servicios, "1" | "2")` sums lines matching that option **plus** all `"ambas"` lines. Anything that renders or totals a quote must handle both the single and double shape. - -### Registro de horas (hours log → payment notes) - -`RegistroHoras` tracks worked time against a quote so the client can be billed for it. Only offered when `esCotizacionPorTiempo(servicios)` is true (i.e. some line uses a time-based `modeloCobro`). - -- `estadoPago` is `"por_pagar"` (default) or `"pagada"`, with `fechaPago` stamped on transition. The two buckets must stay separated in totals — pending is what goes on the payment note, paid is history. `resumenPagoHoras` / `esPagada` in `calculators.ts` are the only place that logic should live. -- Routes: `GET|POST /api/cotizaciones/[id]/horas` (GET takes `?from=&to=` day filters), `PATCH|DELETE .../horas/[registroId]`, and `POST .../nota-horas` which renders the PDF **server-side** via `src/lib/nota-horas-pdf.ts` (no browser URL). -- Hours are entered as `horaInicio`/`horaFin` strings and converted by `calcularHorasRango`. Dates come in as `YYYY-MM-DD` and must go through `fechaRegistroDesdeISO` to avoid UTC off-by-one — don't `new Date(iso)` directly. -- Grouping for display/PDF: `ModoAgrupacion` = `detalle | dia | semana | mes` via `periodoAgrupacion`. - -## Auth - -- **JWT sessions** (`src/lib/auth.ts`) signed with `jose` (HS256, 7-day expiry), stored in the `cotizador-session` httpOnly cookie. `JWT_SECRET` env var is **required** (throws at startup if missing). -- **`src/middleware.ts`** gates everything except `PUBLIC_PATHS` (`/login`, `/api/auth/login`, `/api/auth/logout`, `/api/health`, `/sw.js`). Unauthenticated API calls → 401 JSON; pages → redirect to `/login` (`/login?panel=cliente` para rutas de cliente). On success it injects `x-user-id` / `x-user-role` / `x-cliente-id` request headers for downstream handlers. -- Clientes se dan de alta y se editan en `/clientes` (`POST /api/clientes`, `PATCH /api/clientes/[id]`, helpers en `src/lib/clientes.ts`) sin pasar por una cotización; como las cotizaciones reconocen al cliente por `nombre + empresa`, la API rechaza esa pareja duplicada (sin distinguir mayúsculas) con 409. `/clientes?nuevo=1` abre el alta. `Cliente.puesto` es solo informativo. Passwords hashed with `bcryptjs`. Roles: `admin`, `asesor` (default) y **`cliente`**. El middleware separa paneles: `role=cliente` solo entra a `/cliente*` y `/api/cliente*`; el staff no entra a esas rutas; `/api/comprobantes` y `/api/export/pdf` son **compartidas** (el handler valida pertenencia). Además de middleware, las rutas nuevas usan `requireStaff()` / `requireRole("cliente")` de `src/lib/auth.ts` dentro del handler (defensa en profundidad). El login redirige por rol (`/` vs `/cliente`); la sesión de cliente lleva el claim `clienteId`. - -## CLI (`cli/cotizador.mjs`) - -- Node puro (18+), sin dependencias, habla con la API de Next con la sesión de un usuario staff: `login` guarda el JWT en `~/.cotizador-uj/sesiones.json` y lo manda como cookie `cotizador-session`. Con `COTIZADOR_EMAIL`/`COTIZADOR_PASSWORD` renueva la sesión solo. No hay API key en Next: para eso está la API de Python. -- Pensado para LLMs: JSON en stdout, errores JSON en stderr con códigos de salida fijos (2 uso, 3 auth, 4 no encontrado, 5 validación, 6 duplicado, 7 red), `--campos`, `--dry-run`, `--confirmar` obligatorio para borrar y error ante flags desconocidas. `cotizador esquema` vuelca el registro de comandos; ayuda, validación y esquema salen del mismo arreglo `COMANDOS`, así que un comando nuevo se documenta solo. -- `POST /api/cotizaciones` acepta un cuerpo mínimo para el CLI: sin `numero` lo genera el servidor (`siguienteNumeroCotizacion` en `src/lib/cotizaciones.ts`, misma regla que el formulario), sin `asesorId` usa el usuario de la sesión, sin `fecha`/`vigencia` usa hoy + 15 días hábiles, y `planBucefalo.precio` cae al precio de lista. -- Respuestas JSON de cotizaciones: el asesor sale con `asesorPublicoSelect`, **nunca** `asesor: true` (incluye el hash de la contraseña). -- Skill para agentes: `.claude/skills/cotizador-cli/SKILL.md`. Guía: `docs/CLI.md`. - -## Cobros recurrentes y panel de cliente - -- **Modelos**: `ProgramaPago` (cadencia semanal/quincenal/mensual, ej. `$750 cada sábado`), `PagoRecurrente` (único por `programaId+fecha`; estados `pendiente → en_revision → verificado | rechazado`, más `anulado` = sin cargo; `nota` es interna del admin y el cliente no la ve), `ComprobantePago` (archivo en `UPLOAD_DIR/comprobantes/…`, fuera de `/public`), `SuscripcionPush`. `User.clienteId` vincula la cuenta `role=cliente` con un `Cliente` (1:1). -- **`src/lib/cobros-fechas.ts` vs `src/lib/cobros.ts`**: las utilidades puras (estados, fechas de calendario MX, formatos, `fechasPeriodo`) viven en `cobros-fechas.ts`. **Los componentes `"use client"` importan de `@/lib/cobros-fechas`, NUNCA de `@/lib/cobros`** — ese arrastra Prisma/pg y rompe el build de Next. `cobros.ts` (lado servidor) re-exporta todo y agrega `generarCobros()` idempotente. -- **Fechas**: una fecha de cobro es fecha de calendario en `America/Mexico_City` persistida como medianoche UTC (`parseFechaCalendario` / `formatFechaCobro` / `formatFechaCorta`). No usar `new Date(iso)` directo. -- **Scheduler**: `src/instrumentation.ts` importa `src/lib/scheduler.ts` **dentro del guard `NEXT_RUNTIME === "nodejs"`** (si lo mueves fuera, pg entra al bundle Edge y el build falla). Corre a los 20 s del arranque y cada 60 min: `generarCobros()` + `notificarCobrosNuevos()`. -- **Notificaciones** (`src/lib/notificaciones.ts`): llamar **después** de persistir el cambio — `notificarCobrosNuevos(pagos)`, `notificarVerificacion(pagoId)`, `notificarRechazo(pagoId, motivo)`. Son best-effort; SMTP/VAPID sin configurar solo avisan en log (`email.ts` / `push.ts`), jamás tumbaron el flujo. -- **Recordatorios de pagos pendientes** (`enviarRecordatoriosPendientes` en `notificaciones.ts`): "por pagar" = `pendiente | rechazado` con `fecha <= hoy` (`ESTADOS_POR_PAGAR`, `pagosPorCobrar()` en `cobros.ts`, que incluye programas inactivos). Manda **un estado de cuenta por cliente** (lista, total por moneda, datos bancarios de Configuración) por correo + push y sella `ultimoRecordatorioAt` / `recordatoriosEnviados` **solo si algún canal lo entregó**. El scheduler lo corre desde las 9:00 MX cuando algún cobro lleva `COBROS_RECORDATORIO_DIAS` (default 3; 0 = apagado) sin aviso, y lo hace **antes** de `notificarCobrosNuevos` para no mandar dos correos al mismo cliente en una corrida. Envío manual: `POST /api/cobros/recordatorios` (`{ clienteId? }`, ignora la espera) desde la sección "Pagos por cobrar" de `/cobros`. -- **Pagos fuera del panel** (clientes sin cuenta o que avisan por otro medio): `POST /api/cobros/pagos/[id]/registrar` (`{ fecha, nota? }`, `pendiente|rechazado → verificado` sin comprobante; `verificadoAt = instanteDePago(fecha)`, mediodía MX, para que `calendarioDe()` no lo corra al día anterior), `.../anular` (`{ motivo }` → `anulado`) y `.../reabrir` (manual o anulado → `pendiente`). **Anular no borra el registro**: si se borrara, `generarCobros()` lo volvería a crear como pendiente, porque rellena todos los periodos desde `fechaInicio`. Por eso un programa con historial se carga completo (un registro por periodo) y no solo con los pagos. `GET /api/cobros/pagos` acepta `clienteId` y `estado=por_pagar`. -- **Subidas**: `src/lib/uploads.ts` (`guardarComprobante`/`eliminarComprobante`) convierte imágenes a WebP con sharp (máx 1920 px, q80), PDFs tal cual, 10 MB. Las rutas se guardan con separadores `/` aunque el dev corra en Windows. El rechazo borra el archivo del servidor y el cliente puede volver a subir. -- **UI**: admin en `/cobros` (nav del Sidebar), panel cliente en `/cliente` (shell propio, sin el Sidebar de staff) con `public/sw.js` para Web Push. +- React 19 + TypeScript + Vite 6 + Tailwind CSS v4 + React Router v7 + Zustand + `lucide-react`. +- Compiled to `web/dist/` and embedded in the Go binary (`internal/spa/dist/`). Static assets under `/assets/*` are served immutable; `/sw.js` and `index.html` are served `no-cache`; all non-API paths fall back to `index.html`. +- **Never use native browser `confirm()` / `alert()` / `prompt()`.** Use `useConfirm()`, `usePrompt()`, `useToast()` from `web/src/components/ui/DialogProvider.tsx`. +- Everything user-facing is in **Spanish**, using CSS custom properties from `web/src/index.css`. ## Deployment (Coolify) -- Production stack: postgres + web + api. The live Coolify app (`cotizador`, uuid `e6vie34d83iv5vw3eyzinl3s`, https://cotizador.urieljareth.org) has **Docker Compose Location `/docker-compose.yaml`** — the byte-identical copy — so both files must stay in sync. Local dev keeps using `docker-compose.yml` + `start.bat`. -- **Deploys come from GitHub `main` (`origin`), not Gitea.** Auto-deploy is on: a push to GitHub `main` *is* the deploy (~15 min full build). Pushing to `gitea` only mirrors the code. Don't also trigger the deploy API after a push, or two deploys race. -- `APP_URL` must be set in Coolify (`https://cotizador.urieljareth.org`): email links fall back to `http://localhost:3000` without it. **Never read a runtime value through a `NEXT_PUBLIC_*` name on the server** — Next inlines those at build time (even via a computed key), and the production image is built without them. -- The `web` container runs `prisma migrate deploy` on every start, and the seed only when `RUN_SEED=true`. Seed users/passwords come from `SEED_*` env vars (see `.env.example`) — `prisma/seed.ts` never overwrites an existing password unless the env var is set. -- `DATABASE_URL` is only used by the Prisma CLI (migrations); the apps use individual `DB_*` vars. Both must point to the same DB. -- Healthchecks: web `GET /api/health` (public in middleware, pings DB), api `GET /health`. -- Root `Dockerfile` builds Next.js with `JWT_SECRET=placeholder-build-only` (auth.ts throws at import without it; all pages are force-dynamic so nothing gets baked). +- Production stack: `postgres` + `web` (single Go container, port 3000, `https://cotizador.urieljareth.org`). +- Coolify app (`cotizador`, uuid `e6vie34d83iv5vw3eyzinl3s`) uses **Docker Compose Location `/docker-compose.yaml`** — keep `docker-compose.coolify.yml` and `docker-compose.yaml` byte-identical. +- **Deploys come from GitHub `main` (`origin`), not Gitea.** Auto-deploy is on: pushing to `origin main` triggers deployment; pushing to `gitea` mirrors the repo. +- `APP_URL` must be set to `https://cotizador.urieljareth.org` in Coolify. +- `postgres_data` (`cotizador_e3`) and `uploads_data` (`/app/uploads`) volumes are preserved across deploys. +- Healthcheck: `GET /api/health` (pings PostgreSQL and returns `{"status":"ok","runtime":"go",...}`). - `*.xlsx` is gitignored (business files must never be committed). ## Architecture ``` -src/ - app/ - (app)/ # Authed route group: dashboard, cotizaciones, clientes, catalogo, configuracion (has its own layout.tsx + Sidebar + DialogProvider) - api/ # Next.js route handlers (REST): auth, catalogo, categorias, cotizaciones (+ horas, nota-horas, precio), - # configuracion, paquetes, export, import, health - login/ # Public login page - components/ # CotizacionForm (~1.5k lines), ServicioFormModal, ExportButtons, EstadoBadge, layout/Sidebar, ui/DialogProvider - lib/ # auth, db, store, calculators, schemas, config-helpers, catalogo, cotizaciones, - # pdf-generator (quote PDF), nota-horas-pdf (hours-note PDF), excel-builder - generated/prisma/ # Prisma client output (gitignored) -prisma/ - schema.prisma # 14 models (User, Cliente, Cotizacion, Categoria, Paquete, FasePaquete, - # ServicioCatalogo, ServicioPaquete, ServicioCotizado, PlanBucefaloCotizacion, - # RegistroHoras, Configuracion, Bono, FinanciamientoPlan) - seed.ts # All catalog data (services, categorias, bonos, planes, config) — idempotent upserts - migrations/ # 10 migrations -cli/ # cotizador.mjs — CLI para humanos y LLMs (see docs/CLI.md) -api/ # Standalone Python FastAPI service (see below) -docs/ # Business/product notes (Spanish), not code docs +cmd/cotizador/ # Unified binary entrypoint (serve, migrate, seed, provision-keys, cli) +internal/ + config/ # Env var loading + db/ # pgxpool connector, CUID generator, embedded SQL migrations + domain/ # Business logic: calculators, cobros dates, approval & soloAdmin rules + auth/ # JWT sessions, bcrypt, AgentApiKey SHA-256, 9 scopes, rate limiter + audit/ # AuditLog writer + idempotency/ # 24h Idempotency-Key store + webhooks/ # HMAC-SHA256 dispatcher, n8n WhatsApp invoker, delivery log + uploads/ # Pure-Go WebP converter & receipt file storage + notify/ # SMTP MIME + Web Push VAPID + domain email/push notifications + scheduler/ # Recurring charge generation & overdue reminders + pdf/ # Quote, hours-note, consultative proposal & internal annex PDFs + excel/ # Quote Excel workbook & catalog CSV export/import + propuesta/ # MiniMax AI consultative proposal pipeline + seed/ # Idempotent catalog/config/user seed & agent key provisioning + cli/ # Self-describing LLM-friendly CLI (30 commands, JSON stdout/stderr) + spa/ # //go:embed Vite SPA handler + httpapi/ # chi/v5 router & all REST handlers + OpenAPI 3.1 +web/ # Vite + React 19 + Tailwind v4 SPA (staff app + client portal + /aprobar/:token) +docs/ # Product & migration docs ``` - -- **Zustand store** (`src/lib/store.ts`) holds the cotización draft. Used by both the new (`cotizaciones/nueva`) and edit (`cotizaciones/[id]/editar`) pages, both of which render `CotizacionForm.tsx`. -- **ExportButtons.tsx** has 4 variants: `ExportExcelButtonSaved` / `ExportPDFButtonSaved` (GET by ID) and `ExportExcelButtonDraft` / `ExportPDFButtonDraft` (POST with body). -- **Business logic belongs in `calculators.ts`**, not in components or route handlers. It's the shared source of truth for totals, charge models, hours, phases, and formatting — and the file the Python `calculators.py` mirrors. - -## UI Conventions - -- **Never use the browser's native `confirm()` / `alert()` / `prompt()`.** They render as "«domain» dice…" and break the brand. Use the platform's own dialogs: `useConfirm()`, `usePrompt()`, `useToast()` from `@/components/ui/DialogProvider`, mounted once in `src/app/(app)/layout.tsx`. `confirm` and `prompt` return promises (`boolean` / `string | null`); pass `danger: true` for destructive actions. -- Everything user-facing is in **Spanish**. Code identifiers are Spanish too (`cotizacion`, `servicio`, `horas`) — match the surrounding naming rather than introducing English terms. -- Icons come from `lucide-react`. Colors use the CSS custom properties from `globals.css` (`bg-card-bg`, `border-border`, `text-primary`, `text-muted`), not hardcoded Tailwind palette values. - -## Python API (`api/`) — Optional Second Backend - -- **FastAPI app** (`api/main.py`) exposing the same domain as REST, for n8n and other integrations. -- **The MCP server was removed on 2026-07-28.** It was unused, its transport had been broken for some time (it built a `StreamableHTTPServerTransport` per request with no session handling and returned 500 even with valid credentials), and its unpinned SDK took the whole API down in production when `mcp` jumped to 2.0.0. To revive it: `git show edb500f5:api/app/mcp/server.py`. -- **`api/requirements.txt` pins exact versions on purpose.** That outage is why. Bump a dependency deliberately — never by accident on a redeploy. -- Auth: **API key** (`X-API-Key` or `Authorization: Bearer`) for agents; JWT for human login. Routers in `api/app/routers/`, business logic in `api/app/services/` (its own `calculators.py`, `pdf_generator.py`, `excel_generator.py` — mirror the TS versions). -- Run: `cd api && pip install -r requirements.txt && uvicorn main:app --reload --port 8000`. Swagger at `/docs`. Full endpoint reference in `api/COTIZADOR_API_SKILL.md`. -- It reads `DB_*`, `API_KEY`, `JWT_SECRET` env vars (same DB as Prisma). - -## Domain - -Quotation system for Uriel Jareth Consulting. Services organized in 4 phases: Fase 0 (Auditorías), Fase 1 (Setup/Infra), Fase 2 (Publicidad/Manejo), Fase 3 (Contenido/SEO). Two payment types: `unico` (one-time) and `mensual` (recurring). Optional Bucéfalo CRM plans and Openpay financing. - -## API para Agentes, Aprobación y Webhooks - -- **API unificada:** Next.js (`/api/**`) es la API principal (OpenAPI 3.1 en `/api/openapi.json`). FastAPI (`api/`) se mantiene en **paridad de seguridad** contra la misma PostgreSQL (`AgentApiKey` SHA-256, scopes, rate limit, `AuditLog`, bloqueo de aprobación/envío, `ALLOW_LEGACY_API_KEY=false` por defecto y lectura `/cobros/programas` + `/cobros/pagos`). -- **Edge vs Node:** `src/middleware.ts` corre en Edge y NO importa Prisma ni `pg`. Si llega `X-API-Key` o `Authorization: Bearer` sin cookie de sesión, limpia headers `x-user-*`/`x-cliente-id` y delega la validación al Route Handler vía `requireActor()` en `src/lib/agent-auth.ts`. -- **Regla de hierro de aprobación:** ningún agente puede aprobar cotizaciones (jamás agregar un scope de aprobación). Estados: `borrador → aprobada → enviada → aceptada | rechazada | vencida`. Aprobar exige usuario humano `role="admin"` (`POST /api/cotizaciones/[id]/aprobar`) o enlace firmado de un solo uso (`/aprobar/[token]` con `POST { confirmar: true }`). Enviar (`POST /api/cotizaciones/[id]/enviar`) exige `estado === "aprobada" && aprobadaAt !== null`. -- **Idempotencia y auditoría:** `withIdempotency()` (`src/lib/idempotency.ts`) en `POST /api/cotizaciones`, `POST /api/cotizaciones/[id]/enviar`, `POST /api/clientes` y `POST /api/cobros/pagos/[id]/registrar`. Toda acción relevante o intento bloqueado se registra en `AuditLog` (`src/lib/audit.ts`). -- **Webhooks HMAC-SHA256:** `src/lib/webhooks.ts` firma con `X-Cotizador-Signature: sha256=...`, incluye automáticamente `WEBHOOK_N8N_URL`/`WEBHOOK_N8N_SECRET` y guarda historial en `WebhookDelivery`. `enviarRecordatoriosPendientes` emite `pago.vencido` de forma best-effort sin alterar los correos/push ni `ultimoRecordatorioAt`. -- **Provisioning CLI:** `npx tsx scripts/provision-agent-keys.ts --preset` (incluido en el `Dockerfile` runner). -- **Pruebas automáticas:** `npm test` (`node --import tsx --test tests/*.test.ts`) valida scopes, rate limit, guardia de aprobación, firmas HMAC y paridad numérica exacta entre `src/lib/calculators.ts` y `api/app/services/calculators.py`. diff --git a/Dockerfile b/Dockerfile index db4aa99..4a3cd90 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,49 +1,41 @@ -# Cotizador — Uriel Jareth Consulting — Next.js (web) -# Multi-stage build. El runner conserva node_modules completo para que -# `prisma migrate deploy` y el seed (tsx) funcionen dentro del contenedor. +# Cotizador — Uriel Jareth Consulting — Binario unificado Go + SPA Vite embebido +# Multi-stage build: +# 1. node:22-alpine compila el SPA React 19 + Tailwind CSS v4 (web/dist) +# 2. golang:1.27-alpine embebe web/dist via //go:embed y compila binario estatico (CGO_ENABLED=0) +# 3. alpine:3.21 ejecuta el binario unico (~25 MB) con ca-certificates y tzdata -FROM node:22-slim AS base +# ── Stage 1: Frontend SPA (Vite + React 19 + Tailwind v4) ── +FROM node:22-alpine AS web-builder +WORKDIR /web +COPY web/package.json web/package-lock.json* ./ +RUN if [ -f package-lock.json ]; then npm ci; else npm install; fi +COPY web/ ./ +RUN npm run build + +# ── Stage 2: Backend Go + SPA embebido ── +FROM golang:1.27-alpine AS go-builder +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ +RUN rm -rf internal/spa/dist/* +COPY --from=web-builder /web/dist/ ./internal/spa/dist/ +RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/cotizador ./cmd/cotizador + +# ── Stage 3: Runtime minimo ── +FROM alpine:3.21 AS runner +RUN apk add --no-cache ca-certificates tzdata wget WORKDIR /app -ENV NEXT_TELEMETRY_DISABLED=1 +COPY --from=go-builder /out/cotizador /app/cotizador -# ── Dependencias ── -FROM base AS deps -COPY package.json package-lock.json ./ -RUN npm ci - -# ── Build ── -FROM base AS builder -COPY --from=deps /app/node_modules ./node_modules -COPY . . -# Placeholder solo para el build: src/lib/auth.ts lanza error al importarse -# sin JWT_SECRET. Todas las páginas son force-dynamic, nada queda horneado. -ENV JWT_SECRET=placeholder-build-only -RUN npx prisma generate && npm run build - -# ── Runtime ── -FROM base AS runner -ENV NODE_ENV=production ENV PORT=3000 - -# openssl: el CLI de Prisma lo necesita para detectar la versión de libssl -RUN apt-get update -y && apt-get install -y --no-install-recommends openssl \ - && rm -rf /var/lib/apt/lists/* - -COPY --from=builder /app/node_modules ./node_modules -COPY --from=builder /app/.next ./.next -COPY --from=builder /app/public ./public -COPY --from=builder /app/prisma ./prisma -COPY --from=builder /app/scripts ./scripts -COPY --from=builder /app/src/generated ./src/generated -COPY --from=builder /app/prisma.config.ts ./prisma.config.ts -COPY --from=builder /app/next.config.ts ./next.config.ts -COPY --from=builder /app/tsconfig.json ./tsconfig.json -COPY --from=builder /app/package.json ./package.json +ENV UPLOAD_DIR=/app/uploads EXPOSE 3000 -HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=5 \ - CMD node -e "fetch('http://localhost:3000/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" +HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=5 \ + CMD wget -qO- http://localhost:3000/api/health >/dev/null || exit 1 -# Migraciones primero, seed opcional (RUN_SEED=true), luego el servidor. -CMD ["sh", "-c", "npx prisma migrate deploy && if [ \"$RUN_SEED\" = \"true\" ]; then npx tsx prisma/seed.ts; fi && exec node_modules/.bin/next start -p ${PORT:-3000}"] +ENTRYPOINT ["/app/cotizador"] +CMD ["serve"] diff --git a/README.md b/README.md index 31ba013..cd67336 100644 --- a/README.md +++ b/README.md @@ -1,115 +1,59 @@ # Cotizador — Uriel Jareth Consulting -Sistema de generación de cotizaciones para Uriel Jareth Consulting. -Servicios organizados en 4 fases, dos tipos de pago (único / mensual), planes CRM Bucéfalo -y financiamiento opcional. Exporta a PDF y Excel. +Sistema de generación de cotizaciones, registro de horas, cobros recurrentes, propuestas consultivas con IA y portal de clientes para Uriel Jareth Consulting. +Servicios organizados en 4 fases, dos tipos de pago (único / mensual), propuestas simples o dobles, planes CRM Bucéfalo y financiamiento opcional. Exporta a PDF y Excel. ## Stack -- **Frontend / app web:** Next.js 16 (App Router) + React 19 + Tailwind CSS v4 + Zustand -- **ORM:** Prisma 7 (cliente generado en `src/generated/prisma`, driver adapter `PrismaPg`) -- **Base de datos:** PostgreSQL 16 (vía Docker) -- **Auth:** JWT (`jose`) en cookie httpOnly, contraseñas con `bcryptjs` -- **API alterna:** servicio Python FastAPI en [`api/`](api/) (para n8n / integraciones) +- **Backend unificado:** Go 1.27 (`chi/v5`, `pgx/v5`, `fpdf`, `excelize/v2`, `webpush-go`, `nativewebp`, `CGO_ENABLED=0`) +- **Frontend SPA:** React 19 + TypeScript + Vite + Tailwind CSS v4 + Zustand (compilado y embebido en el binario Go vía `//go:embed`) +- **Base de datos:** PostgreSQL 16 (migraciones SQL idempotentes embebidas en el binario) +- **Auth:** JWT HS256 en cookie httpOnly (`cotizador-session`) + contraseñas `bcrypt` + `AgentApiKey` SHA-256 con 9 alcances granulares y rate limit -## Requisitos +## Requisitos (desarrollo local) -- Node.js 20+ +- Go 1.27+ +- Node.js 22+ (solo para compilar el frontend en `web/`) - Docker (para PostgreSQL) - Un archivo `.env` en la raíz — copia [.env.example](.env.example) y define al menos `JWT_SECRET` ## Arranque rápido (Windows) ```bat -start.bat :: levanta PostgreSQL en Docker, aplica migraciones y arranca Next.js -stop.bat :: detiene todo -``` - -## Arranque manual - -```bash -docker compose up -d postgres # base de datos -npx prisma migrate deploy # aplica migraciones -npx tsx prisma/seed.ts # carga catálogo (idempotente) -npm run dev # http://localhost:3000 +start.bat :: levanta PostgreSQL, compila el SPA Vite y arranca el servidor Go en :3000 +stop.bat :: detiene el servidor y PostgreSQL ``` ## Comandos | Comando | Propósito | |---------|-----------| -| `npm run dev` | Servidor de desarrollo (puerto 3000) | -| `npm run build` | Build de producción (incluye chequeo de tipos) | -| `npm run lint` | ESLint | -| `npm run db:migrate` | `prisma migrate dev` | -| `npm run db:seed` | Carga de datos semilla | -| `npm run db:studio` | Prisma Studio | -| `npm run db:generate` | Regenera el cliente Prisma | +| `go run ./cmd/cotizador serve` | Inicia el servidor (aplica migraciones automáticamente) en `http://localhost:3000` | +| `go run ./cmd/cotizador migrate` | Aplica migraciones SQL idempotentes | +| `go run ./cmd/cotizador seed` | Carga catálogo, planes y usuarios iniciales (idempotente) | +| `go run ./cmd/cotizador provision-keys --preset` | Provisiona llaves `AgentApiKey` en PostgreSQL | +| `go run ./cmd/cotizador cli esquema` | Describe los 30 comandos del CLI en JSON | +| `go test -count=1 ./...` | Ejecuta todas las pruebas unitarias y de seguridad HTTP | +| `go vet ./...` | Análisis estático de Go | +| `cd web && npm run dev` | Dev server de Vite con proxy `/api` → `:3000` | +| `cd web && npm run build` | Compila el SPA en `web/dist/` | -## API Python (opcional) +## API para agentes, aprobación humana y webhooks -```bash -cd api -pip install -r requirements.txt -uvicorn main:app --reload --port 8000 # Swagger en /docs -``` - -Referencia completa de endpoints en [`api/COTIZADOR_API_SKILL.md`](api/COTIZADOR_API_SKILL.md). +- **Especificación OpenAPI 3.1:** `GET /api/openapi.json` +- **Claves granulares (`AgentApiKey`):** prefijo `ujc_live_*`, hash SHA-256 en PostgreSQL, rate limit por minuto y bitácora `AuditLog`. +- **Aprobación humana obligatoria:** toda cotización creada por agente nace en `borrador`, notifica a `ADMIN_NOTIFY_EMAIL` con un enlace firmado de un solo uso (`/aprobar/`) y no puede enviarse (`POST /api/cotizaciones/:id/enviar`) hasta quedar `aprobada` por un administrador humano. +- **Webhooks salientes HMAC-SHA256:** firmados con `X-Cotizador-Signature: sha256=...`, reintentos automáticos y registro en `WebhookDelivery`. ## Despliegue en Coolify -El stack de producción está en [docker-compose.coolify.yml](docker-compose.coolify.yml): `postgres` + `web` (Next.js) + `api` (FastAPI). El contenedor `web` aplica las migraciones de Prisma automáticamente en cada arranque. +El stack de producción está en [docker-compose.coolify.yml](docker-compose.coolify.yml) (y su copia byte-idéntica [docker-compose.yaml](docker-compose.yaml)): `postgres` + `web` (binario Go + SPA embebido en imagen Alpine minimalista). -### Pasos +1. `web` ejecuta las migraciones SQL automáticamente en cada arranque y el seed solo cuando `RUN_SEED=true`. +2. Los volúmenes `postgres_data` (`cotizador_e3`) y `uploads_data` (`/app/uploads`) persisten entre despliegues. +3. Healthcheck: `GET /api/health` (verifica conexión a PostgreSQL). +4. Los despliegues automáticos se disparan al hacer push a `main` en GitHub (`origin`). -1. **Sube el repo a GitHub** (privado recomendado). -2. En Coolify: **+ New Resource → Docker Compose**, conecta el repo y la rama. -3. En la configuración del recurso, define **Docker Compose Location** = `/docker-compose.coolify.yml`. -4. Coolify detecta los servicios y asigna dominio a `web` (puerto 3000) y `api` (puerto 8000) vía las variables `SERVICE_FQDN_*` — configura los dominios deseados en la UI. -5. Define las variables de entorno en Coolify: +## Documentación técnica -| Variable | Obligatoria | Notas | -|----------|-------------|-------| -| `JWT_SECRET` | Sí | `openssl rand -base64 32` | -| `API_KEY` | Sí (para el API) | Clave para agentes/n8n | -| `DB_PASSWORD` | Recomendada | Password de PostgreSQL (default `postgres`) | -| `RUN_SEED` | Primer deploy | `true` solo la primera vez; luego `false` | -| `SEED_ADMIN_EMAIL` / `SEED_ADMIN_PASSWORD` / `SEED_ADMIN_NAME` | Primer deploy | Usuario admin inicial | -| `SEED_ASESOR_EMAIL` / `SEED_ASESOR_PASSWORD` / `SEED_ASESOR_NAME` | No | Asesor opcional | - -6. **Deploy.** Orden de arranque: `postgres` (healthy) → `web` (migra + seed + sirve) → `api`. -7. Después del primer despliegue exitoso, cambia `RUN_SEED` a `false` y redeploya (el seed es idempotente, pero no hace falta correrlo cada vez). - -### Healthchecks - -- Web: `GET /api/health` (verifica también la conexión a la BD) -- API: `GET /health` - -### Notas - -- No expongas el puerto 5432: los servicios se comunican por la red interna del compose. -- El volumen `postgres_data` persiste la base de datos entre deploys. No lo borres. -- El API expone REST en `https://` con auth por `X-API-Key` o JWT. El servidor MCP se retiro el 2026-07-28 (ver `AGENTS.md`). -- Las versiones de `api/requirements.txt` estan fijas a proposito: un rango abierto dejo entrar `mcp` 2.0.0 y tumbo el API en produccion. Sube dependencias a proposito, no al redesplegar. -- La fórmula de financiamiento y los cálculos viven duplicados en `src/lib/calculators.ts` y `api/app/services/calculators.py` — mantenlos en paridad. - -## Documentación para agentes - -Las convenciones del proyecto, gotchas de Prisma 7 / PDFKit / Next.js 16 y el modelo de datos -están en [`AGENTS.md`](AGENTS.md) (importado por `CLAUDE.md`). - -## API para agentes, aprobación y webhooks - -- **Especificación OpenAPI 3.1:** `GET /api/openapi.json` -- **Claves granulares (`AgentApiKey`):** prefijo `ujc_live_*`, hash SHA-256 en PostgreSQL, rate limit por minuto y bitácora `AuditLog`. Provisioning por CLI: `npx tsx scripts/provision-agent-keys.ts --preset`. -- **Aprobación humana obligatoria:** toda cotización creada por agente nace en `borrador`, notifica a `ADMIN_NOTIFY_EMAIL` con un enlace firmado de un solo uso (`/aprobar/`) y no puede enviarse (`POST /api/cotizaciones/:id/enviar`) hasta quedar `aprobada` por un administrador humano. -- **Webhooks salientes HMAC-SHA256:** firmados con `X-Cotizador-Signature: sha256=...`, reintentos automáticos y registro en `WebhookDelivery`. -- **Paridad en `api/` (FastAPI):** valida las mismas `AgentApiKey`, scopes, rate limit y reglas de aprobación; `ALLOW_LEGACY_API_KEY=false` por defecto; agrega `GET /cobros/programas` y `GET /cobros/pagos`. - -## Pruebas automáticas - -```bash -npm test # Pruebas unitarias y paridad TS/Python (node --test + tsx) -npm run lint # ESLint -npm run build # Build de producción Next.js -``` +Ver [`AGENTS.md`](AGENTS.md) para convenciones, modelo de datos, reglas de negocio y guía de arquitectura. diff --git a/api/.dockerignore b/api/.dockerignore deleted file mode 100644 index 3bd7460..0000000 --- a/api/.dockerignore +++ /dev/null @@ -1,9 +0,0 @@ -__pycache__ -*.pyc -*.pyo -.venv -venv -.pytest_cache -.ruff_cache -.env* -Dockerfile diff --git a/api/.env.example b/api/.env.example deleted file mode 100644 index e94d4a1..0000000 --- a/api/.env.example +++ /dev/null @@ -1,16 +0,0 @@ -# Database -DB_HOST=localhost -DB_PORT=5432 -DB_USER=postgres -DB_PASSWORD=postgres -# Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data. -DB_NAME=cotizador_e3 - -# Auth -API_KEY=change-me-to-a-secure-random-key -JWT_SECRET=change-me-to-a-secure-jwt-secret - -# Server -API_HOST=0.0.0.0 -API_PORT=8000 -ALLOW_LEGACY_API_KEY=false diff --git a/api/COTIZADOR_API_SKILL.md b/api/COTIZADOR_API_SKILL.md deleted file mode 100644 index bc4fb5f..0000000 --- a/api/COTIZADOR_API_SKILL.md +++ /dev/null @@ -1,52 +0,0 @@ -# Cotizador — Uriel Jareth Consulting — Guía de API para Agentes - -## Arquitectura unificada - -- **API principal (Next.js `/api/**`):** `https://cotizador.urieljareth.org/api` — OpenAPI 3.1 en `GET /api/openapi.json`. - - Incluye catálogo, clientes, cotizaciones, flujo de aprobación humana, envío por correo/WhatsApp, PDF/Excel, cobros recurrentes, claves de agentes, auditoría y webhooks HMAC-SHA256. -- **API Python en paridad (FastAPI):** `https://cotizador-api.urieljareth.org` — Swagger en `/docs`. - - Valida las mismas claves `AgentApiKey` (SHA-256) contra la misma PostgreSQL, aplica scopes, rate limit, auditoría (`AuditLog`), paridad de cálculo (`calculators.py`) y lectura de `/cobros/programas` y `/cobros/pagos`. - - La vieja `API_KEY` ilimitada está desactivada por defecto (`ALLOW_LEGACY_API_KEY=false`). - -## Autenticación y alcances (`AgentApiKey`) - -Envía la clave con prefijo `ujc_live_*` en `X-API-Key: ujc_live_...` o `Authorization: Bearer ujc_live_...`. - -Alcances válidos (jamás existe un scope de aprobación): -- `catalogo:leer` — catálogo, categorías, paquetes, bonos, financiamiento -- `clientes:leer` / `clientes:escribir` — consultar, crear y editar clientes -- `cotizaciones:leer` — listar y leer cotizaciones -- `cotizaciones:leer_aceptadas` — solo cotizaciones en estado `aceptada` (y sus PDFs) -- `cotizaciones:borrador` — crear y editar borradores (nunca aprobar ni cambiar estado) -- `cotizaciones:enviar` — enviar cotizaciones **ya aprobadas** vía `POST /api/cotizaciones/:id/enviar` -- `cobros:leer` / `cobros:registrar` — consultar programas/cobros y registrar pagos fuera del panel - -Headers de rate limit en respuestas de agente: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (y `Retry-After` en `429`). -Para `POST` mutantes se soporta `Idempotency-Key` (TTL 24h; replay devuelve `X-Idempotency-Replayed: true`, cuerpo distinto devuelve `409`). - -## Flujo de aprobación humana (regla de hierro) - -Estados: `borrador` → `aprobada` → `enviada` → `aceptada` | `rechazada` | `vencida`. - -1. Un agente con `cotizaciones:borrador` crea la cotización con `POST /api/cotizaciones`. **Siempre** nace en `borrador`. -2. El servidor genera un enlace firmado de un solo uso (expira en 72h) y lo envía por correo exclusivamente a Jareth (`ADMIN_NOTIFY_EMAIL`), además de emitir el webhook `cotizacion.creada` (sin exponer el token raw). -3. Jareth aprueba desde el panel (`POST /api/cotizaciones/:id/aprobar`) o desde `/aprobar/` (`POST /api/aprobar/` con `{ "confirmar": true }`). Ningún agente ni asesor puede aprobar (`403` + `AuditLog`). -4. Una vez en `aprobada` (con `aprobadaAt`), el agente con `cotizaciones:enviar` puede ejecutar `POST /api/cotizaciones/:id/enviar` con `canal: "email" | "whatsapp_chatwoot"` y opcionalmente `verificarContacto` (email o teléfono del prospecto; si no coincide → `403`). Sin aprobación previa devuelve `409`. - -## Webhooks salientes (HMAC-SHA256) - -Eventos: `cotizacion.creada`, `cotizacion.aprobada`, `cotizacion.enviada`, `cotizacion.aceptada`, `cotizacion.rechazada`, `cotizacion.vencida`, `pago.registrado`, `pago.vencido`. - -Headers enviados: -- `X-Cotizador-Event` -- `X-Cotizador-Timestamp` -- `X-Cotizador-Delivery-Id` -- `X-Cotizador-Signature: sha256=` - -## Provisioning de claves (operador) - -```bash -npx tsx scripts/provision-agent-keys.ts --preset -npx tsx scripts/provision-agent-keys.ts --list -npx tsx scripts/provision-agent-keys.ts --nombre sales-agent --rotate -``` diff --git a/api/Dockerfile b/api/Dockerfile deleted file mode 100644 index 3edfb4d..0000000 --- a/api/Dockerfile +++ /dev/null @@ -1,19 +0,0 @@ -FROM python:3.12-slim - -WORKDIR /app - -ENV PYTHONDONTWRITEBYTECODE=1 \ - PYTHONUNBUFFERED=1 - -COPY requirements.txt . -RUN pip install --no-cache-dir -r requirements.txt - -COPY . . - -EXPOSE 8000 - -HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=5 \ - CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/health').status==200 else 1)" - -# --proxy-headers: necesario detrás del reverse proxy (Traefik/Coolify) -CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips=*"] diff --git a/api/app/__init__.py b/api/app/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/app/auth.py b/api/app/auth.py deleted file mode 100644 index f377a98..0000000 --- a/api/app/auth.py +++ /dev/null @@ -1,346 +0,0 @@ -from __future__ import annotations - -import hashlib -import json -import math -import time -import uuid -from datetime import datetime, timedelta, timezone -from typing import Any - -from fastapi import Depends, Header, HTTPException, Request, status -from jose import JWTError, jwt -from passlib.context import CryptContext - -from app.config import settings -from app.database import get_pool - -pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") - -ALGORITHM = "HS256" -ACCESS_TOKEN_EXPIRE_DAYS = 7 - -# Rate limiter en memoria con ventana deslizante de 60 segundos por key_id. -_WINDOW_SECS = 60.0 -_rate_buckets: dict[str, list[float]] = {} - - -def hash_secret(raw: str) -> str: - return hashlib.sha256(raw.encode("utf-8")).hexdigest() - - -def verify_password(plain: str, hashed: str) -> bool: - return pwd_context.verify(plain, hashed) - - -def get_password_hash(password: str) -> str: - return pwd_context.hash(password) - - -def create_access_token(data: dict) -> str: - to_encode = data.copy() - expire = datetime.now(timezone.utc) + timedelta(days=ACCESS_TOKEN_EXPIRE_DAYS) - to_encode.update({"exp": expire, "iat": datetime.now(timezone.utc)}) - return jwt.encode(to_encode, settings.JWT_SECRET, algorithm=ALGORITHM) - - -def decode_token(token: str) -> dict | None: - try: - return jwt.decode(token, settings.JWT_SECRET, algorithms=[ALGORITHM]) - except JWTError: - return None - - -def _client_ip(request: Request | None) -> str | None: - if request is None: - return None - xff = request.headers.get("x-forwarded-for") - if xff: - first = xff.split(",")[0].strip() - if first: - return first - xri = request.headers.get("x-real-ip") - if xri: - return xri.strip() - return request.client.host if request.client else None - - -def check_rate_limit(key_id: str, limit_per_min: int, now: float | None = None) -> dict[str, Any]: - now_ts = now if now is not None else time.time() - limit = max(1, limit_per_min or 60) - cutoff = now_ts - _WINDOW_SECS - stamps = [ts for ts in _rate_buckets.get(key_id, []) if ts > cutoff] - - if len(stamps) >= limit: - oldest = stamps[0] if stamps else now_ts - reset_ts = oldest + _WINDOW_SECS - retry_after = max(1, math.ceil(reset_ts - now_ts)) - _rate_buckets[key_id] = stamps - return { - "ok": False, - "limit": limit, - "remaining": 0, - "reset_at": math.ceil(reset_ts), - "retry_after": retry_after, - } - - stamps.append(now_ts) - _rate_buckets[key_id] = stamps - oldest = stamps[0] if stamps else now_ts - reset_ts = oldest + _WINDOW_SECS - return { - "ok": True, - "limit": limit, - "remaining": max(0, limit - len(stamps)), - "reset_at": math.ceil(reset_ts), - "retry_after": 0, - } - - -async def registrar_auditoria( - conn, - auth: dict | None, - accion: str, - recurso_tipo: str, - recurso_id: str | None = None, - exito: bool = True, - detalle: dict[str, Any] | None = None, - ip: str | None = None, -) -> None: - """Registra una entrada en AuditLog (best-effort; nunca tumba el request).""" - try: - actor_tipo = "system" - actor_id: str | None = None - actor_nombre = "system" - - if auth: - atype = auth.get("auth_type") - if atype == "jwt": - actor_tipo = "user" - actor_id = auth.get("userId") - actor_nombre = auth.get("email") or auth.get("name") or str(actor_id or "user") - elif atype == "agent": - actor_tipo = "agent" - actor_id = auth.get("key_id") - actor_nombre = auth.get("nombre") or "agent" - elif atype == "legacy_api_key": - actor_tipo = "system" - actor_nombre = "legacy_api_key" - - ip_final = ip or (auth.get("ip") if auth else None) - await conn.execute( - """ - INSERT INTO "AuditLog" - (id, "actorTipo", "actorId", "actorNombre", accion, "recursoTipo", - "recursoId", ip, exito, detalle, "createdAt") - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, NOW()) - """, - uuid.uuid4().hex[:25], - actor_tipo, - actor_id, - actor_nombre, - accion, - recurso_tipo, - recurso_id, - ip_final, - exito, - json.dumps(detalle) if detalle is not None else None, - ) - except Exception: - pass - - -async def _validate_agent_key(raw_key: str, ip: str | None) -> dict | None: - pool = await get_pool() - key_hash = hash_secret(raw_key) - row = await pool.fetchrow( - """ - SELECT id, nombre, prefijo, scopes, "rateLimitPerMin", "lastUsedAt" - FROM "AgentApiKey" - WHERE "keyHash" = $1 AND activo = true AND "revokedAt" IS NULL - """, - key_hash, - ) - if not row: - return None - - rl = check_rate_limit(row["id"], row["rateLimitPerMin"]) - actor = { - "auth_type": "agent", - "key_id": row["id"], - "nombre": row["nombre"], - "prefijo": row["prefijo"], - "scopes": list(row["scopes"] or []), - "rate_limit": row["rateLimitPerMin"], - "ip": ip, - } - if not rl["ok"]: - await registrar_auditoria( - pool, - actor, - "auth.rate_limit", - "api", - exito=False, - detalle={"limit": rl["limit"]}, - ip=ip, - ) - raise HTTPException( - status_code=status.HTTP_429_TOO_MANY_REQUESTS, - detail="Limite de peticiones por minuto excedido", - headers={ - "X-RateLimit-Limit": str(rl["limit"]), - "X-RateLimit-Remaining": "0", - "X-RateLimit-Reset": str(rl["reset_at"]), - "Retry-After": str(rl["retry_after"]), - }, - ) - - last_used = row["lastUsedAt"] - now_dt = datetime.now(timezone.utc) - if last_used is None or ( - now_dt - (last_used.replace(tzinfo=timezone.utc) if last_used.tzinfo is None else last_used) - ).total_seconds() > 60: - try: - await pool.execute( - 'UPDATE "AgentApiKey" SET "lastUsedAt" = NOW() WHERE id = $1', - row["id"], - ) - except Exception: - pass - - return actor - - -async def require_auth( - request: Request, - authorization: str | None = Header(None), - x_api_key: str | None = Header(None), -) -> dict: - ip = _client_ip(request) - bearer_token: str | None = None - - if authorization: - scheme, _, token = authorization.partition(" ") - if scheme.lower() == "bearer" and token.strip(): - bearer_token = token.strip() - # 1. Intentar JWT humano primero - payload = decode_token(bearer_token) - if payload: - if payload.get("role") == "cliente": - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Acceso restringido al panel de cliente", - ) - return {"auth_type": "jwt", "ip": ip, **payload} - - raw_key = (x_api_key or "").strip() or bearer_token - if raw_key: - # 2. Validar contra AgentApiKey en PostgreSQL (SHA-256) - agent_actor = await _validate_agent_key(raw_key, ip) - if agent_actor: - return agent_actor - - # 3. Compatibilidad legacy SOLO si ALLOW_LEGACY_API_KEY=true explicitamente - if settings.ALLOW_LEGACY_API_KEY and raw_key == settings.API_KEY: - return {"auth_type": "legacy_api_key", "scopes": [], "ip": ip} - - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Credenciales de autenticacion invalidas o ausentes", - headers={"WWW-Authenticate": "Bearer"}, - ) - - -def require_scope(*required_scopes: str, mode: str = "any"): - async def _checker( - request: Request, - auth: dict = Depends(require_auth), - ) -> dict: - atype = auth.get("auth_type") - if atype in ("jwt", "legacy_api_key"): - return auth - - scopes = set(auth.get("scopes") or []) - ok = ( - all(s in scopes for s in required_scopes) - if mode == "all" - else any(s in scopes for s in required_scopes) - ) - if not ok: - pool = await get_pool() - await registrar_auditoria( - pool, - auth, - "auth.scope_insuficiente", - "api", - exito=False, - detalle={ - "path": request.url.path, - "requiredScopes": list(required_scopes), - "actorScopes": list(scopes), - }, - ip=auth.get("ip"), - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail=f"Alcance insuficiente. Requerido: {', '.join(required_scopes)}", - ) - return auth - - return _checker - - -async def require_staff_human( - request: Request, - auth: dict = Depends(require_auth), -) -> dict: - atype = auth.get("auth_type") - if atype == "jwt" and auth.get("role") != "cliente": - return auth - if atype == "legacy_api_key": - return auth - - pool = await get_pool() - await registrar_auditoria( - pool, - auth, - "auth.staff_requerido", - "api", - exito=False, - detalle={"path": request.url.path, "auth_type": atype}, - ip=auth.get("ip"), - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Accion restringida a personal humano", - ) - - -async def require_admin_human( - request: Request, - auth: dict = Depends(require_auth), -) -> dict: - if auth.get("auth_type") == "jwt" and auth.get("role") == "admin": - return auth - - pool = await get_pool() - await registrar_auditoria( - pool, - auth, - "auth.admin_requerido", - "api", - exito=False, - detalle={"path": request.url.path, "auth_type": auth.get("auth_type")}, - ip=auth.get("ip"), - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Accion restringida exclusivamente a un administrador humano", - ) - - -def es_agente_solo_aceptadas(auth: dict) -> bool: - if auth.get("auth_type") != "agent": - return False - scopes = set(auth.get("scopes") or []) - return "cotizaciones:leer_aceptadas" in scopes and "cotizaciones:leer" not in scopes diff --git a/api/app/config.py b/api/app/config.py deleted file mode 100644 index 046a3f9..0000000 --- a/api/app/config.py +++ /dev/null @@ -1,20 +0,0 @@ -from pydantic_settings import BaseSettings - - -class Settings(BaseSettings): - DB_HOST: str = "localhost" - DB_PORT: int = 5432 - DB_USER: str = "postgres" - DB_PASSWORD: str = "postgres" - # Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data. - DB_NAME: str = "cotizador_e3" - API_KEY: str = "change-me-to-a-secure-random-key" - ALLOW_LEGACY_API_KEY: bool = False - JWT_SECRET: str = "change-me-to-a-secure-jwt-secret" - API_HOST: str = "0.0.0.0" - API_PORT: int = 8000 - - model_config = {"env_file": ".env", "env_file_encoding": "utf-8", "extra": "ignore"} - - -settings = Settings() diff --git a/api/app/database.py b/api/app/database.py deleted file mode 100644 index 44221fe..0000000 --- a/api/app/database.py +++ /dev/null @@ -1,33 +0,0 @@ -from __future__ import annotations - -import asyncpg - -from app.config import settings - -pool: asyncpg.Pool | None = None - - -async def init_db() -> None: - global pool - pool = await asyncpg.create_pool( - host=settings.DB_HOST, - port=settings.DB_PORT, - user=settings.DB_USER, - password=settings.DB_PASSWORD, - database=settings.DB_NAME, - min_size=5, - max_size=20, - ) - - -async def close_db() -> None: - global pool - if pool: - await pool.close() - pool = None - - -async def get_pool() -> asyncpg.Pool: - if pool is None: - raise RuntimeError("Database pool not initialized. Call init_db() first.") - return pool diff --git a/api/app/dependencies.py b/api/app/dependencies.py deleted file mode 100644 index e0a2e43..0000000 --- a/api/app/dependencies.py +++ /dev/null @@ -1,37 +0,0 @@ -from __future__ import annotations - -from typing import Annotated - -from fastapi import Depends, Query - -from app.database import get_pool - - -async def get_db(): - pool = await get_pool() - async with pool.acquire() as conn: - yield conn - - -class PaginationParams: - def __init__( - self, - page: Annotated[int, Query(ge=1)] = 1, - limit: Annotated[int, Query(ge=1, le=200)] = 50, - ): - self.page = page - self.limit = limit - self.offset = (page - 1) * limit - - -def parse_date(date_str: str | None): - if not date_str: - return None - from datetime import datetime - try: - return datetime.fromisoformat(date_str.replace("Z", "+00:00")) - except ValueError: - try: - return datetime.strptime(date_str, "%Y-%m-%d") - except ValueError: - return None diff --git a/api/app/models/__init__.py b/api/app/models/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/app/models/catalogo.py b/api/app/models/catalogo.py deleted file mode 100644 index a6632ec..0000000 --- a/api/app/models/catalogo.py +++ /dev/null @@ -1,81 +0,0 @@ -from __future__ import annotations - -from datetime import datetime - -from pydantic import BaseModel, Field - - -class CategoriaBase(BaseModel): - nombre: str = Field(..., min_length=1, description="Nombre de la categoría") - descripcion: str | None = None - color: str = Field("#6b7280", description="Color hex para UI") - orden: int = Field(0, ge=0) - - -class CategoriaCreate(CategoriaBase): - pass - - -class CategoriaUpdate(BaseModel): - nombre: str | None = Field(None, min_length=1) - descripcion: str | None = None - color: str | None = None - orden: int | None = Field(None, ge=0) - activo: bool | None = None - - -class CategoriaResponse(CategoriaBase): - id: str - activo: bool - createdAt: datetime - updatedAt: datetime - - model_config = {"from_attributes": True} - - -class ServicioCatalogoBase(BaseModel): - nombre: str = Field(..., min_length=1, description="Nombre del servicio") - descripcion: str | None = None - fase: int = Field(..., ge=0, le=3, description="Fase: 0=Auditoría, 1=Setup, 2=Publicidad, 3=Contenido/SEO") - tipoPago: str = Field(..., pattern="^(unico|mensual)$", description="Tipo de pago") - precioBase: float = Field(..., ge=0, description="Precio base en la moneda local") - tiempoEntrega: str = Field("7 - 14 dias", description="Tiempo de entrega estimado") - entregablesDefault: list[str] = Field(default_factory=list, description="Lista de entregables") - categoriaId: str = Field(..., min_length=1, description="ID de la categoría") - variante: str | None = None - nivel: str | None = Field(None, description="Nivel/tier: Emprendedor, PYME, Empresario, Corporativo") - soloAdmin: bool = Field(False, description="Visible solo para admin humano; oculto para agentes IA") - orden: int = Field(0, ge=0) - - -class ServicioCatalogoCreate(ServicioCatalogoBase): - pass - - -class ServicioCatalogoUpdate(BaseModel): - nombre: str | None = Field(None, min_length=1) - descripcion: str | None = None - fase: int | None = Field(None, ge=0, le=3) - tipoPago: str | None = Field(None, pattern="^(unico|mensual)$") - precioBase: float | None = Field(None, ge=0) - tiempoEntrega: str | None = None - entregablesDefault: list[str] | None = None - categoriaId: str | None = None - variante: str | None = None - nivel: str | None = None - activo: bool | None = None - soloAdmin: bool | None = None - orden: int | None = Field(None, ge=0) - - -class ServicioCatalogoResponse(ServicioCatalogoBase): - id: str - activo: bool - createdAt: datetime - updatedAt: datetime - categoriaRel: CategoriaResponse | None = None - - model_config = {"from_attributes": True} - - -from app.models.cliente import ClienteResponse diff --git a/api/app/models/cliente.py b/api/app/models/cliente.py deleted file mode 100644 index bff5d85..0000000 --- a/api/app/models/cliente.py +++ /dev/null @@ -1,35 +0,0 @@ -from __future__ import annotations - -from datetime import datetime - -from pydantic import BaseModel, Field - - -class ClienteBase(BaseModel): - nombre: str = Field(..., min_length=1, description="Nombre completo del contacto") - empresa: str | None = Field(None, description="Nombre de la empresa") - email: str | None = Field(None, description="Email de contacto") - telefono: str | None = Field(None, description="Teléfono de contacto") - - -class ClienteCreate(ClienteBase): - pass - - -class ClienteUpdate(BaseModel): - nombre: str | None = Field(None, min_length=1) - empresa: str | None = None - email: str | None = None - telefono: str | None = None - - -class ClienteResponse(ClienteBase): - id: str - createdAt: datetime - updatedAt: datetime - - model_config = {"from_attributes": True} - - -class ClienteWithCotizaciones(ClienteResponse): - cotizaciones: list[dict] | None = None diff --git a/api/app/models/common.py b/api/app/models/common.py deleted file mode 100644 index 406360b..0000000 --- a/api/app/models/common.py +++ /dev/null @@ -1,57 +0,0 @@ -from __future__ import annotations - -from typing import Any, Generic, TypeVar - -from pydantic import BaseModel, Field - -T = TypeVar("T") - - -class Meta(BaseModel): - total: int = 0 - page: int = 1 - limit: int = 50 - pages: int = 0 - - -class PaginatedResponse(BaseModel, Generic[T]): - data: list[T] - meta: Meta - - -class ErrorResponse(BaseModel): - error: str - detail: str | None = None - code: str | None = None - - -class OkResponse(BaseModel): - ok: bool = True - - -class ArchivedResponse(BaseModel): - ok: bool = True - archived: bool - - -class HealthResponse(BaseModel): - status: str = "ok" - timestamp: str - database: str = "connected" - - -class APIInfoResponse(BaseModel): - name: str = "Cotizador — Uriel Jareth Consulting API" - version: str = "1.0.0" - description: str = "API para el sistema de cotizaciones de Uriel Jareth Consulting" - capabilities: list[str] = Field(default_factory=list) - - -class LoginRequest(BaseModel): - email: str - password: str - - -class LoginResponse(BaseModel): - user: dict[str, Any] - token: str | None = None diff --git a/api/app/models/configuracion.py b/api/app/models/configuracion.py deleted file mode 100644 index 0fd4490..0000000 --- a/api/app/models/configuracion.py +++ /dev/null @@ -1,41 +0,0 @@ -from __future__ import annotations - -from pydantic import BaseModel, Field - -ALLOWED_CONFIG_KEYS: set[str] = { - "color_primario", - "color_secundario", - "logo_base64", - "razon_social", - "rfc", - "domicilio_fiscal", # Opcional interno; no se imprime en documentos generados - "cuenta_nacional", - "clabe_interbancaria", - "cuenta_internacional", - "cuenta_internacional_swift", - "hora_centinela", - "anualidad_hosting", - "iva", - "terminos_condiciones", - "no_incluye", - "notas_adicionales", -} - - -class ConfigUpdate(BaseModel): - config: dict[str, str] = Field( - ..., - description="Key-value config pairs. Only whitelisted keys are processed.", - json_schema_extra={ - "examples": [ - {"color_primario": "#0400C4", "razon_social": "Uriel Jareth Consulting"} - ] - }, - ) - - def get_allowed(self) -> dict[str, str]: - return {k: v for k, v in self.config.items() if k in ALLOWED_CONFIG_KEYS} - - -class ConfigResponse(BaseModel): - config: dict[str, str] diff --git a/api/app/models/cotizacion.py b/api/app/models/cotizacion.py deleted file mode 100644 index 75ab2d3..0000000 --- a/api/app/models/cotizacion.py +++ /dev/null @@ -1,130 +0,0 @@ -from __future__ import annotations - -from datetime import datetime -from typing import Any - -from pydantic import BaseModel, Field - -ESTADOS_PATTERN = "^(borrador|aprobada|enviada|aceptada|rechazada|vencida)$" - - -class ServicioCotizadoInput(BaseModel): - catalogoId: str = Field(..., min_length=1, description="ID del servicio del catálogo o 'custom-...' para partidas personalizadas") - nombre: str = Field(..., min_length=1, description="Nombre del servicio") - fase: int = Field(..., ge=0, le=3) - tipoPago: str = Field(..., pattern="^(unico|mensual)$") - precio: float = Field(..., ge=0, description="Precio (puede diferir del precioBase)") - tiempoEntrega: str - entregables: list[str] = Field(default_factory=list) - esPersonalizado: bool = False - horas: float | None = Field(None, ge=0) - tarifaHora: float | None = Field(None, ge=0) - modeloCobro: str | None = Field(None, pattern="^(fijo|horas|retainer|demanda)$") - montoMinimo: float | None = Field(None, ge=0) - horasIncluidas: float | None = Field(None, ge=0) - opcion: str | None = Field(None, pattern="^(1|2|ambas)$") - - -class MetaOpcionInput(BaseModel): - titulo: str | None = None - descripcion: str | None = None - noIncluye: str | None = None - - -class PlanBucefaloInput(BaseModel): - nivel: str = Field(..., description="Nivel: basico, estandar, premium, empresarial") - precio: float = Field(..., ge=0) - - -class ClienteInput(BaseModel): - nombre: str = Field(..., min_length=1) - empresa: str = "" - email: str = "" - telefono: str = "" - - -class CotizacionCreate(BaseModel): - numero: str = Field(..., min_length=1, description="Número de cotización (formato UJ{YY}{MM}{init}{seq})") - fecha: datetime - vigencia: datetime - moneda: str = Field("MXN", pattern="^(MXN|USD)$") - tipoCambio: str = "NA" - proyecto: str = "MKT Digital" - esquemaPago: str = Field("Pago Unico/Mensual", pattern=r"^(Pago Unico|Mensual|Pago Unico/Mensual|Por hora \(postpago\))$") - incluirBonos: bool = False - incluirFinanciamiento: bool = False - incluirIva: bool = True - esDoble: bool = False - opciones: dict[str, MetaOpcionInput] | None = None - observaciones: str = "" - asesorId: str | None = None - cliente: ClienteInput - servicios: list[ServicioCotizadoInput] = Field(..., min_length=1) - planBucefalo: PlanBucefaloInput | None = None - - -class CotizacionUpdate(BaseModel): - fecha: datetime | None = None - vigencia: datetime | None = None - moneda: str | None = Field(None, pattern="^(MXN|USD)$") - tipoCambio: str | None = None - proyecto: str | None = None - esquemaPago: str | None = Field(None, pattern=r"^(Pago Unico|Mensual|Pago Unico/Mensual|Por hora \(postpago\))$") - incluirBonos: bool | None = None - incluirFinanciamiento: bool | None = None - incluirIva: bool | None = None - esDoble: bool | None = None - opciones: dict[str, MetaOpcionInput] | None = None - observaciones: str | None = None - estado: str | None = Field(None, pattern=ESTADOS_PATTERN) - cliente: ClienteInput | None = None - servicios: list[ServicioCotizadoInput] | None = None - planBucefalo: PlanBucefaloInput | None = None - - -class CambiarEstadoRequest(BaseModel): - estado: str = Field(..., pattern=ESTADOS_PATTERN) - - -class ActualizarPrecioRequest(BaseModel): - servicioId: str = Field(..., min_length=1) - precio: float = Field(..., ge=0) - - -class CotizacionResponse(BaseModel): - id: str - numero: str - fecha: datetime - vigencia: datetime - moneda: str - tipoCambio: str - proyecto: str - esquemaPago: str - estado: str - incluirBonos: bool - incluirFinanciamiento: bool - incluirIva: bool = True - esDoble: bool = False - opcionesMetadata: dict[str, Any] | None = None - observaciones: str | None - clienteId: str - asesorId: str - aprobadaPorId: str | None = None - aprobadaAt: datetime | None = None - aprobacionMetodo: str | None = None - enviadaAt: datetime | None = None - enviadaPor: str | None = None - enviadaCanal: str | None = None - enviadaDestino: str | None = None - aceptadaAt: datetime | None = None - rechazadaAt: datetime | None = None - vencidaAt: datetime | None = None - creadaPorAgente: str | None = None - createdAt: datetime - updatedAt: datetime - cliente: dict[str, Any] | None = None - asesor: dict[str, Any] | None = None - servicios: list[dict[str, Any]] | None = None - planBucefalo: dict[str, Any] | None = None - - model_config = {"from_attributes": True} diff --git a/api/app/models/export_.py b/api/app/models/export_.py deleted file mode 100644 index 4ceb365..0000000 --- a/api/app/models/export_.py +++ /dev/null @@ -1,73 +0,0 @@ -from __future__ import annotations - -from pydantic import BaseModel, Field - - -class ServicioDraft(BaseModel): - nombre: str - fase: int - tipoPago: str - precio: float - tiempoEntrega: str - entregables: list[str] = Field(default_factory=list) - esPersonalizado: bool = False - horas: float | None = None - tarifaHora: float | None = None - modeloCobro: str | None = None - montoMinimo: float | None = None - horasIncluidas: float | None = None - # Doble propuesta: "1" | "2" | "ambas". - opcion: str | None = None - - -class MetaOpcionDraft(BaseModel): - titulo: str | None = None - descripcion: str | None = None - noIncluye: str | None = None - - -class ExportDraft(BaseModel): - clienteNombre: str = "" - clienteEmpresa: str = "" - asesorNombre: str = "" - fecha: str = "" - moneda: str = "MXN" - tipoCambio: str = "NA" - proyecto: str = "MKT Digital" - esquemaPago: str = "Pago Unico/Mensual" - incluirBonos: bool = False - servicios: list[ServicioDraft] = Field(default_factory=list) - planBucefaloNivel: str | None = None - observaciones: str = "" - esDoble: bool = False - opciones: dict[str, MetaOpcionDraft] | None = None - - -class FinanciamientoRequest(BaseModel): - monto: float = Field(..., ge=0, description="Monto total a financiar en MXN") - meses: int = Field(..., ge=3, le=12, description="Plazo en meses: 3, 6, 9, o 12") - - -class FinanciamientoResponse(BaseModel): - pagoMensual: float - ivaMensual: float - totalMensual: float - comisionTotal: float - granTotal: float - meses: int - tasa: float - comision: float - - -class BonoResponse(BaseModel): - id: str - numero: int - titulo: str - descripcion: str - activo: bool - - -class PlanBucefaloResponse(BaseModel): - nivel: str - label: str - precio: float diff --git a/api/app/models/paquete.py b/api/app/models/paquete.py deleted file mode 100644 index 6cb8fdb..0000000 --- a/api/app/models/paquete.py +++ /dev/null @@ -1,55 +0,0 @@ -from __future__ import annotations - -from datetime import datetime - -from pydantic import BaseModel, Field - - -class FasePaqueteInput(BaseModel): - nombre: str = Field(..., min_length=1) - orden: int = Field(0, ge=0) - - -class PaqueteCreate(BaseModel): - nombre: str = Field(..., min_length=1, description="Nombre del paquete") - descripcion: str | None = None - fases: list[FasePaqueteInput] = Field(default_factory=list) - - -class PaqueteUpdate(BaseModel): - nombre: str | None = Field(None, min_length=1) - descripcion: str | None = None - activo: bool | None = None - - -class ManageAction(BaseModel): - action: str = Field(..., description="Acción: addFase, updateFase, deleteFase, addServicio, removeServicio") - faseId: str | None = None - nombre: str | None = None - orden: int | None = None - servicioCatalogoId: str | None = None - fasePaqueteId: str | None = None - - -class FasePaqueteResponse(BaseModel): - id: str - paqueteId: str - nombre: str - orden: int - createdAt: datetime - updatedAt: datetime - servicios: list[dict] | None = None - - model_config = {"from_attributes": True} - - -class PaqueteResponse(BaseModel): - id: str - nombre: str - descripcion: str | None - activo: bool - createdAt: datetime - updatedAt: datetime - fases: list[FasePaqueteResponse] | None = None - - model_config = {"from_attributes": True} diff --git a/api/app/routers/__init__.py b/api/app/routers/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/app/routers/auth.py b/api/app/routers/auth.py deleted file mode 100644 index 9f96d51..0000000 --- a/api/app/routers/auth.py +++ /dev/null @@ -1,71 +0,0 @@ -from fastapi import APIRouter, Depends, HTTPException, status - -from app.database import get_pool -from app.auth import verify_password, create_access_token, require_auth, get_password_hash -from app.models.common import LoginRequest, LoginResponse, OkResponse, ErrorResponse - -router = APIRouter(prefix="/auth", tags=["Auth"]) - - -@router.post("/login", response_model=LoginResponse) -async def login(body: LoginRequest): - pool = get_pool() - async with pool.acquire() as conn: - row = await conn.fetchrow( - 'SELECT id, email, password, name, role FROM "User" WHERE email = $1', - body.email, - ) - - if not row: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Credenciales inválidas", - ) - - if not verify_password(body.password, row["password"]): - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Credenciales inválidas", - ) - - token = create_access_token({"sub": str(row["id"]), "email": row["email"], "role": row["role"]}) - - return LoginResponse( - access_token=token, - user={ - "id": row["id"], - "email": row["email"], - "name": row["name"], - "role": row["role"], - }, - ) - - -@router.post("/logout", response_model=OkResponse) -async def logout(): - return OkResponse(ok=True) - - -@router.get("/me") -async def me(current_user: dict = Depends(require_auth)): - pool = get_pool() - async with pool.acquire() as conn: - row = await conn.fetchrow( - 'SELECT id, email, name, role, "createdAt", "updatedAt" FROM "User" WHERE id = $1', - current_user["sub"], - ) - - if not row: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Usuario no encontrado", - ) - - return { - "id": row["id"], - "email": row["email"], - "name": row["name"], - "role": row["role"], - "createdAt": row["createdAt"].isoformat() if row["createdAt"] else None, - "updatedAt": row["updatedAt"].isoformat() if row["updatedAt"] else None, - } diff --git a/api/app/routers/bonos.py b/api/app/routers/bonos.py deleted file mode 100644 index c2f8670..0000000 --- a/api/app/routers/bonos.py +++ /dev/null @@ -1,14 +0,0 @@ -from __future__ import annotations - -from fastapi import APIRouter, Depends - -from app.auth import require_scope -from app.models.export_ import BonoResponse -from app.services.calculators import BONOS - -router = APIRouter(prefix="/bonos", tags=["Bonos"]) - - -@router.get("", response_model=list[BonoResponse]) -async def get_bonos(_auth: dict = Depends(require_scope("catalogo:leer"))): - return [BonoResponse(**b) for b in BONOS] diff --git a/api/app/routers/catalogo.py b/api/app/routers/catalogo.py deleted file mode 100644 index b303725..0000000 --- a/api/app/routers/catalogo.py +++ /dev/null @@ -1,308 +0,0 @@ -from __future__ import annotations - -import json - -from fastapi import APIRouter, Depends, HTTPException, Query, status -from asyncpg import Connection - -from app.auth import registrar_auditoria, require_scope, require_staff_human -from app.dependencies import get_db -from app.models.catalogo import ( - ServicioCatalogoCreate, - ServicioCatalogoUpdate, - ServicioCatalogoResponse, - CategoriaResponse, -) -from app.models.common import ArchivedResponse, ErrorResponse, OkResponse - -router = APIRouter(prefix="/catalogo", tags=["Catalogo"]) - - -def _row_to_response(row, categoria_row=None) -> ServicioCatalogoResponse: - entregables = row["entregablesDefault"] - if isinstance(entregables, str): - entregables = json.loads(entregables) - - categoria = None - if categoria_row: - categoria = CategoriaResponse( - id=categoria_row["id"], - nombre=categoria_row["nombre"], - descripcion=categoria_row["descripcion"], - color=categoria_row["color"], - orden=categoria_row["orden"], - activo=categoria_row["activo"], - createdAt=categoria_row["createdAt"], - updatedAt=categoria_row["updatedAt"], - ) - - return ServicioCatalogoResponse( - id=row["id"], - nombre=row["nombre"], - descripcion=row["descripcion"], - fase=row["fase"], - tipoPago=row["tipoPago"], - precioBase=float(row["precioBase"]), - tiempoEntrega=row["tiempoEntrega"], - entregablesDefault=entregables, - categoriaId=row["categoriaId"], - variante=row["variante"], - nivel=row["nivel"], - activo=row["activo"], - soloAdmin=bool(row.get("soloAdmin", False)), - orden=row["orden"], - createdAt=row["createdAt"], - updatedAt=row["updatedAt"], - categoriaRel=categoria, - ) - - -@router.get( - "", - response_model=list[ServicioCatalogoResponse], - summary="List active catalog services with filters", -) -async def list_catalogo( - db: Connection = Depends(get_db), - auth: dict = Depends(require_scope("catalogo:leer")), - fase: int | None = Query(None, ge=0, le=3), - tipoPago: str | None = Query(None, pattern="^(unico|mensual)$"), - categoriaId: str | None = Query(None), - q: str | None = Query(None, description="Search by nombre or descripcion"), -): - where_clauses: list[str] = ['activo = true'] - if auth.get("auth_type") == "agent": - where_clauses.append('"soloAdmin" = false') - params: list = [] - idx = 1 - - if fase is not None: - where_clauses.append(f"fase = ${idx}") - params.append(fase) - idx += 1 - - if tipoPago: - where_clauses.append(f'"tipoPago" = ${idx}') - params.append(tipoPago) - idx += 1 - - if categoriaId: - where_clauses.append(f'"categoriaId" = ${idx}') - params.append(categoriaId) - idx += 1 - - if q: - where_clauses.append(f"(nombre ILIKE ${idx} OR descripcion ILIKE ${idx})") - params.append(f"%{q}%") - idx += 1 - - where_sql = f"WHERE {' AND '.join(where_clauses)}" - - rows = await db.fetch( - f'SELECT * FROM "ServicioCatalogo" {where_sql} ORDER BY fase ASC, orden ASC', - *params, - ) - - # Una sola query para todas las categorías referenciadas (evita N+1). - cat_ids = list({r["categoriaId"] for r in rows if r["categoriaId"]}) - cat_map: dict = {} - if cat_ids: - cat_rows = await db.fetch( - 'SELECT * FROM "Categoria" WHERE id = ANY($1::text[])', cat_ids - ) - cat_map = {c["id"]: c for c in cat_rows} - - return [_row_to_response(r, cat_map.get(r["categoriaId"])) for r in rows] - - -@router.post( - "", - response_model=ServicioCatalogoResponse, - status_code=status.HTTP_201_CREATED, - summary="Create a new catalog service", -) -async def create_catalogo( - body: ServicioCatalogoCreate, - db: Connection = Depends(get_db), - auth: dict = Depends(require_staff_human), -): - if body.categoriaId: - cat = await db.fetchrow( - 'SELECT id FROM "Categoria" WHERE id = $1', body.categoriaId - ) - if not cat: - raise HTTPException(status_code=400, detail="Categoria no encontrada") - - entregables_json = json.dumps(body.entregablesDefault) - - row = await db.fetchrow( - 'INSERT INTO "ServicioCatalogo" ' - '(nombre, descripcion, fase, "tipoPago", "precioBase", "tiempoEntrega", ' - '"entregablesDefault", "categoriaId", variante, nivel, activo, "soloAdmin", orden) ' - "VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, true, $11, $12) RETURNING *", - body.nombre, - body.descripcion, - body.fase, - body.tipoPago, - body.precioBase, - body.tiempoEntrega, - entregables_json, - body.categoriaId, - body.variante, - body.nivel, - body.soloAdmin, - body.orden, - ) - - cat_row = None - if row["categoriaId"]: - cat_row = await db.fetchrow( - 'SELECT * FROM "Categoria" WHERE id = $1', row["categoriaId"] - ) - - return _row_to_response(row, cat_row) - - -@router.get( - "/{servicio_id}", - response_model=ServicioCatalogoResponse, - responses={404: {"model": ErrorResponse}}, - summary="Get catalog service by ID with categoria join", -) -async def get_catalogo( - servicio_id: str, - db: Connection = Depends(get_db), - auth: dict = Depends(require_scope("catalogo:leer")), -): - row = await db.fetchrow( - 'SELECT * FROM "ServicioCatalogo" WHERE id = $1', servicio_id - ) - if not row: - raise HTTPException(status_code=404, detail="Servicio no encontrado") - - if auth.get("auth_type") == "agent" and row.get("soloAdmin"): - await registrar_auditoria( - db, - auth, - "catalogo.solo_admin_bloqueado", - "catalogo", - recurso_id=servicio_id, - exito=False, - detalle={"nombre": row["nombre"]}, - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Este servicio esta restringido solo al administrador y no esta disponible para agentes", - ) - - cat_row = None - if row["categoriaId"]: - cat_row = await db.fetchrow( - 'SELECT * FROM "Categoria" WHERE id = $1', row["categoriaId"] - ) - - return _row_to_response(row, cat_row) - - -@router.put( - "/{servicio_id}", - response_model=ServicioCatalogoResponse, - responses={404: {"model": ErrorResponse}}, - summary="Update a catalog service", -) -async def update_catalogo( - servicio_id: str, - body: ServicioCatalogoUpdate, - db: Connection = Depends(get_db), - auth: dict = Depends(require_staff_human), -): - existing = await db.fetchrow( - 'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id - ) - if not existing: - raise HTTPException(status_code=404, detail="Servicio no encontrado") - - if body.categoriaId: - cat = await db.fetchrow( - 'SELECT id FROM "Categoria" WHERE id = $1', body.categoriaId - ) - if not cat: - raise HTTPException(status_code=400, detail="Categoria no encontrada") - - field_map = { - "nombre": "nombre", - "descripcion": "descripcion", - "fase": "fase", - "tipoPago": '"tipoPago"', - "precioBase": '"precioBase"', - "tiempoEntrega": '"tiempoEntrega"', - "entregablesDefault": '"entregablesDefault"', - "categoriaId": '"categoriaId"', - "variante": "variante", - "nivel": "nivel", - "activo": "activo", - "soloAdmin": '"soloAdmin"', - "orden": "orden", - } - - updates: list[str] = [] - params: list = [] - idx = 1 - - for field, col in field_map.items(): - value = getattr(body, field, None) - if value is not None: - if field == "entregablesDefault": - value = json.dumps(value) - updates.append(f"{col} = ${idx}") - params.append(value) - idx += 1 - - if not updates: - raise HTTPException(status_code=400, detail="No fields to update") - - params.append(servicio_id) - row = await db.fetchrow( - f'UPDATE "ServicioCatalogo" SET {", ".join(updates)} WHERE id = ${idx} RETURNING *', - *params, - ) - - cat_row = None - if row["categoriaId"]: - cat_row = await db.fetchrow( - 'SELECT * FROM "Categoria" WHERE id = $1', row["categoriaId"] - ) - - return _row_to_response(row, cat_row) - - -@router.delete( - "/{servicio_id}", - response_model=ArchivedResponse, - responses={404: {"model": ErrorResponse}}, - summary="Delete or soft-delete a catalog service", -) -async def delete_catalogo( - servicio_id: str, - db: Connection = Depends(get_db), - auth: dict = Depends(require_staff_human), -): - existing = await db.fetchrow( - 'SELECT id FROM "ServicioCatalogo" WHERE id = $1', servicio_id - ) - if not existing: - raise HTTPException(status_code=404, detail="Servicio no encontrado") - - ref_count = await db.fetchval( - 'SELECT COUNT(*) FROM "ServicioCotizado" WHERE "servicioCatalogoId" = $1', - servicio_id, - ) - - if ref_count > 0: - await db.execute( - 'UPDATE "ServicioCatalogo" SET activo = false WHERE id = $1', servicio_id - ) - return ArchivedResponse(ok=True, archived=True) - - await db.execute('DELETE FROM "ServicioCatalogo" WHERE id = $1', servicio_id) - return ArchivedResponse(ok=True, archived=False) diff --git a/api/app/routers/categorias.py b/api/app/routers/categorias.py deleted file mode 100644 index e54d49b..0000000 --- a/api/app/routers/categorias.py +++ /dev/null @@ -1,192 +0,0 @@ -from __future__ import annotations - -from datetime import datetime, timezone - -from fastapi import APIRouter, Depends, HTTPException, status - -from app.database import get_pool -from app.dependencies import get_db -from app.auth import require_scope, require_staff_human -from app.models.catalogo import CategoriaCreate, CategoriaUpdate, CategoriaResponse -from app.models.common import ErrorResponse, OkResponse - -router = APIRouter(prefix="/categorias", tags=["Categorias"]) - - -@router.get("", response_model=list[CategoriaResponse]) -async def list_categorias( - _auth: dict = Depends(require_scope("catalogo:leer")), - conn=Depends(get_db), -): - rows = await conn.fetch( - 'SELECT id, nombre, descripcion, color, activo, orden, "createdAt", "updatedAt"' - ' FROM "Categoria" ORDER BY orden ASC' - ) - return [dict(r) for r in rows] - - -@router.post( - "", - response_model=CategoriaResponse, - status_code=status.HTTP_201_CREATED, - responses={409: {"model": ErrorResponse}}, -) -async def create_categoria( - body: CategoriaCreate, - _auth: dict = Depends(require_staff_human), - conn=Depends(get_db), -): - now = datetime.now(timezone.utc) - try: - row = await conn.fetchrow( - 'INSERT INTO "Categoria" (id, nombre, descripcion, color, orden, "createdAt", "updatedAt")' - " VALUES (gen_random_uuid(), $1, $2, $3, $4, $5, $5)" - ' RETURNING id, nombre, descripcion, color, activo, orden, "createdAt", "updatedAt"', - body.nombre, - body.descripcion, - body.color, - body.orden, - now, - ) - except Exception as e: - if "unique" in str(e).lower() or "duplicate" in str(e).lower(): - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Ya existe una categoría con el nombre '{body.nombre}'", - ) - raise - return dict(row) - - -@router.get( - "/{categoria_id}", - responses={404: {"model": ErrorResponse}}, -) -async def get_categoria( - categoria_id: str, - _auth: dict = Depends(require_scope("catalogo:leer")), - conn=Depends(get_db), -): - row = await conn.fetchrow( - 'SELECT c.id, c.nombre, c.descripcion, c.color, c.activo, c.orden,' - ' c."createdAt", c."updatedAt",' - ' COUNT(s.id)::int AS "serviciosCount"' - ' FROM "Categoria" c' - ' LEFT JOIN "ServicioCatalogo" s ON s."categoriaId" = c.id' - " WHERE c.id = $1" - " GROUP BY c.id", - categoria_id, - ) - if not row: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Categoría no encontrada", - ) - return dict(row) - - -@router.put( - "/{categoria_id}", - response_model=CategoriaResponse, - responses={404: {"model": ErrorResponse}, 409: {"model": ErrorResponse}}, -) -async def update_categoria( - categoria_id: str, - body: CategoriaUpdate, - _auth: dict = Depends(require_staff_human), - conn=Depends(get_db), -): - existing = await conn.fetchrow( - 'SELECT id FROM "Categoria" WHERE id = $1', categoria_id - ) - if not existing: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Categoría no encontrada", - ) - - updates: list[str] = [] - params: list = [] - idx = 1 - - if body.nombre is not None: - updates.append(f"nombre = ${idx}") - params.append(body.nombre) - idx += 1 - if body.descripcion is not None: - updates.append(f"descripcion = ${idx}") - params.append(body.descripcion) - idx += 1 - if body.color is not None: - updates.append(f"color = ${idx}") - params.append(body.color) - idx += 1 - if body.orden is not None: - updates.append(f"orden = ${idx}") - params.append(body.orden) - idx += 1 - if body.activo is not None: - updates.append(f"activo = ${idx}") - params.append(body.activo) - idx += 1 - - if not updates: - row = await conn.fetchrow( - 'SELECT id, nombre, descripcion, color, activo, orden, "createdAt", "updatedAt"' - ' FROM "Categoria" WHERE id = $1', - categoria_id, - ) - return dict(row) - - updates.append(f'"updatedAt" = ${idx}') - params.append(datetime.now(timezone.utc)) - idx += 1 - - params.append(categoria_id) - try: - row = await conn.fetchrow( - f'UPDATE "Categoria" SET {", ".join(updates)} WHERE id = ${idx}' - ' RETURNING id, nombre, descripcion, color, activo, orden, "createdAt", "updatedAt"', - *params, - ) - except Exception as e: - if "unique" in str(e).lower() or "duplicate" in str(e).lower(): - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Ya existe una categoría con el nombre '{body.nombre}'", - ) - raise - return dict(row) - - -@router.delete( - "/{categoria_id}", - response_model=OkResponse, - responses={404: {"model": ErrorResponse}, 409: {"model": ErrorResponse}}, -) -async def delete_categoria( - categoria_id: str, - _auth: dict = Depends(require_staff_human), - conn=Depends(get_db), -): - existing = await conn.fetchrow( - 'SELECT id FROM "Categoria" WHERE id = $1', categoria_id - ) - if not existing: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Categoría no encontrada", - ) - - count = await conn.fetchval( - 'SELECT COUNT(*)::int FROM "ServicioCatalogo" WHERE "categoriaId" = $1', - categoria_id, - ) - if count > 0: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Tiene {count} servicios asociados", - ) - - await conn.execute('DELETE FROM "Categoria" WHERE id = $1', categoria_id) - return OkResponse(ok=True) diff --git a/api/app/routers/clientes.py b/api/app/routers/clientes.py deleted file mode 100644 index e86c237..0000000 --- a/api/app/routers/clientes.py +++ /dev/null @@ -1,214 +0,0 @@ -from __future__ import annotations - -import math - -from fastapi import APIRouter, Depends, HTTPException, Query, status -from asyncpg import Connection - -from app.auth import require_scope, require_staff_human -from app.dependencies import PaginationParams, get_db -from app.models.cliente import ClienteCreate, ClienteUpdate, ClienteResponse -from app.models.common import PaginatedResponse, Meta, ErrorResponse, OkResponse - -router = APIRouter(prefix="/clientes", tags=["Clientes"]) - - -@router.get( - "", - response_model=PaginatedResponse[ClienteResponse], - summary="List clients with pagination and search", -) -async def list_clientes( - db: Connection = Depends(get_db), - auth: dict = Depends(require_scope("clientes:leer")), - pagination: PaginationParams = Depends(PaginationParams), - q: str | None = Query(None, description="Search by nombre, empresa, or email"), - incluirArchivados: bool = Query(False, description="Solo personal humano"), -): - where_clauses: list[str] = [] - if auth.get("auth_type") == "agent" or not incluirArchivados: - where_clauses.append("archivado = false") - params: list = [] - idx = 1 - - if q: - where_clauses.append( - f"(nombre ILIKE ${idx} OR empresa ILIKE ${idx} OR email ILIKE ${idx})" - ) - params.append(f"%{q}%") - idx += 1 - - where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else "" - - count_row = await db.fetchrow( - f"SELECT COUNT(*) AS total FROM \"Cliente\" {where_sql}", *params - ) - total = count_row["total"] - pages = math.ceil(total / pagination.limit) if total > 0 else 0 - - rows = await db.fetch( - f'SELECT * FROM "Cliente" {where_sql} ORDER BY "createdAt" DESC ' - f"LIMIT ${idx} OFFSET ${idx + 1}", - *params, - pagination.limit, - pagination.offset, - ) - - data = [ - ClienteResponse( - id=r["id"], - nombre=r["nombre"], - empresa=r["empresa"], - email=r["email"], - telefono=r["telefono"], - createdAt=r["createdAt"], - updatedAt=r["updatedAt"], - ) - for r in rows - ] - - return PaginatedResponse( - data=data, - meta=Meta(total=total, page=pagination.page, limit=pagination.limit, pages=pages), - ) - - -@router.post( - "", - response_model=ClienteResponse, - status_code=status.HTTP_201_CREATED, - summary="Create a new client", -) -async def create_cliente( - body: ClienteCreate, - db: Connection = Depends(get_db), - auth: dict = Depends(require_scope("clientes:escribir")), -): - row = await db.fetchrow( - 'INSERT INTO "Cliente" (nombre, empresa, email, telefono) ' - "VALUES ($1, $2, $3, $4) RETURNING *", - body.nombre, - body.empresa, - body.email, - body.telefono, - ) - return ClienteResponse( - id=row["id"], - nombre=row["nombre"], - empresa=row["empresa"], - email=row["email"], - telefono=row["telefono"], - createdAt=row["createdAt"], - updatedAt=row["updatedAt"], - ) - - -@router.get( - "/{cliente_id}", - response_model=ClienteResponse, - responses={404: {"model": ErrorResponse}}, - summary="Get client by ID with recent cotizaciones", -) -async def get_cliente( - cliente_id: str, - db: Connection = Depends(get_db), - auth: dict = Depends(require_scope("clientes:leer")), -): - row = await db.fetchrow('SELECT * FROM "Cliente" WHERE id = $1', cliente_id) - if not row: - raise HTTPException(status_code=404, detail="Cliente no encontrado") - - cotizaciones = await db.fetch( - 'SELECT * FROM "Cotizacion" WHERE "clienteId" = $1 AND archivado = false ' - 'ORDER BY "createdAt" DESC LIMIT 10', - cliente_id, - ) - - cliente = ClienteResponse( - id=row["id"], - nombre=row["nombre"], - empresa=row["empresa"], - email=row["email"], - telefono=row["telefono"], - createdAt=row["createdAt"], - updatedAt=row["updatedAt"], - ) - - return cliente.model_copy( - update={"cotizaciones": [dict(c) for c in cotizaciones]} - ) - - -@router.put( - "/{cliente_id}", - response_model=ClienteResponse, - responses={404: {"model": ErrorResponse}}, - summary="Update a client", -) -async def update_cliente( - cliente_id: str, - body: ClienteUpdate, - db: Connection = Depends(get_db), - auth: dict = Depends(require_scope("clientes:escribir")), -): - existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id) - if not existing: - raise HTTPException(status_code=404, detail="Cliente no encontrado") - - updates: list[str] = [] - params: list = [] - idx = 1 - - for field in ("nombre", "empresa", "email", "telefono"): - value = getattr(body, field, None) - if value is not None: - updates.append(f"{field} = ${idx}") - params.append(value) - idx += 1 - - if not updates: - raise HTTPException(status_code=400, detail="No fields to update") - - params.append(cliente_id) - row = await db.fetchrow( - f'UPDATE "Cliente" SET {", ".join(updates)} WHERE id = ${idx} RETURNING *', - *params, - ) - - return ClienteResponse( - id=row["id"], - nombre=row["nombre"], - empresa=row["empresa"], - email=row["email"], - telefono=row["telefono"], - createdAt=row["createdAt"], - updatedAt=row["updatedAt"], - ) - - -@router.delete( - "/{cliente_id}", - response_model=OkResponse, - responses={409: {"model": ErrorResponse}, 404: {"model": ErrorResponse}}, - summary="Delete a client (fails if cotizaciones exist)", -) -async def delete_cliente( - cliente_id: str, - db: Connection = Depends(get_db), - auth: dict = Depends(require_staff_human), -): - existing = await db.fetchrow('SELECT id FROM "Cliente" WHERE id = $1', cliente_id) - if not existing: - raise HTTPException(status_code=404, detail="Cliente no encontrado") - - cot_count = await db.fetchval( - 'SELECT COUNT(*) FROM "Cotizacion" WHERE "clienteId" = $1', cliente_id - ) - if cot_count > 0: - raise HTTPException( - status_code=409, - detail="No se puede eliminar: el cliente tiene cotizaciones asociadas", - ) - - await db.execute('DELETE FROM "Cliente" WHERE id = $1', cliente_id) - return OkResponse() diff --git a/api/app/routers/cobros.py b/api/app/routers/cobros.py deleted file mode 100644 index 5c7890b..0000000 --- a/api/app/routers/cobros.py +++ /dev/null @@ -1,158 +0,0 @@ -from __future__ import annotations - -from fastapi import APIRouter, Depends, Query -from asyncpg import Connection - -from app.auth import require_scope -from app.dependencies import get_db, parse_date - -router = APIRouter(prefix="/cobros", tags=["Cobros"]) - - -@router.get("/programas", summary="Listar programas de cobro recurrente") -async def list_programas_cobro( - activo: bool | None = Query(None), - clienteId: str | None = Query(None), - db: Connection = Depends(get_db), - _auth: dict = Depends(require_scope("cobros:leer")), -): - conditions: list[str] = [] - params: list = [] - idx = 1 - - if activo is not None: - conditions.append(f"p.activo = ${idx}") - params.append(activo) - idx += 1 - if clienteId: - conditions.append(f'p."clienteId" = ${idx}') - params.append(clienteId) - idx += 1 - - where = "WHERE " + " AND ".join(conditions) if conditions else "" - rows = await db.fetch( - f""" - SELECT p.*, - c.nombre AS cliente_nombre, - c.empresa AS cliente_empresa, - (SELECT COUNT(*) FROM "PagoRecurrente" pr WHERE pr."programaId" = p.id) AS pagos_count - FROM "ProgramaPago" p - JOIN "Cliente" c ON c.id = p."clienteId" - {where} - ORDER BY p.activo DESC, p."createdAt" DESC - """, - *params, - ) - - return [ - { - "id": r["id"], - "clienteId": r["clienteId"], - "cotizacionId": r["cotizacionId"], - "concepto": r["concepto"], - "monto": float(r["monto"]), - "moneda": r["moneda"], - "frecuencia": r["frecuencia"], - "diaSemana": r["diaSemana"], - "diaMes": r["diaMes"], - "fechaInicio": r["fechaInicio"].isoformat() if r["fechaInicio"] else None, - "fechaFin": r["fechaFin"].isoformat() if r["fechaFin"] else None, - "activo": r["activo"], - "cliente": { - "id": r["clienteId"], - "nombre": r["cliente_nombre"], - "empresa": r["cliente_empresa"], - }, - "_count": {"pagos": int(r["pagos_count"])}, - } - for r in rows - ] - - -@router.get("/pagos", summary="Listar cobros recurrentes con filtros") -async def list_pagos_cobro( - estado: str | None = Query(None, description="pendiente | en_revision | verificado | rechazado | anulado | por_pagar"), - clienteId: str | None = Query(None), - programaId: str | None = Query(None), - desde: str | None = Query(None), - hasta: str | None = Query(None), - db: Connection = Depends(get_db), - _auth: dict = Depends(require_scope("cobros:leer")), -): - conditions: list[str] = [] - params: list = [] - idx = 1 - - if estado == "por_pagar": - conditions.append("pr.estado IN ('pendiente', 'rechazado')") - elif estado: - conditions.append(f"pr.estado = ${idx}") - params.append(estado) - idx += 1 - - if clienteId: - conditions.append(f'p."clienteId" = ${idx}') - params.append(clienteId) - idx += 1 - - if programaId: - conditions.append(f'pr."programaId" = ${idx}') - params.append(programaId) - idx += 1 - - desde_dt = parse_date(desde) - if desde_dt: - conditions.append(f"pr.fecha >= ${idx}") - params.append(desde_dt) - idx += 1 - - hasta_dt = parse_date(hasta) - if hasta_dt: - conditions.append(f"pr.fecha <= ${idx}") - params.append(hasta_dt) - idx += 1 - - where = "WHERE " + " AND ".join(conditions) if conditions else "" - rows = await db.fetch( - f""" - SELECT pr.*, - p.concepto AS programa_concepto, - p.moneda AS programa_moneda, - p."clienteId" AS programa_cliente_id, - c.nombre AS cliente_nombre, - c.empresa AS cliente_empresa - FROM "PagoRecurrente" pr - JOIN "ProgramaPago" p ON p.id = pr."programaId" - JOIN "Cliente" c ON c.id = p."clienteId" - {where} - ORDER BY pr.fecha DESC - """, - *params, - ) - - return [ - { - "id": r["id"], - "programaId": r["programaId"], - "fecha": r["fecha"].isoformat() if r["fecha"] else None, - "monto": float(r["monto"]), - "estado": r["estado"], - "verificadoAt": r["verificadoAt"].isoformat() if r["verificadoAt"] else None, - "rechazadoAt": r["rechazadoAt"].isoformat() if r["rechazadoAt"] else None, - "rechazoMotivo": r["rechazoMotivo"], - "ultimoRecordatorioAt": r["ultimoRecordatorioAt"].isoformat() if r["ultimoRecordatorioAt"] else None, - "recordatoriosEnviados": r["recordatoriosEnviados"], - "vencidoNotificadoAt": r["vencidoNotificadoAt"].isoformat() if ("vencidoNotificadoAt" in r and r["vencidoNotificadoAt"]) else None, - "nota": r["nota"], - "programa": { - "concepto": r["programa_concepto"], - "moneda": r["programa_moneda"], - "cliente": { - "id": r["programa_cliente_id"], - "nombre": r["cliente_nombre"], - "empresa": r["cliente_empresa"], - }, - }, - } - for r in rows - ] diff --git a/api/app/routers/configuracion.py b/api/app/routers/configuracion.py deleted file mode 100644 index 1f57996..0000000 --- a/api/app/routers/configuracion.py +++ /dev/null @@ -1,49 +0,0 @@ -from __future__ import annotations - -from fastapi import APIRouter, Depends, HTTPException, status -from asyncpg import Connection - -from app.dependencies import get_db -from app.models.configuracion import ConfigUpdate, ConfigResponse, ALLOWED_CONFIG_KEYS -from app.models.common import ErrorResponse, OkResponse -from app.auth import require_staff_human - -router = APIRouter(prefix="/configuracion", tags=["Configuración"]) - - -@router.get("", response_model=ConfigResponse) -async def get_configuracion( - _auth: dict = Depends(require_staff_human), - db: Connection = Depends(get_db), -): - rows = await db.fetch("SELECT clave, valor FROM Configuracion") - config = {row["clave"]: row["valor"] for row in rows} - return ConfigResponse(config=config) - - -@router.put("", response_model=OkResponse, responses={400: {"model": ErrorResponse}}) -async def update_configuracion( - body: ConfigUpdate, - _auth: dict = Depends(require_staff_human), - db: Connection = Depends(get_db), -): - allowed = body.get_allowed() - if not allowed: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="No valid config keys provided", - ) - - async with db.transaction(): - for clave, valor in allowed.items(): - await db.execute( - """ - INSERT INTO "Configuracion" (id, clave, valor, "updatedAt") - VALUES (gen_random_uuid(), $1, $2, now()) - ON CONFLICT (clave) DO UPDATE SET valor = $2, "updatedAt" = now() - """, - clave, - valor, - ) - - return OkResponse() diff --git a/api/app/routers/cotizaciones.py b/api/app/routers/cotizaciones.py deleted file mode 100644 index ad2d037..0000000 --- a/api/app/routers/cotizaciones.py +++ /dev/null @@ -1,1003 +0,0 @@ -from __future__ import annotations - -import json -import re -import uuid -from datetime import datetime, timezone - -from fastapi import APIRouter, Depends, HTTPException, Query, status - -from app.auth import ( - es_agente_solo_aceptadas, - registrar_auditoria, - require_auth, - require_scope, - require_staff_human, -) -from app.database import get_pool -from app.dependencies import PaginationParams, parse_date -from app.models.common import Meta, OkResponse, PaginatedResponse -from app.models.cotizacion import ( - ActualizarPrecioRequest, - CambiarEstadoRequest, - CotizacionCreate, - CotizacionResponse, - CotizacionUpdate, -) -from app.services.calculators import ESTADOS_COTIZACION - -router = APIRouter(prefix="/cotizaciones", tags=["Cotizaciones"]) - - -def _cuid() -> str: - return uuid.uuid4().hex[:25] - - -_PATRON_BUCEFALO = re.compile(r"buc[eé]falo", re.IGNORECASE) - - -async def _validar_solo_admin_agente( - conn, - auth: dict, - servicios, - plan_bucefalo, - recurso_id: str | None = None, -) -> None: - """Bloquea a agentes que intenten incluir servicios soloAdmin o planes de Bucéfalo CRM.""" - if auth.get("auth_type") != "agent": - return - - motivos: list[str] = [] - if plan_bucefalo is not None: - motivos.append("planBucefalo") - - servicios_lista = servicios or [] - catalogo_ids = [ - s.catalogoId - for s in servicios_lista - if getattr(s, "catalogoId", None) - and not s.catalogoId.startswith("custom-") - and not s.catalogoId.lower().startswith("bucefalo-") - ] - - solo_admin_ids: set[str] = set() - if catalogo_ids: - rows = await conn.fetch( - 'SELECT id FROM "ServicioCatalogo" WHERE id = ANY($1::text[]) AND "soloAdmin" = true', - catalogo_ids, - ) - solo_admin_ids = {r["id"] for r in rows} - - for s in servicios_lista: - cid = (getattr(s, "catalogoId", "") or "").strip() - nombre = (getattr(s, "nombre", "") or "").strip() - if cid.lower().startswith("bucefalo-"): - motivos.append(f"catalogoId:{cid}") - elif cid in solo_admin_ids: - motivos.append(f"soloAdmin:{cid}") - elif _PATRON_BUCEFALO.search(nombre): - motivos.append(f"nombre:{nombre}") - - if motivos: - await registrar_auditoria( - conn, - auth, - "cotizacion.servicio_solo_admin_bloqueado", - "cotizacion", - recurso_id=recurso_id, - exito=False, - detalle={"motivos": motivos}, - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Los servicios restringidos al administrador (incluidos los planes de Bucefalo CRM) no pueden ser agregados por agentes", - ) - - -async def _insert_servicio_cotizado( - conn, - cotizacion_id: str, - svc, - bucefalo_servicio_id, - now, - es_doble: bool = False, -) -> None: - es_personalizado = bool(getattr(svc, "esPersonalizado", False)) or svc.catalogoId.startswith("custom-") - - if es_personalizado: - catalogo_id = None - elif svc.catalogoId.startswith("bucefalo-") and bucefalo_servicio_id: - catalogo_id = bucefalo_servicio_id - else: - catalogo_id = svc.catalogoId - - modelo_cobro = svc.modeloCobro or ("horas" if es_personalizado else "fijo") - opcion = (svc.opcion or "ambas") if es_doble else None - precio_final = 0 if modelo_cobro == "demanda" else svc.precio - - await conn.execute( - """ - INSERT INTO "ServicioCotizado" - (id, "cotizacionId", "servicioCatalogoId", nombre, "esPersonalizado", - horas, "tarifaHora", "modeloCobro", "montoMinimo", "horasIncluidas", - opcion, fase, "tipoPago", precio, "tiempoEntrega", entregables, notas, - seleccionado, "createdAt", "updatedAt") - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,true,$18,$18) - """, - _cuid(), - cotizacion_id, - catalogo_id, - svc.nombre if es_personalizado else None, - es_personalizado, - svc.horas if es_personalizado else None, - svc.tarifaHora if es_personalizado else None, - modelo_cobro, - svc.montoMinimo if es_personalizado else None, - svc.horasIncluidas if es_personalizado else None, - opcion, - svc.fase, - svc.tipoPago, - precio_final, - svc.tiempoEntrega, - json.dumps(svc.entregables), - None, - now, - ) - - -def _parse_json(val): - if isinstance(val, str): - try: - return json.loads(val) - except (ValueError, TypeError): - return None - return val - - -def _build_cotizacion_dict(cot, cliente=None, asesor=None, servicios=None, plan=None) -> dict: - d = dict(cot) - if "opcionesMetadata" in d: - d["opcionesMetadata"] = _parse_json(d["opcionesMetadata"]) - d.pop("observacionesInternas", None) - d["cliente"] = dict(cliente) if cliente else None - d["asesor"] = dict(asesor) if asesor else None - d["servicios"] = [dict(s) for s in servicios] if servicios else [] - d["planBucefalo"] = dict(plan) if plan else None - return d - - -_SERVICIOS_SQL = """ - SELECT sc.*, sc."servicioCatalogoId" as "catalogoId", - COALESCE(s.nombre, sc.nombre) AS nombre, s.descripcion, s."categoriaId" - FROM "ServicioCotizado" sc - LEFT JOIN "ServicioCatalogo" s ON s.id = sc."servicioCatalogoId" - WHERE sc."cotizacionId" = {} - ORDER BY sc.fase, sc.opcion, sc.id -""" - - -async def _fetch_cotizacion_full(conn, cot_id: str) -> dict | None: - cot = await conn.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cot_id) - if not cot: - return None - - cliente = await conn.fetchrow('SELECT * FROM "Cliente" WHERE id = $1', cot["clienteId"]) - asesor = await conn.fetchrow('SELECT id, email, name, role FROM "User" WHERE id = $1', cot["asesorId"]) - servicios = await conn.fetch(_SERVICIOS_SQL.format("$1"), cot_id) - plan = await conn.fetchrow('SELECT * FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1', cot_id) - - return _build_cotizacion_dict(cot, cliente, asesor, servicios, plan) - - -async def _fetch_cotizaciones_full(conn, cot_rows) -> list[dict]: - if not cot_rows: - return [] - - cot_ids = [r["id"] for r in cot_rows] - cliente_ids = list({r["clienteId"] for r in cot_rows}) - asesor_ids = list({r["asesorId"] for r in cot_rows}) - - clientes = await conn.fetch('SELECT * FROM "Cliente" WHERE id = ANY($1::text[])', cliente_ids) - asesores = await conn.fetch('SELECT id, email, name, role FROM "User" WHERE id = ANY($1::text[])', asesor_ids) - servicios = await conn.fetch(_SERVICIOS_SQL.format("ANY($1::text[])"), cot_ids) - planes = await conn.fetch('SELECT * FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = ANY($1::text[])', cot_ids) - - clientes_map = {c["id"]: c for c in clientes} - asesores_map = {a["id"]: a for a in asesores} - planes_map = {p["cotizacionId"]: p for p in planes} - servicios_map: dict[str, list] = {} - for s in servicios: - servicios_map.setdefault(s["cotizacionId"], []).append(s) - - return [ - _build_cotizacion_dict( - cot, - clientes_map.get(cot["clienteId"]), - asesores_map.get(cot["asesorId"]), - servicios_map.get(cot["id"], []), - planes_map.get(cot["id"]), - ) - for cot in cot_rows - ] - - -async def _resolve_bucefalo_servicio(conn) -> str | None: - row = await conn.fetchrow( - """ - SELECT s.id FROM "ServicioCatalogo" s - JOIN "Categoria" c ON c.id = s."categoriaId" - WHERE c.nombre = 'CRM' AND s."tipoPago" = 'mensual' AND s.activo = true - ORDER BY s.orden LIMIT 1 - """ - ) - return row["id"] if row else None - - -async def _find_or_create_cliente(conn, nombre: str, empresa: str, email: str, telefono: str) -> str: - row = await conn.fetchrow( - 'SELECT id FROM "Cliente" WHERE archivado = false AND nombre = $1 AND COALESCE(empresa, \'\') = $2', - nombre, - empresa or "", - ) - if row: - if email or telefono: - await conn.execute( - 'UPDATE "Cliente" SET email = COALESCE($1, email), telefono = COALESCE($2, telefono), "updatedAt" = NOW() WHERE id = $3', - email or None, - telefono or None, - row["id"], - ) - return row["id"] - - new_id = _cuid() - await conn.execute( - 'INSERT INTO "Cliente" (id, nombre, empresa, email, telefono, "createdAt", "updatedAt") VALUES ($1, $2, $3, $4, $5, NOW(), NOW())', - new_id, - nombre, - empresa or None, - email or None, - telefono or None, - ) - return new_id - - -# --------------------------------------------------------------------------- -# 1. GET /cotizaciones -# --------------------------------------------------------------------------- -@router.get("", response_model=PaginatedResponse[CotizacionResponse]) -async def list_cotizaciones( - pagination: PaginationParams = Depends(), - estado: str | None = Query(None), - asesorId: str | None = Query(None), - clienteId: str | None = Query(None), - q: str | None = Query(None), - desde: str | None = Query(None), - hasta: str | None = Query(None), - incluirArchivados: bool = Query(False), - auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:leer_aceptadas")), -): - pool = await get_pool() - solo_aceptadas = es_agente_solo_aceptadas(auth) - if solo_aceptadas and estado and estado != "aceptada": - await registrar_auditoria( - pool, - auth, - "cotizacion.leer_bloqueado", - "cotizacion", - exito=False, - detalle={"estadoSolicitado": estado}, - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Tu clave solo permite consultar cotizaciones aceptadas", - ) - - estado_efectivo = "aceptada" if solo_aceptadas else estado - - conditions: list[str] = [] - if auth.get("auth_type") == "agent" or not incluirArchivados: - conditions.append("c.archivado = false") - params: list = [] - idx = 1 - - if estado_efectivo: - conditions.append(f"c.estado = ${idx}") - params.append(estado_efectivo) - idx += 1 - if asesorId: - conditions.append(f'c."asesorId" = ${idx}') - params.append(asesorId) - idx += 1 - if clienteId: - conditions.append(f'c."clienteId" = ${idx}') - params.append(clienteId) - idx += 1 - if q: - conditions.append( - f"(c.numero ILIKE ${idx} OR cl.nombre ILIKE ${idx} OR c.proyecto ILIKE ${idx})" - ) - params.append(f"%{q}%") - idx += 1 - desde_dt = parse_date(desde) - if desde_dt: - conditions.append(f"c.fecha >= ${idx}") - params.append(desde_dt) - idx += 1 - hasta_dt = parse_date(hasta) - if hasta_dt: - conditions.append(f"c.fecha <= ${idx}") - params.append(hasta_dt) - idx += 1 - - where = "WHERE " + " AND ".join(conditions) if conditions else "" - - count_row = await pool.fetchrow( - f'SELECT COUNT(*) FROM "Cotizacion" c LEFT JOIN "Cliente" cl ON cl.id = c."clienteId" {where}', - *params, - ) - total = count_row["count"] - - rows = await pool.fetch( - f""" - SELECT c.* FROM "Cotizacion" c - LEFT JOIN "Cliente" cl ON cl.id = c."clienteId" - {where} - ORDER BY c."createdAt" DESC - LIMIT ${idx} OFFSET ${idx + 1} - """, - *params, - pagination.limit, - pagination.offset, - ) - - cotizaciones = await _fetch_cotizaciones_full(pool, rows) - pages = (total + pagination.limit - 1) // pagination.limit if total > 0 else 0 - - return PaginatedResponse( - data=cotizaciones, - meta=Meta(total=total, page=pagination.page, limit=pagination.limit, pages=pages), - ) - - -# --------------------------------------------------------------------------- -# 2. POST /cotizaciones — Create (SIEMPRE borrador) -# --------------------------------------------------------------------------- -@router.post("", response_model=CotizacionResponse, status_code=status.HTTP_201_CREATED) -async def create_cotizacion( - body: CotizacionCreate, - auth: dict = Depends(require_scope("cotizaciones:borrador")), -): - pool = await get_pool() - async with pool.acquire() as conn: - await _validar_solo_admin_agente(conn, auth, body.servicios, body.planBucefalo) - asesor_id = body.asesorId - if not asesor_id: - if auth.get("auth_type") == "jwt" and auth.get("userId"): - asesor_id = auth["userId"] - else: - admin = await conn.fetchrow( - 'SELECT id FROM "User" WHERE role = \'admin\' ORDER BY "createdAt" ASC LIMIT 1' - ) - if not admin: - raise HTTPException(status_code=500, detail="No hay usuario administrador configurado") - asesor_id = admin["id"] - - creada_por_agente = auth.get("nombre") if auth.get("auth_type") == "agent" else None - - async with conn.transaction(): - cliente_id = await _find_or_create_cliente( - conn, - body.cliente.nombre, - body.cliente.empresa, - body.cliente.email, - body.cliente.telefono, - ) - - cot_id = _cuid() - now = datetime.now(timezone.utc) - opciones_json = None - if body.esDoble and body.opciones: - opciones_json = json.dumps({k: v.model_dump() for k, v in body.opciones.items()}) - - await conn.execute( - """ - INSERT INTO "Cotizacion" - (id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago", - estado, "incluirBonos", "incluirFinanciamiento", "incluirIva", "esDoble", - "opcionesMetadata", observaciones, "clienteId", "asesorId", - "creadaPorAgente", "createdAt", "updatedAt") - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$18) - """, - cot_id, - body.numero, - body.fecha, - body.vigencia, - body.moneda, - body.tipoCambio, - body.proyecto, - body.esquemaPago, - body.incluirBonos, - body.incluirFinanciamiento, - body.incluirIva, - body.esDoble, - opciones_json, - body.observaciones or None, - cliente_id, - asesor_id, - creada_por_agente, - now, - ) - - bucefalo_servicio_id = await _resolve_bucefalo_servicio(conn) - for svc in body.servicios: - await _insert_servicio_cotizado(conn, cot_id, svc, bucefalo_servicio_id, now, body.esDoble) - - if body.planBucefalo: - await conn.execute( - """ - INSERT INTO "PlanBucefaloCotizacion" - (id, "cotizacionId", nivel, precio, seleccionado, "createdAt", "updatedAt") - VALUES ($1,$2,$3,$4,true,$5,$5) - """, - _cuid(), - cot_id, - body.planBucefalo.nivel, - body.planBucefalo.precio, - now, - ) - - await registrar_auditoria( - conn, - auth, - "cotizacion.crear", - "cotizacion", - recurso_id=cot_id, - exito=True, - detalle={"numero": body.numero, "creadaPorAgente": creada_por_agente}, - ) - - full = await _fetch_cotizacion_full(pool, cot_id) - return full - - -# --------------------------------------------------------------------------- -# 3. GET /cotizaciones/{id} -# --------------------------------------------------------------------------- -@router.get("/{cotizacion_id}", response_model=CotizacionResponse) -async def get_cotizacion( - cotizacion_id: str, - auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:leer_aceptadas")), -): - pool = await get_pool() - full = await _fetch_cotizacion_full(pool, cotizacion_id) - if not full: - raise HTTPException(status_code=404, detail="Cotización no encontrada") - - if es_agente_solo_aceptadas(auth) and full["estado"] != "aceptada": - await registrar_auditoria( - pool, - auth, - "cotizacion.leer_bloqueado", - "cotizacion", - recurso_id=cotizacion_id, - exito=False, - detalle={"estadoActual": full["estado"]}, - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Tu clave solo permite consultar cotizaciones aceptadas", - ) - return full - - -# --------------------------------------------------------------------------- -# 4. PUT /cotizaciones/{id} -# --------------------------------------------------------------------------- -@router.put("/{cotizacion_id}", response_model=CotizacionResponse) -async def update_cotizacion( - cotizacion_id: str, - body: CotizacionUpdate, - auth: dict = Depends(require_scope("cotizaciones:borrador")), -): - pool = await get_pool() - async with pool.acquire() as conn: - existing = await conn.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id) - if not existing: - raise HTTPException(status_code=404, detail="Cotización no encontrada") - - if auth.get("auth_type") == "agent": - if existing["estado"] != "borrador": - await registrar_auditoria( - conn, - auth, - "cotizacion.editar_bloqueado", - "cotizacion", - recurso_id=cotizacion_id, - exito=False, - detalle={"estadoActual": existing["estado"]}, - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Los agentes solo pueden editar cotizaciones en borrador", - ) - if body.estado is not None and body.estado != "borrador": - await registrar_auditoria( - conn, - auth, - "cotizacion.aprobar_bloqueado" if body.estado == "aprobada" else "cotizacion.estado_bloqueado", - "cotizacion", - recurso_id=cotizacion_id, - exito=False, - detalle={"actual": existing["estado"], "intento": body.estado}, - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Los agentes no pueden cambiar el estado de la cotización", - ) - await _validar_solo_admin_agente( - conn, - auth, - body.servicios, - body.planBucefalo, - recurso_id=cotizacion_id, - ) - - if body.estado is not None and body.estado != existing["estado"]: - # Si un humano intenta cambiar estado en PUT, exige las mismas reglas que PATCH /estado - if body.estado == "aprobada" and not (auth.get("auth_type") == "jwt" and auth.get("role") == "admin"): - await registrar_auditoria( - conn, - auth, - "cotizacion.aprobar_bloqueado", - "cotizacion", - recurso_id=cotizacion_id, - exito=False, - detalle={"intento": "aprobada"}, - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Solo un administrador humano puede aprobar una cotización", - ) - if body.estado == "enviada" and (existing["estado"] != "aprobada" or existing["aprobadaAt"] is None): - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="La cotización debe estar aprobada antes de marcarse como enviada", - ) - - async with conn.transaction(): - cliente_id = existing["clienteId"] - if body.cliente: - cliente_id = await _find_or_create_cliente( - conn, - body.cliente.nombre, - body.cliente.empresa, - body.cliente.email, - body.cliente.telefono, - ) - - updates: list[str] = [] - params: list = [] - idx = 1 - - def _add(col: str, val): - nonlocal idx - updates.append(f'{col} = ${idx}') - params.append(val) - idx += 1 - - if body.fecha is not None: - _add("fecha", body.fecha) - if body.vigencia is not None: - _add("vigencia", body.vigencia) - if body.moneda is not None: - _add("moneda", body.moneda) - if body.tipoCambio is not None: - _add('"tipoCambio"', body.tipoCambio) - if body.proyecto is not None: - _add("proyecto", body.proyecto) - if body.esquemaPago is not None: - _add('"esquemaPago"', body.esquemaPago) - if body.incluirBonos is not None: - _add('"incluirBonos"', body.incluirBonos) - if body.incluirFinanciamiento is not None: - _add('"incluirFinanciamiento"', body.incluirFinanciamiento) - if body.incluirIva is not None: - _add('"incluirIva"', body.incluirIva) - if body.esDoble is not None: - _add('"esDoble"', body.esDoble) - if body.opciones is not None: - _add('"opcionesMetadata"', json.dumps({k: v.model_dump() for k, v in body.opciones.items()})) - if body.observaciones is not None: - _add("observaciones", body.observaciones) - if body.estado is not None and auth.get("auth_type") != "agent": - _add("estado", body.estado) - if cliente_id != existing["clienteId"]: - _add('"clienteId"', cliente_id) - - if updates: - updates.append('"updatedAt" = NOW()') - params.append(cotizacion_id) - await conn.execute( - f'UPDATE "Cotizacion" SET {", ".join(updates)} WHERE id = ${idx}', - *params, - ) - - now = datetime.now(timezone.utc) - es_doble_final = body.esDoble if body.esDoble is not None else existing["esDoble"] - - if body.servicios is not None: - await conn.execute('DELETE FROM "ServicioCotizado" WHERE "cotizacionId" = $1', cotizacion_id) - bucefalo_servicio_id = await _resolve_bucefalo_servicio(conn) - for svc in body.servicios: - await _insert_servicio_cotizado(conn, cotizacion_id, svc, bucefalo_servicio_id, now, es_doble_final) - - if body.planBucefalo is not None: - existing_plan = await conn.fetchrow( - 'SELECT id FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1', - cotizacion_id, - ) - if existing_plan: - await conn.execute( - 'UPDATE "PlanBucefaloCotizacion" SET nivel = $1, precio = $2, "updatedAt" = $3 WHERE id = $4', - body.planBucefalo.nivel, - body.planBucefalo.precio, - now, - existing_plan["id"], - ) - else: - await conn.execute( - """ - INSERT INTO "PlanBucefaloCotizacion" - (id, "cotizacionId", nivel, precio, seleccionado, "createdAt", "updatedAt") - VALUES ($1,$2,$3,$4,true,$5,$5) - """, - _cuid(), - cotizacion_id, - body.planBucefalo.nivel, - body.planBucefalo.precio, - now, - ) - elif body.planBucefalo is None and "planBucefalo" in body.model_fields_set: - await conn.execute( - 'DELETE FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1', - cotizacion_id, - ) - - await registrar_auditoria( - conn, - auth, - "cotizacion.actualizar", - "cotizacion", - recurso_id=cotizacion_id, - exito=True, - ) - - return await _fetch_cotizacion_full(pool, cotizacion_id) - - -# --------------------------------------------------------------------------- -# 5. DELETE /cotizaciones/{id} (solo personal humano) -# --------------------------------------------------------------------------- -@router.delete("/{cotizacion_id}", response_model=OkResponse) -async def delete_cotizacion( - cotizacion_id: str, - auth: dict = Depends(require_staff_human), -): - pool = await get_pool() - existing = await pool.fetchrow('SELECT id, numero FROM "Cotizacion" WHERE id = $1', cotizacion_id) - if not existing: - raise HTTPException(status_code=404, detail="Cotización no encontrada") - await pool.execute('DELETE FROM "Cotizacion" WHERE id = $1', cotizacion_id) - await registrar_auditoria( - pool, - auth, - "cotizacion.eliminar", - "cotizacion", - recurso_id=cotizacion_id, - exito=True, - detalle={"numero": existing["numero"]}, - ) - return OkResponse(ok=True) - - -# --------------------------------------------------------------------------- -# 6. PATCH /cotizaciones/{id}/precio -# --------------------------------------------------------------------------- -@router.patch("/{cotizacion_id}/precio", response_model=OkResponse) -async def update_precio_servicio( - cotizacion_id: str, - body: ActualizarPrecioRequest, - auth: dict = Depends(require_scope("cotizaciones:borrador")), -): - pool = await get_pool() - cot = await pool.fetchrow('SELECT id, estado FROM "Cotizacion" WHERE id = $1', cotizacion_id) - if not cot: - raise HTTPException(status_code=404, detail="Cotización no encontrada") - - if auth.get("auth_type") == "agent" and cot["estado"] != "borrador": - await registrar_auditoria( - pool, - auth, - "cotizacion.editar_precio_bloqueado", - "cotizacion", - recurso_id=cotizacion_id, - exito=False, - detalle={"estadoActual": cot["estado"]}, - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Los agentes solo pueden editar precios en cotizaciones en borrador", - ) - - svc = await pool.fetchrow( - 'SELECT id FROM "ServicioCotizado" WHERE id = $1 AND "cotizacionId" = $2', - body.servicioId, - cotizacion_id, - ) - if not svc: - raise HTTPException(status_code=404, detail="Servicio no pertenece a esta cotización") - - await pool.execute( - 'UPDATE "ServicioCotizado" SET precio = $1, "updatedAt" = NOW() WHERE id = $2', - body.precio, - body.servicioId, - ) - return OkResponse(ok=True) - - -# --------------------------------------------------------------------------- -# 7. PATCH /cotizaciones/{id}/estado (PARIDAD ESTRICTA DE APROBACIÓN) -# --------------------------------------------------------------------------- -@router.patch("/{cotizacion_id}/estado", response_model=OkResponse) -async def cambiar_estado( - cotizacion_id: str, - body: CambiarEstadoRequest, - auth: dict = Depends(require_auth), -): - if body.estado not in ESTADOS_COTIZACION: - raise HTTPException( - status_code=422, - detail=f"Estado inválido. Permitidos: {', '.join(ESTADOS_COTIZACION)}", - ) - - pool = await get_pool() - existing = await pool.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id) - if not existing: - raise HTTPException(status_code=404, detail="Cotización no encontrada") - - # REGLA DE HIERRO: Ningún agente puede cambiar estado (ni aprobar ni enviar por este endpoint). - if auth.get("auth_type") == "agent": - await registrar_auditoria( - pool, - auth, - "cotizacion.aprobar_bloqueado" if body.estado == "aprobada" else "cotizacion.estado_bloqueado", - "cotizacion", - recurso_id=cotizacion_id, - exito=False, - detalle={"actual": existing["estado"], "intento": body.estado}, - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Los agentes no pueden aprobar ni cambiar el estado directamente. Usa el flujo de aprobación humana y POST /api/cotizaciones/:id/enviar.", - ) - - es_admin = auth.get("auth_type") == "jwt" and auth.get("role") == "admin" - actual = existing["estado"] - nuevo = body.estado - - if nuevo == "aprobada": - if not es_admin: - await registrar_auditoria( - pool, - auth, - "cotizacion.aprobar_bloqueado", - "cotizacion", - recurso_id=cotizacion_id, - exito=False, - detalle={"actual": actual, "intento": nuevo}, - ) - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Solo un administrador humano puede aprobar una cotización", - ) - if actual != "borrador": - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Solo se puede aprobar una cotización en borrador (estado actual: {actual})", - ) - await pool.execute( - """ - UPDATE "Cotizacion" - SET estado = 'aprobada', - "aprobadaPorId" = $1, - "aprobadaAt" = NOW(), - "aprobacionMetodo" = 'web_admin', - "updatedAt" = NOW() - WHERE id = $2 - """, - auth.get("userId"), - cotizacion_id, - ) - elif nuevo == "enviada": - if actual != "aprobada" or existing["aprobadaAt"] is None: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="La cotización debe estar aprobada antes de marcarse como enviada", - ) - await pool.execute( - """ - UPDATE "Cotizacion" - SET estado = 'enviada', - "enviadaAt" = NOW(), - "enviadaCanal" = 'manual', - "enviadaPor" = $1, - "updatedAt" = NOW() - WHERE id = $2 - """, - f"user:{auth.get('email') or auth.get('userId')}", - cotizacion_id, - ) - elif nuevo == "borrador": - if not es_admin: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Solo un administrador humano puede regresar a borrador", - ) - await pool.execute( - """ - UPDATE "Cotizacion" - SET estado = 'borrador', - "aprobadaPorId" = NULL, - "aprobadaAt" = NULL, - "aprobacionMetodo" = NULL, - "updatedAt" = NOW() - WHERE id = $1 - """, - cotizacion_id, - ) - elif nuevo in ("aceptada", "rechazada", "vencida"): - if actual != "enviada": - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Solo se puede pasar a {nuevo} desde estado enviada (estado actual: {actual})", - ) - col_map = { - "aceptada": '"aceptadaAt"', - "rechazada": '"rechazadaAt"', - "vencida": '"vencidaAt"', - } - col = col_map[nuevo] - await pool.execute( - f'UPDATE "Cotizacion" SET estado = $1, {col} = NOW(), "updatedAt" = NOW() WHERE id = $2', - nuevo, - cotizacion_id, - ) - - await registrar_auditoria( - pool, - auth, - f"cotizacion.estado_{nuevo}", - "cotizacion", - recurso_id=cotizacion_id, - exito=True, - detalle={"anterior": actual, "nuevo": nuevo}, - ) - return OkResponse(ok=True) - - -# --------------------------------------------------------------------------- -# 8. POST /cotizaciones/{id}/duplicate -# --------------------------------------------------------------------------- -@router.post("/{cotizacion_id}/duplicate", response_model=CotizacionResponse, status_code=status.HTTP_201_CREATED) -async def duplicate_cotizacion( - cotizacion_id: str, - auth: dict = Depends(require_scope("cotizaciones:borrador")), -): - pool = await get_pool() - async with pool.acquire() as conn: - original = await conn.fetchrow('SELECT * FROM "Cotizacion" WHERE id = $1', cotizacion_id) - if not original: - raise HTTPException(status_code=404, detail="Cotización no encontrada") - - servicios = await conn.fetch( - 'SELECT * FROM "ServicioCotizado" WHERE "cotizacionId" = $1', - cotizacion_id, - ) - plan = await conn.fetchrow( - 'SELECT * FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1', - cotizacion_id, - ) - - creada_por_agente = auth.get("nombre") if auth.get("auth_type") == "agent" else None - - async with conn.transaction(): - now = datetime.now(timezone.utc) - new_id = _cuid() - new_numero = original["numero"] + "-COPY" - - await conn.execute( - """ - INSERT INTO "Cotizacion" - (id, numero, fecha, vigencia, moneda, "tipoCambio", proyecto, "esquemaPago", - estado, "incluirBonos", "incluirFinanciamiento", "incluirIva", "esDoble", - "opcionesMetadata", observaciones, "clienteId", "asesorId", - "creadaPorAgente", "createdAt", "updatedAt") - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$18) - """, - new_id, - new_numero, - original["fecha"], - original["vigencia"], - original["moneda"], - original["tipoCambio"], - original["proyecto"], - original["esquemaPago"], - original["incluirBonos"], - original["incluirFinanciamiento"], - original["incluirIva"], - original["esDoble"], - original["opcionesMetadata"], - original["observaciones"], - original["clienteId"], - original["asesorId"], - creada_por_agente, - now, - ) - - for svc in servicios: - await conn.execute( - """ - INSERT INTO "ServicioCotizado" - (id, "cotizacionId", "servicioCatalogoId", nombre, "esPersonalizado", - horas, "tarifaHora", "modeloCobro", "montoMinimo", "horasIncluidas", - opcion, fase, "tipoPago", precio, "tiempoEntrega", entregables, notas, - seleccionado, "createdAt", "updatedAt") - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$19) - """, - _cuid(), - new_id, - svc["servicioCatalogoId"], - svc["nombre"], - svc["esPersonalizado"], - svc["horas"], - svc["tarifaHora"], - svc["modeloCobro"], - svc["montoMinimo"], - svc["horasIncluidas"], - svc["opcion"], - svc["fase"], - svc["tipoPago"], - svc["precio"], - svc["tiempoEntrega"], - svc["entregables"], - svc["notas"], - svc["seleccionado"], - now, - ) - - if plan: - await conn.execute( - """ - INSERT INTO "PlanBucefaloCotizacion" - (id, "cotizacionId", nivel, precio, seleccionado, "createdAt", "updatedAt") - VALUES ($1,$2,$3,$4,$5,$6,$6) - """, - _cuid(), - new_id, - plan["nivel"], - plan["precio"], - plan["seleccionado"], - now, - ) - - await registrar_auditoria( - conn, - auth, - "cotizacion.duplicar", - "cotizacion", - recurso_id=new_id, - exito=True, - detalle={"origenId": cotizacion_id, "numero": new_numero}, - ) - - return await _fetch_cotizacion_full(pool, new_id) diff --git a/api/app/routers/export_.py b/api/app/routers/export_.py deleted file mode 100644 index 275c391..0000000 --- a/api/app/routers/export_.py +++ /dev/null @@ -1,368 +0,0 @@ -"""Export endpoints — PDF, Excel, CSV generation.""" - -from __future__ import annotations - -import csv -import io -import json -from datetime import datetime -from typing import Any - -from fastapi import APIRouter, Depends, HTTPException, status -from fastapi.responses import PlainTextResponse, Response -from asyncpg import Connection - -from app.dependencies import get_db -from app.models.export_ import ExportDraft -from app.models.common import ErrorResponse -from app.auth import es_agente_solo_aceptadas, require_scope -from app.services.calculators import bucefalo_precio, calcular_vigencia, sanitize_filename -from app.services.pdf_generator import generate_cotizacion_pdf -from app.services.excel_generator import generate_cotizacion_excel - -router = APIRouter(prefix="/export", tags=["Export"]) - - -async def _load_branding(db: Connection) -> dict[str, str]: - rows = await db.fetch('SELECT clave, valor FROM "Configuracion"') - return {r["clave"]: r["valor"] for r in rows} - - -def _build_pdf_data_from_draft(draft: ExportDraft, branding: dict[str, str]) -> dict[str, Any]: - fecha = datetime.now() - if draft.fecha: - try: - fecha = datetime.fromisoformat(draft.fecha.replace("Z", "+00:00")) - except ValueError: - try: - fecha = datetime.strptime(draft.fecha, "%Y-%m-%d") - except ValueError: - pass - - vigencia = calcular_vigencia(fecha) - logo_raw = branding.get("logo_base64", "") - logo_mime = None - logo_b64 = None - if logo_raw and ":" in logo_raw: - parts = logo_raw.split(":", 1) - logo_mime = parts[0] - logo_b64 = parts[1] - elif logo_raw: - logo_b64 = logo_raw - - return { - "numero": "BORRADOR", - "clienteNombre": draft.clienteNombre, - "clienteEmpresa": draft.clienteEmpresa, - "asesorNombre": draft.asesorNombre, - "fecha": fecha, - "vigencia": vigencia, - "moneda": draft.moneda, - "tipoCambio": draft.tipoCambio, - "proyecto": draft.proyecto, - "esquemaPago": draft.esquemaPago, - "servicios": [ - { - "nombre": s.nombre, - "fase": s.fase, - "tipoPago": s.tipoPago, - "precio": s.precio, - "tiempoEntrega": s.tiempoEntrega, - "entregables": s.entregables, - "esPersonalizado": s.esPersonalizado, - "horas": s.horas, - "tarifaHora": s.tarifaHora, - "modeloCobro": s.modeloCobro, - "montoMinimo": s.montoMinimo, - "horasIncluidas": s.horasIncluidas, - "opcion": s.opcion, - } - for s in draft.servicios - ], - "esDoble": draft.esDoble, - "opcionesMetadata": ( - {k: v.model_dump() for k, v in draft.opciones.items()} if draft.esDoble and draft.opciones else None - ), - "planBucefaloNivel": draft.planBucefaloNivel, - "planBucefaloPrecio": bucefalo_precio(draft.planBucefaloNivel) if draft.planBucefaloNivel else 0, - "incluirBonos": draft.incluirBonos, - "colorPrimario": branding.get("color_primario") or "#0400C4", - "colorSecundario": branding.get("color_secundario") or "#0F172A", - "logoBase64": logo_b64, - "logoMime": logo_mime, - "configBancaria": branding, - "razonSocial": branding.get("razon_social") or "Uriel Jareth Consulting", - } - - -async def _build_pdf_data_from_db(db: Connection, cotizacion_id: str) -> dict[str, Any] | None: - cot = await db.fetchrow( - """SELECT c.*, cl.nombre as cliente_nombre, cl.empresa as cliente_empresa, - u.name as asesor_nombre - FROM "Cotizacion" c - LEFT JOIN "Cliente" cl ON cl.id = c."clienteId" - LEFT JOIN "User" u ON u.id = c."asesorId" - WHERE c.id = $1""", - cotizacion_id, - ) - if not cot: - return None - - servicios = await db.fetch( - """SELECT sc.fase, sc."tipoPago", sc.precio, sc."tiempoEntrega", sc.entregables, - sc."esPersonalizado", sc.horas, sc."tarifaHora", sc."modeloCobro", - sc."montoMinimo", sc."horasIncluidas", sc.opcion, - COALESCE(s.nombre, sc.nombre) AS nombre - FROM "ServicioCotizado" sc - LEFT JOIN "ServicioCatalogo" s ON s.id = sc."servicioCatalogoId" - WHERE sc."cotizacionId" = $1 AND sc.seleccionado = true - ORDER BY sc.fase, sc.opcion, sc.id""", - cotizacion_id, - ) - - plan = await db.fetchrow( - 'SELECT nivel, precio FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1', - cotizacion_id, - ) - - branding = await _load_branding(db) - - logo_raw = branding.get("logo_base64", "") - logo_mime = None - logo_b64 = None - if logo_raw and ":" in logo_raw: - parts = logo_raw.split(":", 1) - logo_mime = parts[0] - logo_b64 = parts[1] - elif logo_raw: - logo_b64 = logo_raw - - servicios_list = [] - for s in servicios: - ent = s["entregables"] - if isinstance(ent, str): - try: - ent = json.loads(ent) - except (json.JSONDecodeError, TypeError): - ent = [] - servicios_list.append({ - "nombre": s["nombre"] or "Servicio", - "fase": s["fase"], - "tipoPago": s["tipoPago"], - "precio": float(s["precio"]), - "tiempoEntrega": s["tiempoEntrega"], - "entregables": ent or [], - "esPersonalizado": s["esPersonalizado"], - "horas": float(s["horas"]) if s["horas"] is not None else None, - "tarifaHora": float(s["tarifaHora"]) if s["tarifaHora"] is not None else None, - "modeloCobro": s["modeloCobro"], - "montoMinimo": float(s["montoMinimo"]) if s["montoMinimo"] is not None else None, - "horasIncluidas": float(s["horasIncluidas"]) if s["horasIncluidas"] is not None else None, - "opcion": s["opcion"], - }) - - opciones_meta = cot["opcionesMetadata"] - if isinstance(opciones_meta, str): - try: - opciones_meta = json.loads(opciones_meta) - except (json.JSONDecodeError, TypeError): - opciones_meta = None - - plan_nivel = plan["nivel"] if plan else None - - return { - "numero": cot["numero"], - "clienteNombre": cot["cliente_nombre"] or "", - "clienteEmpresa": cot["cliente_empresa"] or "", - "asesorNombre": cot["asesor_nombre"] or "", - "fecha": cot["fecha"], - "vigencia": cot["vigencia"], - "moneda": cot["moneda"], - "tipoCambio": cot["tipoCambio"], - "proyecto": cot["proyecto"], - "esquemaPago": cot["esquemaPago"], - "servicios": servicios_list, - "esDoble": cot["esDoble"], - "opcionesMetadata": opciones_meta, - "planBucefaloNivel": plan_nivel, - "planBucefaloPrecio": float(plan["precio"]) if plan else 0, - "incluirBonos": cot["incluirBonos"], - "colorPrimario": branding.get("color_primario") or "#0400C4", - "colorSecundario": branding.get("color_secundario") or "#0F172A", - "logoBase64": logo_b64, - "logoMime": logo_mime, - "configBancaria": branding, - "razonSocial": branding.get("razon_social") or "Uriel Jareth Consulting", - } - - -# ── PDF ENDPOINTS ────────────────────────────────── - -@router.post("/pdf") -async def export_pdf_draft( - body: ExportDraft, - _auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:borrador")), - db: Connection = Depends(get_db), -): - branding = await _load_branding(db) - pdf_data = _build_pdf_data_from_draft(body, branding) - pdf_bytes = generate_cotizacion_pdf(pdf_data) - - empresa = body.clienteEmpresa or body.clienteNombre or "Cotizacion" - filename = f"{sanitize_filename(empresa)} - BORRADOR.pdf" - - return Response( - content=pdf_bytes, - media_type="application/pdf", - headers={"Content-Disposition": f'attachment; filename="{filename}"'}, - ) - - -@router.get("/pdf/{cotizacion_id}") -async def export_pdf_saved( - cotizacion_id: str, - _auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas")), - db: Connection = Depends(get_db), -): - if es_agente_solo_aceptadas(_auth): - row_est = await db.fetchrow('SELECT estado FROM "Cotizacion" WHERE id = $1', cotizacion_id) - if row_est and row_est["estado"] != "aceptada": - raise HTTPException(status_code=403, detail="Tu clave solo permite exportar cotizaciones aceptadas") - pdf_data = await _build_pdf_data_from_db(db, cotizacion_id) - if not pdf_data: - raise HTTPException(status_code=404, detail="Cotización no encontrada") - - pdf_bytes = generate_cotizacion_pdf(pdf_data) - - empresa = pdf_data["clienteEmpresa"] or pdf_data["clienteNombre"] - filename = f"{sanitize_filename(empresa)} - {sanitize_filename(pdf_data['numero'])}.pdf" - - return Response( - content=pdf_bytes, - media_type="application/pdf", - headers={"Content-Disposition": f'attachment; filename="{filename}"'}, - ) - - -# ── EXCEL ENDPOINTS ──────────────────────────────── - -@router.post("/excel") -async def export_excel_draft( - body: ExportDraft, - _auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:borrador")), - db: Connection = Depends(get_db), -): - branding = await _load_branding(db) - excel_data = _build_pdf_data_from_draft(body, branding) - excel_bytes = generate_cotizacion_excel(excel_data, saved=False) - - empresa = body.clienteEmpresa or body.clienteNombre or "Cotizacion" - filename = f"{sanitize_filename(empresa)} - {sanitize_filename(body.clienteNombre)} - BORRADOR.xlsx" - - return Response( - content=excel_bytes, - media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - headers={"Content-Disposition": f'attachment; filename="{filename}"'}, - ) - - -@router.get("/excel/{cotizacion_id}") -async def export_excel_saved( - cotizacion_id: str, - _auth: dict = Depends(require_scope("cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas")), - db: Connection = Depends(get_db), -): - if es_agente_solo_aceptadas(_auth): - row_est = await db.fetchrow('SELECT estado FROM "Cotizacion" WHERE id = $1', cotizacion_id) - if row_est and row_est["estado"] != "aceptada": - raise HTTPException(status_code=403, detail="Tu clave solo permite exportar cotizaciones aceptadas") - excel_data = await _build_pdf_data_from_db(db, cotizacion_id) - if not excel_data: - raise HTTPException(status_code=404, detail="Cotización no encontrada") - - excel_bytes = generate_cotizacion_excel(excel_data, saved=True) - - empresa = excel_data["clienteEmpresa"] or excel_data["clienteNombre"] - filename = f"{sanitize_filename(empresa)} - {sanitize_filename(excel_data['numero'])}.xlsx" - - return Response( - content=excel_bytes, - media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - headers={"Content-Disposition": f'attachment; filename="{filename}"'}, - ) - - -# ── CSV ENDPOINTS ────────────────────────────────── - -@router.get("/catalogo", response_class=PlainTextResponse) -async def export_catalogo_csv( - _auth: dict = Depends(require_scope("catalogo:leer")), - db: Connection = Depends(get_db), -): - rows = await db.fetch( - """SELECT s.id, s.nombre, s.descripcion, s.fase, s."tipoPago", - s."precioBase", s."tiempoEntrega", s."entregablesDefault", - s.variante, s.orden, c.nombre AS categoria - FROM "ServicioCatalogo" s - LEFT JOIN "Categoria" c ON c.id = s."categoriaId" - WHERE s.activo = true - ORDER BY s.fase, s.orden""" - ) - - buf = io.StringIO() - writer = csv.writer(buf) - writer.writerow([ - "Nombre", "Categoria", "Fase", "Tipo de Pago", "Precio Base", - "Tiempo de Entrega", "Entregables", "Variante", - ]) - for r in rows: - entregables = r["entregablesDefault"] or [] - if isinstance(entregables, list): - entregables = " | ".join(entregables) - elif isinstance(entregables, str): - try: - ent_list = json.loads(entregables) - entregables = " | ".join(ent_list) if isinstance(ent_list, list) else entregables - except (json.JSONDecodeError, TypeError): - pass - writer.writerow([ - r["nombre"], r["categoria"], r["fase"], r["tipoPago"], - r["precioBase"], r["tiempoEntrega"], entregables, r["variante"], - ]) - - return PlainTextResponse( - content=buf.getvalue(), - media_type="text/csv; charset=utf-8", - headers={"Content-Disposition": "attachment; filename=catalogo-servicios.csv"}, - ) - - -@router.get("/catalogo/plantilla", response_class=PlainTextResponse) -async def export_catalogo_template(db: Connection = Depends(get_db)): - cats = await db.fetch( - 'SELECT nombre FROM "Categoria" WHERE activo = true ORDER BY orden' - ) - cat_names = [r["nombre"] for r in cats] - - buf = io.StringIO() - writer = csv.writer(buf) - writer.writerow([ - "nombre", "descripcion", "fase", "tipoPago", - "precioBase", "tiempoEntrega", "entregablesDefault", "variante", "categoria", - ]) - writer.writerow([ - "SEO On-Page", "Optimización on-page para buscadores", "Contenido y SEO", "mensual", - "2900", "7 - 14 dias", "Keyword research | On-page optimization", "", "SEO", - ]) - writer.writerow([ - "", "", "", "", "", "", "", "", "", - ]) - writer.writerow([f"CATEGORIAS: {', '.join(cat_names)}"]) - writer.writerow(["FASES: Auditoria, Setup e Infraestructura, Publicidad y Manejo, Contenido y SEO"]) - writer.writerow(["TIPOS DE PAGO: unico, mensual"]) - - return PlainTextResponse( - content=buf.getvalue(), - media_type="text/csv; charset=utf-8", - headers={"Content-Disposition": "attachment; filename=plantilla-catalogo.csv"}, - ) diff --git a/api/app/routers/financiamiento.py b/api/app/routers/financiamiento.py deleted file mode 100644 index c53e95b..0000000 --- a/api/app/routers/financiamiento.py +++ /dev/null @@ -1,122 +0,0 @@ -from __future__ import annotations - -from fastapi import APIRouter, Depends, HTTPException, status -from asyncpg import Connection - -from app.dependencies import get_db -from app.models.export_ import ( - FinanciamientoRequest, - FinanciamientoResponse, - BonoResponse, - PlanBucefaloResponse, -) -from app.models.common import ErrorResponse -from app.auth import require_scope -from app.services.calculators import ( - calcular_financiamiento, - FINANCIAMIENTO_PLANES, - PLANES_BUCEFALO, -) - -router = APIRouter(prefix="/financiamiento", tags=["Financiamiento"]) - - -class PlanResponse(FinanciamientoResponse): - meses: int - tasa: float - comision: float - - -@router.get("/planes", response_model=list[PlanResponse]) -async def get_planes(_auth: dict = Depends(require_scope("catalogo:leer"))): - return [ - PlanResponse( - meses=p["meses"], - tasa=p["tasa"], - comision=p["comision"], - **calcular_financiamiento(1000, p["meses"], p["tasa"], p["comision"]), - ) - for p in sorted(FINANCIAMIENTO_PLANES, key=lambda x: x["meses"]) - ] - - -@router.post( - "/calcular", - response_model=FinanciamientoResponse, - responses={400: {"model": ErrorResponse}}, -) -async def calcular( - body: FinanciamientoRequest, - _auth: dict = Depends(require_scope("catalogo:leer")), -): - plan = next((p for p in FINANCIAMIENTO_PLANES if p["meses"] == body.meses), None) - if not plan: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"No financing plan available for {body.meses} months", - ) - if body.monto < plan["montoMinimo"]: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Minimum amount for {body.meses} months is ${plan['montoMinimo']}", - ) - - result = calcular_financiamiento(body.monto, body.meses, plan["tasa"], plan["comision"]) - return FinanciamientoResponse( - **result, - meses=body.meses, - tasa=plan["tasa"], - comision=plan["comision"], - ) - - -@router.get( - "/simulacion/{cotizacion_id}", - response_model=list[FinanciamientoResponse], - responses={404: {"model": ErrorResponse}}, -) -async def simulacion( - cotizacion_id: str, - _auth: dict = Depends(require_scope("catalogo:leer")), - db: Connection = Depends(get_db), -): - cot = await db.fetchrow( - 'SELECT id FROM "Cotizacion" WHERE id = $1', cotizacion_id - ) - if not cot: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Cotización not found", - ) - - rows = await db.fetch( - 'SELECT precio FROM "ServicioCotizado" WHERE "cotizacionId" = $1 AND seleccionado = true', - cotizacion_id, - ) - total = sum(float(r["precio"]) for r in rows) - - plan_buc = await db.fetchrow( - 'SELECT precio FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1', - cotizacion_id, - ) - if plan_buc: - total += float(plan_buc["precio"]) - - if total <= 0: - return [] - - results = [] - for plan in FINANCIAMIENTO_PLANES: - if total < plan["montoMinimo"]: - continue - result = calcular_financiamiento(total, plan["meses"], plan["tasa"], plan["comision"]) - results.append( - FinanciamientoResponse( - **result, - meses=plan["meses"], - tasa=plan["tasa"], - comision=plan["comision"], - ) - ) - - return results diff --git a/api/app/routers/health.py b/api/app/routers/health.py deleted file mode 100644 index b3a01c8..0000000 --- a/api/app/routers/health.py +++ /dev/null @@ -1,42 +0,0 @@ -from datetime import datetime, timezone - -from fastapi import APIRouter - -from app.database import get_pool -from app.models.common import ErrorResponse, HealthResponse, APIInfoResponse - -router = APIRouter(tags=["Health"]) - - -@router.get("/health", response_model=HealthResponse) -async def health_check(): - pool = await get_pool() - try: - async with pool.acquire() as conn: - await conn.execute("SELECT 1") - db_status = "connected" - except Exception: - db_status = "disconnected" - - return HealthResponse( - status="ok", - timestamp=datetime.now(timezone.utc).isoformat(), - database=db_status, - ) - - -@router.get("/api-info", response_model=APIInfoResponse) -async def api_info(): - return APIInfoResponse( - name="Cotizador — Uriel Jareth Consulting API", - version="1.0.0", - description="API para el sistema de cotizaciones de Uriel Jareth Consulting", - capabilities=[ - "Gestión de cotizaciones", - "Catálogo de servicios", - "Planes Bucéfalo CRM", - "Exportación PDF/Excel", - "Autenticación JWT", - "Financiamiento Openpay", - ], - ) diff --git a/api/app/routers/import_.py b/api/app/routers/import_.py deleted file mode 100644 index fe2823e..0000000 --- a/api/app/routers/import_.py +++ /dev/null @@ -1,113 +0,0 @@ -from __future__ import annotations - -import csv -import io - -from fastapi import APIRouter, Depends, File, UploadFile -from asyncpg import Connection - -from app.dependencies import get_db -from app.auth import require_staff_human - -router = APIRouter(prefix="/import", tags=["Import"]) - -REQUIRED_COLUMNS = {"nombre", "fase", "tipoPago", "precioBase", "categoria"} - - -@router.post("/catalogo") -async def import_catalogo_csv( - file: UploadFile = File(...), - _auth: dict = Depends(require_staff_human), - db: Connection = Depends(get_db), -): - content = await file.read() - text = content.decode("utf-8-sig") - reader = csv.DictReader(io.StringIO(text)) - - if not reader.fieldnames or not REQUIRED_COLUMNS.issubset(set(reader.fieldnames)): - missing = REQUIRED_COLUMNS - set(reader.fieldnames or []) - return { - "creados": 0, - "omitidos": 0, - "errores": [f"Missing required columns: {', '.join(missing)}"], - } - - categorias = await db.fetch('SELECT id, nombre FROM "Categoria" WHERE activo = true') - cat_map = {r["nombre"]: r["id"] for r in categorias} - - existing = await db.fetch('SELECT nombre FROM "ServicioCatalogo" WHERE activo = true') - existing_names = {r["nombre"] for r in existing} - - creados = 0 - omitidos = 0 - errores: list[str] = [] - - async with db.transaction(): - for i, row in enumerate(reader, start=2): - nombre = (row.get("nombre") or "").strip() - if not nombre: - omitidos += 1 - continue - - if nombre in existing_names: - omitidos += 1 - continue - - cat_nombre = (row.get("categoria") or "").strip() - cat_id = cat_map.get(cat_nombre) - if not cat_id: - errores.append(f"Row {i}: category '{cat_nombre}' not found") - continue - - try: - fase = int(row.get("fase", "0")) - if fase not in (0, 1, 2, 3): - raise ValueError - except (ValueError, TypeError): - errores.append(f"Row {i}: invalid fase '{row.get('fase')}'") - continue - - tipo_pago = (row.get("tipoPago") or "").strip() - if tipo_pago not in ("unico", "mensual"): - errores.append(f"Row {i}: invalid tipoPago '{tipo_pago}'") - continue - - try: - precio = float(row.get("precioBase", "0")) - except (ValueError, TypeError): - errores.append(f"Row {i}: invalid precioBase '{row.get('precioBase')}'") - continue - - tiempo = (row.get("tiempoEntrega") or "7 - 14 dias").strip() - variante = (row.get("variante") or "").strip() or None - try: - orden = int(row.get("orden", "0")) - except (ValueError, TypeError): - orden = 0 - - entregables_raw = (row.get("entregablesDefault") or "").strip() - entregables = [e.strip() for e in entregables_raw.split(";") if e.strip()] if entregables_raw else [] - - await db.execute( - """ - INSERT INTO "ServicioCatalogo" - (id, nombre, descripcion, fase, "tipoPago", "precioBase", - "tiempoEntrega", "entregablesDefault", "categoriaId", - variante, orden, activo, "createdAt", "updatedAt") - VALUES (gen_random_uuid(), $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, true, now(), now()) - """, - nombre, - (row.get("descripcion") or "").strip() or None, - fase, - tipo_pago, - precio, - tiempo, - entregables if entregables else None, - cat_id, - variante, - orden, - ) - existing_names.add(nombre) - creados += 1 - - return {"creados": creados, "omitidos": omitidos, "errores": errores} diff --git a/api/app/routers/paquetes.py b/api/app/routers/paquetes.py deleted file mode 100644 index 6fe4365..0000000 --- a/api/app/routers/paquetes.py +++ /dev/null @@ -1,442 +0,0 @@ -from __future__ import annotations - -from datetime import datetime, timezone - -from fastapi import APIRouter, Depends, HTTPException, status - -from app.database import get_pool -from app.dependencies import get_db -from app.auth import require_scope, require_staff_human -from app.models.paquete import ( - PaqueteCreate, - PaqueteUpdate, - PaqueteResponse, - FasePaqueteResponse, - ManageAction, -) -from app.models.common import ErrorResponse, OkResponse - -router = APIRouter(prefix="/paquetes", tags=["Paquetes"]) - - -async def _build_paquetes_responses(conn, paquete_rows: list[dict], excluir_solo_admin: bool = False) -> list[dict]: - """Build PaqueteResponse dicts for several paquetes with 2 queries in total - (instead of 1 + N fases per paquete).""" - if not paquete_rows: - return [] - - paquete_ids = [p["id"] for p in paquete_rows] - fases_rows = await conn.fetch( - 'SELECT id, "paqueteId", nombre, orden, "createdAt", "updatedAt"' - ' FROM "FasePaquete" WHERE "paqueteId" = ANY($1::text[]) ORDER BY orden ASC', - paquete_ids, - ) - - fase_ids = [f["id"] for f in fases_rows] - servicios_rows = [] - if fase_ids: - servicios_rows = await conn.fetch( - 'SELECT sp.id, sp."servicioCatalogoId", sp."fasePaqueteId",' - ' sp."createdAt", sp."updatedAt",' - ' sc.id AS "sc_id", sc.nombre AS "sc_nombre", sc.descripcion AS "sc_descripcion",' - ' sc.fase AS "sc_fase", sc."tipoPago" AS "sc_tipoPago",' - ' sc."precioBase" AS "sc_precioBase", sc."tiempoEntrega" AS "sc_tiempoEntrega",' - ' sc."entregablesDefault" AS "sc_entregablesDefault",' - ' sc."categoriaId" AS "sc_categoriaId", sc.variante AS "sc_variante",' - ' sc.activo AS "sc_activo", sc."soloAdmin" AS "sc_soloAdmin", sc.orden AS "sc_orden",' - ' sc."createdAt" AS "sc_createdAt", sc."updatedAt" AS "sc_updatedAt",' - ' cat.id AS "cat_id", cat.nombre AS "cat_nombre", cat.descripcion AS "cat_descripcion",' - ' cat.color AS "cat_color", cat.activo AS "cat_activo", cat.orden AS "cat_orden",' - ' cat."createdAt" AS "cat_createdAt", cat."updatedAt" AS "cat_updatedAt"' - ' FROM "ServicioPaquete" sp' - ' JOIN "ServicioCatalogo" sc ON sc.id = sp."servicioCatalogoId"' - ' LEFT JOIN "Categoria" cat ON cat.id = sc."categoriaId"' - ' WHERE sp."fasePaqueteId" = ANY($1::text[])', - fase_ids, - ) - - servicios_por_fase: dict[str, list[dict]] = {} - for s in servicios_rows: - if excluir_solo_admin and s.get("sc_soloAdmin"): - continue - cat = None - if s["cat_id"]: - cat = { - "id": s["cat_id"], - "nombre": s["cat_nombre"], - "descripcion": s["cat_descripcion"], - "color": s["cat_color"], - "activo": s["cat_activo"], - "orden": s["cat_orden"], - "createdAt": s["cat_createdAt"], - "updatedAt": s["cat_updatedAt"], - } - servicios_por_fase.setdefault(s["fasePaqueteId"], []).append({ - "id": s["id"], - "servicioCatalogoId": s["servicioCatalogoId"], - "fasePaqueteId": s["fasePaqueteId"], - "createdAt": s["createdAt"], - "updatedAt": s["updatedAt"], - "servicio": { - "id": s["sc_id"], - "nombre": s["sc_nombre"], - "descripcion": s["sc_descripcion"], - "fase": s["sc_fase"], - "tipoPago": s["sc_tipoPago"], - "precioBase": s["sc_precioBase"], - "tiempoEntrega": s["sc_tiempoEntrega"], - "entregablesDefault": s["sc_entregablesDefault"], - "categoriaId": s["sc_categoriaId"], - "variante": s["sc_variante"], - "activo": s["sc_activo"], - "soloAdmin": bool(s.get("sc_soloAdmin", False)), - "orden": s["sc_orden"], - "createdAt": s["sc_createdAt"], - "updatedAt": s["sc_updatedAt"], - "categoriaRel": cat, - }, - }) - - fases_por_paquete: dict[str, list[dict]] = {} - for fase in fases_rows: - fases_por_paquete.setdefault(fase["paqueteId"], []).append({ - "id": fase["id"], - "paqueteId": fase["paqueteId"], - "nombre": fase["nombre"], - "orden": fase["orden"], - "createdAt": fase["createdAt"], - "updatedAt": fase["updatedAt"], - "servicios": servicios_por_fase.get(fase["id"], []), - }) - - return [ - { - "id": p["id"], - "nombre": p["nombre"], - "descripcion": p["descripcion"], - "activo": p["activo"], - "createdAt": p["createdAt"], - "updatedAt": p["updatedAt"], - "fases": fases_por_paquete.get(p["id"], []), - } - for p in paquete_rows - ] - - -async def _build_paquete_response(conn, paquete_row: dict, excluir_solo_admin: bool = False) -> dict: - """Build a PaqueteResponse dict with nested fases and servicios.""" - results = await _build_paquetes_responses(conn, [paquete_row], excluir_solo_admin=excluir_solo_admin) - return results[0] - - -@router.get("", response_model=list[PaqueteResponse]) -async def list_paquetes( - _auth: dict = Depends(require_scope("catalogo:leer")), - conn=Depends(get_db), -): - rows = await conn.fetch( - 'SELECT id, nombre, descripcion, activo, "createdAt", "updatedAt"' - ' FROM "Paquete" WHERE activo = true ORDER BY "createdAt" ASC' - ) - excluir = _auth.get("auth_type") == "agent" - return await _build_paquetes_responses(conn, [dict(row) for row in rows], excluir_solo_admin=excluir) - - -@router.post( - "", - response_model=PaqueteResponse, - status_code=status.HTTP_201_CREATED, -) -async def create_paquete( - body: PaqueteCreate, - _auth: dict = Depends(require_staff_human), - conn=Depends(get_db), -): - now = datetime.now(timezone.utc) - paquete_row = await conn.fetchrow( - 'INSERT INTO "Paquete" (id, nombre, descripcion, "createdAt", "updatedAt")' - " VALUES (gen_random_uuid(), $1, $2, $3, $3)" - ' RETURNING id, nombre, descripcion, activo, "createdAt", "updatedAt"', - body.nombre, - body.descripcion, - now, - ) - - paquete_id = paquete_row["id"] - for fase in body.fases: - await conn.execute( - 'INSERT INTO "FasePaquete" (id, "paqueteId", nombre, orden, "createdAt", "updatedAt")' - " VALUES (gen_random_uuid(), $1, $2, $3, $4, $4)", - paquete_id, - fase.nombre, - fase.orden, - now, - ) - - return await _build_paquete_response(conn, dict(paquete_row)) - - -@router.get( - "/{paquete_id}", - response_model=PaqueteResponse, - responses={404: {"model": ErrorResponse}}, -) -async def get_paquete( - paquete_id: str, - _auth: dict = Depends(require_scope("catalogo:leer")), - conn=Depends(get_db), -): - row = await conn.fetchrow( - 'SELECT id, nombre, descripcion, activo, "createdAt", "updatedAt"' - ' FROM "Paquete" WHERE id = $1', - paquete_id, - ) - if not row: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Paquete no encontrado", - ) - excluir = _auth.get("auth_type") == "agent" - return await _build_paquete_response(conn, dict(row), excluir_solo_admin=excluir) - - -@router.put( - "/{paquete_id}", - response_model=PaqueteResponse, - responses={404: {"model": ErrorResponse}}, -) -async def update_paquete( - paquete_id: str, - body: PaqueteUpdate, - _auth: dict = Depends(require_staff_human), - conn=Depends(get_db), -): - existing = await conn.fetchrow( - 'SELECT id FROM "Paquete" WHERE id = $1', paquete_id - ) - if not existing: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Paquete no encontrado", - ) - - updates: list[str] = [] - params: list = [] - idx = 1 - - if body.nombre is not None: - updates.append(f"nombre = ${idx}") - params.append(body.nombre) - idx += 1 - if body.descripcion is not None: - updates.append(f"descripcion = ${idx}") - params.append(body.descripcion) - idx += 1 - if body.activo is not None: - updates.append(f"activo = ${idx}") - params.append(body.activo) - idx += 1 - - if not updates: - row = await conn.fetchrow( - 'SELECT id, nombre, descripcion, activo, "createdAt", "updatedAt"' - ' FROM "Paquete" WHERE id = $1', - paquete_id, - ) - return await _build_paquete_response(conn, dict(row)) - - updates.append(f'"updatedAt" = ${idx}') - params.append(datetime.now(timezone.utc)) - idx += 1 - - params.append(paquete_id) - row = await conn.fetchrow( - f'UPDATE "Paquete" SET {", ".join(updates)} WHERE id = ${idx}' - ' RETURNING id, nombre, descripcion, activo, "createdAt", "updatedAt"', - *params, - ) - return await _build_paquete_response(conn, dict(row)) - - -@router.delete( - "/{paquete_id}", - response_model=OkResponse, - responses={404: {"model": ErrorResponse}}, -) -async def delete_paquete( - paquete_id: str, - _auth: dict = Depends(require_staff_human), - conn=Depends(get_db), -): - result = await conn.execute( - 'DELETE FROM "Paquete" WHERE id = $1', paquete_id - ) - if result == "DELETE 0": - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Paquete no encontrado", - ) - return OkResponse(ok=True) - - -@router.post( - "/{paquete_id}/manage", - responses={400: {"model": ErrorResponse}, 404: {"model": ErrorResponse}}, -) -async def manage_paquete( - paquete_id: str, - body: ManageAction, - _auth: dict = Depends(require_staff_human), - conn=Depends(get_db), -): - paquete = await conn.fetchrow( - 'SELECT id FROM "Paquete" WHERE id = $1', paquete_id - ) - if not paquete: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Paquete no encontrado", - ) - - now = datetime.now(timezone.utc) - action = body.action - - if action == "addFase": - if not body.nombre: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="El campo 'nombre' es requerido para addFase", - ) - row = await conn.fetchrow( - 'INSERT INTO "FasePaquete" (id, "paqueteId", nombre, orden, "createdAt", "updatedAt")' - " VALUES (gen_random_uuid(), $1, $2, $3, $4, $4)" - ' RETURNING id, "paqueteId", nombre, orden, "createdAt", "updatedAt"', - paquete_id, - body.nombre, - body.orden or 0, - now, - ) - return dict(row), status.HTTP_201_CREATED - - if action == "updateFase": - if not body.faseId: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="El campo 'faseId' es requerido para updateFase", - ) - updates: list[str] = [] - params: list = [] - idx = 1 - if body.nombre is not None: - updates.append(f"nombre = ${idx}") - params.append(body.nombre) - idx += 1 - if body.orden is not None: - updates.append(f"orden = ${idx}") - params.append(body.orden) - idx += 1 - if not updates: - row = await conn.fetchrow( - 'SELECT id, "paqueteId", nombre, orden, "createdAt", "updatedAt"' - ' FROM "FasePaquete" WHERE id = $1 AND "paqueteId" = $2', - body.faseId, - paquete_id, - ) - if not row: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Fase no encontrada", - ) - return dict(row) - updates.append(f'"updatedAt" = ${idx}') - params.append(now) - idx += 1 - params.extend([body.faseId, paquete_id]) - row = await conn.fetchrow( - f'UPDATE "FasePaquete" SET {", ".join(updates)}' - f" WHERE id = ${idx} AND \"paqueteId\" = ${idx + 1}" - ' RETURNING id, "paqueteId", nombre, orden, "createdAt", "updatedAt"', - *params, - ) - if not row: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Fase no encontrada", - ) - return dict(row) - - if action == "deleteFase": - if not body.faseId: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="El campo 'faseId' es requerido para deleteFase", - ) - result = await conn.execute( - 'DELETE FROM "FasePaquete" WHERE id = $1 AND "paqueteId" = $2', - body.faseId, - paquete_id, - ) - if result == "DELETE 0": - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Fase no encontrada", - ) - return {"ok": True} - - if action == "addServicio": - if not body.servicioCatalogoId or not body.fasePaqueteId: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Los campos 'servicioCatalogoId' y 'fasePaqueteId' son requeridos para addServicio", - ) - fase = await conn.fetchrow( - 'SELECT id FROM "FasePaquete" WHERE id = $1 AND "paqueteId" = $2', - body.fasePaqueteId, - paquete_id, - ) - if not fase: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Fase no encontrada en este paquete", - ) - try: - row = await conn.fetchrow( - 'INSERT INTO "ServicioPaquete" (id, "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt")' - " VALUES (gen_random_uuid(), $1, $2, $3, $3)" - ' RETURNING id, "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt"', - body.servicioCatalogoId, - body.fasePaqueteId, - now, - ) - except Exception as e: - if "unique" in str(e).lower() or "duplicate" in str(e).lower(): - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="Este servicio ya está asignado a esta fase", - ) - raise - return dict(row), status.HTTP_201_CREATED - - if action == "removeServicio": - if not body.servicioCatalogoId or not body.fasePaqueteId: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Los campos 'servicioCatalogoId' y 'fasePaqueteId' son requeridos para removeServicio", - ) - result = await conn.execute( - 'DELETE FROM "ServicioPaquete"' - ' WHERE "servicioCatalogoId" = $1 AND "fasePaqueteId" = $2', - body.servicioCatalogoId, - body.fasePaqueteId, - ) - if result == "DELETE 0": - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Servicio no encontrado en esta fase", - ) - return {"ok": True} - - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Acción desconocida: '{action}'. Acciones válidas: addFase, updateFase, deleteFase, addServicio, removeServicio", - ) diff --git a/api/app/services/__init__.py b/api/app/services/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/api/app/services/calculators.py b/api/app/services/calculators.py deleted file mode 100644 index e63b8d3..0000000 --- a/api/app/services/calculators.py +++ /dev/null @@ -1,208 +0,0 @@ -from __future__ import annotations - -import re -from datetime import date, datetime, timedelta - - -IVA_RATE = 0.16 - -# Tarifa por hora sugerida para partidas personalizadas (Hora Centinela). -TARIFA_HORA_DEFAULT = 700 - -# Modelos de cobro de una partida (espejo exacto de src/lib/calculators.ts). -MODELOS_COBRO: dict[str, str] = { - "fijo": "Precio fijo", - "horas": "Por horas", - "retainer": "Retainer (minimo + adicionales)", - "demanda": "Bajo demanda / por hora", -} - -# Doble propuesta: cada partida va en la Opcion 1, la 2 o en ambas (espejo del TS). -OPCIONES = ("1", "2", "ambas") - -FASES: dict[int, str] = { - 0: "FASE 0 - Auditoria / Acompanamiento", - 1: "FASE 1 - Setup e Infraestructura", - 2: "FASE 2 - Publicidad y Manejo", - 3: "FASE 3 - Contenido y SEO", -} - -FASES_SHORT: dict[int, str] = { - 0: "FASE 0 - Auditoria", - 1: "FASE 1 - Setup e Infraestructura", - 2: "FASE 2 - Publicidad y Manejo", - 3: "FASE 3 - Contenido y SEO", -} - -PLANES_BUCEFALO = [ - {"nivel": "basico", "label": "Basico", "precio": 1000}, - {"nivel": "estandar", "label": "Estandar", "precio": 3500}, - {"nivel": "premium", "label": "Premium", "precio": 4500}, - {"nivel": "empresarial", "label": "Empresarial", "precio": 7500}, -] - -ESTADOS_COTIZACION = ["borrador", "aprobada", "enviada", "aceptada", "rechazada", "vencida"] - -FINANCIAMIENTO_PLANES = [ - {"meses": 3, "tasa": 0.077, "comision": 2.5, "montoMinimo": 300}, - {"meses": 6, "tasa": 0.107, "comision": 2.5, "montoMinimo": 600}, - {"meses": 9, "tasa": 0.137, "comision": 2.5, "montoMinimo": 900}, - {"meses": 12, "tasa": 0.167, "comision": 2.5, "montoMinimo": 1200}, -] - -BONOS = [ - {"id": "bono-1", "numero": 1, "titulo": "Servicio Centinela Web", "descripcion": "Monitoreo web 30 min/mes", "activo": True}, - {"id": "bono-2", "numero": 2, "titulo": "Workshop Buyer Persona", "descripcion": "Taller de definición de buyer persona", "activo": True}, - {"id": "bono-3", "numero": 3, "titulo": "Workshop Propuesta de Valor", "descripcion": "Taller de propuesta de valor", "activo": True}, - {"id": "bono-4", "numero": 4, "titulo": "Membresia Premium", "descripcion": "Membresía premium por 1 año", "activo": True}, - {"id": "bono-5", "numero": 5, "titulo": "Mes Gratis Bucefalo CRM", "descripcion": "Un mes gratis del CRM Bucefalo", "activo": True}, - {"id": "bono-6", "numero": 6, "titulo": "Script de Ventas", "descripcion": "Script de ventas con 100+ complementos", "activo": True}, -] - - -def _r2(n: float) -> float: - return round(n + 1e-12, 2) if n >= 0 else -round(-n + 1e-12, 2) - - -def calcular_precio_horas(horas: float, tarifa_hora: float) -> float: - return _r2((horas or 0) * (tarifa_hora or 0)) - - -def describir_retainer(monto_minimo: float, horas_incluidas: float, tarifa_hora: float) -> str: - """Texto descriptivo de un retainer (espejo de describirRetainer en TS).""" - partes = [f"{format_currency(monto_minimo or 0)}/mes"] - if horas_incluidas: - partes.append(f"incluye {horas_incluidas:g} hr") - if tarifa_hora: - partes.append(f"adicional {format_currency(tarifa_hora)}/hr (se factura aparte)") - return " · ".join(partes) - - -def detalle_modelo(serv: dict) -> str: - """Sub-linea de desglose por modelo de cobro para PDF/Excel.""" - modelo = serv.get("modeloCobro") - if modelo == "retainer": - return describir_retainer( - serv.get("montoMinimo") or 0, - serv.get("horasIncluidas") or 0, - serv.get("tarifaHora") or 0, - ) - if modelo == "demanda": - return f"{format_currency(serv.get('tarifaHora') or 0)}/hr · segun consumo" - horas = serv.get("horas") - tarifa = serv.get("tarifaHora") - if (modelo == "horas" or serv.get("esPersonalizado")) and horas and tarifa: - return f"{horas:g} h x {format_currency(tarifa)}/hr" - return "" - - -def calcular_totales_opcion(servicios: list[dict], opcion: str) -> dict: - """Totales de una opcion: suma sus partidas + las marcadas 'ambas'. - - Espejo exacto de calcularTotalesOpcion en TS. Respeta la regla de retainer: - el total usa precio, no horas x tarifa. Las horas son informativas. - """ - rel = [s for s in servicios if s.get("opcion") == "ambas" or s.get("opcion") == opcion] - total_unico = sum((s.get("precio") or 0) for s in rel if s.get("tipoPago") == "unico") - total_mensual = sum((s.get("precio") or 0) for s in rel if s.get("tipoPago") == "mensual") - horas = sum((s.get("horas") or 0) for s in rel) - return { - "totalUnico": _r2(total_unico), - "totalMensual": _r2(total_mensual), - "horas": _r2(horas), - } - - -def calcular_totales_cotizacion( - servicios: list[dict], - incluir_iva: bool = True, -) -> dict: - """Espejo exacto de calcularTotalesCotizacion en src/lib/calculators.ts.""" - activos = [s for s in servicios if s.get("seleccionado", True) is not False] - subtotal_unico = _r2(sum((s.get("precio") or 0) for s in activos if s.get("tipoPago") == "unico")) - subtotal_mensual = _r2(sum((s.get("precio") or 0) for s in activos if s.get("tipoPago") == "mensual")) - - iva_unico = _r2(subtotal_unico * IVA_RATE) if incluir_iva else 0.0 - iva_mensual = _r2(subtotal_mensual * IVA_RATE) if incluir_iva else 0.0 - - total_unico = _r2(subtotal_unico + iva_unico) - total_mensual = _r2(subtotal_mensual + iva_mensual) - - return { - "subtotalUnico": subtotal_unico, - "subtotalMensual": subtotal_mensual, - "ivaUnico": iva_unico, - "ivaMensual": iva_mensual, - "totalUnico": total_unico, - "totalMensual": total_mensual, - "totalPrimerAnio": _r2(total_unico + total_mensual * 12), - "incluyeIva": incluir_iva, - } - - -def con_iva(monto: float, incluir_iva: bool = True) -> float: - return _r2((monto or 0) * (1 + IVA_RATE if incluir_iva else 1)) - - -def bucefalo_precio(nivel: str) -> float: - for p in PLANES_BUCEFALO: - if p["nivel"] == nivel: - return float(p["precio"]) - return 0.0 - - -def calcular_vigencia(fecha: datetime | date) -> datetime: - """Suma exactamente 15 dias habiles (lunes a viernes), espejo de calculators.ts.""" - if isinstance(fecha, datetime): - vigencia = fecha.replace() - else: - vigencia = datetime.combine(fecha, datetime.min.time()) - dias_habiles = 0 - while dias_habiles < 15: - vigencia = vigencia + timedelta(days=1) - if vigencia.weekday() < 5: - dias_habiles += 1 - return vigencia - - -def calcular_financiamiento( - monto: float, - meses: int, - tasa: float, - comision: float, - iva: float = IVA_RATE, -) -> dict: - comision_total = (monto * comision) / 100 - monto_con_comision = monto + comision_total - pago_mensual = monto_con_comision * (1 + tasa) / meses - iva_mensual = pago_mensual * iva - total_mensual = pago_mensual + iva_mensual - return { - "pagoMensual": _r2(pago_mensual), - "ivaMensual": _r2(iva_mensual), - "totalMensual": _r2(total_mensual), - "comisionTotal": _r2(comision_total), - "granTotal": _r2(total_mensual * meses), - } - - -def generar_numero_cotizacion(iniciales: str, secuencia: int) -> str: - now = datetime.now() - yy = str(now.year)[-2:] - mm = f"{now.month:02d}" - seq = f"{secuencia:03d}" - return f"UJ{yy}{mm}{iniciales}{seq}" - - -def sanitize_filename(name: str) -> str: - name = re.sub(r"[^\w\s.\-]", "", name) - name = re.sub(r"\s+", " ", name) - return name.strip() - - -def format_currency(amount: float) -> str: - return f"${amount:,.2f}" - - -def format_date(d: datetime | date) -> str: - return f"{d.day:02d}/{d.month:02d}/{d.year}" diff --git a/api/app/services/excel_generator.py b/api/app/services/excel_generator.py deleted file mode 100644 index b9aeebc..0000000 --- a/api/app/services/excel_generator.py +++ /dev/null @@ -1,531 +0,0 @@ -"""Excel Generator for Cotizador — Uriel Jareth Consulting — port of src/lib/excel-builder.ts using openpyxl. - -Mantiene paridad de layout con el builder de TypeScript: mismas columnas, merges, -celdas dinámicas (wrapText + altura calculada) para que el texto nunca se salga. -""" - -from __future__ import annotations - -import io -import math -import re -from datetime import datetime -from typing import Any - -from openpyxl import Workbook -from openpyxl.styles import Alignment, Border, Font, PatternFill, Side -from openpyxl.utils import column_index_from_string, get_column_letter -from openpyxl.worksheet.worksheet import Worksheet - -from app.services.calculators import bucefalo_precio, detalle_modelo, calcular_totales_opcion, format_currency - -FASES_MAP = {0: "FASE 0", 1: "FASE 1", 2: "FASE 2", 3: "FASE 3"} - - -def _argb(hex_color: str, alpha: str = "FF") -> str: - h = hex_color.lstrip("#") - if len(h) > 6: - h = h[:6] - return f"{alpha}{h.upper()}" - - -def _thin_border(color: str = "FFD1D5DB") -> Border: - side = Side(style="thin", color=color) - return Border(top=side, left=side, bottom=side, right=side) - - -def _sanitize_sheet_name(name: str) -> str: - name = (name or "Servicio")[:31] - return re.sub(r"[/\\*?\[\]:]", "", name) or "Servicio" - - -def _set_col_widths(ws: Worksheet, widths: list[tuple[str, float]]): - for col_letter, width in widths: - ws.column_dimensions[col_letter].width = width - - -def _merged_width(widths: dict[str, float], start_col: str, end_col: str) -> float: - """Suma de anchos (unidades de carácter de Excel) entre dos columnas, inclusive.""" - start = column_index_from_string(start_col) - end = column_index_from_string(end_col) - return sum(widths.get(get_column_letter(c), 8) for c in range(start, end + 1)) - - -def _estimate_row_height(text: str, width_chars: float, font_size: int = 10) -> float: - """Altura (pt) que necesita una fila para mostrar `text` envuelto en `width_chars`.""" - cpl = max(8, int(width_chars)) - if font_size <= 10: - line_h = 14.0 - elif font_size <= 11: - line_h = 15.5 - elif font_size <= 12: - line_h = 17.0 - else: - line_h = 20.0 - lines = 0 - for seg in str(text or "").split("\n"): - lines += max(1, math.ceil(len(seg) / cpl)) - return max(16.0, round(lines * line_h + 4)) - - -def _set_wrapped( - ws: Worksheet, - row: int, - col: str, - text: str, - width_chars: float, - font_size: int = 10, - horizontal: str = "left", - vertical: str = "top", -): - """Marca la celda como envolvente y agranda la fila si el texto lo requiere.""" - cell = ws[f"{col}{row}"] - cell.alignment = Alignment(wrap_text=True, vertical=vertical, horizontal=horizontal) - needed = _estimate_row_height(text, width_chars, font_size) - current = ws.row_dimensions[row].height or 0 - if needed > current: - ws.row_dimensions[row].height = needed - - -def generate_cotizacion_excel(data: dict[str, Any], saved: bool = False) -> bytes: - """Generate a multi-sheet Excel workbook for a quotation. - - Args: - data: dict with quotation data (same as PDF generator) - saved: if True, uses real quotation number instead of "BORRADOR" - """ - config_color = data.get("colorPrimario") or "#0400C4" - PRIMARY = _argb(config_color) - PRIMARY_LIGHT = _argb(config_color, alpha="18") - SECONDARY = _argb(data.get("colorSecundario") or "#0F172A") - WHITE = "FFFFFFFF" - LIGHT_BG = "FFF8FAFC" - MUTED = "FF64748B" - BORDER_COLOR = "FFE2E8F0" - - header_font = Font(bold=True, size=10, name="Calibri", color=WHITE) - label_font = Font(bold=True, size=10, name="Calibri", color=MUTED) - value_font = Font(size=10, name="Calibri") - bold_font = Font(bold=True, size=10, name="Calibri") - total_font = Font(bold=True, size=11, name="Calibri") - small_font = Font(italic=True, size=9, name="Calibri", color=MUTED) - fase_font = Font(bold=True, size=11, name="Calibri", color=PRIMARY) - iva_font = Font(italic=False, size=9, name="Calibri", color=MUTED) - - primary_fill = PatternFill(start_color=PRIMARY, end_color=PRIMARY, fill_type="solid") - primary_light_fill = PatternFill(start_color=PRIMARY_LIGHT, end_color=PRIMARY_LIGHT, fill_type="solid") - secondary_fill = PatternFill(start_color=SECONDARY, end_color=SECONDARY, fill_type="solid") - light_fill = PatternFill(start_color=LIGHT_BG, end_color=LIGHT_BG, fill_type="solid") - white_fill = PatternFill(start_color=WHITE, end_color=WHITE, fill_type="solid") - - razon_social = data.get("razonSocial") or "Uriel Jareth Consulting" - cliente_nombre = data.get("clienteNombre", "") - cliente_empresa = data.get("clienteEmpresa", "") - asesor_nombre = data.get("asesorNombre", "") - fecha = data.get("fecha", datetime.now()) - vigencia = data.get("vigencia", datetime.now()) - moneda = data.get("moneda", "MXN") - tipo_cambio = data.get("tipoCambio", "NA") - proyecto = data.get("proyecto", "MKT Digital") - esquema = data.get("esquemaPago", "Pago Unico/Mensual") - servicios = data.get("servicios", []) - plan_nivel = data.get("planBucefaloNivel") - plan_precio = data.get("planBucefaloPrecio") - numero_label = data.get("numero", "BORRADOR") if saved else "BORRADOR" - - wb = Workbook() - wb.properties.creator = "Cotizador — Uriel Jareth Consulting" - - # ═══════════════════════════════════════════════════════════════════════════ - # HOJA RESUMEN - # ═══════════════════════════════════════════════════════════════════════════ - ws = wb.active - ws.title = "HOJA RESUMEN" - ws.sheet_view.showGridLines = False - - resumen_widths = { - "A": 3, "B": 18, "C": 26, "D": 13, "E": 16, - "F": 22, "G": 6, "H": 6, "I": 6, "J": 6, "K": 16, - } - _set_col_widths(ws, list(resumen_widths.items())) - - # Banner - ws.merge_cells("B2:K2") - cell = ws["B2"] - cell.value = razon_social - cell.font = Font(bold=True, size=16, name="Calibri", color=WHITE) - cell.alignment = Alignment(vertical="center") - for col in range(1, 12): - ws.cell(row=2, column=col).fill = primary_fill - ws.row_dimensions[2].height = 28 - - ws.merge_cells("B3:K3") - cell = ws["B3"] - cell.value = numero_label - cell.font = Font(bold=True, size=11, name="Calibri", color=WHITE) - cell.alignment = Alignment(vertical="center") - for col in range(1, 12): - ws.cell(row=3, column=col).fill = secondary_fill - - # Info section - info_start = 5 - info_rows = [ - [("B", "En atencion a:"), ("C", cliente_nombre), ("E", "Empresa:"), ("F", cliente_empresa or "—")], - [("B", "Proyecto:"), ("C", proyecto), ("E", "Moneda:"), ("F", moneda)], - [("B", "Asesor:"), ("C", asesor_nombre), ("E", "Tipo de Cambio:"), ("F", tipo_cambio)], - [("B", "Fecha:"), ("C", ""), ("E", "Esquema de Pago:"), ("F", esquema)], - ] - c_val_w = _merged_width(resumen_widths, "C", "C") - f_val_w = _merged_width(resumen_widths, "F", "F") - - for i, row_data in enumerate(info_rows): - r = info_start + i - (lc1, lv1), (vc1, vv1), (lc2, lv2), (vc2, vv2) = row_data - ws[f"{lc1}{r}"].value = lv1 - ws[f"{lc1}{r}"].font = label_font - ws[f"{vc1}{r}"].value = vv1 - ws[f"{vc1}{r}"].font = value_font - if vv1: - _set_wrapped(ws, r, vc1, vv1, c_val_w) - ws[f"{lc2}{r}"].value = lv2 - ws[f"{lc2}{r}"].font = label_font - ws[f"{vc2}{r}"].value = vv2 - ws[f"{vc2}{r}"].font = value_font - if vv2: - _set_wrapped(ws, r, vc2, vv2, f_val_w) - - # Fecha (en la fila "Fecha:") - fecha_cell = ws[f"C{info_start + 3}"] - fecha_cell.value = fecha - fecha_cell.number_format = "DD/MM/YYYY" - fecha_cell.font = value_font - - vig_row = info_start + 4 - ws[f"B{vig_row}"].value = "Vigencia:" - ws[f"B{vig_row}"].font = label_font - ws[f"C{vig_row}"].value = vigencia - ws[f"C{vig_row}"].number_format = "DD/MM/YYYY" - ws[f"C{vig_row}"].font = value_font - - # Services table - table_start = info_start + 6 - col_b = column_index_from_string("B") - col_k = column_index_from_string("K") - - def style_table_row(row_num: int, fill: PatternFill, border_color: str): - """Estiliza (relleno + borde) todo el ancho de la fila, de B a K.""" - border = _thin_border(border_color) - for c in range(col_b, col_k + 1): - cell = ws.cell(row=row_num, column=c) - cell.fill = fill - cell.border = border - - ws.merge_cells(f"D{table_start}:J{table_start}") - style_table_row(table_start, primary_fill, PRIMARY) - for col_letter, txt, align in [ - ("B", "Fase", "left"), - ("C", "Tipo de Pago", "left"), - ("D", "Servicio", "left"), - ("K", "Precio", "right"), - ]: - cell = ws[f"{col_letter}{table_start}"] - cell.value = txt - cell.font = header_font - cell.alignment = Alignment(horizontal=align, vertical="center") - ws.row_dimensions[table_start].height = 24 - - servicios_unicos = [s for s in servicios if s.get("tipoPago") == "unico"] - servicios_mensuales = [s for s in servicios if s.get("tipoPago") == "mensual"] - serv_width = _merged_width(resumen_widths, "D", "J") - es_doble = bool(data.get("esDoble")) - opciones_meta = data.get("opcionesMetadata") or {} - - row = table_start + 1 - - # Totales (helpers reutilizados por modo normal y doble propuesta) - def write_total_row(label: str, amount: float, font: Font): - nonlocal row - ws.merge_cells(f"B{row}:J{row}") - ws[f"B{row}"].value = label - ws[f"B{row}"].font = font - ws[f"B{row}"].alignment = Alignment(vertical="center") - ws[f"K{row}"].value = amount - ws[f"K{row}"].number_format = "$#,##0.00" - ws[f"K{row}"].font = font - ws[f"K{row}"].alignment = Alignment(horizontal="right", vertical="center") - style_table_row(row, primary_light_fill, PRIMARY) - row += 1 - - def write_iva_note(): - nonlocal row - ws.merge_cells(f"B{row}:J{row}") - ws[f"B{row}"].value = "(+ IVA)" - ws[f"B{row}"].font = iva_font - row += 1 - - def draw_service_rows(servs): - nonlocal row - current_fase = -1 - for serv in servs: - fase = serv.get("fase", 0) - if fase != current_fase: - current_fase = fase - ws.merge_cells(f"B{row}:K{row}") - ws[f"B{row}"].value = FASES_MAP.get(fase, f"FASE {fase}") - ws[f"B{row}"].font = fase_font - ws[f"B{row}"].alignment = Alignment(vertical="center") - for col in range(2, 12): - ws.cell(row=row, column=col).fill = primary_light_fill - ws.row_dimensions[row].height = 20 - row += 1 - - row_bg = light_fill if row % 2 == 0 else white_fill - ws.merge_cells(f"D{row}:J{row}") - style_table_row(row, row_bg, BORDER_COLOR) - ws[f"C{row}"].value = "Unico" if serv.get("tipoPago") == "unico" else "Mensual" - ws[f"C{row}"].font = value_font - ws[f"C{row}"].alignment = Alignment(vertical="top") - _detalle = detalle_modelo(serv) - serv_text = f"{serv.get('nombre', '')} — {_detalle}" if _detalle else serv.get("nombre", "") - ws[f"D{row}"].value = serv_text - ws[f"D{row}"].font = value_font - _set_wrapped(ws, row, "D", serv_text, serv_width) - ws[f"K{row}"].value = serv.get("precio", 0) - ws[f"K{row}"].number_format = "$#,##0.00" - ws[f"K{row}"].font = value_font - ws[f"K{row}"].alignment = Alignment(horizontal="right", vertical="top") - row += 1 - - def write_opcion_banner(op: str): - nonlocal row - meta = opciones_meta.get(op) or {} - ws.merge_cells(f"B{row}:K{row}") - titulo = meta.get("titulo") - ws[f"B{row}"].value = f"OPCION {op}" + (f": {titulo}" if titulo else "") - ws[f"B{row}"].font = Font(bold=True, size=12, name="Calibri", color=WHITE) - ws[f"B{row}"].alignment = Alignment(vertical="center") - for col in range(2, 12): - ws.cell(row=row, column=col).fill = secondary_fill - ws.row_dimensions[row].height = 22 - row += 1 - desc = meta.get("descripcion") - if desc: - ws.merge_cells(f"B{row}:K{row}") - ws[f"B{row}"].value = desc - ws[f"B{row}"].font = value_font - _set_wrapped(ws, row, "B", desc, _merged_width(resumen_widths, "B", "K")) - row += 1 - no_incluye = meta.get("noIncluye") - if no_incluye: - ws.merge_cells(f"B{row}:K{row}") - ws[f"B{row}"].value = f"No incluye: {no_incluye}" - ws[f"B{row}"].font = small_font - _set_wrapped(ws, row, "B", f"No incluye: {no_incluye}", _merged_width(resumen_widths, "B", "K"), font_size=9) - row += 1 - - if es_doble: - for op in ("1", "2"): - u = [s for s in servicios_unicos if s.get("opcion") in (op, "ambas")] - me = [s for s in servicios_mensuales if s.get("opcion") in (op, "ambas")] - write_opcion_banner(op) - draw_service_rows(u + me) - row += 1 - write_total_row(f"Total Pago Unico - Opcion {op}", sum(s.get("precio", 0) for s in u), total_font) - write_iva_note() - write_total_row(f"Total Pago Mensual - Opcion {op}", sum(s.get("precio", 0) for s in me), total_font) - write_iva_note() - row += 1 - - # Comparativa de opciones (totales con IVA + horas) - t1 = calcular_totales_opcion(servicios, "1") - t2 = calcular_totales_opcion(servicios, "2") - ws.merge_cells(f"B{row}:K{row}") - ws[f"B{row}"].value = "COMPARATIVA DE OPCIONES" - ws[f"B{row}"].font = Font(bold=True, size=12, name="Calibri", color=WHITE) - ws[f"B{row}"].alignment = Alignment(vertical="center") - for col in range(2, 12): - ws.cell(row=row, column=col).fill = primary_fill - ws.row_dimensions[row].height = 22 - row += 1 - t1_tit = (opciones_meta.get("1") or {}).get("titulo") - t2_tit = (opciones_meta.get("2") or {}).get("titulo") - - def comp_row(lab: str, v1: str, v2: str, font: Font): - nonlocal row - ws.merge_cells(f"B{row}:F{row}") - ws[f"B{row}"].value = lab - ws[f"B{row}"].font = font - ws.merge_cells(f"G{row}:H{row}") - ws[f"G{row}"].value = v1 - ws[f"G{row}"].font = font - ws[f"G{row}"].alignment = Alignment(horizontal="right") - ws.merge_cells(f"I{row}:K{row}") - ws[f"I{row}"].value = v2 - ws[f"I{row}"].font = font - ws[f"I{row}"].alignment = Alignment(horizontal="right") - border = _thin_border(BORDER_COLOR) - for col in range(col_b, col_k + 1): - ws.cell(row=row, column=col).border = border - row += 1 - - comp_row("Concepto", "Opcion 1" + (f" - {t1_tit}" if t1_tit else ""), "Opcion 2" + (f" - {t2_tit}" if t2_tit else ""), bold_font) - comp_row("Total unico (c/IVA)", format_currency(t1["totalUnico"] * 1.16), format_currency(t2["totalUnico"] * 1.16), value_font) - comp_row("Total mensual (c/IVA)", format_currency(t1["totalMensual"] * 1.16), format_currency(t2["totalMensual"] * 1.16), value_font) - comp_row("Horas estimadas", f"{t1['horas']:g} h", f"{t2['horas']:g} h", value_font) - row += 1 - else: - draw_service_rows(servicios_unicos + servicios_mensuales) - row += 1 - write_total_row("Total Pago Unico", sum(s.get("precio", 0) for s in servicios_unicos), total_font) - write_iva_note() - write_total_row("Total Pago Mensual", sum(s.get("precio", 0) for s in servicios_mensuales), total_font) - write_iva_note() - row += 1 - - if plan_nivel: - precio = plan_precio if plan_precio is not None else bucefalo_precio(plan_nivel) - write_total_row(f"CRM Bucefalo - {plan_nivel.capitalize()}", precio, bold_font) - row += 1 - - ws.merge_cells(f"B{row}:K{row}") - nota_resumen = "Todos los precios son en Moneda Nacional (MX), los precios no incluyen IVA. Vigencia de 15 dias habiles." - ws[f"B{row}"].value = nota_resumen - ws[f"B{row}"].font = small_font - _set_wrapped(ws, row, "B", nota_resumen, _merged_width(resumen_widths, "B", "K"), font_size=9) - - # ═══════════════════════════════════════════════════════════════════════════ - # HOJAS DETALLADAS POR SERVICIO - # ═══════════════════════════════════════════════════════════════════════════ - detail_widths = { - "A": 3, "B": 16, "C": 30, "D": 8, "E": 4, - "F": 18, "G": 22, "H": 6, "I": 6, "J": 16, - } - used_names: set[str] = set() - for serv in servicios: - base = _sanitize_sheet_name(serv.get("nombre", "Servicio")) - safe_name = base - n = 2 - while safe_name.lower() in used_names: - suffix = f" ({n})" - safe_name = base[: 31 - len(suffix)] + suffix - n += 1 - used_names.add(safe_name.lower()) - - dw = wb.create_sheet(title=safe_name) - dw.sheet_view.showGridLines = False - _set_col_widths(dw, list(detail_widths.items())) - - fase = serv.get("fase", 0) - dw.merge_cells("B1:J1") - banner_text = f"{FASES_MAP.get(fase, f'FASE {fase}')} — {serv.get('nombre', '')}" - dw["B1"].value = banner_text - dw["B1"].font = Font(bold=True, size=14, name="Calibri", color=WHITE) - dw["B1"].alignment = Alignment(vertical="center", wrap_text=True) - for col in range(1, 11): - dw.cell(row=1, column=col).fill = primary_fill - dw.row_dimensions[1].height = max( - 30, _estimate_row_height(banner_text, _merged_width(detail_widths, "B", "J"), 14) - ) - - c_val = _merged_width(detail_widths, "C", "D") - g_val = _merged_width(detail_widths, "G", "H") - - r = 3 - dw[f"B{r}"].value = "Cliente:" - dw[f"B{r}"].font = label_font - dw.merge_cells(f"C{r}:D{r}") - dw[f"C{r}"].value = cliente_empresa or cliente_nombre - dw[f"C{r}"].font = bold_font - _set_wrapped(dw, r, "C", cliente_empresa or cliente_nombre, c_val) - dw[f"F{r}"].value = "No. Cotizacion:" - dw[f"F{r}"].font = label_font - dw.merge_cells(f"G{r}:H{r}") - dw[f"G{r}"].value = numero_label - dw[f"G{r}"].font = bold_font - r += 2 - - dw[f"B{r}"].value = "Servicio:" - dw[f"B{r}"].font = label_font - dw.merge_cells(f"C{r}:D{r}") - dw[f"C{r}"].value = serv.get("nombre", "") - dw[f"C{r}"].font = Font(bold=True, size=12, name="Calibri", color=PRIMARY) - _set_wrapped(dw, r, "C", serv.get("nombre", ""), c_val, font_size=12) - dw[f"F{r}"].value = "Tiempo de Entrega:" - dw[f"F{r}"].font = label_font - dw.merge_cells(f"G{r}:H{r}") - dw[f"G{r}"].value = serv.get("tiempoEntrega", "") - dw[f"G{r}"].font = value_font - _set_wrapped(dw, r, "G", serv.get("tiempoEntrega", ""), g_val) - r += 2 - - _detalle_serv = detalle_modelo(serv) - if _detalle_serv: - dw[f"B{r}"].value = "Detalle:" - dw[f"B{r}"].font = label_font - dw.merge_cells(f"C{r}:J{r}") - dw[f"C{r}"].value = _detalle_serv - dw[f"C{r}"].font = value_font - _set_wrapped(dw, r, "C", _detalle_serv, _merged_width(detail_widths, "C", "J")) - r += 2 - - # Encabezado de entregables — barra completa B:J - dw.merge_cells(f"B{r}:J{r}") - dw[f"B{r}"].value = "Entregables" - dw[f"B{r}"].font = header_font - dw[f"B{r}"].alignment = Alignment(vertical="center") - for col in range(column_index_from_string("B"), column_index_from_string("J") + 1): - dw.cell(row=r, column=col).fill = primary_fill - dw.row_dimensions[r].height = 22 - r += 1 - - ent_width = _merged_width(detail_widths, "B", "J") - entregables = serv.get("entregables", []) - b_idx = column_index_from_string("B") - j_idx = column_index_from_string("J") - for i, ent in enumerate(entregables): - er = r + i - dw.merge_cells(f"B{er}:J{er}") - txt = f"{i + 1}. {ent}" - dw[f"B{er}"].value = txt - dw[f"B{er}"].font = value_font - _set_wrapped(dw, er, "B", txt, ent_width) - bg = light_fill if i % 2 == 1 else white_fill - for col in range(b_idx, j_idx + 1): - dw.cell(row=er, column=col).fill = bg - dw.cell(row=er, column=col).border = _thin_border(BORDER_COLOR) - r += len(entregables) + 1 - - # Total: etiqueta B:H + precio I:J - dw.merge_cells(f"B{r}:H{r}") - tipo_label = "Unico" if serv.get("tipoPago") == "unico" else "Mensual" - dw[f"B{r}"].value = f"Total Pago {tipo_label}" - dw[f"B{r}"].font = total_font - dw[f"B{r}"].alignment = Alignment(vertical="center") - dw.merge_cells(f"I{r}:J{r}") - dw[f"I{r}"].value = serv.get("precio", 0) - dw[f"I{r}"].number_format = "$#,##0.00" - dw[f"I{r}"].font = total_font - dw[f"I{r}"].alignment = Alignment(horizontal="right", vertical="center") - for col in range(b_idx, j_idx + 1): - dw.cell(row=r, column=col).fill = primary_light_fill - dw.cell(row=r, column=col).border = _thin_border(PRIMARY) - r += 1 - dw[f"B{r}"].value = "(+ IVA)" - dw[f"B{r}"].font = iva_font - r += 2 - - dw.merge_cells(f"B{r}:J{r}") - nota_detalle = "Esta cotizacion tiene una vigencia de 15 dias habiles. Todos los precios en MXN, precios + IVA." - dw[f"B{r}"].value = nota_detalle - dw[f"B{r}"].font = small_font - _set_wrapped(dw, r, "B", nota_detalle, ent_width, font_size=9) - r += 2 - - dw.merge_cells(f"B{r}:J{r}") - dw[f"B{r}"].value = razon_social - dw[f"B{r}"].font = Font(bold=True, size=10, name="Calibri", color=PRIMARY) - # Decision de marca: no imprimir domicilio fiscal ni ciudad en documentos generados. - - output = io.BytesIO() - wb.save(output) - return output.getvalue() diff --git a/api/app/services/pdf_generator.py b/api/app/services/pdf_generator.py deleted file mode 100644 index 7de69e6..0000000 --- a/api/app/services/pdf_generator.py +++ /dev/null @@ -1,552 +0,0 @@ -"""PDF Generator for Cotizador — Uriel Jareth Consulting — port of pdf-generator.ts using ReportLab.""" - -from __future__ import annotations - -import base64 -import io -from datetime import datetime -from typing import Any - -from reportlab.lib import colors -from reportlab.lib.pagesizes import LETTER -from reportlab.lib.units import inch -from reportlab.pdfgen import canvas -from reportlab.lib.utils import ImageReader - -from app.services.calculators import FASES_SHORT, PLANES_BUCEFALO, bucefalo_precio, detalle_modelo, calcular_totales_opcion - -PRIMARY_DEFAULT = "#0400C4" -DARK_DEFAULT = "#0F172A" -MUTED = "#64748b" -BORDER = "#cbd5e1" -LIGHT_BG = "#f1f5f9" -WHITE = "#ffffff" - -PAGE_W, PAGE_H = LETTER -MARGIN_TOP = 45 -MARGIN_BOTTOM = 55 -MARGIN_LEFT = 50 -MARGIN_RIGHT = 50 -CONTENT_W = PAGE_W - MARGIN_LEFT - MARGIN_RIGHT - - -def _hex_to_rgb(hex_color: str) -> colors.Color: - h = hex_color.lstrip("#") - r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16) - return colors.Color(r / 255, g / 255, b / 255) - - -def _fmt_currency(n: float) -> str: - return f"${n:,.2f}" - - -def _wrap_text(c, text: str, font: str, size: float, max_width: float) -> list[str]: - """Envuelve texto en lineas que caben en max_width (respeta saltos de linea).""" - lines: list[str] = [] - for paragraph in str(text or "").split("\n"): - words = paragraph.split() - line = "" - for word in words: - test = f"{line} {word}".strip() - if c.stringWidth(test, font, size) > max_width and line: - lines.append(line) - line = word - else: - line = test - lines.append(line) - return lines - - -def _fmt_date(d: datetime) -> str: - months = [ - "enero", "febrero", "marzo", "abril", "mayo", "junio", - "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre", - ] - return f"{d.day} de {months[d.month - 1]} de {d.year}" - - -def _load_logo(logo_base64: str | None, logo_mime: str | None) -> ImageReader | None: - if not logo_base64: - return None - try: - raw = base64.b64decode(logo_base64) - return io.BytesIO(raw) - except Exception: - return None - - -def generate_cotizacion_pdf(data: dict[str, Any]) -> bytes: - """Generate a professional quotation PDF. - - Args: - data: dict with keys matching CotizacionPDFData interface: - numero, clienteNombre, clienteEmpresa, asesorNombre, fecha, vigencia, - moneda, tipoCambio, proyecto, esquemaPago, servicios[], - planBucefaloNivel, planBucefaloPrecio, incluirBonos, - configBancaria{}, colorPrimario, colorSecundario, logoBase64, logoMime - """ - PRIMARY = data.get("colorPrimario") or PRIMARY_DEFAULT - DARK = data.get("colorSecundario") or DARK_DEFAULT - primary_rgb = _hex_to_rgb(PRIMARY) - dark_rgb = _hex_to_rgb(DARK) - muted_rgb = _hex_to_rgb(MUTED) - border_rgb = _hex_to_rgb(BORDER) - light_rgb = _hex_to_rgb(LIGHT_BG) - white_rgb = _hex_to_rgb(WHITE) - - buf = io.BytesIO() - c = canvas.Canvas(buf, pagesize=LETTER) - c.setTitle(f"Cotizacion {data.get('numero', '')}") - - logo = _load_logo(data.get("logoBase64"), data.get("logoMime")) - - servicios = data.get("servicios", []) - plan_nivel = data.get("planBucefaloNivel") - plan_precio = data.get("planBucefaloPrecio", 0) - incluir_bonos = data.get("incluirBonos", False) - cfg_bancaria = data.get("configBancaria") or {} - - # ── PAGE 1: COVER ────────────────────────────── - c.setFillColor(white_rgb) - c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0) - - y = PAGE_H - 80 - if logo: - try: - c.drawImage(logo, MARGIN_LEFT, y - 20, width=65, height=65, preserveAspectRatio=True, mask="auto") - y -= 85 - except Exception: - logo = None - - if not logo: - c.setFont("Helvetica-Bold", 28) - c.setFillColor(primary_rgb) - c.drawString(MARGIN_LEFT, y, "UJ") - c.setFont("Helvetica", 9) - c.setFillColor(muted_rgb) - c.drawString(MARGIN_LEFT + 48, y - 15, "Uriel Jareth Consulting") - y -= 40 - - bar_y = y - c.setFillColor(primary_rgb) - c.rect(MARGIN_LEFT, bar_y, CONTENT_W, 4, fill=1, stroke=0) - - c.setFont("Helvetica-Bold", 36) - c.setFillColor(dark_rgb) - c.drawString(MARGIN_LEFT, bar_y - 40, "Cotizacion") - c.setFont("Helvetica", 18) - c.setFillColor(primary_rgb) - c.drawString(MARGIN_LEFT, bar_y - 65, data.get("numero", "")) - - iy = bar_y - 100 - cL = MARGIN_LEFT - cR = MARGIN_LEFT + CONTENT_W * 0.52 - - info_l = [ - ("Cliente", data.get("clienteNombre", "")), - ("Empresa", data.get("clienteEmpresa", "")), - ("Proyecto", data.get("proyecto", "")), - ("Asesor", data.get("asesorNombre", "")), - ] - info_r = [ - ("Fecha", _fmt_date(data.get("fecha", datetime.now()))), - ("Vigencia", _fmt_date(data.get("vigencia", datetime.now()))), - ("Moneda", data.get("moneda", "MXN")), - ("Esquema", data.get("esquemaPago", "")), - ] - - for i in range(max(len(info_l), len(info_r))): - if i < len(info_l) and info_l[i][1]: - c.setFont("Helvetica", 9) - c.setFillColor(muted_rgb) - c.drawString(cL, iy, info_l[i][0]) - c.setFont("Helvetica", 11) - c.setFillColor(dark_rgb) - c.drawString(cL, iy - 14, info_l[i][1]) - if i < len(info_r) and info_r[i][1]: - c.setFont("Helvetica", 9) - c.setFillColor(muted_rgb) - c.drawString(cR, iy, info_r[i][0]) - c.setFont("Helvetica", 11) - c.setFillColor(dark_rgb) - c.drawString(cR, iy - 14, str(info_r[i][1])) - iy -= 32 - - # ── PAGE 2+: RESUMEN ────────────────────────── - c.showPage() - y = PAGE_H - MARGIN_TOP - - if logo: - try: - c.drawImage(logo, MARGIN_LEFT + CONTENT_W - 70, y - 5, width=22, height=22, preserveAspectRatio=True, mask="auto") - except Exception: - pass - - c.setFillColor(primary_rgb) - c.rect(MARGIN_LEFT, y - 16, 4, 16, fill=1, stroke=0) - c.setFont("Helvetica-Bold", 15) - c.setFillColor(dark_rgb) - c.drawString(MARGIN_LEFT + 12, y - 15, "Hoja Resumen") - y -= 28 - - cliente_ref = data.get("clienteEmpresa") or data.get("clienteNombre", "") - c.setFont("Helvetica", 8) - c.setFillColor(muted_rgb) - c.drawString(MARGIN_LEFT, y, f"En atencion a: {cliente_ref}") - c.drawString(MARGIN_LEFT + CONTENT_W * 0.45, y, f"No. Cotizacion: {data.get('numero', '')}") - y -= 11 - c.drawString(MARGIN_LEFT, y, f"Asesor: {data.get('asesorNombre', '')}") - c.drawString(MARGIN_LEFT + CONTENT_W * 0.45, y, f"Fecha: {_fmt_date(data.get('fecha', datetime.now()))} | Moneda: {data.get('moneda', 'MXN')}") - y -= 18 - - col_nombre = MARGIN_LEFT - col_tipo = MARGIN_LEFT + CONTENT_W - 200 - col_tiempo = MARGIN_LEFT + CONTENT_W - 120 - col_precio = MARGIN_LEFT + CONTENT_W - 60 - - es_doble = bool(data.get("esDoble")) - opciones_meta = data.get("opcionesMetadata") or {} - - def _draw_table_header(y_pos): - c.setFillColor(light_rgb) - c.rect(MARGIN_LEFT, y_pos - 2, CONTENT_W, 16, fill=1, stroke=0) - c.setFont("Helvetica-Bold", 7) - c.setFillColor(dark_rgb) - c.drawString(col_nombre + 6, y_pos + 3, "Servicio") - c.drawString(col_tipo + 4, y_pos + 3, "Tipo") - c.drawString(col_tiempo + 4, y_pos + 3, "Entrega") - c.drawRightString(col_precio + 60, y_pos + 3, "Precio") - y_pos -= 4 - c.setStrokeColor(border_rgb) - c.setLineWidth(0.3) - c.line(MARGIN_LEFT, y_pos, MARGIN_LEFT + CONTENT_W, y_pos) - return y_pos - 14 - - unicos = [s for s in servicios if s.get("tipoPago") == "unico"] - mensuales = [s for s in servicios if s.get("tipoPago") == "mensual"] - - def _draw_section(srv_list, tipo_label, titulo_total, y_pos): - if not srv_list: - return y_pos - current_fase = -1 - max_y = PAGE_H - MARGIN_BOTTOM - 5 - - for serv in srv_list: - fase = serv.get("fase", 0) - if fase != current_fase: - current_fase = fase - if y_pos - 20 < max_y - PAGE_H: - c.showPage() - y_pos = PAGE_H - MARGIN_TOP - c.setFillColor(light_rgb) - c.rect(MARGIN_LEFT, y_pos - 14, CONTENT_W, 14, fill=1, stroke=0) - c.setFont("Helvetica-Bold", 7) - c.setFillColor(primary_rgb) - c.drawString(MARGIN_LEFT + 6, y_pos - 11, FASES_SHORT.get(fase, f"FASE {fase}")) - y_pos -= 18 - - c.setFont("Helvetica", 8) - c.setFillColor(dark_rgb) - nombre = serv.get("nombre", "") - c.drawString(col_nombre + 6, y_pos - 10, nombre[:60]) - c.setFont("Helvetica", 7) - c.setFillColor(muted_rgb) - c.drawString(col_tipo + 4, y_pos - 10, tipo_label) - c.drawString(col_tiempo + 4, y_pos - 10, serv.get("tiempoEntrega", "")[:15]) - c.setFont("Helvetica-Bold", 8) - c.setFillColor(dark_rgb) - c.drawRightString(col_precio + 60, y_pos - 10, _fmt_currency(serv.get("precio", 0))) - y_pos -= 14 - - detalle = detalle_modelo(serv) - if detalle: - c.setFont("Helvetica-Oblique", 6.5) - c.setFillColor(muted_rgb) - c.drawString(col_nombre + 10, y_pos - 7, detalle[:90]) - y_pos -= 9 - - entregables = serv.get("entregables", []) - if entregables: - half = (len(entregables) + 1) // 2 - for idx in range(half): - e1 = entregables[idx] - e2 = entregables[idx + half] if idx + half < len(entregables) else None - c.setFont("Helvetica", 6) - c.setFillColor(muted_rgb) - c.drawString(col_nombre + 10, y_pos - 8, f"\u2022 {e1[:50]}") - if e2: - c.drawString(col_nombre + CONTENT_W * 0.48, y_pos - 8, f"\u2022 {e2[:50]}") - y_pos -= 9 - - c.setStrokeColor(_hex_to_rgb("#e5e7eb")) - c.setLineWidth(0.2) - c.line(col_nombre + 6, y_pos, MARGIN_LEFT + CONTENT_W, y_pos) - y_pos -= 6 - - total = sum(s.get("precio", 0) for s in srv_list) - y_pos -= 4 - c.setFillColor(_hex_to_rgb("#f8fafc")) - c.rect(MARGIN_LEFT, y_pos - 2, CONTENT_W, 18, fill=1, stroke=0) - c.setFont("Helvetica-Bold", 8.5) - c.setFillColor(primary_rgb) - c.drawString(col_nombre + 6, y_pos + 3, titulo_total) - c.drawRightString(col_precio + 60, y_pos + 3, _fmt_currency(total)) - y_pos -= 18 - c.setFont("Helvetica", 6) - c.setFillColor(muted_rgb) - c.drawString(col_nombre + 6, y_pos, "(Precios en Moneda Nacional, no incluyen IVA)") - y_pos -= 14 - return y_pos - - def _draw_opcion_header(op, y_pos): - meta = opciones_meta.get(op) or {} - max_y = PAGE_H - MARGIN_BOTTOM - 5 - if y_pos - 30 < max_y: - c.showPage() - y_pos = PAGE_H - MARGIN_TOP - titulo = meta.get("titulo") - c.setFillColor(primary_rgb) - c.rect(MARGIN_LEFT, y_pos - 18, CONTENT_W, 18, fill=1, stroke=0) - c.setFont("Helvetica-Bold", 10) - c.setFillColor(white_rgb) - c.drawString(MARGIN_LEFT + 8, y_pos - 13, f"OPCION {op}" + (f": {titulo}" if titulo else "")) - y_pos -= 24 - desc = meta.get("descripcion") - if desc: - c.setFont("Helvetica", 7.5) - c.setFillColor(dark_rgb) - for line in _wrap_text(c, desc, "Helvetica", 7.5, CONTENT_W - 12): - c.drawString(MARGIN_LEFT + 6, y_pos - 8, line) - y_pos -= 10 - y_pos -= 2 - no_incluye = meta.get("noIncluye") - if no_incluye: - c.setFont("Helvetica-Oblique", 7) - c.setFillColor(muted_rgb) - for line in _wrap_text(c, f"No incluye: {no_incluye}", "Helvetica-Oblique", 7, CONTENT_W - 12): - c.drawString(MARGIN_LEFT + 6, y_pos - 8, line) - y_pos -= 10 - y_pos -= 4 - return y_pos - - def _draw_comparativa(y_pos): - t1 = calcular_totales_opcion(servicios, "1") - t2 = calcular_totales_opcion(servicios, "2") - max_y = PAGE_H - MARGIN_BOTTOM - 5 - if y_pos - 90 < max_y: - c.showPage() - y_pos = PAGE_H - MARGIN_TOP - y_pos -= 6 - c.setFillColor(primary_rgb) - c.rect(MARGIN_LEFT, y_pos - 10, 3, 10, fill=1, stroke=0) - c.setFont("Helvetica-Bold", 10) - c.setFillColor(dark_rgb) - c.drawString(MARGIN_LEFT + 10, y_pos - 8, "Comparativa de opciones") - y_pos -= 22 - c_label = MARGIN_LEFT - c_op1 = MARGIN_LEFT + CONTENT_W * 0.45 - c_op2 = MARGIN_LEFT + CONTENT_W * 0.72 - t1_tit = (opciones_meta.get("1") or {}).get("titulo") - t2_tit = (opciones_meta.get("2") or {}).get("titulo") - c.setFillColor(light_rgb) - c.rect(MARGIN_LEFT, y_pos - 2, CONTENT_W, 16, fill=1, stroke=0) - c.setFont("Helvetica-Bold", 7.5) - c.setFillColor(dark_rgb) - c.drawString(c_label + 6, y_pos + 3, "Concepto") - c.drawString(c_op1, y_pos + 3, f"Opcion 1" + (f" - {t1_tit}" if t1_tit else "")) - c.drawString(c_op2, y_pos + 3, f"Opcion 2" + (f" - {t2_tit}" if t2_tit else "")) - y_pos -= 18 - filas = [ - ("Total unico (c/IVA)", _fmt_currency(t1["totalUnico"] * 1.16), _fmt_currency(t2["totalUnico"] * 1.16)), - ("Total mensual (c/IVA)", _fmt_currency(t1["totalMensual"] * 1.16), _fmt_currency(t2["totalMensual"] * 1.16)), - ("Horas estimadas", f"{t1['horas']:g} h", f"{t2['horas']:g} h"), - ] - for lab, v1, v2 in filas: - c.setFont("Helvetica", 8) - c.setFillColor(dark_rgb) - c.drawString(c_label + 6, y_pos - 8, lab) - c.setFont("Helvetica-Bold", 8) - c.drawString(c_op1, y_pos - 8, v1) - c.drawString(c_op2, y_pos - 8, v2) - c.setStrokeColor(_hex_to_rgb("#e5e7eb")) - c.setLineWidth(0.2) - c.line(c_label + 6, y_pos - 12, MARGIN_LEFT + CONTENT_W, y_pos - 12) - y_pos -= 14 - return y_pos - 8 - - if es_doble: - for op in ("1", "2"): - y = _draw_opcion_header(op, y) - y = _draw_table_header(y) - u = [s for s in unicos if s.get("opcion") in (op, "ambas")] - me = [s for s in mensuales if s.get("opcion") in (op, "ambas")] - if u: - y = _draw_section(u, "Unico", f"Total Pago Unico - Opcion {op}", y) - if me: - y = _draw_section(me, "Mensual", f"Total Pago Mensual - Opcion {op}", y) - y = _draw_comparativa(y) - else: - y = _draw_table_header(y) - if unicos: - y = _draw_section(unicos, "Unico", "Total Pago Unico", y) - if mensuales: - y = _draw_section(mensuales, "Mensual", "Total Pago Mensual", y) - - if plan_nivel: - label = plan_nivel.capitalize() - c.setFillColor(light_rgb) - c.rect(MARGIN_LEFT, y - 2, CONTENT_W, 14, fill=1, stroke=0) - c.setFont("Helvetica-Bold", 7.5) - c.setFillColor(dark_rgb) - c.drawString(col_nombre + 6, y + 3, f"Plan Bucefalo CRM - {label}") - c.drawRightString(col_precio + 60, y + 3, _fmt_currency(plan_precio)) - y -= 20 - - if incluir_bonos: - y -= 6 - c.setFillColor(primary_rgb) - c.rect(MARGIN_LEFT, y - 10, 3, 10, fill=1, stroke=0) - c.setFont("Helvetica-Bold", 9) - c.setFillColor(dark_rgb) - c.drawString(MARGIN_LEFT + 10, y - 8, "Bonos (Pago en una exhibicion)") - y -= 20 - bonos = [ - "Bono 1: 30 min mensuales en servicios Centinela (Sitio Web)", - "Bono 2: Workshop Estrategico de Buyer Persona", - "Bono 3: Workshop de Propuestas de Valor y Oferta Irresistible", - "Bono 4: 1 ano de Membresia Premium", - "Bono 5: Un mes gratis de Bucefalo CRM", - "Bono 6: Script de Ventas con mas de 100 complementos", - ] - for b in bonos: - c.setFont("Helvetica", 7) - c.setFillColor(dark_rgb) - c.drawString(MARGIN_LEFT + 8, y - 8, f"\u2713 {b}") - y -= 12 - - # ── T&C PAGE ────────────────────────────────── - c.showPage() - y = PAGE_H - MARGIN_TOP - - if logo: - try: - c.drawImage(logo, MARGIN_LEFT + CONTENT_W - 70, y - 5, width=22, height=22, preserveAspectRatio=True, mask="auto") - except Exception: - pass - - c.setFillColor(primary_rgb) - c.rect(MARGIN_LEFT, y - 16, 4, 16, fill=1, stroke=0) - c.setFont("Helvetica-Bold", 15) - c.setFillColor(dark_rgb) - c.drawString(MARGIN_LEFT + 12, y - 15, "Terminos y Condiciones") - y -= 30 - - def _section_title(title, yy): - c.setFillColor(primary_rgb) - c.rect(MARGIN_LEFT, yy - 9, 3, 9, fill=1, stroke=0) - c.setFont("Helvetica-Bold", 9) - c.setFillColor(dark_rgb) - c.drawString(MARGIN_LEFT + 10, yy - 8, title) - return yy - 20 - - def _draw_bullets(title, items, yy): - yy = _section_title(title, yy) - for t in items: - c.setFont("Helvetica", 7.5) - c.setFillColor(dark_rgb) - # Simple text wrapping - words = t.split() - line = "" - for word in words: - test = f"{line} {word}".strip() - if c.stringWidth(test, "Helvetica", 7.5) > CONTENT_W - 10: - c.drawString(MARGIN_LEFT + 2, yy - 8, f"\u2022 {line}") - yy -= 11 - line = word - else: - line = test - if line: - c.drawString(MARGIN_LEFT + 2, yy - 8, f"\u2022 {line}") - yy -= 11 - return yy - 8 - - y = _draw_bullets("Condiciones", [ - "Esta cotizacion tiene una vigencia de 15 dias habiles.", - "Cualquier ajuste al proyecto despues de la aprobacion del contenido afectara la fecha de entrega y por consiguiente el costo.", - "El cliente debera proporcionar la informacion solicitada por Uriel Jareth Consulting en tiempo y forma.", - "Si la falta de informacion provoca un excedente en los plazos de entrega del proyecto, las horas adicionales de servicio se cotizaran por separado.", - "Los pagos correspondientes a los servicios mensuales deberan realizarse en los primeros 5 dias del mes.", - "Todo el material e informacion necesarios para la realizacion del sitio web deberan ser entregados en un plazo maximo de 40 dias naturales a partir del arranque del proyecto.", - ], y) - - y = _draw_bullets("Que no incluye el proyecto?", [ - "Generacion de disenos, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado.", - "Redaccion de entradas de Blog.", - "Integracion de Servicios de terceros ajenos a los cotizados.", - "Servicio de Recuperacion de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads.", - "Creacion de Redes Sociales (En caso de requerir el servicio incluira un costo adicional).", - ], y) - - y = _draw_bullets("Notas", [ - "El presente proyecto debera tener un responsable oficial.", - "La Hora Centinela tiene un precio de $700.00 MXN.", - "Los archivos editables/fuente (AI, PSD) son propiedad intelectual de la agencia. Si requiere los archivos editables, estos pueden ser adquiridos abonando una tarifa de liberacion (buy-out fee).", - "Si el proyecto se pausa por razones ajenas a Uriel Jareth Consulting, esto generara costo extra del 15% al 30% para retomar el proyecto.", - ], y) - - y -= 8 - c.setFillColor(primary_rgb) - c.rect(MARGIN_LEFT, y - 9, 3, 9, fill=1, stroke=0) - c.setFont("Helvetica-Bold", 9) - c.setFillColor(dark_rgb) - c.drawString(MARGIN_LEFT + 10, y - 8, "Datos Bancarios") - y -= 20 - - razon_social = cfg_bancaria.get("razon_social", "URIEL JARETH ALVARADO ORTIZ") - rfc = cfg_bancaria.get("rfc", "AAOU970201SU7") - clabe_nac = cfg_bancaria.get("clabe_interbancaria", cfg_bancaria.get("cuenta_nacional", "")) - cuenta_nac = cfg_bancaria.get("cuenta_nacional", "") - banco_nac = "BBVA" if cuenta_nac else "" - - box_h = 48 - c.setFillColor(light_rgb) - c.setStrokeColor(border_rgb) - c.rect(MARGIN_LEFT, y - box_h, CONTENT_W, box_h, fill=1, stroke=1) - c.setFont("Helvetica-Bold", 7) - c.setFillColor(dark_rgb) - c.drawString(MARGIN_LEFT + 8, y - 12, "Transferencia Nacional") - c.setFont("Helvetica", 6.5) - if cuenta_nac: - c.drawString(MARGIN_LEFT + 8, y - 24, f"Cuenta: {cuenta_nac}") - if clabe_nac: - c.drawString(MARGIN_LEFT + CONTENT_W * 0.45, y - 24, f"CLABE: {clabe_nac}") - c.drawString(MARGIN_LEFT + 8, y - 35, f"Razon Social: {razon_social}") - c.drawString(MARGIN_LEFT + CONTENT_W * 0.45, y - 35, f"RFC: {rfc}") - if banco_nac: - c.drawString(MARGIN_LEFT + 8, y - 46, f"Banco: {banco_nac}") - y -= box_h + 8 - - c.setFillColor(light_rgb) - c.rect(MARGIN_LEFT, y - box_h, CONTENT_W, box_h, fill=1, stroke=1) - c.setFont("Helvetica-Bold", 7) - c.setFillColor(dark_rgb) - c.drawString(MARGIN_LEFT + 8, y - 12, "Transferencia Internacional") - c.setFont("Helvetica", 6.5) - c.drawString(MARGIN_LEFT + 8, y - 24, f"Beneficiario: {razon_social}") - c.drawString(MARGIN_LEFT + 8, y - 35, "Banco: BBVA Mexico") - c.drawString(MARGIN_LEFT + CONTENT_W * 0.45, y - 35, "SWIFT: BCMRMXMMPYM") - - # ── FOOTER ON ALL PAGES ────────────────────── - page_count = c.getPageNumber() - for i in range(1, page_count + 1): - c.setPageSize(LETTER) - c.setFont("Helvetica", 6) - c.setFillColor(muted_rgb) - c.setStrokeColor(border_rgb) - c.setLineWidth(0.5) - c.line(MARGIN_LEFT, MARGIN_BOTTOM - 10, MARGIN_LEFT + CONTENT_W, MARGIN_BOTTOM - 10) - c.drawCentredString(PAGE_W / 2, MARGIN_BOTTOM - 22, "Uriel Jareth Consulting") - c.drawCentredString(PAGE_W / 2, MARGIN_BOTTOM - 32, "urieljareth.com | contacto@urieljareth.com | (445) 182 9943") - - c.save() - return buf.getvalue() diff --git a/api/main.py b/api/main.py deleted file mode 100644 index e6fee75..0000000 --- a/api/main.py +++ /dev/null @@ -1,123 +0,0 @@ -"""Cotizador — Uriel Jareth Consulting (FastAPI Application) - -REST API for digital marketing quotation management. -Optimized for n8n workflows and other integrations. -""" - -from __future__ import annotations - -from contextlib import asynccontextmanager -from datetime import datetime, timezone - -from fastapi import FastAPI, Request -from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import JSONResponse - -from app.config import settings -from app.database import close_db, init_db - - -@asynccontextmanager -async def lifespan(app: FastAPI): - await init_db() - yield - await close_db() - - -app = FastAPI( - title="Cotizador — Uriel Jareth Consulting API", - description=( - "API REST para el sistema de cotizaciones de Uriel Jareth Consulting. " - "Optimizada para integración con n8n y otros consumidores. " - "Autenticación por X-API-Key o Bearer JWT." - ), - version="2.0.0", - lifespan=lifespan, - docs_url="/docs", - redoc_url="/redoc", - openapi_url="/openapi.json", - openapi_tags=[ - {"name": "Health", "description": "Health check y información de la API"}, - {"name": "Auth", "description": "Autenticación (API Key + JWT)"}, - {"name": "Clientes", "description": "Gestión de clientes"}, - {"name": "Catálogo", "description": "Catálogo de servicios de marketing digital"}, - {"name": "Categorías", "description": "Categorías de servicios"}, - {"name": "Cotizaciones", "description": "Cotizaciones — CRUD con paridad de aprobación humana"}, - {"name": "Cobros", "description": "Consulta de programas y pagos recurrentes (scope cobros:leer)"}, - {"name": "Paquetes", "description": "Paquetes de servicios con fases"}, - {"name": "Configuración", "description": "Configuración de la empresa (key-value)"}, - {"name": "Bonos", "description": "Bonos disponibles para cotizaciones"}, - {"name": "Financiamiento", "description": "Planes y cálculo de financiamiento"}, - {"name": "Export", "description": "Exportación de PDF, Excel y CSV"}, - {"name": "Import", "description": "Importación masiva de servicios"}, - ], -) - -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) - - -@app.exception_handler(Exception) -async def global_exception_handler(request: Request, exc: Exception): - return JSONResponse( - status_code=500, - content={"error": "Error interno del servidor", "detail": str(exc)}, - ) - - -# Register routers -from app.routers import ( - auth, - bonos, - catalogo, - categorias, - clientes, - configuracion, - cotizaciones, - export_, - financiamiento, - health, - import_, - paquetes, -) - -app.include_router(health.router) -app.include_router(auth.router) -app.include_router(clientes.router) -app.include_router(catalogo.router) -app.include_router(categorias.router) -app.include_router(cotizaciones.router) -app.include_router(paquetes.router) -app.include_router(configuracion.router) -app.include_router(bonos.router) -app.include_router(financiamiento.router) -app.include_router(export_.router) -app.include_router(import_.router) - -# El servidor MCP se retiro (2026-07-28). No se estaba usando, su transporte -# llevaba tiempo roto (instanciaba un StreamableHTTPServerTransport por peticion, -# sin manejo de sesion, y devolvia 500 con credencial valida) y su SDK sin fijar -# tumbo el API entero en produccion al saltar a 2.0.0. Si algun dia se retoma, -# el codigo esta en el historial: `git show edb500f5:api/app/mcp/server.py`. - - -@app.get("/", include_in_schema=False) -async def root(): - return { - "name": "Cotizador — Uriel Jareth Consulting API", - "version": "2.0.0", - "docs": "/docs", - "openapi": "/openapi.json", - "health": "/health", - } - - -if __name__ == "__main__": - import uvicorn - - uvicorn.run("main:app", host=settings.API_HOST, port=settings.API_PORT, reload=True) diff --git a/api/requirements.txt b/api/requirements.txt deleted file mode 100644 index 5297cca..0000000 --- a/api/requirements.txt +++ /dev/null @@ -1,30 +0,0 @@ -# Versiones FIJAS a proposito. -# -# Por que: el 2026-07-28 una reconstruccion del API tomo mcp 2.0.0 (el rango era -# `mcp>=1.0.0`), que elimino Server.list_tools(). El import lanzo AttributeError -# al arrancar y dejo el contenedor en crash-loop ~50 minutos. Once de las doce -# dependencias eran rangos `>=` sin techo, o sea que cada build era una tirada de -# dados contra PyPI: `pydantic>=2.0` habria aceptado pydantic 3 igual de alegre. -# -# Estas versiones son exactamente las que corrian sanas en produccion cuando se -# fijaron (capturadas con `pip freeze` del contenedor healthy). -# -# Para subir una dependencia: cambiala aqui a proposito, reconstruye y prueba. -# Nunca por accidente al redesplegar. -# -# Limitacion conocida: esto fija las dependencias DIRECTAS. Las transitivas -# (starlette, cryptography, anyio...) las sigue resolviendo pip. Es un riesgo -# mucho menor, pero si algun dia muerde, el siguiente paso es un lock completo -# con pip-tools o uv. - -fastapi==0.140.13 -uvicorn[standard]==0.51.0 -asyncpg==0.31.0 -pydantic==2.13.4 -pydantic-settings==2.14.2 -python-jose[cryptography]==3.5.0 -passlib[bcrypt]==1.7.4 -python-multipart==0.0.32 -reportlab==5.0.0 -openpyxl==3.1.5 -httpx==0.28.1 diff --git a/cazar-tmp.ts b/cazar-tmp.ts deleted file mode 100644 index 21a6d6d..0000000 --- a/cazar-tmp.ts +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Caza del error intermitente: corre el pipeline real contra UJ2606UR001 hasta que - * falle, e imprime TODO lo que sepamos de la peticion que lo provoco. - */ -import { cargarEconomia } from "@/lib/propuesta/economia"; -import { crearCliente, modelo } from "@/lib/propuesta/cliente-ia"; -import { hechosSchema, diagnosticoSchema, redaccionSchema, aJsonSchema, type Hechos, type Diagnostico } from "@/lib/propuesta/schemas"; -import { SYSTEM_BASE, mensajePaso1, mensajePaso2, mensajePaso3, type ContextoEntrada } from "@/lib/propuesta/prompts"; -import { prisma } from "@/lib/db"; -import type Anthropic from "@anthropic-ai/sdk"; -import type { z } from "zod"; -import fs from "node:fs"; - -const LOG = process.argv[2]; -// Escritura directa: el buffer de stdout se pierde si el proceso muere. -function log(...a: unknown[]) { - const linea = a.map((x) => (typeof x === "string" ? x : JSON.stringify(x))).join(" "); - fs.appendFileSync(LOG, linea + "\n"); -} -const console = { log } as unknown as Console; - -const NUMERO = "UJ2606UR001"; -const TRANSCRIPCION = "Una propuesta de zero to hero para un negocio inicial"; - -/** Igual que llamarConHerramienta pero registra cada peticion y explota con detalle. */ -async function correrPaso(nombre: string, msg: string, schema: z.ZodType, maxTokens: number, maxIntentos: number) { - const cliente = crearCliente(); - const tools = [{ name: nombre, description: "Registra el resultado.", input_schema: aJsonSchema(schema) as never }]; - const mensajes: Anthropic.MessageParam[] = [{ role: "user", content: msg }]; - - for (let intento = 1; intento <= maxIntentos; intento++) { - let res: Anthropic.Message; - try { - res = await cliente.messages.create({ - model: modelo(), max_tokens: maxTokens, - system: [{ type: "text", text: SYSTEM_BASE, cache_control: { type: "ephemeral" } }], - tools, messages: mensajes, - }); - } catch (e) { - const err = e as { status?: number; message?: string; error?: unknown }; - console.log(`\n*** ERROR EN ${nombre} intento ${intento} ***`); - console.log(" status:", err.status); - console.log(" message:", String(err.message).slice(0, 600)); - if (err.error) console.log(" error:", JSON.stringify(err.error).slice(0, 800)); - console.log("\n --- FORMA DE LOS MENSAJES ENVIADOS ---"); - mensajes.forEach((m, i) => { - const c = m.content; - const tipos = typeof c === "string" ? "string" : (c as { type: string }[]).map((b) => b.type).join(","); - console.log(` [${i}] role=${m.role} bloques=${tipos}`); - }); - throw new Error("REPRODUCIDO"); - } - - const bloques = res.content.map((b) => b.type).join(","); - console.log(` ${nombre} intento ${intento}: stop=${res.stop_reason} bloques=[${bloques}] out=${res.usage.output_tokens}`); - - const tus = res.content.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use"); - const ok = tus.find((b) => b.name === nombre); - if (ok) { - const parsed = schema.safeParse(ok.input); - if (parsed.success) return parsed.data; - const errTxt = (await import("zod")).z.prettifyError(parsed.error); - console.log(` zod rechazo: ${errTxt.split("\n")[0]}`); - mensajes.push( - { role: "assistant", content: res.content }, - { role: "user", content: [ - ...tus.map((b) => ({ type: "tool_result" as const, tool_use_id: b.id, is_error: true, content: errTxt })), - { type: "text" as const, text: "Corrige y reintenta." }, - ] }, - ); - continue; - } - mensajes.push( - { role: "assistant", content: res.content }, - { role: "user", content: `Debes llamar a ${nombre}.` }, - ); - } - return null; -} - -async function unaVuelta(entrada: ContextoEntrada, econ: Awaited>, n: number) { - console.log(`\n===== VUELTA ${n} =====`); - const h = (await correrPaso("registrar_hechos", mensajePaso1(entrada), hechosSchema, 8000, 5)) as Hechos | null; - if (!h) { console.log(" extraccion agoto intentos"); return; } - const d = (await correrPaso("registrar_diagnostico", mensajePaso2(entrada, h, econ), diagnosticoSchema, 8000, 4)) as Diagnostico | null; - if (!d) { console.log(" diagnostico agoto intentos"); return; } - const r = await correrPaso("registrar_propuesta", mensajePaso3(entrada, h, d, econ), redaccionSchema, 12000, 4); - console.log(r ? " vuelta completa OK" : " redaccion agoto intentos"); -} - -async function main() { - const cot = await prisma.cotizacion.findFirst({ where: { numero: NUMERO }, include: { cliente: true, servicios: true } }); - if (!cot) throw new Error("no encontrada"); - const econ = await cargarEconomia(cot.id); - const entrada: ContextoEntrada = { - transcripcion: TRANSCRIPCION, - notas: cot.servicios.map((s) => s.notas).filter(Boolean).join("\n"), - observaciones: cot.observaciones || "", - cliente: cot.cliente.nombre, empresa: cot.cliente.empresa || "", proyecto: cot.proyecto, - }; - console.log(`${econ.partidas.length} partidas`); - - for (let i = 1; i <= 3; i++) { - try { await unaVuelta(entrada, econ, i); } - catch (e) { - if (e instanceof Error && e.message === "REPRODUCIDO") { console.log("\n>>> error reproducido, deteniendo"); break; } - throw e; - } - } - await prisma.$disconnect(); -} - -main().catch((e) => { console.error("fallo:", e); process.exit(1); }); diff --git a/cli/cotizador.mjs b/cli/cotizador.mjs deleted file mode 100644 index eb80069..0000000 --- a/cli/cotizador.mjs +++ /dev/null @@ -1,1450 +0,0 @@ -#!/usr/bin/env node -// cotizador — CLI del Cotizador — Uriel Jareth Consulting, pensado para humanos y para LLMs. -// -// - Habla con la API REST de Next.js (la misma que usa la web), con la sesion -// de un usuario staff (login con correo y contrasena). -// - Salida: JSON en stdout. Errores: JSON en stderr + codigo de salida (ver -// CODIGOS). Nada de prompts interactivos: todo entra por flags, --datos o stdin. -// - `cotizador esquema` describe TODOS los comandos en JSON (flags, tipos, -// ejemplos, endpoint) para que un agente descubra la herramienta solo. -// -// Sin dependencias: Node 18+ (fetch nativo). Ver docs/CLI.md. - -import { readFile, writeFile, mkdir } from "node:fs/promises"; -import { homedir } from "node:os"; -import { join, resolve, dirname } from "node:path"; -import { randomUUID } from "node:crypto"; - -const VERSION = "1.0.0"; - -const CODIGOS = { - ok: 0, - error: 1, - uso: 2, - auth: 3, - noEncontrado: 4, - validacion: 5, - conflicto: 6, - red: 7, -}; - -const DESCRIPCION_CODIGOS = { - 0: "ok", - 1: "error del servidor o inesperado", - 2: "uso incorrecto (flag faltante o invalida, comando desconocido)", - 3: "sin sesion o sin permiso (ejecuta `cotizador login`)", - 4: "no encontrado", - 5: "validacion rechazada por el servidor (ver `detalles`)", - 6: "conflicto (duplicado)", - 7: "no se pudo conectar con el servidor", -}; - -// --------------------------------------------------------------------------- -// Dominio (espejo de src/lib/calculators.ts; solo para validar y documentar) -// --------------------------------------------------------------------------- - -const DOMINIO = { - fases: { - 0: "Auditoria / Acompanamiento", - 1: "Setup e Infraestructura", - 2: "Publicidad y Manejo", - 3: "Contenido y SEO", - }, - tiposPago: { unico: "pago unico", mensual: "pago recurrente mensual" }, - nivelesServicio: ["Emprendedor", "PYME", "Empresario", "Corporativo"], - estadosCotizacion: ["borrador", "enviada", "aprobada", "rechazada"], - esquemasPago: ["Pago Unico", "Mensual", "Pago Unico/Mensual", "Por hora (postpago)"], - monedas: ["MXN", "USD"], - planesBucefaloCRM: ["basico", "estandar", "premium", "empresarial"], - iva: 0.16, - tarifaHoraDefault: 700, -}; - -// --------------------------------------------------------------------------- -// Errores -// --------------------------------------------------------------------------- - -class CliError extends Error { - constructor(mensaje, { codigo = CODIGOS.error, status, detalles, sugerencia } = {}) { - super(mensaje); - this.codigo = codigo; - this.status = status; - this.detalles = detalles; - this.sugerencia = sugerencia; - } -} - -const errorUso = (mensaje, sugerencia) => new CliError(mensaje, { codigo: CODIGOS.uso, sugerencia }); - -// --------------------------------------------------------------------------- -// Parseo de argumentos -// --------------------------------------------------------------------------- - -const FLAGS_GLOBALES = [ - { flag: "url", tipo: "texto", descripcion: "URL base de la plataforma (default: $COTIZADOR_URL o http://localhost:3000)" }, - { flag: "campos", tipo: "lista", descripcion: "Devuelve solo estos campos, separados por coma (ej. id,nombre,precioBase). Ahorra tokens." }, - { flag: "formato", tipo: "texto", valores: ["json", "tabla"], descripcion: "json (default) o tabla legible" }, - { flag: "compacto", tipo: "booleano", descripcion: "JSON en una sola linea" }, - { flag: "dry-run", tipo: "booleano", descripcion: "En comandos de escritura: muestra la peticion que se enviaria y no la envia" }, - { flag: "ayuda", tipo: "booleano", descripcion: "Ayuda del comando (tambien -h, --help)" }, - { flag: "version", tipo: "booleano", descripcion: "Version del CLI" }, -]; - -function aCamel(s) { - return s.replace(/-([a-z])/g, (_, c) => c.toUpperCase()); -} - -// Devuelve { posicionales, flags }. Las flags booleanas se reconocen por la -// especificacion; el resto consume el siguiente argumento como valor. -// Las flags `repetible` acumulan un arreglo. -function parsearArgs(argv, especFlags) { - const booleanas = new Set( - especFlags.filter((f) => f.tipo === "booleano").map((f) => f.flag) - ); - const repetibles = new Set(especFlags.filter((f) => f.repetible).map((f) => f.flag)); - const posicionales = []; - const flags = {}; - for (let i = 0; i < argv.length; i++) { - const a = argv[i]; - if (a === "--") { - posicionales.push(...argv.slice(i + 1)); - break; - } - if (a === "-h") { - flags.ayuda = true; - continue; - } - if (!a.startsWith("--")) { - posicionales.push(a); - continue; - } - let nombre = a.slice(2); - let valor; - const igual = nombre.indexOf("="); - if (igual >= 0) { - valor = nombre.slice(igual + 1); - nombre = nombre.slice(0, igual); - } - if (nombre === "help") nombre = "ayuda"; - if (nombre.startsWith("no-") && booleanas.has(nombre.slice(3))) { - flags[aCamel(nombre.slice(3))] = false; - continue; - } - if (booleanas.has(nombre)) { - flags[aCamel(nombre)] = valor === undefined ? true : !["false", "0", "no"].includes(valor); - continue; - } - if (valor === undefined) { - const sig = argv[i + 1]; - if (sig === undefined || (sig.startsWith("--") && sig !== "--")) { - throw errorUso(`La flag --${nombre} necesita un valor`); - } - valor = sig; - i++; - } - const clave = aCamel(nombre); - if (repetibles.has(nombre)) { - (flags[clave] ??= []).push(valor); - } else { - flags[clave] = valor; - } - } - return { posicionales, flags }; -} - -// --------------------------------------------------------------------------- -// Conversion de valores -// --------------------------------------------------------------------------- - -function numero(valor, flag) { - if (valor === undefined) return undefined; - const limpio = String(valor).replace(/[$,\s]/g, ""); - const n = Number(limpio); - if (limpio === "" || !Number.isFinite(n)) throw errorUso(`--${flag} debe ser un numero (recibi "${valor}")`); - return n; -} - -function entero(valor, flag) { - const n = numero(valor, flag); - if (n !== undefined && !Number.isInteger(n)) throw errorUso(`--${flag} debe ser un entero (recibi "${valor}")`); - return n; -} - -function unoDe(valor, opciones, flag) { - if (valor === undefined) return undefined; - if (!opciones.includes(valor)) { - throw errorUso(`--${flag} debe ser uno de: ${opciones.join(", ")} (recibi "${valor}")`); - } - return valor; -} - -// "" o "null" o "ninguno" en un texto opcional = borrar el valor. -function textoOpcional(valor) { - if (valor === undefined) return undefined; - return ["", "null", "ninguno", "ninguna"].includes(String(valor).toLowerCase()) ? null : valor; -} - -function fechaISO(valor, flag) { - if (valor === undefined) return undefined; - if (!/^\d{4}-\d{2}-\d{2}$/.test(valor)) throw errorUso(`--${flag} debe tener formato YYYY-MM-DD (recibi "${valor}")`); - return valor; -} - -function quitarIndefinidos(obj) { - return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)); -} - -async function leerStdin() { - const partes = []; - for await (const p of process.stdin) partes.push(p); - return Buffer.concat(partes).toString("utf8"); -} - -// --datos acepta JSON en linea, @archivo.json o "-" (stdin). -async function leerDatos(valor) { - if (valor === undefined) return {}; - let texto = valor; - if (valor === "-") texto = await leerStdin(); - else if (valor.startsWith("@")) { - try { - texto = await readFile(resolve(valor.slice(1)), "utf8"); - } catch { - throw errorUso(`No pude leer el archivo ${valor.slice(1)}`); - } - } - try { - const datos = JSON.parse(texto); - if (datos === null || typeof datos !== "object" || Array.isArray(datos)) { - throw new Error(); - } - return datos; - } catch { - throw errorUso("--datos debe ser un objeto JSON valido (en linea, @archivo.json o - para stdin)"); - } -} - -// --------------------------------------------------------------------------- -// Sesion y HTTP -// --------------------------------------------------------------------------- - -const DIR_CONFIG = process.env.COTIZADOR_HOME || join(homedir(), ".cotizador-uj"); -const ARCHIVO_SESIONES = join(DIR_CONFIG, "sesiones.json"); -// Fallback de solo lectura para sesiones previas antes del renombre. -const ARCHIVO_SESIONES_LEGACY = join(homedir(), ".cotizador-e3", "sesiones.json"); - -async function leerSesiones() { - try { - return JSON.parse(await readFile(ARCHIVO_SESIONES, "utf8")); - } catch { - if (!process.env.COTIZADOR_HOME) { - try { - return JSON.parse(await readFile(ARCHIVO_SESIONES_LEGACY, "utf8")); - } catch { - return {}; - } - } - return {}; - } -} - -async function guardarSesiones(sesiones) { - await mkdir(DIR_CONFIG, { recursive: true }); - await writeFile(ARCHIVO_SESIONES, JSON.stringify(sesiones, null, 2), { mode: 0o600 }); -} - -function urlBase(flags) { - const url = (flags.url || process.env.COTIZADOR_URL || "http://localhost:3000").replace(/\/+$/, ""); - try { - new URL(url); - } catch { - throw errorUso(`URL invalida: ${url}`); - } - return url; -} - -function codigoPorStatus(status) { - if (status === 400 || status === 422) return CODIGOS.validacion; - if (status === 401 || status === 403) return CODIGOS.auth; - if (status === 404) return CODIGOS.noEncontrado; - if (status === 409) return CODIGOS.conflicto; - return CODIGOS.error; -} - -function extraerToken(res) { - const cookies = - typeof res.headers.getSetCookie === "function" - ? res.headers.getSetCookie() - : [res.headers.get("set-cookie") || ""]; - for (const c of cookies) { - const m = c.match(/cotizador-session=([^;]+)/); - if (m && m[1]) return m[1]; - } - return null; -} - -function crearCliente(flags) { - const base = urlBase(flags); - let tokenEnMemoria = process.env.COTIZADOR_TOKEN || null; - - async function token() { - if (tokenEnMemoria) return tokenEnMemoria; - const sesiones = await leerSesiones(); - tokenEnMemoria = sesiones[base]?.token ?? null; - return tokenEnMemoria; - } - - async function login(email, password) { - let res; - try { - res = await fetch(`${base}/api/auth/login`, { - method: "POST", - headers: { "Content-Type": "application/json", Accept: "application/json" }, - body: JSON.stringify({ email, password }), - }); - } catch (e) { - throw errorRed(base, e); - } - const cuerpo = await res.json().catch(() => ({})); - if (!res.ok) { - throw new CliError(cuerpo.error || `Login fallido (HTTP ${res.status})`, { - codigo: CODIGOS.auth, - status: res.status, - }); - } - const nuevo = extraerToken(res); - if (!nuevo) throw new CliError("El servidor no devolvio la cookie de sesion", { codigo: CODIGOS.auth }); - if (cuerpo.user?.role === "cliente") { - throw new CliError("Esa cuenta es de rol cliente; el CLI necesita una cuenta de staff (admin o asesor)", { - codigo: CODIGOS.auth, - }); - } - const sesiones = await leerSesiones(); - sesiones[base] = { token: nuevo, usuario: cuerpo.user, iniciada: new Date().toISOString() }; - await guardarSesiones(sesiones); - tokenEnMemoria = nuevo; - return cuerpo.user; - } - - // Peticion JSON. `binario: true` devuelve { buffer, nombreArchivo, tipo }. - async function api(metodo, ruta, { cuerpo, binario = false, escritura } = {}) { - const url = `${base}${ruta}`; - const esEscritura = escritura ?? metodo !== "GET"; - if (flags.dryRun && esEscritura) { - throw new DryRun({ metodo, url, cuerpo: cuerpo ?? null }); - } - let reintentado = false; - for (;;) { - const t = await token(); - const headers = { Accept: binario ? "*/*" : "application/json" }; - if (cuerpo !== undefined) headers["Content-Type"] = "application/json"; - if (t) headers.Cookie = `cotizador-session=${t}`; - let res; - try { - res = await fetch(url, { - method: metodo, - headers, - body: cuerpo !== undefined ? JSON.stringify(cuerpo) : undefined, - redirect: "manual", - }); - } catch (e) { - throw errorRed(base, e); - } - // Sesion vencida o ausente: si hay credenciales en el entorno, se renueva sola. - if (res.status === 401 && !reintentado && process.env.COTIZADOR_EMAIL && process.env.COTIZADOR_PASSWORD) { - reintentado = true; - tokenEnMemoria = null; - await login(process.env.COTIZADOR_EMAIL, process.env.COTIZADOR_PASSWORD); - continue; - } - if (res.status >= 300 && res.status < 400) { - throw new CliError(`El servidor redirigio a ${res.headers.get("location")} (¿sesion invalida?)`, { - codigo: CODIGOS.auth, - status: res.status, - sugerencia: "Ejecuta: cotizador login --email --password ", - }); - } - if (!res.ok) { - const err = await res.json().catch(() => ({})); - throw new CliError(err.error || `HTTP ${res.status}`, { - codigo: codigoPorStatus(res.status), - status: res.status, - detalles: err.detalles, - sugerencia: - res.status === 401 - ? "Ejecuta: cotizador login --email --password (o define COTIZADOR_EMAIL y COTIZADOR_PASSWORD)" - : res.status === 403 - ? "La cuenta no tiene permiso para esta accion (el CLI necesita rol admin o asesor)" - : undefined, - }); - } - if (binario) { - const disp = res.headers.get("content-disposition") || ""; - const m = disp.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i); - return { - buffer: Buffer.from(await res.arrayBuffer()), - nombreArchivo: m ? decodeURIComponent(m[1]) : null, - tipo: res.headers.get("content-type"), - }; - } - const texto = await res.text(); - return texto ? JSON.parse(texto) : null; - } - } - - async function cerrarSesion() { - const sesiones = await leerSesiones(); - const habia = !!sesiones[base]; - delete sesiones[base]; - await guardarSesiones(sesiones); - tokenEnMemoria = null; - return habia; - } - - return { base, api, login, cerrarSesion }; -} - -function errorRed(base, e) { - return new CliError(`No se pudo conectar con ${base}: ${e.cause?.code || e.message}`, { - codigo: CODIGOS.red, - sugerencia: "Revisa que el servidor este arriba (npm run dev) o pasa la URL correcta con --url o COTIZADOR_URL", - }); -} - -class DryRun { - constructor(peticion) { - this.peticion = peticion; - } -} - -// --------------------------------------------------------------------------- -// Salida -// --------------------------------------------------------------------------- - -function elegirCampos(datos, campos) { - if (!campos) return datos; - const lista = campos.split(",").map((c) => c.trim()).filter(Boolean); - const pick = (o) => - o && typeof o === "object" - ? Object.fromEntries(lista.map((c) => [c, c.split(".").reduce((v, k) => (v == null ? v : v[k]), o)])) - : o; - return Array.isArray(datos) ? datos.map(pick) : pick(datos); -} - -function aTabla(datos) { - const filas = Array.isArray(datos) ? datos : [datos]; - if (filas.length === 0) return "(sin resultados)"; - const columnas = [...new Set(filas.flatMap((f) => Object.keys(f ?? {})))].filter((c) => - filas.every((f) => f?.[c] == null || typeof f[c] !== "object" || Array.isArray(f[c])) - ); - const celda = (v) => { - if (v == null) return ""; - const s = Array.isArray(v) ? v.join("; ") : String(v); - return s.length > 60 ? s.slice(0, 57) + "..." : s; - }; - const anchos = columnas.map((c) => Math.max(c.length, ...filas.map((f) => celda(f?.[c]).length))); - const linea = (vals) => vals.map((v, i) => v.padEnd(anchos[i])).join(" "); - return [ - linea(columnas), - linea(anchos.map((a) => "-".repeat(a))), - ...filas.map((f) => linea(columnas.map((c) => celda(f?.[c])))), - ].join("\n"); -} - -function imprimir(datos, flags) { - const filtrado = elegirCampos(datos, flags.campos); - if (flags.formato === "tabla") { - process.stdout.write(aTabla(filtrado) + "\n"); - return; - } - process.stdout.write(JSON.stringify(filtrado, null, flags.compacto ? 0 : 2) + "\n"); -} - -function imprimirError(err) { - const salida = { - ok: false, - error: err.message, - codigo: err.codigo, - ...(err.status && { status: err.status }), - ...(err.detalles && { detalles: err.detalles }), - ...(err.sugerencia && { sugerencia: err.sugerencia }), - }; - process.stderr.write(JSON.stringify(salida, null, 2) + "\n"); -} - -// --------------------------------------------------------------------------- -// Resolucion de referencias (nombre -> id) -// --------------------------------------------------------------------------- - -// Los ids no tienen un formato fijo (cuid o slug del seed), asi que cada -// resolutor prueba primero como id y luego por nombre/numero. - -async function resolverCategoria(api, valor) { - const v = textoOpcional(valor); - if (v === undefined || v === null) return v; - const cats = await api("GET", "/api/categorias"); - const hallada = - cats.find((c) => c.id === v) ?? cats.find((c) => c.nombre.toLowerCase() === v.toLowerCase()); - if (!hallada) { - throw errorUso( - `No existe la categoria "${v}"`, - `Categorias disponibles: ${cats.map((c) => c.nombre).join(", ")}. Crea una con: cotizador categorias crear --nombre "${v}"` - ); - } - return hallada.id; -} - -async function intentarPorId(api, ruta) { - try { - return await api("GET", ruta); - } catch (e) { - if (e instanceof CliError && e.codigo === CODIGOS.noEncontrado) return null; - throw e; - } -} - -async function resolverServicio(api, ref) { - const porId = await intentarPorId(api, `/api/catalogo/${encodeURIComponent(ref)}`); - if (porId) return porId; - const candidatos = await api("GET", `/api/catalogo?activo=true&q=${encodeURIComponent(ref)}`); - const exactos = candidatos.filter((s) => s.nombre.toLowerCase() === ref.toLowerCase()); - if (exactos.length === 1) return exactos[0]; - if (candidatos.length === 1) return candidatos[0]; - if (candidatos.length === 0) { - throw new CliError(`No existe el servicio "${ref}" (ni como id ni como nombre de un servicio activo)`, { - codigo: CODIGOS.noEncontrado, - sugerencia: "Busca con: cotizador servicios listar --q (agrega --todos para incluir archivados)", - }); - } - throw errorUso( - `"${ref}" es ambiguo (${candidatos.length} coincidencias)`, - `Usa el id. Coincidencias: ${candidatos.slice(0, 10).map((s) => `${s.id} (${s.nombre})`).join("; ")}` - ); -} - -async function resolverCotizacion(api, ref) { - const porId = await intentarPorId(api, `/api/cotizaciones/${encodeURIComponent(ref)}`); - if (porId) return porId.id; - const lista = await api("GET", `/api/cotizaciones?q=${encodeURIComponent(ref)}&limit=20`); - const exacta = lista.find((c) => c.numero.toLowerCase() === ref.toLowerCase()); - if (exacta) return exacta.id; - throw new CliError(`No existe la cotizacion "${ref}"`, { - codigo: CODIGOS.noEncontrado, - sugerencia: "Pasa el id o el numero exacto (ej. UJ2605AG001). Busca con: cotizador cotizaciones listar --q ", - }); -} - -// --------------------------------------------------------------------------- -// Constructores de cuerpos -// --------------------------------------------------------------------------- - -const FLAGS_SERVICIO = [ - { flag: "nombre", tipo: "texto", descripcion: "Nombre del servicio" }, - { flag: "fase", tipo: "entero", valores: [0, 1, 2, 3], descripcion: "0 Auditoria, 1 Setup, 2 Publicidad, 3 Contenido/SEO" }, - { flag: "tipo-pago", tipo: "texto", valores: ["unico", "mensual"], descripcion: "unico o mensual" }, - { flag: "precio", tipo: "numero", descripcion: "Precio base en MXN, sin IVA (acepta 4500 o 4,500)" }, - { flag: "descripcion", tipo: "texto", descripcion: 'Descripcion (usa "" para borrarla)' }, - { flag: "tiempo-entrega", tipo: "texto", descripcion: 'Ej. "4 - 10 dias" (default al crear)' }, - { flag: "entregable", tipo: "texto", repetible: true, descripcion: "Un entregable; repite la flag para varios. En editar REEMPLAZA la lista" }, - { flag: "categoria", tipo: "texto", descripcion: 'Id o nombre de la categoria ("ninguna" para quitarla)' }, - { flag: "variante", tipo: "texto", descripcion: "Ej. WooCommerce, Shopify" }, - { flag: "nivel", tipo: "texto", valores: DOMINIO.nivelesServicio, descripcion: 'Nivel de cliente ("ninguno" para quitarlo)' }, - { flag: "orden", tipo: "entero", descripcion: "Posicion dentro de su fase (default al crear: al final)" }, - { flag: "datos", tipo: "json", descripcion: "Objeto JSON con los campos de la API (en linea, @archivo.json o - para stdin). Las flags tienen prioridad" }, -]; - -async function cuerpoServicio(api, flags) { - const base = await leerDatos(flags.datos); - const desdeFlags = quitarIndefinidos({ - nombre: flags.nombre, - fase: entero(flags.fase, "fase"), - tipoPago: unoDe(flags.tipoPago, ["unico", "mensual"], "tipo-pago"), - precioBase: numero(flags.precio, "precio"), - descripcion: textoOpcional(flags.descripcion), - tiempoEntrega: flags.tiempoEntrega, - entregablesDefault: flags.entregable, - categoriaId: flags.categoria !== undefined ? await resolverCategoria(api, flags.categoria) : undefined, - variante: textoOpcional(flags.variante), - nivel: flags.nivel !== undefined ? (textoOpcional(flags.nivel) === null ? null : unoDe(flags.nivel, DOMINIO.nivelesServicio, "nivel")) : undefined, - orden: entero(flags.orden, "orden"), - }); - if (desdeFlags.fase !== undefined && ![0, 1, 2, 3].includes(desdeFlags.fase)) { - throw errorUso("--fase debe ser 0, 1, 2 o 3"); - } - // Admite categoria por nombre tambien dentro de --datos. - if (typeof base.categoria === "string" && base.categoriaId === undefined) { - base.categoriaId = await resolverCategoria(api, base.categoria); - delete base.categoria; - } - return { ...base, ...desdeFlags }; -} - -// Partida de cotizacion a partir de un servicio del catalogo. -function partidaDesdeCatalogo(s, precio) { - return { - catalogoId: s.id, - nombre: s.nombre, - fase: s.fase, - tipoPago: s.tipoPago, - precio: precio ?? s.precioBase, - tiempoEntrega: s.tiempoEntrega, - entregables: s.entregablesDefault ?? [], - }; -} - -// "Concepto|horas|tarifa" -> partida personalizada cobrada por horas. -function partidaPorHoras(texto) { - const [concepto, horasTxt, tarifaTxt] = texto.split("|").map((p) => p?.trim()); - if (!concepto || !horasTxt) { - throw errorUso(`--partida-horas debe ser "Concepto|horas|tarifa" (tarifa opcional, default ${DOMINIO.tarifaHoraDefault}); recibi "${texto}"`); - } - const horas = numero(horasTxt, "partida-horas"); - const tarifaHora = tarifaTxt ? numero(tarifaTxt, "partida-horas") : DOMINIO.tarifaHoraDefault; - return { - catalogoId: `custom-${randomUUID()}`, - nombre: concepto, - fase: 1, - tipoPago: "unico", - precio: Math.round(horas * tarifaHora * 100) / 100, - tiempoEntrega: "A convenir", - entregables: [], - esPersonalizado: true, - modeloCobro: "horas", - horas, - tarifaHora, - }; -} - -// Resumen de una cotizacion para listados (la version completa sale con `ver`). -function resumenCotizacion(c) { - return { - id: c.id, - numero: c.numero, - estado: c.estado, - fecha: c.fecha?.slice(0, 10), - vigencia: c.vigencia?.slice(0, 10), - cliente: c.cliente?.nombre, - empresa: c.cliente?.empresa, - proyecto: c.proyecto, - moneda: c.moneda, - esDoble: c.esDoble, - partidas: c.servicios?.length ?? 0, - planBucefaloCRM: c.planBucefalo?.nivel ?? null, - asesor: c.asesor?.name, - }; -} - -// --------------------------------------------------------------------------- -// Comandos -// --------------------------------------------------------------------------- - -const CONFIRMAR = { flag: "confirmar", tipo: "booleano", descripcion: "Obligatoria: confirma una accion que no se puede deshacer" }; - -function exigirConfirmacion(flags, accion) { - if (!flags.confirmar && !flags.dryRun) { - throw errorUso(`${accion} no se puede deshacer. Repite el comando con --confirmar si es lo que quieres.`); - } -} - -function exigirPosicional(pos, i, nombre, comando) { - const v = pos[i]; - if (!v) throw errorUso(`Falta el argumento <${nombre}>`, `Uso: cotizador ${comando} <${nombre}>`); - return v; -} - -const COMANDOS = [ - // ----- sesion ----- - { - comando: "login", - descripcion: "Inicia sesion con una cuenta staff y guarda el token en ~/.cotizador-uj/sesiones.json (7 dias).", - flags: [ - { flag: "email", tipo: "texto", descripcion: "Correo (o $COTIZADOR_EMAIL)" }, - { flag: "password", tipo: "texto", descripcion: "Contrasena (o $COTIZADOR_PASSWORD)" }, - { flag: "password-stdin", tipo: "booleano", descripcion: "Lee la contrasena de stdin (no queda en el historial)" }, - ], - ejemplos: [ - "cotizador login --email admin@urieljareth.com --password-stdin < pass.txt", - "COTIZADOR_EMAIL=... COTIZADOR_PASSWORD=... cotizador login", - ], - endpoint: "POST /api/auth/login", - async run({ flags, cliente }) { - const email = flags.email || process.env.COTIZADOR_EMAIL; - let password = flags.password || process.env.COTIZADOR_PASSWORD; - if (flags.passwordStdin) password = (await leerStdin()).trim(); - if (!email || !password) { - throw errorUso("Faltan credenciales", "Pasa --email y --password (o --password-stdin), o define COTIZADOR_EMAIL y COTIZADOR_PASSWORD"); - } - const usuario = await cliente.login(email, password); - return { ok: true, url: cliente.base, usuario }; - }, - }, - { - comando: "logout", - descripcion: "Borra la sesion guardada para la URL actual.", - endpoint: null, - async run({ cliente }) { - const habia = await cliente.cerrarSesion(); - return { ok: true, url: cliente.base, sesionBorrada: habia }; - }, - }, - { - comando: "whoami", - alias: ["yo"], - descripcion: "Muestra el usuario de la sesion actual.", - endpoint: "GET /api/auth/me", - async run({ cliente }) { - const r = await cliente.api("GET", "/api/auth/me"); - return { url: cliente.base, usuario: r.user }; - }, - }, - - // ----- servicios (catalogo) ----- - { - comando: "servicios listar", - alias: ["servicios", "servicios ls"], - descripcion: "Lista servicios del catalogo. Por defecto solo los activos.", - flags: [ - { flag: "q", tipo: "texto", descripcion: "Busca en nombre y descripcion" }, - { flag: "fase", tipo: "entero", valores: [0, 1, 2, 3], descripcion: "Filtra por fase" }, - { flag: "tipo-pago", tipo: "texto", valores: ["unico", "mensual"], descripcion: "Filtra por tipo de pago" }, - { flag: "categoria", tipo: "texto", descripcion: "Id o nombre de categoria" }, - { flag: "archivados", tipo: "booleano", descripcion: "Solo los archivados" }, - { flag: "todos", tipo: "booleano", descripcion: "Activos y archivados" }, - ], - ejemplos: [ - "cotizador servicios listar --fase 1 --campos id,nombre,precioBase", - 'cotizador servicios listar --q "landing" --formato tabla', - ], - endpoint: "GET /api/catalogo", - async run({ flags, cliente }) { - const p = new URLSearchParams(); - if (flags.q) p.set("q", flags.q); - if (flags.fase !== undefined) p.set("fase", String(entero(flags.fase, "fase"))); - if (flags.tipoPago) p.set("tipoPago", unoDe(flags.tipoPago, ["unico", "mensual"], "tipo-pago")); - if (flags.categoria) p.set("categoriaId", await resolverCategoria(cliente.api, flags.categoria)); - if (flags.archivados) p.set("activo", "false"); - else if (!flags.todos) p.set("activo", "true"); - return cliente.api("GET", `/api/catalogo?${p}`); - }, - }, - { - comando: "servicios ver", - descripcion: "Muestra un servicio del catalogo (por id o por nombre exacto).", - argumentos: [{ nombre: "id", descripcion: "Id del servicio o su nombre" }], - ejemplos: ["cotizador servicios ver cmabc123...", 'cotizador servicios ver "Landing Page"'], - endpoint: "GET /api/catalogo/{id}", - async run({ pos, cliente }) { - return resolverServicio(cliente.api, exigirPosicional(pos, 0, "id", "servicios ver")); - }, - }, - { - comando: "servicios crear", - alias: ["servicios nuevo"], - descripcion: - "Crea un servicio en el catalogo. Obligatorios: --nombre, --fase, --tipo-pago, --precio. Queda activo y al final de su fase.", - flags: FLAGS_SERVICIO, - ejemplos: [ - 'cotizador servicios crear --nombre "Auditoria SEO tecnica" --fase 0 --tipo-pago unico --precio 6500 --categoria SEO --entregable "Reporte PDF" --entregable "Sesion de 1 h"', - `cotizador servicios crear --datos '{"nombre":"Gestion de Google Ads","fase":2,"tipoPago":"mensual","precioBase":5500}'`, - ], - endpoint: "POST /api/catalogo", - async run({ flags, cliente }) { - const cuerpo = await cuerpoServicio(cliente.api, flags); - const faltan = ["nombre", "fase", "tipoPago", "precioBase"].filter((k) => cuerpo[k] === undefined); - if (faltan.length) { - const aFlag = { nombre: "--nombre", fase: "--fase", tipoPago: "--tipo-pago", precioBase: "--precio" }; - throw errorUso( - `Faltan campos obligatorios: ${faltan.map((k) => aFlag[k]).join(", ")}`, - 'Ejemplo: cotizador servicios crear --nombre "Mi servicio" --fase 1 --tipo-pago unico --precio 5000' - ); - } - return cliente.api("POST", "/api/catalogo", { cuerpo }); - }, - }, - { - comando: "servicios editar", - descripcion: - "Edita un servicio: solo cambia los campos que pases. Las cotizaciones ya guardadas conservan su precio y entregables.", - argumentos: [{ nombre: "id", descripcion: "Id del servicio o su nombre exacto" }], - flags: [ - ...FLAGS_SERVICIO, - { flag: "agregar-entregable", tipo: "texto", repetible: true, descripcion: "Agrega un entregable a la lista actual (sin reemplazarla)" }, - { flag: "quitar-entregable", tipo: "texto", repetible: true, descripcion: "Quita un entregable de la lista actual (texto exacto)" }, - ], - ejemplos: [ - "cotizador servicios editar cmabc123... --precio 7200", - 'cotizador servicios editar "Landing Page" --agregar-entregable "Formulario conectado a Bucefalo CRM"', - ], - endpoint: "PATCH /api/catalogo/{id}", - async run({ pos, flags, cliente }) { - const ref = exigirPosicional(pos, 0, "id", "servicios editar"); - const actual = await resolverServicio(cliente.api, ref); - const cuerpo = await cuerpoServicio(cliente.api, flags); - if (flags.agregarEntregable || flags.quitarEntregable) { - let lista = cuerpo.entregablesDefault ?? [...actual.entregablesDefault]; - if (flags.quitarEntregable) { - const faltantes = flags.quitarEntregable.filter((q) => !lista.includes(q)); - if (faltantes.length) { - throw errorUso( - `No encontre estos entregables: ${faltantes.join("; ")}`, - `Entregables actuales: ${lista.join("; ") || "(ninguno)"}` - ); - } - lista = lista.filter((e) => !flags.quitarEntregable.includes(e)); - } - if (flags.agregarEntregable) lista = [...lista, ...flags.agregarEntregable]; - cuerpo.entregablesDefault = lista; - } - if (Object.keys(cuerpo).length === 0) { - throw errorUso("No pasaste ningun campo para cambiar", "Ejemplo: cotizador servicios editar --precio 5000"); - } - return cliente.api("PATCH", `/api/catalogo/${actual.id}`, { cuerpo }); - }, - }, - { - comando: "servicios archivar", - descripcion: "Oculta un servicio al cotizar (activo=false). Reversible con `servicios activar`.", - argumentos: [{ nombre: "id", descripcion: "Id del servicio o su nombre exacto" }], - endpoint: "PATCH /api/catalogo/{id}", - async run({ pos, cliente }) { - const s = await resolverServicio(cliente.api, exigirPosicional(pos, 0, "id", "servicios archivar")); - return cliente.api("PATCH", `/api/catalogo/${s.id}`, { cuerpo: { activo: false } }); - }, - }, - { - comando: "servicios activar", - descripcion: "Vuelve a mostrar un servicio archivado.", - argumentos: [{ nombre: "id", descripcion: "Id del servicio" }], - endpoint: "PATCH /api/catalogo/{id}", - async run({ pos, cliente }) { - const id = exigirPosicional(pos, 0, "id", "servicios activar"); - return cliente.api("PATCH", `/api/catalogo/${encodeURIComponent(id)}`, { cuerpo: { activo: true } }); - }, - }, - { - comando: "servicios eliminar", - descripcion: - "Borra un servicio. Si alguna cotizacion lo usa, el servidor lo ARCHIVA en vez de borrarlo (respuesta archived=true).", - argumentos: [{ nombre: "id", descripcion: "Id del servicio" }], - flags: [CONFIRMAR], - ejemplos: ["cotizador servicios eliminar cmabc123... --confirmar"], - endpoint: "DELETE /api/catalogo/{id}", - async run({ pos, flags, cliente }) { - const id = exigirPosicional(pos, 0, "id", "servicios eliminar"); - exigirConfirmacion(flags, "Eliminar un servicio"); - return cliente.api("DELETE", `/api/catalogo/${encodeURIComponent(id)}`); - }, - }, - - // ----- categorias y paquetes ----- - { - comando: "categorias listar", - alias: ["categorias"], - descripcion: "Lista las categorias del catalogo.", - endpoint: "GET /api/categorias", - async run({ cliente }) { - return cliente.api("GET", "/api/categorias"); - }, - }, - { - comando: "categorias crear", - descripcion: "Crea una categoria.", - flags: [ - { flag: "nombre", tipo: "texto", descripcion: "Nombre (unico)" }, - { flag: "color", tipo: "texto", descripcion: "Color hex, ej. #2563eb" }, - { flag: "descripcion", tipo: "texto", descripcion: "Descripcion" }, - ], - ejemplos: ['cotizador categorias crear --nombre "Automatizacion" --color "#0ea5e9"'], - endpoint: "POST /api/categorias", - async run({ flags, cliente }) { - if (!flags.nombre) throw errorUso("Falta --nombre"); - if (flags.color && !/^#[0-9a-f]{6}$/i.test(flags.color)) throw errorUso("--color debe ser hex de 6 digitos, ej. #2563eb"); - return cliente.api("POST", "/api/categorias", { - cuerpo: quitarIndefinidos({ nombre: flags.nombre, color: flags.color, descripcion: flags.descripcion }), - }); - }, - }, - { - comando: "paquetes listar", - alias: ["paquetes"], - descripcion: "Lista los paquetes activos con sus fases y servicios (resumido; usa `paquetes ver` para el detalle).", - endpoint: "GET /api/paquetes", - async run({ cliente }) { - const paquetes = await cliente.api("GET", "/api/paquetes"); - return paquetes.map((p) => ({ - id: p.id, - nombre: p.nombre, - descripcion: p.descripcion, - fases: p.fases.map((f) => ({ - nombre: f.nombre, - servicios: f.servicios.map((sp) => ({ id: sp.servicio.id, nombre: sp.servicio.nombre, precioBase: sp.servicio.precioBase, tipoPago: sp.servicio.tipoPago })), - })), - })); - }, - }, - { - comando: "paquetes ver", - descripcion: "Detalle completo de un paquete.", - argumentos: [{ nombre: "id", descripcion: "Id del paquete" }], - endpoint: "GET /api/paquetes/{id}", - async run({ pos, cliente }) { - return cliente.api("GET", `/api/paquetes/${encodeURIComponent(exigirPosicional(pos, 0, "id", "paquetes ver"))}`); - }, - }, - - // ----- clientes ----- - { - comando: "clientes listar", - alias: ["clientes"], - descripcion: "Lista clientes.", - flags: [{ flag: "q", tipo: "texto", descripcion: "Busca en nombre, empresa, correo y RFC" }], - endpoint: "GET /api/clientes", - async run({ flags, cliente }) { - return cliente.api("GET", `/api/clientes${flags.q ? `?q=${encodeURIComponent(flags.q)}` : ""}`); - }, - }, - { - comando: "clientes crear", - descripcion: "Da de alta un cliente (nombre + empresa deben ser unicos).", - flags: [ - { flag: "nombre", tipo: "texto", descripcion: "Nombre del contacto (obligatorio)" }, - { flag: "empresa", tipo: "texto", descripcion: "Empresa" }, - { flag: "puesto", tipo: "texto", descripcion: "Puesto" }, - { flag: "email", tipo: "texto", descripcion: "Correo" }, - { flag: "telefono", tipo: "texto", descripcion: "Telefono" }, - { flag: "rfc", tipo: "texto", descripcion: "RFC" }, - ], - ejemplos: ['cotizador clientes crear --nombre "Ana Ruiz" --empresa "Panaderia Sol" --email ana@sol.mx'], - endpoint: "POST /api/clientes", - async run({ flags, cliente }) { - if (!flags.nombre) throw errorUso("Falta --nombre"); - return cliente.api("POST", "/api/clientes", { - cuerpo: quitarIndefinidos({ - nombre: flags.nombre, - empresa: flags.empresa, - puesto: flags.puesto, - email: flags.email, - telefono: flags.telefono, - rfc: flags.rfc, - }), - }); - }, - }, - { - comando: "clientes editar", - descripcion: "Edita un cliente (solo los campos que pases).", - argumentos: [{ nombre: "id", descripcion: "Id del cliente" }], - flags: [ - { flag: "nombre", tipo: "texto", descripcion: "Nombre" }, - { flag: "empresa", tipo: "texto", descripcion: 'Empresa ("" para quitarla)' }, - { flag: "puesto", tipo: "texto", descripcion: "Puesto" }, - { flag: "email", tipo: "texto", descripcion: "Correo" }, - { flag: "telefono", tipo: "texto", descripcion: "Telefono" }, - { flag: "rfc", tipo: "texto", descripcion: "RFC" }, - ], - endpoint: "PATCH /api/clientes/{id}", - async run({ pos, flags, cliente }) { - const id = exigirPosicional(pos, 0, "id", "clientes editar"); - const cuerpo = quitarIndefinidos({ - nombre: flags.nombre, - empresa: flags.empresa, - puesto: flags.puesto, - email: flags.email, - telefono: flags.telefono, - rfc: flags.rfc, - }); - if (Object.keys(cuerpo).length === 0) throw errorUso("No pasaste ningun campo para cambiar"); - return cliente.api("PATCH", `/api/clientes/${encodeURIComponent(id)}`, { cuerpo }); - }, - }, - - // ----- cotizaciones ----- - { - comando: "cotizaciones listar", - alias: ["cotizaciones", "cotizaciones ls"], - descripcion: "Lista cotizaciones resumidas, de la mas reciente a la mas antigua.", - flags: [ - { flag: "estado", tipo: "texto", valores: DOMINIO.estadosCotizacion, descripcion: "Filtra por estado" }, - { flag: "q", tipo: "texto", descripcion: "Busca en numero, proyecto, cliente y empresa" }, - { flag: "cliente", tipo: "texto", descripcion: "Id del cliente" }, - { flag: "limit", tipo: "entero", descripcion: "Maximo de resultados (default 50)" }, - { flag: "completo", tipo: "booleano", descripcion: "Devuelve el registro completo (con partidas) en vez del resumen" }, - ], - ejemplos: ["cotizador cotizaciones listar --estado enviada --formato tabla"], - endpoint: "GET /api/cotizaciones", - async run({ flags, cliente }) { - const p = new URLSearchParams(); - if (flags.estado) p.set("estado", unoDe(flags.estado, DOMINIO.estadosCotizacion, "estado")); - if (flags.q) p.set("q", flags.q); - if (flags.cliente) p.set("clienteId", flags.cliente); - p.set("limit", String(entero(flags.limit ?? 50, "limit"))); - const lista = await cliente.api("GET", `/api/cotizaciones?${p}`); - return flags.completo ? lista : lista.map(resumenCotizacion); - }, - }, - { - comando: "cotizaciones ver", - descripcion: "Detalle completo de una cotizacion (por id o por numero, ej. UJ2605AG001).", - argumentos: [{ nombre: "id", descripcion: "Id o numero de la cotizacion" }], - endpoint: "GET /api/cotizaciones/{id}", - async run({ pos, cliente }) { - const id = await resolverCotizacion(cliente.api, exigirPosicional(pos, 0, "id", "cotizaciones ver")); - return cliente.api("GET", `/api/cotizaciones/${id}`); - }, - }, - { - comando: "cotizaciones crear", - alias: ["cotizaciones nueva"], - descripcion: - "Crea una cotizacion en borrador. El servidor asigna numero, asesor (tu usuario), fecha y vigencia (15 dias habiles). Si el cliente (nombre+empresa) no existe, se crea.", - flags: [ - { flag: "cliente", tipo: "texto", descripcion: "Nombre del cliente (obligatorio)" }, - { flag: "empresa", tipo: "texto", descripcion: "Empresa del cliente" }, - { flag: "email", tipo: "texto", descripcion: "Correo del cliente" }, - { flag: "telefono", tipo: "texto", descripcion: "Telefono del cliente" }, - { flag: "servicio", tipo: "texto", repetible: true, descripcion: 'Servicio del catalogo: "id", "nombre exacto" o "id=precio" para ajustar el precio. Repetible' }, - { flag: "partida-horas", tipo: "texto", repetible: true, descripcion: 'Partida por horas: "Concepto|horas|tarifa" (tarifa opcional). Repetible' }, - { flag: "proyecto", tipo: "texto", descripcion: 'Nombre del proyecto (default "MKT Digital")' }, - { flag: "moneda", tipo: "texto", valores: DOMINIO.monedas, descripcion: "MXN (default) o USD" }, - { flag: "esquema-pago", tipo: "texto", valores: DOMINIO.esquemasPago, descripcion: 'Default "Pago Unico/Mensual"' }, - { flag: "bucefalo", tipo: "texto", valores: DOMINIO.planesBucefaloCRM, descripcion: "Agrega un plan de Bucefalo CRM (precio de lista)" }, - { flag: "observaciones", tipo: "texto", descripcion: "Observaciones visibles para el cliente" }, - { flag: "notas-internas", tipo: "texto", descripcion: "Observaciones internas (no salen en el PDF)" }, - { flag: "sin-iva", tipo: "booleano", descripcion: "No sumar IVA" }, - { flag: "bonos", tipo: "booleano", descripcion: "Incluir bonos" }, - { flag: "financiamiento", tipo: "booleano", descripcion: "Incluir financiamiento" }, - { flag: "fecha", tipo: "fecha", descripcion: "YYYY-MM-DD (default hoy)" }, - { flag: "asesor", tipo: "texto", descripcion: "Id del asesor (default: el usuario de la sesion)" }, - { flag: "datos", tipo: "json", descripcion: "Cuerpo JSON completo de POST /api/cotizaciones (ver `cotizador esquema`). Las flags tienen prioridad" }, - ], - ejemplos: [ - 'cotizador cotizaciones crear --cliente "Ana Ruiz" --empresa "Panaderia Sol" --servicio "Landing Page" --servicio cmabc123...=4500 --bucefalo estandar', - 'cotizador cotizaciones crear --cliente "Ana Ruiz" --partida-horas "Soporte tecnico|10|700"', - ], - endpoint: "POST /api/cotizaciones", - async run({ flags, cliente }) { - const base = await leerDatos(flags.datos); - const partidas = [...(Array.isArray(base.servicios) ? base.servicios : [])]; - for (const ref of flags.servicio ?? []) { - const m = ref.match(/^(.*?)\s*=\s*([\d.,$\s]+)$/); - const nombreOId = m ? m[1] : ref; - const precio = m ? numero(m[2], "servicio") : undefined; - const s = await resolverServicio(cliente.api, nombreOId); - partidas.push(partidaDesdeCatalogo(s, precio)); - } - for (const txt of flags.partidaHoras ?? []) partidas.push(partidaPorHoras(txt)); - - const clienteBase = base.cliente && typeof base.cliente === "object" ? base.cliente : {}; - const datosCliente = quitarIndefinidos({ - ...clienteBase, - nombre: flags.cliente ?? clienteBase.nombre, - empresa: flags.empresa ?? clienteBase.empresa, - email: flags.email ?? clienteBase.email, - telefono: flags.telefono ?? clienteBase.telefono, - }); - if (!datosCliente.nombre) { - throw errorUso("Falta --cliente", 'Ejemplo: cotizador cotizaciones crear --cliente "Ana Ruiz" --servicio "Landing Page"'); - } - if (partidas.length === 0 && !flags.bucefalo && !base.planBucefalo) { - throw errorUso( - "La cotizacion no tiene partidas", - "Agrega --servicio (busca con `cotizador servicios listar`), --partida-horas o --bucefalo" - ); - } - const cuerpo = { - ...base, - ...quitarIndefinidos({ - proyecto: flags.proyecto, - moneda: unoDe(flags.moneda, DOMINIO.monedas, "moneda"), - esquemaPago: unoDe(flags.esquemaPago, DOMINIO.esquemasPago, "esquema-pago"), - observaciones: flags.observaciones, - observacionesInternas: flags.notasInternas, - incluirIva: flags.sinIva ? false : undefined, - incluirBonos: flags.bonos, - incluirFinanciamiento: flags.financiamiento, - fecha: fechaISO(flags.fecha, "fecha"), - asesorId: flags.asesor, - planBucefalo: flags.bucefalo ? { nivel: unoDe(flags.bucefalo, DOMINIO.planesBucefaloCRM, "bucefalo") } : undefined, - }), - cliente: datosCliente, - servicios: partidas, - }; - const creada = await cliente.api("POST", "/api/cotizaciones", { cuerpo }); - return { ok: true, id: creada.id, numero: creada.numero, estado: creada.estado, url: `${cliente.base}/cotizaciones/${creada.id}` }; - }, - }, - { - comando: "cotizaciones estado", - descripcion: "Cambia el estado de una cotizacion.", - argumentos: [ - { nombre: "id", descripcion: "Id o numero de la cotizacion" }, - { nombre: "estado", descripcion: DOMINIO.estadosCotizacion.join(" | ") }, - ], - ejemplos: ["cotizador cotizaciones estado UJ2605AG001 enviada"], - endpoint: "PUT /api/cotizaciones/{id}", - async run({ pos, cliente }) { - const ref = exigirPosicional(pos, 0, "id", "cotizaciones estado"); - const estado = unoDe(exigirPosicional(pos, 1, "estado", "cotizaciones estado "), DOMINIO.estadosCotizacion, "estado"); - const id = await resolverCotizacion(cliente.api, ref); - const r = await cliente.api("PUT", `/api/cotizaciones/${id}`, { cuerpo: { estado } }); - return { ok: true, id: r.id, numero: r.numero, estado: r.estado }; - }, - }, - { - comando: "cotizaciones pdf", - descripcion: "Descarga el PDF de una cotizacion.", - argumentos: [{ nombre: "id", descripcion: "Id o numero de la cotizacion" }], - flags: [{ flag: "salida", tipo: "texto", descripcion: "Ruta del archivo (default: nombre que da el servidor, en la carpeta actual)" }], - endpoint: "GET /api/export/pdf/{id}", - async run({ pos, flags, cliente }) { - const id = await resolverCotizacion(cliente.api, exigirPosicional(pos, 0, "id", "cotizaciones pdf")); - return descargar(cliente, `/api/export/pdf/${id}`, flags.salida, `cotizacion-${id}.pdf`); - }, - }, - { - comando: "cotizaciones excel", - descripcion: "Descarga el Excel de una cotizacion.", - argumentos: [{ nombre: "id", descripcion: "Id o numero de la cotizacion" }], - flags: [{ flag: "salida", tipo: "texto", descripcion: "Ruta del archivo" }], - endpoint: "GET /api/export/excel/{id}", - async run({ pos, flags, cliente }) { - const id = await resolverCotizacion(cliente.api, exigirPosicional(pos, 0, "id", "cotizaciones excel")); - return descargar(cliente, `/api/export/excel/${id}`, flags.salida, `cotizacion-${id}.xlsx`); - }, - }, - { - comando: "cotizaciones eliminar", - descripcion: "Borra una cotizacion y sus partidas.", - argumentos: [{ nombre: "id", descripcion: "Id o numero de la cotizacion" }], - flags: [CONFIRMAR], - endpoint: "DELETE /api/cotizaciones/{id}", - async run({ pos, flags, cliente }) { - const ref = exigirPosicional(pos, 0, "id", "cotizaciones eliminar"); - exigirConfirmacion(flags, "Eliminar una cotizacion"); - const id = await resolverCotizacion(cliente.api, ref); - return cliente.api("DELETE", `/api/cotizaciones/${id}`); - }, - }, - - // ----- horas ----- - { - comando: "horas listar", - descripcion: "Registros de horas de una cotizacion por tiempo.", - argumentos: [{ nombre: "cotizacion", descripcion: "Id o numero de la cotizacion" }], - flags: [ - { flag: "desde", tipo: "fecha", descripcion: "YYYY-MM-DD" }, - { flag: "hasta", tipo: "fecha", descripcion: "YYYY-MM-DD" }, - ], - endpoint: "GET /api/cotizaciones/{id}/horas", - async run({ pos, flags, cliente }) { - const id = await resolverCotizacion(cliente.api, exigirPosicional(pos, 0, "cotizacion", "horas listar")); - const p = new URLSearchParams(); - if (flags.desde) p.set("from", fechaISO(flags.desde, "desde")); - if (flags.hasta) p.set("to", fechaISO(flags.hasta, "hasta")); - const qs = p.toString(); - return cliente.api("GET", `/api/cotizaciones/${id}/horas${qs ? `?${qs}` : ""}`); - }, - }, - { - comando: "horas registrar", - descripcion: "Registra horas trabajadas (solo en cotizaciones con partidas por horas, retainer o demanda).", - argumentos: [{ nombre: "cotizacion", descripcion: "Id o numero de la cotizacion" }], - flags: [ - { flag: "fecha", tipo: "fecha", descripcion: "YYYY-MM-DD (obligatoria)" }, - { flag: "inicio", tipo: "texto", descripcion: "HH:MM (obligatoria)" }, - { flag: "fin", tipo: "texto", descripcion: "HH:MM (obligatoria)" }, - { flag: "descripcion", tipo: "texto", descripcion: "Que se hizo (obligatoria)" }, - { flag: "tarifa", tipo: "numero", descripcion: "Tarifa por hora (default: la de la cotizacion)" }, - ], - ejemplos: ['cotizador horas registrar UJ2605AG001 --fecha 2026-11-20 --inicio 09:00 --fin 11:30 --descripcion "Ajustes de campanas"'], - endpoint: "POST /api/cotizaciones/{id}/horas", - async run({ pos, flags, cliente }) { - const id = await resolverCotizacion(cliente.api, exigirPosicional(pos, 0, "cotizacion", "horas registrar")); - const faltan = ["fecha", "inicio", "fin", "descripcion"].filter((k) => !flags[k]); - if (faltan.length) throw errorUso(`Faltan: ${faltan.map((f) => `--${f}`).join(", ")}`); - return cliente.api("POST", `/api/cotizaciones/${id}/horas`, { - cuerpo: quitarIndefinidos({ - fecha: fechaISO(flags.fecha, "fecha"), - horaInicio: flags.inicio, - horaFin: flags.fin, - descripcion: flags.descripcion, - tarifaHora: numero(flags.tarifa, "tarifa"), - }), - }); - }, - }, - - // ----- utilidades ----- - { - comando: "api", - descripcion: - "Llamada directa a cualquier endpoint de la API (escape para lo que no cubren los comandos). La ruta empieza con /api/.", - argumentos: [ - { nombre: "metodo", descripcion: "GET | POST | PUT | PATCH | DELETE" }, - { nombre: "ruta", descripcion: "Ej. /api/configuracion" }, - ], - flags: [{ flag: "datos", tipo: "json", descripcion: "Cuerpo JSON (en linea, @archivo.json o -)" }], - ejemplos: ["cotizador api GET /api/configuracion", `cotizador api POST /api/cobros/recordatorios --datos '{}'`], - endpoint: "*", - async run({ pos, flags, cliente }) { - const metodo = unoDe(exigirPosicional(pos, 0, "metodo", "api").toUpperCase(), ["GET", "POST", "PUT", "PATCH", "DELETE"], "metodo"); - let ruta = exigirPosicional(pos, 1, "ruta", "api ").replace(/\\/g, "/"); - // Git Bash (MSYS) convierte "/api/x" en "C:/Program Files/Git/api/x": se - // recupera la parte desde "/api/". Tambien se acepta "api/x" sin barra. - const corte = ruta.indexOf("/api/"); - if (corte > 0) ruta = ruta.slice(corte); - if (ruta.startsWith("api/")) ruta = "/" + ruta; - if (!ruta.startsWith("/api/")) throw errorUso("La ruta debe empezar con /api/ (ej. /api/configuracion)"); - const cuerpo = flags.datos !== undefined ? await leerDatos(flags.datos) : undefined; - return cliente.api(metodo, ruta, { cuerpo }); - }, - }, - { - comando: "esquema", - alias: ["schema"], - descripcion: "Describe en JSON todos los comandos, flags, tipos, ejemplos, codigos de salida y el dominio. Pensado para LLMs.", - sinServidor: true, - async run() { - return esquema(); - }, - }, - { - comando: "ayuda", - alias: ["help"], - descripcion: "Ayuda legible. `cotizador ayuda ` para uno en particular.", - sinServidor: true, - async run({ pos }) { - process.stdout.write(pos.length ? ayudaComando(buscarComando(pos).cmd ?? fallarComando(pos)) : ayudaGeneral()); - return undefined; - }, - }, - { - comando: "version", - sinServidor: true, - descripcion: "Version del CLI.", - async run() { - return { version: VERSION }; - }, - }, -]; - -async function descargar(cliente, ruta, salida, porDefecto) { - const { buffer, nombreArchivo, tipo } = await cliente.api("GET", ruta, { binario: true }); - const destino = resolve(salida || nombreArchivo || porDefecto); - await mkdir(dirname(destino), { recursive: true }); - await writeFile(destino, buffer); - return { ok: true, archivo: destino, bytes: buffer.length, tipo }; -} - -// --------------------------------------------------------------------------- -// Ayuda y esquema -// --------------------------------------------------------------------------- - -function buscarComando(palabras) { - // Coincidencia mas larga primero: "servicios crear" antes que "servicios". - for (let n = Math.min(palabras.length, 3); n >= 1; n--) { - const clave = palabras.slice(0, n).join(" ").toLowerCase(); - const cmd = COMANDOS.find((c) => c.comando === clave || (c.alias ?? []).includes(clave)); - if (cmd) return { cmd, consumidas: n }; - } - return { cmd: null, consumidas: 0 }; -} - -function fallarComando(palabras) { - const grupo = palabras[0]?.toLowerCase(); - const delGrupo = COMANDOS.filter((c) => c.comando.split(" ")[0] === grupo).map((c) => c.comando); - throw errorUso( - `Comando desconocido: ${palabras.join(" ")}`, - delGrupo.length - ? `Comandos de "${grupo}": ${delGrupo.join(", ")}` - : "Ejecuta `cotizador ayuda` o `cotizador esquema` para ver los comandos" - ); -} - -function esquema() { - return { - nombre: "cotizador", - version: VERSION, - descripcion: - "CLI del Cotizador — Uriel Jareth Consulting. Gestiona el catalogo de servicios, clientes, cotizaciones y horas a traves de la API REST de la plataforma.", - convenciones: { - salida: "JSON en stdout (usa --campos para recortar, --formato tabla para humanos)", - errores: "JSON en stderr: { ok:false, error, codigo, status?, detalles?, sugerencia? }", - entrada: "Flags --kebab-case; --datos acepta JSON en linea, @archivo.json o - (stdin). Las flags tienen prioridad sobre --datos", - ids: "Donde se pide de servicio tambien vale su nombre exacto; para cotizaciones, el numero (UJ...)", - escritura: "Usa --dry-run para ver la peticion sin enviarla. Borrar exige --confirmar", - montos: "Precios en MXN sin IVA (IVA 16% se calcula al cotizar)", - }, - configuracion: { - COTIZADOR_URL: "URL base (default http://localhost:3000; produccion: https://cotizador.urieljareth.org)", - COTIZADOR_EMAIL: "Correo para login automatico cuando no hay sesion o vencio", - COTIZADOR_PASSWORD: "Contrasena para login automatico", - COTIZADOR_TOKEN: "Token de sesion explicito (omite el archivo de sesiones)", - COTIZADOR_HOME: "Carpeta de la sesion guardada (default ~/.cotizador-uj)", - }, - codigosSalida: DESCRIPCION_CODIGOS, - dominio: DOMINIO, - formatos: { - servicioCatalogo: { - nombre: "texto (obligatorio)", - fase: "0-3 (obligatorio)", - tipoPago: "unico | mensual (obligatorio)", - precioBase: "numero >= 0 (obligatorio)", - descripcion: "texto | null", - tiempoEntrega: 'texto (default "4 - 10 dias")', - entregablesDefault: "texto[]", - categoriaId: "id | null (en el CLI tambien `categoria`: nombre)", - variante: "texto | null", - nivel: `${DOMINIO.nivelesServicio.join(" | ")} | null`, - orden: "entero (default: al final de su fase)", - activo: "booleano (default true)", - }, - partidaCotizacion: { - catalogoId: 'id del servicio, o "custom-" si esPersonalizado', - nombre: "texto", - fase: "0-3", - tipoPago: "unico | mensual", - precio: "numero: total autoritativo de la partida", - tiempoEntrega: "texto", - entregables: "texto[]", - esPersonalizado: "booleano (partidas fuera del catalogo)", - modeloCobro: "fijo | horas | retainer | demanda", - horas: "numero (modelo horas)", - tarifaHora: "numero", - montoMinimo: "numero (retainer)", - horasIncluidas: "numero (retainer)", - opcion: '"1" | "2" | "ambas" (solo cotizaciones doble propuesta)', - }, - }, - flagsGlobales: FLAGS_GLOBALES.map(describirFlag), - comandos: COMANDOS.map((c) => ({ - comando: c.comando, - ...(c.alias && { alias: c.alias }), - descripcion: c.descripcion, - uso: usoDe(c), - argumentos: c.argumentos ?? [], - flags: (c.flags ?? []).map(describirFlag), - ejemplos: c.ejemplos ?? [], - endpoint: c.endpoint ?? null, - })), - }; -} - -function describirFlag(f) { - return quitarIndefinidos({ - flag: `--${f.flag}`, - tipo: f.tipo, - valores: f.valores, - repetible: f.repetible || undefined, - descripcion: f.descripcion, - }); -} - -function usoDe(c) { - const args = (c.argumentos ?? []).map((a) => `<${a.nombre}>`).join(" "); - return `cotizador ${c.comando}${args ? " " + args : ""}${c.flags?.length ? " [flags]" : ""}`; -} - -function ayudaGeneral() { - const grupos = new Map(); - for (const c of COMANDOS) { - const g = c.comando.includes(" ") ? c.comando.split(" ")[0] : "general"; - if (!grupos.has(g)) grupos.set(g, []); - grupos.get(g).push(c); - } - const ancho = Math.max(...COMANDOS.map((c) => c.comando.length)) + 2; - let txt = `cotizador ${VERSION} — CLI del Cotizador — Uriel Jareth Consulting\n\nUso: cotizador [argumentos] [flags]\n`; - for (const [g, cmds] of grupos) { - txt += `\n${g.toUpperCase()}\n`; - for (const c of cmds) txt += ` ${c.comando.padEnd(ancho)}${c.descripcion.split(/\.\s+(?=[A-Z(])/)[0]}\n`; - } - txt += `\nFLAGS GLOBALES\n`; - for (const f of FLAGS_GLOBALES) txt += ` --${f.flag.padEnd(ancho - 2)}${f.descripcion}\n`; - txt += - "\nPrimeros pasos:\n" + - " cotizador login --email --password-stdin\n" + - " cotizador servicios listar --formato tabla\n" + - " cotizador esquema (descripcion completa en JSON, para LLMs)\n" + - "\nMas: cotizador ayuda · docs/CLI.md\n"; - return txt; -} - -function ayudaComando(c) { - let txt = `${usoDe(c)}\n\n${c.descripcion}\n`; - if (c.endpoint) txt += `\nEndpoint: ${c.endpoint}\n`; - if (c.argumentos?.length) { - txt += "\nArgumentos:\n"; - for (const a of c.argumentos) txt += ` <${a.nombre}> ${a.descripcion}\n`; - } - if (c.flags?.length) { - txt += "\nFlags:\n"; - const ancho = Math.max(...c.flags.map((f) => f.flag.length)) + 4; - for (const f of c.flags) { - const extra = [f.valores ? `valores: ${f.valores.join(", ")}` : null, f.repetible ? "repetible" : null].filter(Boolean).join("; "); - txt += ` --${f.flag.padEnd(ancho)}${f.descripcion}${extra ? ` (${extra})` : ""}\n`; - } - } - if (c.ejemplos?.length) { - txt += "\nEjemplos:\n"; - for (const e of c.ejemplos) txt += ` ${e}\n`; - } - if (c.alias?.length) txt += `\nAlias: ${c.alias.join(", ")}\n`; - return txt; -} - -// --------------------------------------------------------------------------- -// Main -// --------------------------------------------------------------------------- - -async function main(argv) { - // Todas las flags conocidas, para que el parser sepa cuales son booleanas. - const todasLasFlags = [...FLAGS_GLOBALES, ...COMANDOS.flatMap((c) => c.flags ?? [])]; - const { posicionales, flags } = parsearArgs(argv, todasLasFlags); - - if (flags.version) return imprimir({ version: VERSION }, flags); - if (posicionales.length === 0) { - process.stdout.write(ayudaGeneral()); - return; - } - - const { cmd, consumidas } = buscarComando(posicionales); - if (!cmd) fallarComando(posicionales); - const pos = posicionales.slice(consumidas); - - if (flags.ayuda) { - process.stdout.write(ayudaComando(cmd)); - return; - } - if (flags.formato && !["json", "tabla"].includes(flags.formato)) { - throw errorUso("--formato debe ser json o tabla"); - } - - // Flags que el comando no reconoce: mejor fallar que ignorarlas en silencio. - const validas = new Set([...FLAGS_GLOBALES, ...(cmd.flags ?? [])].map((f) => aCamel(f.flag))); - const desconocidas = Object.keys(flags).filter((k) => !validas.has(k)); - if (desconocidas.length) { - throw errorUso( - `Flag no valida para "${cmd.comando}": ${desconocidas.map((k) => "--" + k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase())).join(", ")}`, - `Flags validas: ${(cmd.flags ?? []).map((f) => "--" + f.flag).join(", ") || "(ninguna)"}. Ver: cotizador ayuda ${cmd.comando}` - ); - } - - const cliente = cmd.sinServidor ? null : crearCliente(flags); - const resultado = await cmd.run({ pos, flags, cliente }); - if (resultado !== undefined) imprimir(resultado, flags); -} - -main(process.argv.slice(2)).then( - () => process.exit(CODIGOS.ok), - (err) => { - if (err instanceof DryRun) { - process.stdout.write(JSON.stringify({ dryRun: true, ...err.peticion }, null, 2) + "\n"); - process.exit(CODIGOS.ok); - } - if (err instanceof CliError) { - imprimirError(err); - process.exit(err.codigo); - } - imprimirError(new CliError(err?.message || String(err))); - process.exit(CODIGOS.error); - } -); diff --git a/cmd/cotizador/main.go b/cmd/cotizador/main.go new file mode 100644 index 0000000..3da2295 --- /dev/null +++ b/cmd/cotizador/main.go @@ -0,0 +1,171 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "cotizador/internal/auth" + "cotizador/internal/cli" + "cotizador/internal/config" + "cotizador/internal/db" + "cotizador/internal/httpapi" + "cotizador/internal/notify" + "cotizador/internal/scheduler" + "cotizador/internal/seed" + "cotizador/internal/webhooks" +) + +func main() { + subcmd := "serve" + var subArgs []string + if len(os.Args) > 1 { + subcmd = os.Args[1] + subArgs = os.Args[2:] + } + + switch subcmd { + case "cli": + os.Exit(cli.Run(subArgs)) + case "migrate": + if err := runMigrate(); err != nil { + log.Fatalf("[migrate] %v", err) + } + log.Println("[migrate] migraciones aplicadas correctamente") + case "seed": + if err := runSeed(); err != nil { + log.Fatalf("[seed] %v", err) + } + log.Println("[seed] catalogo y configuracion inicial aplicados correctamente") + case "provision-keys": + if err := runProvisionKeys(subArgs); err != nil { + log.Fatalf("[provision-keys] %v", err) + } + case "serve": + if err := runServer(); err != nil { + log.Fatalf("[serve] %v", err) + } + default: + // Allow direct CLI commands like `cotizador esquema` or `cotizador servicios listar` + os.Exit(cli.Run(os.Args[1:])) + } +} + +func runMigrate() error { + cfg, err := config.Load() + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + pool, err := db.Connect(ctx, cfg) + if err != nil { + return err + } + defer pool.Close() + return db.Migrate(ctx, pool) +} + +func runSeed() error { + cfg, err := config.Load() + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + pool, err := db.Connect(ctx, cfg) + if err != nil { + return err + } + defer pool.Close() + if err := db.Migrate(ctx, pool); err != nil { + return err + } + return seed.Run(ctx, pool, cfg) +} + +func runProvisionKeys(args []string) error { + cfg, err := config.Load() + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + pool, err := db.Connect(ctx, cfg) + if err != nil { + return err + } + defer pool.Close() + return seed.RunProvisionKeys(ctx, pool, args) +} + +func runServer() error { + cfg, err := config.Load() + if err != nil { + return err + } + if err := cfg.RequireJWTSecret(); err != nil { + return err + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + pool, err := db.Connect(ctx, cfg) + if err != nil { + return err + } + defer pool.Close() + + // Always ensure schema migrations are applied on boot (safe & idempotent on live DBs) + if err := db.Migrate(ctx, pool); err != nil { + return fmt.Errorf("error en migracion automatica: %w", err) + } + if cfg.RunSeed { + if err := seed.Run(ctx, pool, cfg); err != nil { + return fmt.Errorf("error en seed automatico: %w", err) + } + log.Println("[boot] RUN_SEED=true aplicado correctamente") + } + + authSvc := auth.NewService(cfg.JWTSecret, cfg.IsProduction(), pool) + whDispatcher := webhooks.NewDispatcher(pool, cfg) + notifSvc := notify.NewService(cfg, pool, whDispatcher) + + // Start recurring payment & reminder scheduler + scheduler.Start(ctx, pool, notifSvc) + + srv := httpapi.NewServer(cfg, pool, authSvc, whDispatcher, notifSvc) + httpSrv := &http.Server{ + Addr: ":" + cfg.Port, + Handler: srv.Router(), + ReadHeaderTimeout: 15 * time.Second, + ReadTimeout: 60 * time.Second, + WriteTimeout: 300 * time.Second, + IdleTimeout: 120 * time.Second, + } + + errCh := make(chan error, 1) + go func() { + log.Printf("[cotizador] servidor Go escuchando en :%s (APP_URL=%s)", cfg.Port, cfg.AppURL) + if err := httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + errCh <- err + } + }() + + select { + case <-ctx.Done(): + log.Println("[cotizador] cerrando servidor ordenadamente...") + shutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return httpSrv.Shutdown(shutCtx) + case err := <-errCh: + return err + } +} diff --git a/docker-compose.coolify.yml b/docker-compose.coolify.yml index 28e8736..350d22c 100644 --- a/docker-compose.coolify.yml +++ b/docker-compose.coolify.yml @@ -1,13 +1,10 @@ -# Cotizador — Uriel Jareth Consulting — stack de producción para Coolify +# Cotizador — Uriel Jareth Consulting — stack de producción para Coolify (Go + SPA embebido) # -# En Coolify: crear recurso "Docker Compose" apuntando a este repo y configurar -# "Docker Compose Location" = /docker-compose.coolify.yml +# En Coolify: Docker Compose Location = /docker-compose.yaml (copia byte-identica de este archivo). +# Las variables SERVICE_FQDN_WEB_3000 las resuelve Coolify automáticamente. +# Define JWT_SECRET, DB_PASSWORD y las variables opcionales en Coolify. # -# Las variables SERVICE_FQDN_* las resuelve Coolify automáticamente (asignan -# dominio a cada servicio). Define JWT_SECRET, API_KEY, DB_PASSWORD y las -# SEED_* en el panel de variables de entorno de Coolify. -# -# Para desarrollo local sigue usándose docker-compose.yml + start.bat. +# Para desarrollo local usa docker-compose.yml + start.bat. services: postgres: @@ -16,7 +13,7 @@ services: environment: POSTGRES_USER: ${DB_USER:-postgres} POSTGRES_PASSWORD: ${DB_PASSWORD:-postgres} - # Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data. + # Se conserva el nombre físico de BD en producción para no romper el volumen postgres_data. POSTGRES_DB: ${DB_NAME:-cotizador_e3} volumes: - postgres_data:/var/lib/postgresql/data @@ -33,18 +30,14 @@ services: restart: unless-stopped environment: - SERVICE_FQDN_WEB_3000 + - PORT=3000 - DB_HOST=postgres - DB_PORT=5432 - DB_USER=${DB_USER:-postgres} - DB_PASSWORD=${DB_PASSWORD:-postgres} - DB_NAME=${DB_NAME:-cotizador_e3} - # Solo la usa el CLI de Prisma (migrate deploy); debe coincidir con DB_* - - DATABASE_URL=postgresql://${DB_USER:-postgres}:${DB_PASSWORD:-postgres}@postgres:5432/${DB_NAME:-cotizador_e3} - JWT_SECRET=${JWT_SECRET} - # Propuesta consultiva con IA (MiniMax). Sin MINIMAX_API_KEY el boton de - # generar devuelve un error claro; el resto de la app funciona igual. - # OJO: el prefijo NO puede ser ANTHROPIC_*, el SDK lo lee por su cuenta y - # mandaria la clave de MiniMax a api.anthropic.com. + # Propuesta consultiva con IA (MiniMax). Sin MINIMAX_API_KEY el botón devuelve error claro. - MINIMAX_API_KEY=${MINIMAX_API_KEY} - MINIMAX_BASE_URL=${MINIMAX_BASE_URL:-https://api.minimax.io/anthropic} - MINIMAX_MODEL=${MINIMAX_MODEL:-MiniMax-M3} @@ -56,25 +49,23 @@ services: - SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL} - SEED_ASESOR_PASSWORD=${SEED_ASESOR_PASSWORD} - SEED_ASESOR_NAME=${SEED_ASESOR_NAME} - # URL publica: la usan los links de correo y de las notificaciones push. - # Se lee en tiempo de ejecucion (no NEXT_PUBLIC_*: Next lo fijaria al compilar). + # URL pública para links de correo, aprobación y notificaciones push - APP_URL=${APP_URL} - # Web Push (VAPID). Generar con: node -e "console.log(require('web-push').generateVAPIDKeys())" - # La app funciona sin ellas: las notificaciones se omiten con aviso en log. + # Web Push (VAPID) - VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY} - VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY} - # SMTP de correos. Sin SMTP_HOST la app no falla: omito el envio y lo avisa en log. + # SMTP de correos (opcional: sin SMTP_HOST se omite el envío y avisa en log) - SMTP_HOST=${SMTP_HOST} - SMTP_PORT=${SMTP_PORT:-587} - SMTP_USER=${SMTP_USER} - SMTP_PASS=${SMTP_PASS} - SMTP_FROM=${SMTP_FROM} - SMTP_FROM_NAME=${SMTP_FROM_NAME:-Uriel Jareth Consulting} - # Cada cuantos dias se reenvia el recordatorio de pagos pendientes (0 = apagado). + # Recordatorios de pagos pendientes (días; 0 = apagado) - COBROS_RECORDATORIO_DIAS=${COBROS_RECORDATORIO_DIAS:-3} - # Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente. + # Comprobantes de pago en volumen persistente - UPLOAD_DIR=/app/uploads - # Notificaciones de aprobacion humana y webhooks HMAC-SHA256 hacia n8n + # Notificaciones de aprobación humana y webhooks HMAC-SHA256 hacia n8n - ADMIN_NOTIFY_EMAIL=${ADMIN_NOTIFY_EMAIL} - WEBHOOK_N8N_URL=${WEBHOOK_N8N_URL} - WEBHOOK_N8N_SECRET=${WEBHOOK_N8N_SECRET} @@ -85,36 +76,7 @@ services: postgres: condition: service_healthy healthcheck: - test: ["CMD", "node", "-e", "fetch('http://localhost:3000/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] - interval: 30s - timeout: 10s - start_period: 60s - retries: 5 - - api: - build: - context: ./api - dockerfile: Dockerfile - restart: unless-stopped - environment: - - SERVICE_FQDN_API_8000 - - DB_HOST=postgres - - DB_PORT=5432 - - DB_USER=${DB_USER:-postgres} - - DB_PASSWORD=${DB_PASSWORD:-postgres} - - DB_NAME=${DB_NAME:-cotizador_e3} - - API_KEY=${API_KEY} - - JWT_SECRET=${JWT_SECRET} - # La vieja API_KEY sin alcances queda desactivada por defecto; usar AgentApiKey - - ALLOW_LEGACY_API_KEY=${ALLOW_LEGACY_API_KEY:-false} - depends_on: - postgres: - condition: service_healthy - # web aplica las migraciones de Prisma; el api usa las mismas tablas - web: - condition: service_healthy - healthcheck: - test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/health').status==200 else 1)"] + test: ["CMD-SHELL", "wget -qO- http://localhost:3000/api/health >/dev/null || exit 1"] interval: 30s timeout: 10s start_period: 30s diff --git a/docker-compose.yaml b/docker-compose.yaml index 28e8736..350d22c 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -1,13 +1,10 @@ -# Cotizador — Uriel Jareth Consulting — stack de producción para Coolify +# Cotizador — Uriel Jareth Consulting — stack de producción para Coolify (Go + SPA embebido) # -# En Coolify: crear recurso "Docker Compose" apuntando a este repo y configurar -# "Docker Compose Location" = /docker-compose.coolify.yml +# En Coolify: Docker Compose Location = /docker-compose.yaml (copia byte-identica de este archivo). +# Las variables SERVICE_FQDN_WEB_3000 las resuelve Coolify automáticamente. +# Define JWT_SECRET, DB_PASSWORD y las variables opcionales en Coolify. # -# Las variables SERVICE_FQDN_* las resuelve Coolify automáticamente (asignan -# dominio a cada servicio). Define JWT_SECRET, API_KEY, DB_PASSWORD y las -# SEED_* en el panel de variables de entorno de Coolify. -# -# Para desarrollo local sigue usándose docker-compose.yml + start.bat. +# Para desarrollo local usa docker-compose.yml + start.bat. services: postgres: @@ -16,7 +13,7 @@ services: environment: POSTGRES_USER: ${DB_USER:-postgres} POSTGRES_PASSWORD: ${DB_PASSWORD:-postgres} - # Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data. + # Se conserva el nombre físico de BD en producción para no romper el volumen postgres_data. POSTGRES_DB: ${DB_NAME:-cotizador_e3} volumes: - postgres_data:/var/lib/postgresql/data @@ -33,18 +30,14 @@ services: restart: unless-stopped environment: - SERVICE_FQDN_WEB_3000 + - PORT=3000 - DB_HOST=postgres - DB_PORT=5432 - DB_USER=${DB_USER:-postgres} - DB_PASSWORD=${DB_PASSWORD:-postgres} - DB_NAME=${DB_NAME:-cotizador_e3} - # Solo la usa el CLI de Prisma (migrate deploy); debe coincidir con DB_* - - DATABASE_URL=postgresql://${DB_USER:-postgres}:${DB_PASSWORD:-postgres}@postgres:5432/${DB_NAME:-cotizador_e3} - JWT_SECRET=${JWT_SECRET} - # Propuesta consultiva con IA (MiniMax). Sin MINIMAX_API_KEY el boton de - # generar devuelve un error claro; el resto de la app funciona igual. - # OJO: el prefijo NO puede ser ANTHROPIC_*, el SDK lo lee por su cuenta y - # mandaria la clave de MiniMax a api.anthropic.com. + # Propuesta consultiva con IA (MiniMax). Sin MINIMAX_API_KEY el botón devuelve error claro. - MINIMAX_API_KEY=${MINIMAX_API_KEY} - MINIMAX_BASE_URL=${MINIMAX_BASE_URL:-https://api.minimax.io/anthropic} - MINIMAX_MODEL=${MINIMAX_MODEL:-MiniMax-M3} @@ -56,25 +49,23 @@ services: - SEED_ASESOR_EMAIL=${SEED_ASESOR_EMAIL} - SEED_ASESOR_PASSWORD=${SEED_ASESOR_PASSWORD} - SEED_ASESOR_NAME=${SEED_ASESOR_NAME} - # URL publica: la usan los links de correo y de las notificaciones push. - # Se lee en tiempo de ejecucion (no NEXT_PUBLIC_*: Next lo fijaria al compilar). + # URL pública para links de correo, aprobación y notificaciones push - APP_URL=${APP_URL} - # Web Push (VAPID). Generar con: node -e "console.log(require('web-push').generateVAPIDKeys())" - # La app funciona sin ellas: las notificaciones se omiten con aviso en log. + # Web Push (VAPID) - VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY} - VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY} - # SMTP de correos. Sin SMTP_HOST la app no falla: omito el envio y lo avisa en log. + # SMTP de correos (opcional: sin SMTP_HOST se omite el envío y avisa en log) - SMTP_HOST=${SMTP_HOST} - SMTP_PORT=${SMTP_PORT:-587} - SMTP_USER=${SMTP_USER} - SMTP_PASS=${SMTP_PASS} - SMTP_FROM=${SMTP_FROM} - SMTP_FROM_NAME=${SMTP_FROM_NAME:-Uriel Jareth Consulting} - # Cada cuantos dias se reenvia el recordatorio de pagos pendientes (0 = apagado). + # Recordatorios de pagos pendientes (días; 0 = apagado) - COBROS_RECORDATORIO_DIAS=${COBROS_RECORDATORIO_DIAS:-3} - # Comprobantes de pago (imagenes convertidas a webp + PDFs) en volumen persistente. + # Comprobantes de pago en volumen persistente - UPLOAD_DIR=/app/uploads - # Notificaciones de aprobacion humana y webhooks HMAC-SHA256 hacia n8n + # Notificaciones de aprobación humana y webhooks HMAC-SHA256 hacia n8n - ADMIN_NOTIFY_EMAIL=${ADMIN_NOTIFY_EMAIL} - WEBHOOK_N8N_URL=${WEBHOOK_N8N_URL} - WEBHOOK_N8N_SECRET=${WEBHOOK_N8N_SECRET} @@ -85,36 +76,7 @@ services: postgres: condition: service_healthy healthcheck: - test: ["CMD", "node", "-e", "fetch('http://localhost:3000/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] - interval: 30s - timeout: 10s - start_period: 60s - retries: 5 - - api: - build: - context: ./api - dockerfile: Dockerfile - restart: unless-stopped - environment: - - SERVICE_FQDN_API_8000 - - DB_HOST=postgres - - DB_PORT=5432 - - DB_USER=${DB_USER:-postgres} - - DB_PASSWORD=${DB_PASSWORD:-postgres} - - DB_NAME=${DB_NAME:-cotizador_e3} - - API_KEY=${API_KEY} - - JWT_SECRET=${JWT_SECRET} - # La vieja API_KEY sin alcances queda desactivada por defecto; usar AgentApiKey - - ALLOW_LEGACY_API_KEY=${ALLOW_LEGACY_API_KEY:-false} - depends_on: - postgres: - condition: service_healthy - # web aplica las migraciones de Prisma; el api usa las mismas tablas - web: - condition: service_healthy - healthcheck: - test: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/health').status==200 else 1)"] + test: ["CMD-SHELL", "wget -qO- http://localhost:3000/api/health >/dev/null || exit 1"] interval: 30s timeout: 10s start_period: 30s diff --git a/docker-compose.yml b/docker-compose.yml index e6a71dd..b1e20de 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -6,29 +6,17 @@ services: environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres - # Se conserva el nombre fisico de BD para no romper el volumen postgres_data. + # Se conserva el nombre físico de BD para no romper el volumen postgres_data. POSTGRES_DB: cotizador_e3 ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data - - api: - build: ./api - container_name: cotizador-uj-api - restart: unless-stopped - ports: - - "8000:8000" - environment: - - DB_HOST=postgres - - DB_PORT=5432 - - DB_USER=postgres - - DB_PASSWORD=postgres - - DB_NAME=cotizador_e3 - - API_KEY=${API_KEY:-change-me} - - JWT_SECRET=${JWT_SECRET:-change-me} - depends_on: - - postgres + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres -d cotizador_e3"] + interval: 5s + timeout: 5s + retries: 20 volumes: postgres_data: diff --git a/docs/superpowers/specs/2026-11-28-migracion-go-design.md b/docs/superpowers/specs/2026-11-28-migracion-go-design.md new file mode 100644 index 0000000..33695d9 --- /dev/null +++ b/docs/superpowers/specs/2026-11-28-migracion-go-design.md @@ -0,0 +1,63 @@ +# Migración Completa a Go — Cotizador Uriel Jareth Consulting + +Fecha: 2026-11-28 +Estado: Aprobado (Opción A — ejecución autónoma hasta producción) + +## 1. Objetivo y Alcance + +Unificar todo el sistema Cotizador en **un único binario en Go** (`cotizador`) acompañado del frontend React actual compilado como SPA estática (Vite) y embebido vía `//go:embed`, eliminando Node.js y Python FastAPI de producción. + +- **Producción (Coolify)**: `postgres` (`postgres:16-alpine`, volumen `postgres_data` intacto) + `web` (binario Go en puerto `3000`, volumen `uploads_data:/app/uploads`). El servicio `api` (puerto `8000`, FastAPI) se elimina; todo el tráfico humano, de cliente y de agentes/n8n usa `/api/**` en `https://cotizador.urieljareth.org`. +- **Compatibilidad de datos**: Conexión directa a las 25 tablas PostgreSQL existentes (nombres PascalCase/camelCase creados por Prisma) sin pérdidas ni cambios destructivos. Sesiones JWT (`cotizador-session`, HS256 con `JWT_SECRET`) y contraseñas `bcrypt` mantienen compatibilidad al 100%. + +## 2. Arquitectura del Proyecto + +```text +cmd/ + cotizador/ # Binario único: serve (default), migrate, seed, provision-keys, cli +internal/ + config/ # Variables de entorno (DB_*, JWT_SECRET, APP_URL, SMTP_*, VAPID_*, MINIMAX_*, WEBHOOK_*, etc.) + db/ # pgxpool, migraciones SQL idempotentes embebidas, generador CUID + seed/ # Seed idempotente (usuarios, 7 categorías, 59 servicios, 7 paquetes, 6 bonos, 4 financiamiento, 16 config) + domain/ # calculators.go, cobros_fechas.go, aprobacion_core.go, solo_admin_core.go, models.go + auth/ # JWT HS256, bcrypt, AgentApiKey SHA-256, 9 scopes, rate limiter 60s, RequireActor + audit/ # Escritura best-effort a AuditLog + idempotency/ # Idempotency-Key (TTL 24h, SHA-256 body, 409 mismatch, X-Idempotency-Replayed) + webhooks/ # HMAC-SHA256, 8 eventos, fan-out WebhookEndpoint + WEBHOOK_N8N_URL, reintentos, WhatsApp n8n, pago.vencido idempotente + notify/ # SMTP HTML/PDF, Web Push (VAPID), recordatorios pendientes, alertas de aprobación a Jareth + uploads/ # Comprobantes en UPLOAD_DIR/comprobantes//. (<=10MB, WebP/JPEG/PDF, anti path-traversal) + pdf/ # 4 generadores PDF con fuente TrueType UTF-8 embebida (cotización, nota de horas, propuesta IA cliente, anexo interno) + excel/ # excelize/v2 (HOJA RESUMEN + hoja por servicio, simple y doble) + CSV catálogo export/plantilla/import + propuesta/ # Cliente MiniMax (Anthropic Messages + tool-calling + cache), economía, prompts, pipeline 3 pasos, validación R0..R6/filtros + scheduler/ # Goroutine (20s arranque, cada 60 min): generarCobros -> (>=9h MX) enviarRecordatoriosPendientes -> notificarCobrosNuevos + httpapi/ # chi/v5 router, middlewares de seguridad y separación de paneles, 62+ endpoints + 4 endpoints SPA + OpenAPI 3.1 + SPA embebida + cli/ # CLI en Go (29 comandos, esquema JSON, códigos de salida 0..7, ~/.cotizador-uj/sesiones.json) + spa/ # //go:embed dist/* (build estático de web/) +web/ # Vite + React 19 + React Router + Tailwind v4 + Zustand (15 vistas migradas de Next.js) +``` + +## 3. Reglas de Seguridad e Invariantes + +1. **Sin bypass de API key**: toda ruta protegida valida JWT o `AgentApiKey` directamente contra PostgreSQL (cierra el hueco de ~15 rutas que en Next.js dependían del middleware Edge). +2. **Separación estricta de paneles**: `role=cliente` solo accede a `/cliente*`, `/api/cliente*`, `/api/comprobantes/{pagoId}` (propios) y `GET /api/export/pdf/{id}` (propios). Staff no accede a `/cliente*` ni `/api/cliente*`. API keys jamás acceden a `/api/cliente*`. +3. **Regla de hierro de aprobación**: ningún agente puede aprobar cotizaciones (9 scopes permitidos, cero scope de aprobación). Transición `borrador -> aprobada` exige usuario humano `role="admin"` (`POST /api/cotizaciones/{id}/aprobar`) o enlace firmado de un solo uso (`/aprobar/{token}` con `POST { confirmar: true }`). Enviar exige `estado == "aprobada" && aprobadaAt != nil`. +4. **Restricción `soloAdmin` (Bucéfalo CRM)**: oculto en catálogo/paquetes y bloqueado en creación/edición de cotizaciones para cualquier agente. +5. **Privacidad estructural**: `observacionesInternas` nunca se expone en PDF/Excel ni a agentes con solo `cotizaciones:leer_aceptadas`. +6. **Idempotencia**: `Idempotency-Key` en `POST /api/clientes`, `POST /api/cotizaciones`, `POST /api/cotizaciones/{id}/enviar` y `POST /api/cobros/pagos/{id}/registrar`. + +## 4. Endpoints Adicionales para la SPA (reemplazo de Server Components) + +- `GET /api/dashboard`: conteos de cotizaciones/clientes/servicios activos + 10 cotizaciones recientes. +- `GET /api/asesores`: lista segura (`id`, `name`, `email`, `role`) de asesores/admins + siguiente secuencia de folio (`nextSeq`). +- `GET /api/cobros/resumen`: datos consolidados de `/cobros` (programas con `proximaFecha`, clientes, pagos `en_revision`, saldos `pagosPorCobrar` agrupados por cliente y `diasRecordatorio`). +- `GET /api/cliente/pagos`: incluye tanto `pagos` (compatibilidad) como `programas` agrupados y `bancaria` (`getConfigBancaria`). + +## 5. Estrategia de Base de Datos y Despliegue + +- `cotizador migrate` ejecuta `001_initial_schema.sql` completamente idempotente (`CREATE TABLE IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`, `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`) compatible al 100% con bases creadas por Prisma y bases nuevas vacías. +- `Dockerfile` multi-stage: + 1. `node:22-alpine`: compila `web/` → `dist/`. + 2. `golang:1.25-alpine`: incrusta `web/dist` en `internal/spa/dist`, compila binario estático (`CGO_ENABLED=0`). + 3. `alpine:3.21`: `ca-certificates` + `tzdata` (para `America/Mexico_City`) + binario `cotizador`. Al arrancar corre `cotizador migrate`, condicionalmente `cotizador seed` (`RUN_SEED=true`), y luego `cotizador serve`. +- `docker-compose.coolify.yml` y `docker-compose.yaml` (copia idéntica) mantienen `postgres` y `web` (puerto 3000) con los volúmenes `postgres_data` y `uploads_data`. +- Despliegue: push a `origin` (GitHub `main`, auto-deploy Coolify) y espejo a `gitea`, seguido de verificación en vivo contra `https://cotizador.urieljareth.org`. diff --git a/eslint.config.mjs b/eslint.config.mjs deleted file mode 100644 index 05e726d..0000000 --- a/eslint.config.mjs +++ /dev/null @@ -1,18 +0,0 @@ -import { defineConfig, globalIgnores } from "eslint/config"; -import nextVitals from "eslint-config-next/core-web-vitals"; -import nextTs from "eslint-config-next/typescript"; - -const eslintConfig = defineConfig([ - ...nextVitals, - ...nextTs, - // Override default ignores of eslint-config-next. - globalIgnores([ - // Default ignores of eslint-config-next: - ".next/**", - "out/**", - "build/**", - "next-env.d.ts", - ]), -]); - -export default eslintConfig; diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..6156e2d --- /dev/null +++ b/go.mod @@ -0,0 +1,31 @@ +module cotizador + +go 1.27.4 + +require ( + codeberg.org/go-pdf/fpdf v0.12.0 + github.com/HugoSmits86/nativewebp v1.3.0 + github.com/SherClockHolmes/webpush-go v1.4.0 + github.com/go-chi/chi/v5 v5.5.0 + github.com/golang-jwt/jwt/v5 v5.3.1 + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.13.0 + github.com/joho/godotenv v1.5.1 + github.com/xuri/excelize/v2 v2.11.1 + golang.org/x/crypto v0.59.0 + golang.org/x/image v0.48.0 + golang.org/x/text v0.44.0 +) + +require ( + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.3 // indirect + github.com/richardlehane/mscfb v1.0.9 // indirect + github.com/richardlehane/msoleps v1.0.6 // indirect + github.com/tiendc/go-deepcopy v1.7.2 // indirect + github.com/xuri/efp v0.0.3-0.20260924042702-217b81952dec // indirect + github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect + golang.org/x/net v0.62.0 // indirect + golang.org/x/sync v0.25.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..6eaf680 --- /dev/null +++ b/go.sum @@ -0,0 +1,125 @@ +codeberg.org/go-pdf/fpdf v0.12.0 h1:g8E/1VqGqB2lZUUaqQrrTnA0IEJLPTTX1DZ0qS/ZmhU= +codeberg.org/go-pdf/fpdf v0.12.0/go.mod h1:WJNJ2bvCj81rZBdhOf7lKOGoSl+OKMXcIcXqDcP8r5Y= +github.com/HugoSmits86/nativewebp v1.3.0 h1:n1egtEzSV4KwFtealr7dzdYq1wI/uj/bOQ/QcTcIyVE= +github.com/HugoSmits86/nativewebp v1.3.0/go.mod h1:YNQuWenlVmSUUASVNhTDwf4d7FwYQGbGhklC8p72Vr8= +github.com/SherClockHolmes/webpush-go v1.4.0 h1:ocnzNKWN23T9nvHi6IfyrQjkIc0oJWv1B1pULsf9i3s= +github.com/SherClockHolmes/webpush-go v1.4.0/go.mod h1:XSq8pKX11vNV8MJEMwjrlTkxhAj1zKfxmyhdV7Pd6UA= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg= +github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4= +github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= +github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= +github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/richardlehane/mscfb v1.0.9 h1:8xdd9auUvXbFoCw3L9h1spnQHZgjNsSX+ek46J6A9tE= +github.com/richardlehane/mscfb v1.0.9/go.mod h1:pe0+IUIc0AHh0+teNzBlJCtSyZdFOGgV4ZK9bsoV+Jo= +github.com/richardlehane/msoleps v1.0.6 h1:9BvkpjvD+iUBalUY4esMwv6uBkfOip/Lzvd93jvR9gg= +github.com/richardlehane/msoleps v1.0.6/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/tiendc/go-deepcopy v1.7.2 h1:Ut2yYR7W9tWjTQitganoIue4UGxZwCcJy3orjrrIj44= +github.com/tiendc/go-deepcopy v1.7.2/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ= +github.com/xuri/efp v0.0.3-0.20260924042702-217b81952dec h1:sZZokRLgr8nyrzkDDCQcvEYBsTrZr6eqXa/R9qALoQA= +github.com/xuri/efp v0.0.3-0.20260924042702-217b81952dec/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI= +github.com/xuri/excelize/v2 v2.11.1 h1:tm/FVufArvfUiJXJtGv8jna/zZS1t9Uji2ImsnS9iBo= +github.com/xuri/excelize/v2 v2.11.1/go.mod h1:NQLBThVu4BB7tYM8wJIBj2dZsptXbDW4WyrFlL8YLZQ= +github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE= +github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= +golang.org/x/image v0.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik= +golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= +golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/audit/audit.go b/internal/audit/audit.go new file mode 100644 index 0000000..383aee9 --- /dev/null +++ b/internal/audit/audit.go @@ -0,0 +1,87 @@ +package audit + +import ( + "context" + "encoding/json" + "log" + "net/http" + "strings" + + "cotizador/internal/db" + + "github.com/jackc/pgx/v5/pgxpool" +) + +type Entry struct { + ActorTipo string + ActorID string + ActorNombre string + Accion string + RecursoTipo string + RecursoID string + IP string + RequestID string + Exito bool + Detalle any +} + +func ClientIP(r *http.Request) string { + if r == nil { + return "" + } + if xff := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); xff != "" { + parts := strings.Split(xff, ",") + if len(parts) > 0 && strings.TrimSpace(parts[0]) != "" { + return strings.TrimSpace(parts[0]) + } + } + if xri := strings.TrimSpace(r.Header.Get("X-Real-IP")); xri != "" { + return xri + } + return r.RemoteAddr +} + +func RequestID(r *http.Request) string { + if r == nil { + return "" + } + return strings.TrimSpace(r.Header.Get("X-Request-Id")) +} + +// Registrar writes an AuditLog row best-effort (never fails caller flow). +func Registrar(ctx context.Context, pool *pgxpool.Pool, e Entry) { + if pool == nil { + return + } + var detalleBytes []byte + if e.Detalle != nil { + if b, err := json.Marshal(e.Detalle); err == nil { + detalleBytes = b + } + } + var actorID, recursoID, ip, reqID *string + if e.ActorID != "" { + v := e.ActorID + actorID = &v + } + if e.RecursoID != "" { + v := e.RecursoID + recursoID = &v + } + if e.IP != "" { + v := e.IP + ip = &v + } + if e.RequestID != "" { + v := e.RequestID + reqID = &v + } + + _, err := pool.Exec(ctx, ` + INSERT INTO "AuditLog" ("id", "actorTipo", "actorId", "actorNombre", "accion", "recursoTipo", "recursoId", "ip", "requestId", "exito", "detalle") + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) + `, db.NewID(), e.ActorTipo, actorID, e.ActorNombre, e.Accion, e.RecursoTipo, recursoID, ip, reqID, e.Exito, detalleBytes) + if err != nil { + log.Printf("[audit] error escribiendo AuditLog (%s): %v", e.Accion, err) + } +} diff --git a/internal/auth/auth.go b/internal/auth/auth.go new file mode 100644 index 0000000..5ce66b0 --- /dev/null +++ b/internal/auth/auth.go @@ -0,0 +1,601 @@ +package auth + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "regexp" + "slices" + "strconv" + "strings" + "sync" + "time" + + "cotizador/internal/audit" + "cotizador/internal/domain" + + "github.com/golang-jwt/jwt/v5" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "golang.org/x/crypto/bcrypt" +) + +const ( + SessionCookieName = "cotizador-session" + SessionTTL = 7 * 24 * time.Hour + APIKeyPrefix = "ujc_live_" +) + +// Exact 9 allowed agent scopes. NEVER add an approval scope. +var AgentScopes = []string{ + "catalogo:leer", + "clientes:leer", + "clientes:escribir", + "cotizaciones:leer", + "cotizaciones:leer_aceptadas", + "cotizaciones:borrador", + "cotizaciones:enviar", + "cobros:leer", + "cobros:registrar", +} + +func IsValidScope(s string) bool { + return slices.Contains(AgentScopes, s) +} + +type SessionPayload struct { + UserID string `json:"userId"` + Email string `json:"email"` + Name string `json:"name"` + Role string `json:"role"` + ClienteID string `json:"clienteId,omitempty"` +} + +type jwtClaims struct { + UserID string `json:"userId"` + Email string `json:"email"` + Name string `json:"name"` + Role string `json:"role"` + ClienteID string `json:"clienteId,omitempty"` + jwt.RegisteredClaims +} + +type Actor struct { + Type string // "user" | "agent" + UserID string + Email string + Name string + Role string // "admin" | "asesor" | "cliente" + ClienteID string + KeyID string + KeyNombre string + Scopes []string + RateLimitPerMin int + RateHeaders map[string]string +} + +func (a *Actor) ToDomainActor() domain.ActorInfo { + return domain.ActorInfo{ + Type: a.Type, + Role: a.Role, + Scopes: a.Scopes, + } +} + +func (a *Actor) AuditActor() (tipo, id, nombre string) { + if a.Type == "agent" { + return "agent", a.KeyID, a.KeyNombre + } + return "user", a.UserID, a.Email +} + +func (a *Actor) IsAdmin() bool { + return a.Type == "user" && a.Role == "admin" +} + +func (a *Actor) IsStaff() bool { + return a.Type == "user" && a.Role != "cliente" +} + +func (a *Actor) IsCliente() bool { + return a.Type == "user" && a.Role == "cliente" +} + +func (a *Actor) IsAgent() bool { + return a.Type == "agent" +} + +func (a *Actor) HasScopes(required []string, mode string) bool { + if a.IsStaff() { + return true + } + if !a.IsAgent() { + return false + } + if len(required) == 0 { + return true + } + if mode == "all" { + for _, req := range required { + if !slices.Contains(a.Scopes, req) { + return false + } + } + return true + } + for _, req := range required { + if slices.Contains(a.Scopes, req) { + return true + } + } + return false +} + +// EsAgenteSoloAceptadas returns true when agent has cotizaciones:leer_aceptadas and NOT cotizaciones:leer. +func (a *Actor) EsAgenteSoloAceptadas() bool { + return a.IsAgent() && + slices.Contains(a.Scopes, "cotizaciones:leer_aceptadas") && + !slices.Contains(a.Scopes, "cotizaciones:leer") +} + +func (a *Actor) ApplyHeaders(w http.ResponseWriter) { + for k, v := range a.RateHeaders { + w.Header().Set(k, v) + } +} + +func HashPassword(plain string) (string, error) { + b, err := bcrypt.GenerateFromPassword([]byte(plain), 10) + return string(b), err +} + +func ComparePassword(hash, plain string) bool { + return bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) == nil +} + +func HashSecret(raw string) string { + sum := sha256.Sum256([]byte(raw)) + return hex.EncodeToString(sum[:]) +} + +func GenerateAPIKey() (rawKey, prefijo, keyHash string) { + var b [32]byte + _, _ = rand.Read(b[:]) + rawKey = APIKeyPrefix + hex.EncodeToString(b[:]) + prefijo = rawKey[:14] + keyHash = HashSecret(rawKey) + return +} + +func GenerateRandomToken(numBytes int) (raw, hash string) { + b := make([]byte, numBytes) + _, _ = rand.Read(b) + raw = hex.EncodeToString(b) + hash = HashSecret(raw) + return +} + +var nonDigitsRe = regexp.MustCompile(`\D+`) + +// CoincideContacto matches exact email (case-insensitive) or last 10 digits of phone. +func CoincideContacto(verificar string, clienteEmail, clienteTelefono string) bool { + v := strings.TrimSpace(verificar) + if v == "" { + return false + } + if strings.Contains(v, "@") { + return clienteEmail != "" && strings.EqualFold(v, strings.TrimSpace(clienteEmail)) + } + digitsV := nonDigitsRe.ReplaceAllString(v, "") + digitsC := nonDigitsRe.ReplaceAllString(clienteTelefono, "") + if len(digitsV) < 7 || len(digitsC) < 7 { + return false + } + if len(digitsV) > 10 { + digitsV = digitsV[len(digitsV)-10:] + } + if len(digitsC) > 10 { + digitsC = digitsC[len(digitsC)-10:] + } + return digitsV == digitsC +} + +// RateLimiter implements an in-memory 60-second sliding window per API key. +type RateLimiter struct { + mu sync.Mutex + buckets map[string][]time.Time +} + +func NewRateLimiter() *RateLimiter { + return &RateLimiter{buckets: make(map[string][]time.Time)} +} + +type RateLimitResult struct { + Allowed bool + Limit int + Remaining int + ResetUnix int64 + RetryAfter int +} + +func (rl *RateLimiter) Check(keyID string, limit int, now time.Time) RateLimitResult { + if limit < 1 { + limit = 60 + } + windowStart := now.Add(-60 * time.Second) + + rl.mu.Lock() + defer rl.mu.Unlock() + + existing := rl.buckets[keyID] + kept := existing[:0] + for _, ts := range existing { + if ts.After(windowStart) { + kept = append(kept, ts) + } + } + + if len(kept) >= limit { + rl.buckets[keyID] = kept + oldest := kept[0] + resetAt := oldest.Add(60 * time.Second) + retrySec := int(time.Until(resetAt).Seconds()) + if now != (time.Time{}) { + retrySec = int(resetAt.Sub(now).Seconds()) + } + if retrySec < 1 { + retrySec = 1 + } + return RateLimitResult{ + Allowed: false, + Limit: limit, + Remaining: 0, + ResetUnix: resetAt.Unix(), + RetryAfter: retrySec, + } + } + + kept = append(kept, now) + rl.buckets[keyID] = kept + resetAt := kept[0].Add(60 * time.Second) + return RateLimitResult{ + Allowed: true, + Limit: limit, + Remaining: limit - len(kept), + ResetUnix: resetAt.Unix(), + } +} + +func BuildRateLimitHeaders(res RateLimitResult) map[string]string { + h := map[string]string{ + "X-RateLimit-Limit": strconv.Itoa(res.Limit), + "X-RateLimit-Remaining": strconv.Itoa(res.Remaining), + "X-RateLimit-Reset": strconv.FormatInt(res.ResetUnix, 10), + } + if !res.Allowed { + retry := res.RetryAfter + if retry < 1 { + retry = 1 + } + h["Retry-After"] = strconv.Itoa(retry) + } + return h +} + +type Service struct { + jwtSecret []byte + isProduction bool + pool *pgxpool.Pool + limiter *RateLimiter +} + +func NewService(jwtSecret string, isProduction bool, pool *pgxpool.Pool) *Service { + return &Service{ + jwtSecret: []byte(jwtSecret), + isProduction: isProduction, + pool: pool, + limiter: NewRateLimiter(), + } +} + +func (s *Service) SignSession(p SessionPayload) (string, error) { + now := time.Now() + claims := jwtClaims{ + UserID: p.UserID, + Email: p.Email, + Name: p.Name, + Role: p.Role, + ClienteID: p.ClienteID, + RegisteredClaims: jwt.RegisteredClaims{ + IssuedAt: jwt.NewNumericDate(now), + ExpiresAt: jwt.NewNumericDate(now.Add(SessionTTL)), + }, + } + tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + return tok.SignedString(s.jwtSecret) +} + +func (s *Service) VerifySession(tokenStr string) (*SessionPayload, error) { + if tokenStr == "" { + return nil, errors.New("empty token") + } + tok, err := jwt.ParseWithClaims(tokenStr, &jwtClaims{}, func(t *jwt.Token) (any, error) { + if t.Method.Alg() != jwt.SigningMethodHS256.Alg() { + return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"]) + } + return s.jwtSecret, nil + }) + if err != nil || !tok.Valid { + return nil, errors.New("invalid token") + } + c, ok := tok.Claims.(*jwtClaims) + if !ok || c.UserID == "" { + return nil, errors.New("invalid claims") + } + role := c.Role + if role == "" { + role = "asesor" + } + return &SessionPayload{ + UserID: c.UserID, + Email: c.Email, + Name: c.Name, + Role: role, + ClienteID: c.ClienteID, + }, nil +} + +func (s *Service) SetSessionCookie(w http.ResponseWriter, token string) { + http.SetCookie(w, &http.Cookie{ + Name: SessionCookieName, + Value: token, + Path: "/", + MaxAge: int(SessionTTL.Seconds()), + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: s.isProduction, + }) +} + +func (s *Service) ClearSessionCookie(w http.ResponseWriter) { + http.SetCookie(w, &http.Cookie{ + Name: SessionCookieName, + Value: "", + Path: "/", + MaxAge: -1, + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: s.isProduction, + }) +} + +func (s *Service) SessionFromRequest(r *http.Request) (*SessionPayload, bool) { + c, err := r.Cookie(SessionCookieName) + if err != nil || c.Value == "" { + return nil, false + } + p, err := s.VerifySession(c.Value) + if err != nil { + return nil, false + } + return p, true +} + +func ExtractAPIKey(r *http.Request) string { + if k := strings.TrimSpace(r.Header.Get("X-API-Key")); k != "" { + return k + } + authz := strings.TrimSpace(r.Header.Get("Authorization")) + if len(authz) > 7 && strings.EqualFold(authz[:7], "bearer ") { + return strings.TrimSpace(authz[7:]) + } + return "" +} + +type RequireOptions struct { + AdminOnly bool + StaffOnly bool + AllowCliente bool + Scopes []string + ScopeMode string // "any" (default) | "all" + AccionBloqueo string + RecursoTipo string + RecursoID string +} + +// RequireActor authenticates either cookie session (priority) or AgentApiKey, +// enforces role/scope/rate-limit rules, logs failures to AuditLog, and writes the HTTP error response if denied. +func (s *Service) RequireActor(w http.ResponseWriter, r *http.Request, opts RequireOptions) (*Actor, bool) { + var actor *Actor + + // 1. Cookie JWT takes priority + if sess, ok := s.SessionFromRequest(r); ok { + actor = &Actor{ + Type: "user", + UserID: sess.UserID, + Email: sess.Email, + Name: sess.Name, + Role: sess.Role, + ClienteID: sess.ClienteID, + } + } else if rawKey := ExtractAPIKey(r); rawKey != "" { + // 2. Agent API Key lookup via SHA-256 + keyHash := HashSecret(rawKey) + var id, nombre string + var scopes []string + var rateLimit int + var lastUsedAt *time.Time + err := s.pool.QueryRow(r.Context(), ` + SELECT "id", "nombre", "scopes", "rateLimitPerMin", "lastUsedAt" + FROM "AgentApiKey" + WHERE "keyHash" = $1 AND "activo" = true AND "revokedAt" IS NULL + `, keyHash).Scan(&id, &nombre, &scopes, &rateLimit, &lastUsedAt) + if err != nil { + if !errors.Is(err, pgx.ErrNoRows) { + writeAuthJSON(w, http.StatusInternalServerError, map[string]any{"error": "Error validando credenciales"}) + return nil, false + } + audit.Registrar(r.Context(), s.pool, audit.Entry{ + ActorTipo: "agent", + ActorNombre: "clave_invalida", + Accion: "auth.api_key_invalida", + RecursoTipo: firstOr(opts.RecursoTipo, "auth"), + RecursoID: opts.RecursoID, + IP: audit.ClientIP(r), + RequestID: audit.RequestID(r), + Exito: false, + Detalle: map[string]any{"path": r.URL.Path, "method": r.Method}, + }) + writeAuthJSON(w, http.StatusUnauthorized, map[string]any{"error": "API key invalida o revocada"}) + return nil, false + } + + // Rate limit check + rlRes := s.limiter.Check(id, rateLimit, time.Now()) + headers := BuildRateLimitHeaders(rlRes) + if !rlRes.Allowed { + for k, v := range headers { + w.Header().Set(k, v) + } + audit.Registrar(r.Context(), s.pool, audit.Entry{ + ActorTipo: "agent", + ActorID: id, + ActorNombre: nombre, + Accion: "auth.rate_limit", + RecursoTipo: firstOr(opts.RecursoTipo, "auth"), + RecursoID: opts.RecursoID, + IP: audit.ClientIP(r), + RequestID: audit.RequestID(r), + Exito: false, + Detalle: map[string]any{"limit": rateLimit, "path": r.URL.Path}, + }) + writeAuthJSON(w, http.StatusTooManyRequests, map[string]any{"error": "Limite de peticiones por minuto excedido"}) + return nil, false + } + + // Throttled async lastUsedAt update (>60s) + if lastUsedAt == nil || time.Since(*lastUsedAt) > 60*time.Second { + go func(keyID string) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + _, _ = s.pool.Exec(ctx, `UPDATE "AgentApiKey" SET "lastUsedAt" = NOW(), "updatedAt" = NOW() WHERE "id" = $1`, keyID) + }(id) + } + + actor = &Actor{ + Type: "agent", + KeyID: id, + KeyNombre: nombre, + Scopes: scopes, + RateLimitPerMin: rateLimit, + RateHeaders: headers, + } + } else { + writeAuthJSON(w, http.StatusUnauthorized, map[string]any{"error": "No autenticado"}) + return nil, false + } + + // Role / Scope enforcement + if opts.AdminOnly && !actor.IsAdmin() { + tipo, aid, anombre := actor.AuditActor() + audit.Registrar(r.Context(), s.pool, audit.Entry{ + ActorTipo: tipo, + ActorID: aid, + ActorNombre: anombre, + Accion: firstOr(opts.AccionBloqueo, "auth.admin_requerido"), + RecursoTipo: firstOr(opts.RecursoTipo, "auth"), + RecursoID: opts.RecursoID, + IP: audit.ClientIP(r), + RequestID: audit.RequestID(r), + Exito: false, + Detalle: map[string]any{"path": r.URL.Path, "method": r.Method}, + }) + writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Solo un administrador humano puede realizar esta accion"}) + return nil, false + } + + if opts.StaffOnly && !actor.IsStaff() { + tipo, aid, anombre := actor.AuditActor() + audit.Registrar(r.Context(), s.pool, audit.Entry{ + ActorTipo: tipo, + ActorID: aid, + ActorNombre: anombre, + Accion: firstOr(opts.AccionBloqueo, "auth.staff_requerido"), + RecursoTipo: firstOr(opts.RecursoTipo, "auth"), + RecursoID: opts.RecursoID, + IP: audit.ClientIP(r), + RequestID: audit.RequestID(r), + Exito: false, + Detalle: map[string]any{"path": r.URL.Path, "method": r.Method}, + }) + writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Acceso exclusivo para equipo interno"}) + return nil, false + } + + if actor.IsCliente() && !opts.AllowCliente { + writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Acceso no permitido para cuentas de cliente"}) + return nil, false + } + + if len(opts.Scopes) > 0 && !actor.IsCliente() { + mode := opts.ScopeMode + if mode == "" { + mode = "any" + } + if !actor.HasScopes(opts.Scopes, mode) { + tipo, aid, anombre := actor.AuditActor() + audit.Registrar(r.Context(), s.pool, audit.Entry{ + ActorTipo: tipo, + ActorID: aid, + ActorNombre: anombre, + Accion: firstOr(opts.AccionBloqueo, "auth.scope_insuficiente"), + RecursoTipo: firstOr(opts.RecursoTipo, "auth"), + RecursoID: opts.RecursoID, + IP: audit.ClientIP(r), + RequestID: audit.RequestID(r), + Exito: false, + Detalle: map[string]any{"requiredScopes": opts.Scopes, "path": r.URL.Path}, + }) + writeAuthJSON(w, http.StatusForbidden, map[string]any{ + "error": "Alcance insuficiente para esta operacion", + "requiredScopes": opts.Scopes, + }) + return nil, false + } + } + + actor.ApplyHeaders(w) + return actor, true +} + +// RequireCliente enforces a valid cookie session with role == "cliente" and non-empty clienteId. +func (s *Service) RequireCliente(w http.ResponseWriter, r *http.Request) (*SessionPayload, bool) { + sess, ok := s.SessionFromRequest(r) + if !ok { + writeAuthJSON(w, http.StatusUnauthorized, map[string]any{"error": "No autenticado"}) + return nil, false + } + if sess.Role != "cliente" || sess.ClienteID == "" { + writeAuthJSON(w, http.StatusForbidden, map[string]any{"error": "Acceso exclusivo para clientes"}) + return nil, false + } + return sess, true +} + +func firstOr(v, fallback string) string { + if v != "" { + return v + } + return fallback +} + +func writeAuthJSON(w http.ResponseWriter, status int, payload any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(payload) +} diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go new file mode 100644 index 0000000..0c63397 --- /dev/null +++ b/internal/auth/auth_test.go @@ -0,0 +1,79 @@ +package auth + +import ( + "strings" + "testing" + "time" +) + +func TestAPIKeyAndScopes(t *testing.T) { + raw, pref, hash := GenerateAPIKey() + if !strings.HasPrefix(raw, APIKeyPrefix) || len(raw) != 73 { + t.Fatalf("unexpected raw key format: len=%d", len(raw)) + } + if pref != raw[:14] || len(hash) != 64 || hash != HashSecret(raw) { + t.Fatalf("hash/prefix mismatch") + } + if len(AgentScopes) != 9 { + t.Fatalf("expected 9 scopes, got %d", len(AgentScopes)) + } + for _, s := range AgentScopes { + if strings.Contains(s, "aprobar") { + t.Fatalf("approval scope must never exist: %s", s) + } + } + + entrega := &Actor{Type: "agent", Scopes: []string{"cotizaciones:leer_aceptadas"}} + if !entrega.EsAgenteSoloAceptadas() { + t.Fatalf("expected EsAgenteSoloAceptadas=true") + } + ops := &Actor{Type: "agent", Scopes: []string{"cotizaciones:leer", "cotizaciones:leer_aceptadas"}} + if ops.EsAgenteSoloAceptadas() { + t.Fatalf("expected EsAgenteSoloAceptadas=false when cotizaciones:leer present") + } +} + +func TestRateLimiter(t *testing.T) { + rl := NewRateLimiter() + now := time.Now() + for i := 0; i < 3; i++ { + res := rl.Check("k1", 3, now.Add(time.Duration(i)*time.Second)) + if !res.Allowed { + t.Fatalf("request %d should be allowed", i) + } + } + blocked := rl.Check("k1", 3, now.Add(4*time.Second)) + if blocked.Allowed || blocked.Remaining != 0 { + t.Fatalf("4th request should be blocked: %+v", blocked) + } + afterWindow := rl.Check("k1", 3, now.Add(65*time.Second)) + if !afterWindow.Allowed { + t.Fatalf("request after 60s window should be allowed") + } +} + +func TestCoincideContacto(t *testing.T) { + if !CoincideContacto("ANA@Empresa.MX", "ana@empresa.mx", "") { + t.Fatal("case-insensitive email should match") + } + if !CoincideContacto("+52 1 55 1234-5678", "", "5512345678") { + t.Fatal("last 10 phone digits should match") + } + if CoincideContacto("otro@x.com", "ana@empresa.mx", "5512345678") { + t.Fatal("mismatched contact should fail") + } +} + +func TestJWTSignAndVerify(t *testing.T) { + svc := NewService("super-secret-test-key", false, nil) + tok, err := svc.SignSession(SessionPayload{ + UserID: "u1", Email: "admin@urieljareth.com", Name: "Admin", Role: "admin", + }) + if err != nil { + t.Fatalf("sign failed: %v", err) + } + got, err := svc.VerifySession(tok) + if err != nil || got.UserID != "u1" || got.Role != "admin" { + t.Fatalf("verify failed: %+v, err=%v", got, err) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go new file mode 100644 index 0000000..8c8d9ae --- /dev/null +++ b/internal/cli/cli.go @@ -0,0 +1,1131 @@ +package cli + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net/http" + "net/url" + "os" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode" +) + +const Version = "1.0.0" + +// Exit codes matching cli/cotizador.mjs. +const ( + ExitOK = 0 + ExitError = 1 + ExitUso = 2 + ExitAuth = 3 + ExitNoEncontrado = 4 + ExitValidacion = 5 + ExitConflicto = 6 + ExitRed = 7 +) + +var descripcionCodigos = map[string]string{ + "0": "ok", + "1": "error del servidor o inesperado", + "2": "uso incorrecto (flag faltante o invalida, comando desconocido)", + "3": "sin sesion o sin permiso (ejecuta `cotizador login`)", + "4": "no encontrado", + "5": "validacion rechazada por el servidor (ver `detalles`)", + "6": "conflicto (duplicado)", + "7": "no se pudo conectar con el servidor", +} + +// --------------------------------------------------------------------------- +// Dominio (espejo de src/lib/calculators.ts y cli/cotizador.mjs) +// --------------------------------------------------------------------------- + +var ( + nivelesServicio = []string{"Emprendedor", "PYME", "Empresario", "Corporativo"} + estadosCotizacion = []string{"borrador", "enviada", "aprobada", "rechazada"} + esquemasPago = []string{"Pago Unico", "Mensual", "Pago Unico/Mensual", "Por hora (postpago)"} + monedasValidas = []string{"MXN", "USD"} + planesBucefaloCRM = []string{"basico", "estandar", "premium", "empresarial"} + tarifaHoraDefault = 700.0 + ivaRate = 0.16 +) + +func dominioInfo() map[string]any { + return map[string]any{ + "fases": map[string]string{ + "0": "Auditoria / Acompanamiento", + "1": "Setup e Infraestructura", + "2": "Publicidad y Manejo", + "3": "Contenido y SEO", + }, + "tiposPago": map[string]string{ + "unico": "pago unico", + "mensual": "pago recurrente mensual", + }, + "nivelesServicio": nivelesServicio, + "estadosCotizacion": estadosCotizacion, + "esquemasPago": esquemasPago, + "monedas": monedasValidas, + "planesBucefaloCRM": planesBucefaloCRM, + "iva": ivaRate, + "tarifaHoraDefault": tarifaHoraDefault, + } +} + +// --------------------------------------------------------------------------- +// Errors & dry-run signal +// --------------------------------------------------------------------------- + +type cliError struct { + Mensaje string + Codigo int + Status int + Detalles any + Sugerencia string +} + +func (e *cliError) Error() string { return e.Mensaje } + +func errorUso(mensaje string, sugerencia ...string) *cliError { + sug := "" + if len(sugerencia) > 0 { + sug = sugerencia[0] + } + return &cliError{ + Mensaje: mensaje, + Codigo: ExitUso, + Sugerencia: sug, + } +} + +type dryRunSignal struct { + Metodo string `json:"metodo"` + URL string `json:"url"` + Cuerpo any `json:"cuerpo"` +} + +func (d *dryRunSignal) Error() string { return "dry-run" } + +// --------------------------------------------------------------------------- +// Flag specifications & argument parsing +// --------------------------------------------------------------------------- + +type flagSpec struct { + Flag string + Tipo string // texto | entero | numero | booleano | lista | fecha | json + Valores []any + Repetible bool + Descripcion string +} + +type argSpec struct { + Nombre string `json:"nombre"` + Descripcion string `json:"descripcion"` +} + +type cmdContext struct { + Pos []string + Flags *parsedFlags + Cliente *apiClient + Stdin io.Reader + Stdout io.Writer +} + +type commandSpec struct { + Comando string + Alias []string + Descripcion string + Argumentos []argSpec + Flags []flagSpec + Ejemplos []string + Endpoint string + HasEndpoint bool + SinServidor bool + Run func(ctx *cmdContext) (any, bool, error) +} + +var flagsGlobales = []flagSpec{ + {Flag: "url", Tipo: "texto", Descripcion: "URL base de la plataforma (default: $COTIZADOR_URL o http://localhost:3000)"}, + {Flag: "campos", Tipo: "lista", Descripcion: "Devuelve solo estos campos, separados por coma (ej. id,nombre,precioBase). Ahorra tokens."}, + {Flag: "formato", Tipo: "texto", Valores: []any{"json", "tabla"}, Descripcion: "json (default) o tabla legible"}, + {Flag: "compacto", Tipo: "booleano", Descripcion: "JSON en una sola linea"}, + {Flag: "dry-run", Tipo: "booleano", Descripcion: "En comandos de escritura: muestra la peticion que se enviaria y no la envia"}, + {Flag: "ayuda", Tipo: "booleano", Descripcion: "Ayuda del comando (tambien -h, --help)"}, + {Flag: "version", Tipo: "booleano", Descripcion: "Version del CLI"}, +} + +type parsedFlags struct { + present map[string]bool + values map[string]string + bools map[string]bool + lists map[string][]string +} + +func newParsedFlags() *parsedFlags { + return &parsedFlags{ + present: make(map[string]bool), + values: make(map[string]string), + bools: make(map[string]bool), + lists: make(map[string][]string), + } +} + +func (f *parsedFlags) Has(key string) bool { return f.present[key] } +func (f *parsedFlags) Str(key string) string { return f.values[key] } +func (f *parsedFlags) Bool(key string) bool { return f.bools[key] } +func (f *parsedFlags) List(key string) []string { return f.lists[key] } + +func aCamel(s string) string { + var b strings.Builder + upperNext := false + for _, r := range s { + if r == '-' { + upperNext = true + continue + } + if upperNext && r >= 'a' && r <= 'z' { + b.WriteRune(unicode.ToUpper(r)) + upperNext = false + continue + } + if upperNext { + b.WriteRune('-') + upperNext = false + } + b.WriteRune(r) + } + if upperNext { + b.WriteRune('-') + } + return b.String() +} + +func aKebab(s string) string { + var b strings.Builder + for _, r := range s { + if unicode.IsUpper(r) { + b.WriteRune('-') + b.WriteRune(unicode.ToLower(r)) + } else { + b.WriteRune(r) + } + } + return b.String() +} + +func parsearArgs(argv []string, especFlags []flagSpec) ([]string, *parsedFlags, error) { + booleanas := make(map[string]bool) + repetibles := make(map[string]bool) + conocidas := make(map[string]bool) + for _, f := range especFlags { + conocidas[f.Flag] = true + if f.Tipo == "booleano" { + booleanas[f.Flag] = true + } + if f.Repetible { + repetibles[f.Flag] = true + } + } + + var posicionales []string + flags := newParsedFlags() + + for i := 0; i < len(argv); i++ { + a := argv[i] + if a == "--" { + posicionales = append(posicionales, argv[i+1:]...) + break + } + if a == "-h" { + flags.present["ayuda"] = true + flags.bools["ayuda"] = true + continue + } + if !strings.HasPrefix(a, "--") { + posicionales = append(posicionales, a) + continue + } + nombre := a[2:] + var valor string + hasValor := false + if eq := strings.IndexByte(nombre, '='); eq >= 0 { + valor = nombre[eq+1:] + nombre = nombre[:eq] + hasValor = true + } + if nombre == "help" { + nombre = "ayuda" + } + if strings.HasPrefix(nombre, "no-") && booleanas[nombre[3:]] { + clave := aCamel(nombre[3:]) + flags.present[clave] = true + flags.bools[clave] = false + continue + } + if booleanas[nombre] { + clave := aCamel(nombre) + flags.present[clave] = true + if !hasValor { + flags.bools[clave] = true + } else { + low := strings.ToLower(valor) + flags.bools[clave] = low != "false" && low != "0" && low != "no" + } + continue + } + // Unknown flag without value: record it so per-command validation reports unknown flag clearly + if !conocidas[nombre] && !hasValor { + clave := aCamel(nombre) + flags.present[clave] = true + if i+1 < len(argv) && !strings.HasPrefix(argv[i+1], "--") { + flags.values[clave] = argv[i+1] + i++ + } + continue + } + if !hasValor { + if i+1 >= len(argv) || (strings.HasPrefix(argv[i+1], "--") && argv[i+1] != "--") { + return nil, nil, errorUso(fmt.Sprintf("La flag --%s necesita un valor", nombre)) + } + valor = argv[i+1] + i++ + } + clave := aCamel(nombre) + flags.present[clave] = true + if repetibles[nombre] { + flags.lists[clave] = append(flags.lists[clave], valor) + } else { + flags.values[clave] = valor + } + } + + return posicionales, flags, nil +} + +// --------------------------------------------------------------------------- +// Value conversion helpers +// --------------------------------------------------------------------------- + +var ( + fechaISORe = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`) + colorHexRe = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`) + cleanNumRe = regexp.MustCompile(`[$,\s]`) + servicioRefRe = regexp.MustCompile(`^(.*?)\s*=\s*([\d.,$\s]+)$`) + filenameRe = regexp.MustCompile(`(?i)filename\*?=(?:UTF-8'')?"?([^";]+)"?`) + cookieSessRe = regexp.MustCompile(`cotizador-session=([^;]+)`) +) + +func parseNumero(valor, flag string) (float64, error) { + limpio := cleanNumRe.ReplaceAllString(valor, "") + if limpio == "" { + return 0, errorUso(fmt.Sprintf(`--%s debe ser un numero (recibi "%s")`, flag, valor)) + } + n, err := strconv.ParseFloat(limpio, 64) + if err != nil || math.IsNaN(n) || math.IsInf(n, 0) { + return 0, errorUso(fmt.Sprintf(`--%s debe ser un numero (recibi "%s")`, flag, valor)) + } + return n, nil +} + +func parseEntero(valor, flag string) (int, error) { + n, err := parseNumero(valor, flag) + if err != nil { + return 0, err + } + if math.Trunc(n) != n { + return 0, errorUso(fmt.Sprintf(`--%s debe ser un entero (recibi "%s")`, flag, valor)) + } + return int(n), nil +} + +func unoDe(valor string, opciones []string, flag string) (string, error) { + for _, op := range opciones { + if op == valor { + return valor, nil + } + } + return "", errorUso(fmt.Sprintf(`--%s debe ser uno de: %s (recibi "%s")`, flag, strings.Join(opciones, ", "), valor)) +} + +func textoOpcional(valor string) (string, bool) { + low := strings.ToLower(valor) + if low == "" || low == "null" || low == "ninguno" || low == "ninguna" { + return "", true + } + return valor, false +} + +func validarFechaISO(valor, flag string) (string, error) { + if !fechaISORe.MatchString(valor) { + return "", errorUso(fmt.Sprintf(`--%s debe tener formato YYYY-MM-DD (recibi "%s")`, flag, valor)) + } + return valor, nil +} + +func leerStdin(r io.Reader) (string, error) { + if r == nil { + return "", nil + } + b, err := io.ReadAll(r) + if err != nil { + return "", err + } + return string(b), nil +} + +func leerDatos(valor string, hasValor bool, stdin io.Reader) (map[string]any, error) { + if !hasValor { + return map[string]any{}, nil + } + texto := valor + if valor == "-" { + var err error + texto, err = leerStdin(stdin) + if err != nil { + return nil, errorUso("No pude leer stdin") + } + } else if strings.HasPrefix(valor, "@") { + p := valor[1:] + b, err := os.ReadFile(p) + if err != nil { + return nil, errorUso(fmt.Sprintf("No pude leer el archivo %s", p)) + } + texto = string(b) + } + + var raw any + if err := json.Unmarshal([]byte(texto), &raw); err != nil { + return nil, errorUso("--datos debe ser un objeto JSON valido (en linea, @archivo.json o - para stdin)") + } + obj, ok := raw.(map[string]any) + if !ok || obj == nil { + return nil, errorUso("--datos debe ser un objeto JSON valido (en linea, @archivo.json o - para stdin)") + } + return obj, nil +} + +// --------------------------------------------------------------------------- +// Sessions & HTTP client +// --------------------------------------------------------------------------- + +type sessionEntry struct { + Token string `json:"token"` + Usuario any `json:"usuario"` + Iniciada string `json:"iniciada"` +} + +func sessionPaths() (dir string, file string, legacyFile string) { + home, _ := os.UserHomeDir() + envHome := os.Getenv("COTIZADOR_HOME") + if envHome != "" { + dir = envHome + } else { + dir = filepath.Join(home, ".cotizador-uj") + } + file = filepath.Join(dir, "sesiones.json") + if envHome == "" && home != "" { + legacyFile = filepath.Join(home, ".cotizador-e3", "sesiones.json") + } + return dir, file, legacyFile +} + +func leerSesiones() map[string]sessionEntry { + _, file, legacy := sessionPaths() + if b, err := os.ReadFile(file); err == nil { + var s map[string]sessionEntry + if json.Unmarshal(b, &s) == nil && s != nil { + return s + } + } + if legacy != "" { + if b, err := os.ReadFile(legacy); err == nil { + var s map[string]sessionEntry + if json.Unmarshal(b, &s) == nil && s != nil { + return s + } + } + } + return map[string]sessionEntry{} +} + +func guardarSesiones(sesiones map[string]sessionEntry) error { + dir, file, _ := sessionPaths() + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + b, err := json.MarshalIndent(sesiones, "", " ") + if err != nil { + return err + } + return os.WriteFile(file, b, 0o600) +} + +func resolverURLBase(flags *parsedFlags) (string, error) { + raw := flags.Str("url") + if raw == "" { + raw = os.Getenv("COTIZADOR_URL") + } + if raw == "" { + raw = "http://localhost:3000" + } + raw = strings.TrimRight(raw, "/") + u, err := url.Parse(raw) + if err != nil || u.Scheme == "" || u.Host == "" { + return "", errorUso(fmt.Sprintf("URL invalida: %s", raw)) + } + return raw, nil +} + +func codigoPorStatus(status int) int { + switch status { + case 400, 422: + return ExitValidacion + case 401, 403: + return ExitAuth + case 404: + return ExitNoEncontrado + case 409: + return ExitConflicto + default: + return ExitError + } +} + +func extraerToken(res *http.Response) string { + for _, c := range res.Cookies() { + if c.Name == "cotizador-session" && c.Value != "" { + return c.Value + } + } + for _, raw := range res.Header.Values("Set-Cookie") { + if m := cookieSessRe.FindStringSubmatch(raw); len(m) == 2 && m[1] != "" { + return m[1] + } + } + return "" +} + +type apiClient struct { + base string + dryRun bool + tokenEnMemoria string + httpClient *http.Client +} + +func crearCliente(flags *parsedFlags) (*apiClient, error) { + base, err := resolverURLBase(flags) + if err != nil { + return nil, err + } + return &apiClient{ + base: base, + dryRun: flags.Bool("dryRun"), + tokenEnMemoria: os.Getenv("COTIZADOR_TOKEN"), + httpClient: &http.Client{ + Timeout: 60 * time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + }, + }, nil +} + +func (c *apiClient) token() string { + if c.tokenEnMemoria != "" { + return c.tokenEnMemoria + } + sesiones := leerSesiones() + if s, ok := sesiones[c.base]; ok && s.Token != "" { + c.tokenEnMemoria = s.Token + return s.Token + } + return "" +} + +func (c *apiClient) errorRed(err error) *cliError { + return &cliError{ + Mensaje: fmt.Sprintf("No se pudo conectar con %s: %v", c.base, err), + Codigo: ExitRed, + Sugerencia: "Revisa que el servidor este arriba o pasa la URL correcta con --url o COTIZADOR_URL", + } +} + +func (c *apiClient) login(email, password string) (any, error) { + payload, _ := json.Marshal(map[string]string{ + "email": email, + "password": password, + }) + req, err := http.NewRequest(http.MethodPost, c.base+"/api/auth/login", bytes.NewReader(payload)) + if err != nil { + return nil, c.errorRed(err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json") + + res, err := c.httpClient.Do(req) + if err != nil { + return nil, c.errorRed(err) + } + defer res.Body.Close() + + bodyBytes, _ := io.ReadAll(res.Body) + var cuerpo map[string]any + _ = json.Unmarshal(bodyBytes, &cuerpo) + + if res.StatusCode < 200 || res.StatusCode >= 300 { + msg := fmt.Sprintf("Login fallido (HTTP %d)", res.StatusCode) + if s, ok := cuerpo["error"].(string); ok && s != "" { + msg = s + } + return nil, &cliError{Mensaje: msg, Codigo: ExitAuth, Status: res.StatusCode} + } + + nuevo := extraerToken(res) + if nuevo == "" { + return nil, &cliError{Mensaje: "El servidor no devolvio la cookie de sesion", Codigo: ExitAuth} + } + if u, ok := cuerpo["user"].(map[string]any); ok { + if role, _ := u["role"].(string); role == "cliente" { + return nil, &cliError{ + Mensaje: "Esa cuenta es de rol cliente; el CLI necesita una cuenta de staff (admin o asesor)", + Codigo: ExitAuth, + } + } + } + + sesiones := leerSesiones() + sesiones[c.base] = sessionEntry{ + Token: nuevo, + Usuario: cuerpo["user"], + Iniciada: time.Now().UTC().Format(time.RFC3339), + } + if err := guardarSesiones(sesiones); err != nil { + return nil, &cliError{Mensaje: fmt.Sprintf("No pude guardar la sesion: %v", err), Codigo: ExitError} + } + c.tokenEnMemoria = nuevo + return cuerpo["user"], nil +} + +func (c *apiClient) cerrarSesion() (bool, error) { + sesiones := leerSesiones() + _, habia := sesiones[c.base] + delete(sesiones, c.base) + if err := guardarSesiones(sesiones); err != nil { + return false, err + } + c.tokenEnMemoria = "" + return habia, nil +} + +type apiOpts struct { + Cuerpo any + HasCuerpo bool + Binario bool + Escritura *bool +} + +type binaryResponse struct { + Buffer []byte + NombreArchivo string + Tipo string +} + +func (c *apiClient) api(metodo, ruta string, opts ...apiOpts) (any, error) { + var opt apiOpts + if len(opts) > 0 { + opt = opts[0] + } + + fullURL := c.base + ruta + esEscritura := metodo != http.MethodGet + if opt.Escritura != nil { + esEscritura = *opt.Escritura + } + if c.dryRun && esEscritura { + var cuerpo any + if opt.HasCuerpo { + cuerpo = opt.Cuerpo + } + return nil, &dryRunSignal{ + Metodo: metodo, + URL: fullURL, + Cuerpo: cuerpo, + } + } + + reintentado := false + for { + var bodyReader io.Reader + if opt.HasCuerpo { + b, err := json.Marshal(opt.Cuerpo) + if err != nil { + return nil, &cliError{Mensaje: fmt.Sprintf("Error serializando cuerpo JSON: %v", err), Codigo: ExitError} + } + bodyReader = bytes.NewReader(b) + } + + req, err := http.NewRequest(metodo, fullURL, bodyReader) + if err != nil { + return nil, c.errorRed(err) + } + if opt.Binario { + req.Header.Set("Accept", "*/*") + } else { + req.Header.Set("Accept", "application/json") + } + if opt.HasCuerpo { + req.Header.Set("Content-Type", "application/json") + } + if t := c.token(); t != "" { + req.Header.Set("Cookie", "cotizador-session="+t) + } + + res, err := c.httpClient.Do(req) + if err != nil { + return nil, c.errorRed(err) + } + bodyBytes, readErr := io.ReadAll(res.Body) + res.Body.Close() + if readErr != nil { + return nil, c.errorRed(readErr) + } + + // Auto-reauth on 401 when COTIZADOR_EMAIL and COTIZADOR_PASSWORD are set. + if res.StatusCode == http.StatusUnauthorized && !reintentado && + os.Getenv("COTIZADOR_EMAIL") != "" && os.Getenv("COTIZADOR_PASSWORD") != "" { + reintentado = true + c.tokenEnMemoria = "" + if _, err := c.login(os.Getenv("COTIZADOR_EMAIL"), os.Getenv("COTIZADOR_PASSWORD")); err != nil { + return nil, err + } + continue + } + + if res.StatusCode >= 300 && res.StatusCode < 400 { + return nil, &cliError{ + Mensaje: fmt.Sprintf("El servidor redirigio a %s (¿sesion invalida?)", res.Header.Get("Location")), + Codigo: ExitAuth, + Status: res.StatusCode, + Sugerencia: "Ejecuta: cotizador login --email --password ", + } + } + + if res.StatusCode < 200 || res.StatusCode >= 300 { + var errBody map[string]any + _ = json.Unmarshal(bodyBytes, &errBody) + msg := fmt.Sprintf("HTTP %d", res.StatusCode) + if s, ok := errBody["error"].(string); ok && s != "" { + msg = s + } + var sug string + if res.StatusCode == http.StatusUnauthorized { + sug = "Ejecuta: cotizador login --email --password (o define COTIZADOR_EMAIL y COTIZADOR_PASSWORD)" + } else if res.StatusCode == http.StatusForbidden { + sug = "La cuenta no tiene permiso para esta accion (el CLI necesita rol admin o asesor)" + } + return nil, &cliError{ + Mensaje: msg, + Codigo: codigoPorStatus(res.StatusCode), + Status: res.StatusCode, + Detalles: errBody["detalles"], + Sugerencia: sug, + } + } + + if opt.Binario { + disp := res.Header.Get("Content-Disposition") + nombre := "" + if m := filenameRe.FindStringSubmatch(disp); len(m) == 2 { + if decoded, err := url.PathUnescape(m[1]); err == nil { + nombre = decoded + } else { + nombre = m[1] + } + } + return &binaryResponse{ + Buffer: bodyBytes, + NombreArchivo: nombre, + Tipo: res.Header.Get("Content-Type"), + }, nil + } + + trimmed := bytes.TrimSpace(bodyBytes) + if len(trimmed) == 0 { + return nil, nil + } + var out any + if err := json.Unmarshal(trimmed, &out); err != nil { + return nil, &cliError{Mensaje: fmt.Sprintf("Respuesta JSON invalida del servidor: %v", err), Codigo: ExitError} + } + return out, nil + } +} + +// --------------------------------------------------------------------------- +// Output formatting (--campos, --formato tabla, --compacto) +// --------------------------------------------------------------------------- + +func normalizeAny(v any) any { + b, err := json.Marshal(v) + if err != nil { + return v + } + var out any + if err := json.Unmarshal(b, &out); err != nil { + return v + } + return out +} + +func getDotPath(obj map[string]any, path string) (any, bool) { + parts := strings.Split(path, ".") + var cur any = obj + for _, k := range parts { + m, ok := cur.(map[string]any) + if !ok || m == nil { + return nil, false + } + val, exists := m[k] + if !exists { + return nil, false + } + cur = val + } + return cur, true +} + +func elegirCampos(datos any, campos string) (any, []string) { + if strings.TrimSpace(campos) == "" { + return datos, nil + } + var lista []string + for _, c := range strings.Split(campos, ",") { + c = strings.TrimSpace(c) + if c != "" { + lista = append(lista, c) + } + } + if len(lista) == 0 { + return datos, nil + } + + norm := normalizeAny(datos) + pick := func(v any) any { + m, ok := v.(map[string]any) + if !ok || m == nil { + return v + } + res := make(map[string]any, len(lista)) + for _, c := range lista { + if val, exists := getDotPath(m, c); exists { + res[c] = val + } + } + return res + } + + if arr, ok := norm.([]any); ok { + out := make([]any, len(arr)) + for i, item := range arr { + out[i] = pick(item) + } + return out, lista + } + return pick(norm), lista +} + +func celdaTabla(v any) string { + if v == nil { + return "" + } + var s string + switch x := v.(type) { + case []any: + parts := make([]string, len(x)) + for i, item := range x { + parts[i] = fmt.Sprint(item) + } + s = strings.Join(parts, "; ") + case float64: + if math.Trunc(x) == x { + s = strconv.FormatInt(int64(x), 10) + } else { + s = strconv.FormatFloat(x, 'f', -1, 64) + } + default: + s = fmt.Sprint(x) + } + runes := []rune(s) + if len(runes) > 60 { + return string(runes[:57]) + "..." + } + return s +} + +func aTabla(datos any, orderedCols []string) string { + norm := normalizeAny(datos) + var filas []map[string]any + switch x := norm.(type) { + case []any: + if len(x) == 0 { + return "(sin resultados)" + } + for _, item := range x { + if m, ok := item.(map[string]any); ok { + filas = append(filas, m) + } else { + filas = append(filas, map[string]any{"valor": item}) + } + } + case map[string]any: + filas = []map[string]any{x} + default: + if norm == nil { + return "(sin resultados)" + } + filas = []map[string]any{{"valor": norm}} + } + + var colCandidates []string + if len(orderedCols) > 0 { + colCandidates = orderedCols + } else { + seen := make(map[string]bool) + for _, f := range filas { + for k := range f { + if !seen[k] { + seen[k] = true + colCandidates = append(colCandidates, k) + } + } + } + sort.Strings(colCandidates) + } + + var columnas []string + for _, c := range colCandidates { + ok := true + for _, f := range filas { + if v, exists := f[c]; exists && v != nil { + if _, isMap := v.(map[string]any); isMap { + ok = false + break + } + } + } + if ok { + columnas = append(columnas, c) + } + } + + anchos := make([]int, len(columnas)) + for i, c := range columnas { + anchos[i] = len([]rune(c)) + for _, f := range filas { + l := len([]rune(celdaTabla(f[c]))) + if l > anchos[i] { + anchos[i] = l + } + } + } + + padRight := func(s string, width int) string { + r := len([]rune(s)) + if r >= width { + return s + } + return s + strings.Repeat(" ", width-r) + } + linea := func(vals []string) string { + padded := make([]string, len(vals)) + for i, v := range vals { + padded[i] = padRight(v, anchos[i]) + } + return strings.Join(padded, " ") + } + + var lines []string + lines = append(lines, linea(columnas)) + dashes := make([]string, len(anchos)) + for i, a := range anchos { + dashes[i] = strings.Repeat("-", a) + } + lines = append(lines, linea(dashes)) + for _, f := range filas { + vals := make([]string, len(columnas)) + for i, c := range columnas { + vals[i] = celdaTabla(f[c]) + } + lines = append(lines, linea(vals)) + } + return strings.Join(lines, "\n") +} + +func imprimir(w io.Writer, datos any, flags *parsedFlags) { + filtrado, orderedCols := elegirCampos(datos, flags.Str("campos")) + if flags.Str("formato") == "tabla" { + _, _ = fmt.Fprintln(w, aTabla(filtrado, orderedCols)) + return + } + var b []byte + if flags.Bool("compacto") { + b, _ = json.Marshal(filtrado) + } else { + b, _ = json.MarshalIndent(filtrado, "", " ") + } + _, _ = fmt.Fprintln(w, string(b)) +} + +func imprimirError(w io.Writer, err *cliError) { + salida := map[string]any{ + "ok": false, + "error": err.Mensaje, + "codigo": err.Codigo, + } + if err.Status != 0 { + salida["status"] = err.Status + } + if err.Detalles != nil { + salida["detalles"] = err.Detalles + } + if err.Sugerencia != "" { + salida["sugerencia"] = err.Sugerencia + } + b, _ := json.MarshalIndent(salida, "", " ") + _, _ = fmt.Fprintln(w, string(b)) +} + +// --------------------------------------------------------------------------- +// Entry points +// --------------------------------------------------------------------------- + +// Run executes the cotizador CLI with the given arguments and returns its exit code. +func Run(args []string) int { + return runWithIO(args, os.Stdin, os.Stdout, os.Stderr) +} + +func runWithIO(args []string, stdin io.Reader, stdout, stderr io.Writer) int { + err := execute(args, stdin, stdout) + if err == nil { + return ExitOK + } + var dr *dryRunSignal + if errors.As(err, &dr) { + b, _ := json.MarshalIndent(map[string]any{ + "dryRun": true, + "metodo": dr.Metodo, + "url": dr.URL, + "cuerpo": dr.Cuerpo, + }, "", " ") + _, _ = fmt.Fprintln(stdout, string(b)) + return ExitOK + } + var ce *cliError + if errors.As(err, &ce) { + imprimirError(stderr, ce) + return ce.Codigo + } + imprimirError(stderr, &cliError{Mensaje: err.Error(), Codigo: ExitError}) + return ExitError +} + +func execute(args []string, stdin io.Reader, stdout io.Writer) error { + cmds := allCommands() + todasLasFlags := make([]flagSpec, 0, len(flagsGlobales)+64) + todasLasFlags = append(todasLasFlags, flagsGlobales...) + for _, c := range cmds { + todasLasFlags = append(todasLasFlags, c.Flags...) + } + + posicionales, flags, err := parsearArgs(args, todasLasFlags) + if err != nil { + return err + } + + if flags.Bool("version") { + imprimir(stdout, map[string]any{"version": Version}, flags) + return nil + } + if len(posicionales) == 0 { + _, _ = io.WriteString(stdout, ayudaGeneral(cmds)) + return nil + } + + cmd, consumidas := buscarComando(cmds, posicionales) + if cmd == nil { + return fallarComando(cmds, posicionales) + } + pos := posicionales[consumidas:] + + if flags.Bool("ayuda") { + _, _ = io.WriteString(stdout, ayudaComando(cmd)) + return nil + } + if flags.Has("formato") { + f := flags.Str("formato") + if f != "json" && f != "tabla" { + return errorUso("--formato debe ser json o tabla") + } + } + + // Reject unknown flags for this command instead of silently ignoring them. + validas := make(map[string]bool, len(flagsGlobales)+len(cmd.Flags)) + for _, f := range flagsGlobales { + validas[aCamel(f.Flag)] = true + } + for _, f := range cmd.Flags { + validas[aCamel(f.Flag)] = true + } + var desconocidas []string + for k := range flags.present { + if !validas[k] { + desconocidas = append(desconocidas, "--"+aKebab(k)) + } + } + if len(desconocidas) > 0 { + sort.Strings(desconocidas) + validFlagsList := make([]string, len(cmd.Flags)) + for i, f := range cmd.Flags { + validFlagsList[i] = "--" + f.Flag + } + validStr := strings.Join(validFlagsList, ", ") + if validStr == "" { + validStr = "(ninguna)" + } + return errorUso( + fmt.Sprintf(`Flag no valida para "%s": %s`, cmd.Comando, strings.Join(desconocidas, ", ")), + fmt.Sprintf("Flags validas: %s. Ver: cotizador ayuda %s", validStr, cmd.Comando), + ) + } + + var cliente *apiClient + if !cmd.SinServidor { + cliente, err = crearCliente(flags) + if err != nil { + return err + } + } + + res, hasOutput, err := cmd.Run(&cmdContext{ + Pos: pos, + Flags: flags, + Cliente: cliente, + Stdin: stdin, + Stdout: stdout, + }) + if err != nil { + return err + } + if hasOutput { + imprimir(stdout, res, flags) + } + return nil +} diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go new file mode 100644 index 0000000..69b9948 --- /dev/null +++ b/internal/cli/cli_test.go @@ -0,0 +1,399 @@ +package cli + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" +) + +func runCLI(t *testing.T, args []string, stdin string) (int, string, string) { + t.Helper() + var stdout, stderr bytes.Buffer + code := runWithIO(args, strings.NewReader(stdin), &stdout, &stderr) + return code, stdout.String(), stderr.String() +} + +func TestEsquemaAndSchemaAlias(t *testing.T) { + for _, cmd := range []string{"esquema", "schema"} { + code, stdout, stderr := runCLI(t, []string{cmd}, "") + if code != ExitOK { + t.Fatalf("%s: expected exit 0, got %d (stderr=%s)", cmd, code, stderr) + } + if stderr != "" { + t.Fatalf("%s: expected empty stderr, got %s", cmd, stderr) + } + + var doc map[string]any + if err := json.Unmarshal([]byte(stdout), &doc); err != nil { + t.Fatalf("%s: invalid JSON output: %v", cmd, err) + } + if doc["nombre"] != "cotizador" || doc["version"] != Version { + t.Errorf("%s: unexpected nombre/version: %v / %v", cmd, doc["nombre"], doc["version"]) + } + + cmds, ok := doc["comandos"].([]any) + if !ok { + t.Fatalf("%s: comandos missing or not array", cmd) + } + if len(cmds) != 30 { + t.Fatalf("%s: expected 30 commands in esquema, got %d", cmd, len(cmds)) + } + + // Verify all expected command names exist + names := make(map[string]bool) + for _, item := range cmds { + m := item.(map[string]any) + names[m["comando"].(string)] = true + } + required := []string{ + "login", "logout", "whoami", + "servicios listar", "servicios ver", "servicios crear", "servicios editar", + "servicios archivar", "servicios activar", "servicios eliminar", + "categorias listar", "categorias crear", + "paquetes listar", "paquetes ver", + "clientes listar", "clientes crear", "clientes editar", + "cotizaciones listar", "cotizaciones ver", "cotizaciones crear", + "cotizaciones estado", "cotizaciones pdf", "cotizaciones excel", "cotizaciones eliminar", + "horas listar", "horas registrar", + "api", "esquema", "ayuda", "version", + } + for _, r := range required { + if !names[r] { + t.Errorf("%s: missing command %q in esquema", cmd, r) + } + } + + codigos, ok := doc["codigosSalida"].(map[string]any) + if !ok || len(codigos) != 8 { + t.Errorf("%s: expected 8 codigosSalida (0..7), got %v", cmd, codigos) + } + } +} + +func TestVersionAndHelp(t *testing.T) { + code, stdout, _ := runCLI(t, []string{"--version", "--compacto"}, "") + if code != ExitOK { + t.Fatalf("expected 0, got %d", code) + } + if strings.TrimSpace(stdout) != `{"version":"1.0.0"}` { + t.Fatalf("unexpected compact version output: %q", stdout) + } + + code, stdout, _ = runCLI(t, []string{}, "") + if code != ExitOK || !strings.Contains(stdout, "FLAGS GLOBALES") { + t.Fatalf("empty args should print general help, got code=%d stdout=%q", code, stdout) + } + + code, stdout, _ = runCLI(t, []string{"servicios", "crear", "-h"}, "") + if code != ExitOK || !strings.Contains(stdout, "POST /api/catalogo") { + t.Fatalf("-h should print command help, got code=%d stdout=%q", code, stdout) + } + + code, stdout, _ = runCLI(t, []string{"ayuda", "cotizaciones", "crear"}, "") + if code != ExitOK || !strings.Contains(stdout, "POST /api/cotizaciones") { + t.Fatalf("ayuda failed, got code=%d stdout=%q", code, stdout) + } +} + +func TestFlagParsingAndUnknownFlags(t *testing.T) { + // Unknown flag on valid command -> ExitUso (2) + JSON stderr + code, stdout, stderr := runCLI(t, []string{"servicios", "listar", "--bandera-invalida", "123"}, "") + if code != ExitUso { + t.Fatalf("expected ExitUso (2), got %d", code) + } + if stdout != "" { + t.Fatalf("expected empty stdout on error, got %q", stdout) + } + var errDoc map[string]any + if err := json.Unmarshal([]byte(stderr), &errDoc); err != nil { + t.Fatalf("expected JSON stderr, got %q: %v", stderr, err) + } + if errDoc["ok"] != false || int(errDoc["codigo"].(float64)) != ExitUso { + t.Fatalf("unexpected error JSON: %+v", errDoc) + } + + // Flag belonging to another command -> ExitUso (2) + code, _, stderr = runCLI(t, []string{"categorias", "listar", "--precio", "100"}, "") + if code != ExitUso || !strings.Contains(stderr, "--precio") { + t.Fatalf("expected ExitUso mentioning --precio, got code=%d stderr=%s", code, stderr) + } + + // Unknown command -> ExitUso (2) + code, _, stderr = runCLI(t, []string{"noexiste"}, "") + if code != ExitUso || !strings.Contains(stderr, "Comando desconocido") { + t.Fatalf("expected ExitUso for unknown command, got code=%d stderr=%s", code, stderr) + } + + // Invalid --formato -> ExitUso (2) + code, _, _ = runCLI(t, []string{"version", "--formato", "xml"}, "") + if code != ExitUso { + t.Fatalf("expected ExitUso for invalid --formato, got %d", code) + } + + // Destructive delete without --confirmar -> ExitUso (2) + code, _, stderr = runCLI(t, []string{"servicios", "eliminar", "abc123"}, "") + if code != ExitUso || !strings.Contains(stderr, "--confirmar") { + t.Fatalf("expected ExitUso requiring --confirmar, got code=%d stderr=%s", code, stderr) + } + + // --no-compacto boolean negation + pos, flags, err := parsearArgs([]string{"version", "--no-compacto", "--entregable=Uno", "--entregable", "Dos"}, append(flagsGlobales, flagsServicio...)) + if err != nil { + t.Fatalf("parsearArgs failed: %v", err) + } + if len(pos) != 1 || pos[0] != "version" { + t.Fatalf("unexpected positionals: %v", pos) + } + if !flags.Has("compacto") || flags.Bool("compacto") { + t.Fatalf("expected compacto=false") + } + if got := flags.List("entregable"); len(got) != 2 || got[0] != "Uno" || got[1] != "Dos" { + t.Fatalf("expected 2 repeatable entregables, got %v", got) + } +} + +func TestDryRunWriteCommands(t *testing.T) { + // 1. servicios crear --dry-run (with repeatable --entregable and formatted price) + code, stdout, stderr := runCLI(t, []string{ + "servicios", "crear", + "--url", "http://example.test", + "--nombre", "Auditoria SEO", + "--fase", "0", + "--tipo-pago", "unico", + "--precio", "$6,500", + "--entregable", "Reporte PDF", + "--entregable", "Sesion 1h", + "--dry-run", + }, "") + if code != ExitOK { + t.Fatalf("servicios crear --dry-run failed: code=%d stderr=%s", code, stderr) + } + var dr map[string]any + if err := json.Unmarshal([]byte(stdout), &dr); err != nil { + t.Fatalf("invalid dry-run JSON: %v", err) + } + if dr["dryRun"] != true || dr["metodo"] != "POST" || dr["url"] != "http://example.test/api/catalogo" { + t.Fatalf("unexpected dry-run payload: %+v", dr) + } + cuerpo := dr["cuerpo"].(map[string]any) + if cuerpo["nombre"] != "Auditoria SEO" || cuerpo["precioBase"].(float64) != 6500 { + t.Fatalf("unexpected dry-run cuerpo: %+v", cuerpo) + } + + // 2. cotizaciones crear with --partida-horas and --dry-run + code, stdout, stderr = runCLI(t, []string{ + "cotizaciones", "crear", + "--url", "http://example.test", + "--cliente", "Ana Ruiz", + "--empresa", "Panaderia Sol", + "--partida-horas", "Soporte tecnico|10|700", + "--sin-iva", + "--dry-run", + }, "") + if code != ExitOK { + t.Fatalf("cotizaciones crear --dry-run failed: code=%d stderr=%s", code, stderr) + } + if err := json.Unmarshal([]byte(stdout), &dr); err != nil { + t.Fatalf("invalid dry-run JSON: %v", err) + } + cuerpo = dr["cuerpo"].(map[string]any) + if cuerpo["incluirIva"] != false { + t.Errorf("expected incluirIva=false, got %v", cuerpo["incluirIva"]) + } + partidas := cuerpo["servicios"].([]any) + if len(partidas) != 1 { + t.Fatalf("expected 1 partida, got %d", len(partidas)) + } + p0 := partidas[0].(map[string]any) + if p0["precio"].(float64) != 7000 || p0["modeloCobro"] != "horas" { + t.Errorf("unexpected partida por horas: %+v", p0) + } + + // 3. servicios eliminar --dry-run works without --confirmar + code, stdout, stderr = runCLI(t, []string{ + "servicios", "eliminar", "srv-123", + "--url", "http://example.test", + "--dry-run", + }, "") + if code != ExitOK { + t.Fatalf("servicios eliminar --dry-run failed: code=%d stderr=%s", code, stderr) + } + if !strings.Contains(stdout, `"metodo": "DELETE"`) { + t.Errorf("expected DELETE in dry-run output: %s", stdout) + } + + // 4. api POST with --datos from stdin and --dry-run + code, stdout, stderr = runCLI(t, []string{ + "api", "POST", "api/cobros/recordatorios", + "--url", "http://example.test", + "--datos", "-", + "--dry-run", + }, `{"clienteId":"cli-1"}`) + if code != ExitOK { + t.Fatalf("api POST --datos - --dry-run failed: code=%d stderr=%s", code, stderr) + } + if !strings.Contains(stdout, `"clienteId": "cli-1"`) || !strings.Contains(stdout, "http://example.test/api/cobros/recordatorios") { + t.Errorf("unexpected api dry-run output: %s", stdout) + } +} + +func TestSessionLoginAutoReauthAndExitCodes(t *testing.T) { + tmpHome := t.TempDir() + t.Setenv("COTIZADOR_HOME", tmpHome) + t.Setenv("COTIZADOR_TOKEN", "") + t.Setenv("COTIZADOR_EMAIL", "") + t.Setenv("COTIZADOR_PASSWORD", "") + + var loginCalls atomic.Int32 + var meCalls atomic.Int32 + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodPost && r.URL.Path == "/api/auth/login": + loginCalls.Add(1) + var body map[string]string + _ = json.NewDecoder(r.Body).Decode(&body) + if body["email"] == "cliente@test.com" { + http.SetCookie(w, &http.Cookie{Name: "cotizador-session", Value: "tok-cli"}) + _ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"email": "cliente@test.com", "role": "cliente"}}) + return + } + if body["password"] != "secret" { + w.WriteHeader(http.StatusUnauthorized) + _ = json.NewEncoder(w).Encode(map[string]any{"error": "Credenciales invalidas"}) + return + } + http.SetCookie(w, &http.Cookie{Name: "cotizador-session", Value: "jwt-staff-token"}) + _ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"email": body["email"], "name": "Admin", "role": "admin"}}) + + case r.Method == http.MethodGet && r.URL.Path == "/api/auth/me": + n := meCalls.Add(1) + c, err := r.Cookie("cotizador-session") + if err != nil || c.Value != "jwt-staff-token" || n == 2 { + w.WriteHeader(http.StatusUnauthorized) + _ = json.NewEncoder(w).Encode(map[string]any{"error": "No autenticado"}) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"user": map[string]any{"email": "admin@test.com", "role": "admin"}}) + + case r.URL.Path == "/api/catalogo" && r.Method == http.MethodGet: + _ = json.NewEncoder(w).Encode([]map[string]any{ + {"id": "s1", "nombre": "SEO Basico", "precioBase": 2900, "extra": map[string]any{"nested": "val"}}, + {"id": "s2", "nombre": "Google Ads", "precioBase": 4900, "extra": map[string]any{"nested": "val2"}}, + }) + + case r.URL.Path == "/api/test/400": + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(map[string]any{"error": "invalido", "detalles": []string{"campo"}}) + case r.URL.Path == "/api/test/404": + w.WriteHeader(http.StatusNotFound) + _ = json.NewEncoder(w).Encode(map[string]any{"error": "no existe"}) + case r.URL.Path == "/api/test/409": + w.WriteHeader(http.StatusConflict) + _ = json.NewEncoder(w).Encode(map[string]any{"error": "duplicado"}) + case r.URL.Path == "/api/test/500": + w.WriteHeader(http.StatusInternalServerError) + _ = json.NewEncoder(w).Encode(map[string]any{"error": "boom"}) + case r.URL.Path == "/api/cotizaciones/cot-1": + _ = json.NewEncoder(w).Encode(map[string]any{"id": "cot-1", "numero": "UJ2605AG001"}) + case r.URL.Path == "/api/export/pdf/cot-1": + w.Header().Set("Content-Type", "application/pdf") + w.Header().Set("Content-Disposition", `attachment; filename="UJ2605AG001.pdf"`) + _, _ = w.Write([]byte("%PDF-1.4 mock")) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + // Cliente role rejected on login -> ExitAuth (3) + code, _, _ := runCLI(t, []string{"login", "--url", srv.URL, "--email", "cliente@test.com", "--password", "x"}, "") + if code != ExitAuth { + t.Fatalf("expected ExitAuth for cliente role, got %d", code) + } + + // Staff login via --password-stdin persists sesiones.json + code, stdout, stderr := runCLI(t, []string{"login", "--url", srv.URL, "--email", "admin@test.com", "--password-stdin"}, "secret\n") + if code != ExitOK { + t.Fatalf("login failed: code=%d stderr=%s", code, stderr) + } + if !strings.Contains(stdout, `"ok": true`) { + t.Fatalf("unexpected login stdout: %s", stdout) + } + if _, err := os.Stat(filepath.Join(tmpHome, "sesiones.json")); err != nil { + t.Fatalf("expected sesiones.json to be written: %v", err) + } + + // whoami uses saved cookie (meCalls == 1) + code, stdout, stderr = runCLI(t, []string{"whoami", "--url", srv.URL}, "") + if code != ExitOK || !strings.Contains(stdout, "admin@test.com") { + t.Fatalf("whoami failed: code=%d stdout=%s stderr=%s", code, stdout, stderr) + } + + // Auto-reauth on 401 when COTIZADOR_EMAIL/PASSWORD are set (meCalls == 2 returns 401, triggers login, retry meCalls == 3 succeeds) + t.Setenv("COTIZADOR_EMAIL", "admin@test.com") + t.Setenv("COTIZADOR_PASSWORD", "secret") + beforeLogins := loginCalls.Load() + code, stdout, stderr = runCLI(t, []string{"whoami", "--url", srv.URL}, "") + if code != ExitOK { + t.Fatalf("auto-reauth whoami failed: code=%d stderr=%s", code, stderr) + } + if loginCalls.Load() != beforeLogins+1 { + t.Fatalf("expected 1 auto-reauth login call, got delta %d", loginCalls.Load()-beforeLogins) + } + + // --campos + --formato tabla + code, stdout, stderr = runCLI(t, []string{"servicios", "listar", "--url", srv.URL, "--campos", "id,nombre,extra.nested", "--formato", "tabla"}, "") + if code != ExitOK { + t.Fatalf("servicios listar tabla failed: code=%d stderr=%s", code, stderr) + } + if !strings.Contains(stdout, "SEO Basico") || !strings.Contains(stdout, "extra.nested") || !strings.Contains(stdout, "val2") { + t.Fatalf("unexpected table output:\n%s", stdout) + } + + // Status-to-exit-code mapping + cases := []struct { + path string + want int + }{ + {"/api/test/400", ExitValidacion}, + {"/api/test/404", ExitNoEncontrado}, + {"/api/test/409", ExitConflicto}, + {"/api/test/500", ExitError}, + } + for _, tc := range cases { + code, _, _ = runCLI(t, []string{"api", "GET", tc.path, "--url", srv.URL}, "") + if code != tc.want { + t.Errorf("%s: expected exit %d, got %d", tc.path, tc.want, code) + } + } + + // Binary PDF download + outPDF := filepath.Join(tmpHome, "out.pdf") + code, stdout, stderr = runCLI(t, []string{"cotizaciones", "pdf", "cot-1", "--url", srv.URL, "--salida", outPDF}, "") + if code != ExitOK { + t.Fatalf("cotizaciones pdf failed: code=%d stderr=%s", code, stderr) + } + b, err := os.ReadFile(outPDF) + if err != nil || string(b) != "%PDF-1.4 mock" { + t.Fatalf("downloaded PDF mismatch: err=%v content=%q", err, string(b)) + } + + // Logout removes saved session + code, stdout, _ = runCLI(t, []string{"logout", "--url", srv.URL}, "") + if code != ExitOK || !strings.Contains(stdout, `"sesionBorrada": true`) { + t.Fatalf("logout failed: code=%d stdout=%s", code, stdout) + } + + // Network error -> ExitRed (7) + code, _, stderr = runCLI(t, []string{"whoami", "--url", "http://127.0.0.1:1"}, "") + if code != ExitRed { + t.Fatalf("expected ExitRed (7) on unreachable port, got %d (stderr=%s)", code, stderr) + } +} diff --git a/internal/cli/commands.go b/internal/cli/commands.go new file mode 100644 index 0000000..8a23251 --- /dev/null +++ b/internal/cli/commands.go @@ -0,0 +1,1744 @@ +package cli + +import ( + "errors" + "fmt" + "io" + "math" + "net/http" + "net/url" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + + "github.com/google/uuid" +) + +// --------------------------------------------------------------------------- +// Reference resolvers (nombre -> id) +// --------------------------------------------------------------------------- + +func asMap(v any) map[string]any { + m, _ := v.(map[string]any) + return m +} + +func asSlice(v any) []any { + s, _ := v.([]any) + return s +} + +func mapStr(m map[string]any, key string) string { + if m == nil { + return "" + } + s, _ := m[key].(string) + return s +} + +func resolverCategoria(c *apiClient, valor string) (any, error) { + v, isNull := textoOpcional(valor) + if isNull { + return nil, nil + } + raw, err := c.api(http.MethodGet, "/api/categorias") + if err != nil { + return nil, err + } + cats := asSlice(raw) + for _, item := range cats { + m := asMap(item) + if mapStr(m, "id") == v { + return mapStr(m, "id"), nil + } + } + var nombres []string + for _, item := range cats { + m := asMap(item) + nom := mapStr(m, "nombre") + nombres = append(nombres, nom) + if strings.EqualFold(nom, v) { + return mapStr(m, "id"), nil + } + } + return nil, errorUso( + fmt.Sprintf(`No existe la categoria "%s"`, v), + fmt.Sprintf(`Categorias disponibles: %s. Crea una con: cotizador categorias crear --nombre "%s"`, strings.Join(nombres, ", "), v), + ) +} + +func intentarPorID(c *apiClient, ruta string) (any, error) { + res, err := c.api(http.MethodGet, ruta) + if err != nil { + var ce *cliError + if errors.As(err, &ce) && ce.Codigo == ExitNoEncontrado { + return nil, nil + } + return nil, err + } + return res, nil +} + +func resolverServicio(c *apiClient, ref string) (map[string]any, error) { + porID, err := intentarPorID(c, "/api/catalogo/"+url.PathEscape(ref)) + if err != nil { + return nil, err + } + if m := asMap(porID); m != nil { + return m, nil + } + + raw, err := c.api(http.MethodGet, "/api/catalogo?activo=true&q="+url.QueryEscape(ref)) + if err != nil { + return nil, err + } + candidatos := asSlice(raw) + var exactos []map[string]any + for _, item := range candidatos { + m := asMap(item) + if strings.EqualFold(mapStr(m, "nombre"), ref) { + exactos = append(exactos, m) + } + } + if len(exactos) == 1 { + return exactos[0], nil + } + if len(candidatos) == 1 { + return asMap(candidatos[0]), nil + } + if len(candidatos) == 0 { + return nil, &cliError{ + Mensaje: fmt.Sprintf(`No existe el servicio "%s" (ni como id ni como nombre de un servicio activo)`, ref), + Codigo: ExitNoEncontrado, + Sugerencia: "Busca con: cotizador servicios listar --q (agrega --todos para incluir archivados)", + } + } + var sample []string + limit := len(candidatos) + if limit > 10 { + limit = 10 + } + for _, item := range candidatos[:limit] { + m := asMap(item) + sample = append(sample, fmt.Sprintf("%s (%s)", mapStr(m, "id"), mapStr(m, "nombre"))) + } + return nil, errorUso( + fmt.Sprintf(`"%s" es ambiguo (%d coincidencias)`, ref, len(candidatos)), + fmt.Sprintf("Usa el id. Coincidencias: %s", strings.Join(sample, "; ")), + ) +} + +func resolverCotizacion(c *apiClient, ref string) (string, error) { + porID, err := intentarPorID(c, "/api/cotizaciones/"+url.PathEscape(ref)) + if err != nil { + return "", err + } + if m := asMap(porID); m != nil && mapStr(m, "id") != "" { + return mapStr(m, "id"), nil + } + raw, err := c.api(http.MethodGet, "/api/cotizaciones?q="+url.QueryEscape(ref)+"&limit=20") + if err != nil { + return "", err + } + for _, item := range asSlice(raw) { + m := asMap(item) + if strings.EqualFold(mapStr(m, "numero"), ref) { + return mapStr(m, "id"), nil + } + } + return "", &cliError{ + Mensaje: fmt.Sprintf(`No existe la cotizacion "%s"`, ref), + Codigo: ExitNoEncontrado, + Sugerencia: "Pasa el id o el numero exacto (ej. UJ2605AG001). Busca con: cotizador cotizaciones listar --q ", + } +} + +func descargar(c *apiClient, ruta, salida, porDefecto string) (map[string]any, error) { + raw, err := c.api(http.MethodGet, ruta, apiOpts{Binario: true}) + if err != nil { + return nil, err + } + bin := raw.(*binaryResponse) + destName := salida + if destName == "" { + destName = bin.NombreArchivo + } + if destName == "" { + destName = porDefecto + } + destino, err := filepath.Abs(destName) + if err != nil { + destino = destName + } + if err := os.MkdirAll(filepath.Dir(destino), 0o755); err != nil { + return nil, err + } + if err := os.WriteFile(destino, bin.Buffer, 0o644); err != nil { + return nil, err + } + return map[string]any{ + "ok": true, + "archivo": destino, + "bytes": len(bin.Buffer), + "tipo": bin.Tipo, + }, nil +} + +// --------------------------------------------------------------------------- +// Body builders & shared flags +// --------------------------------------------------------------------------- + +var flagConfirmar = flagSpec{ + Flag: "confirmar", + Tipo: "booleano", + Descripcion: "Obligatoria: confirma una accion que no se puede deshacer", +} + +func toAnySlice(ss []string) []any { + out := make([]any, len(ss)) + for i, s := range ss { + out[i] = s + } + return out +} + +var flagsServicio = []flagSpec{ + {Flag: "nombre", Tipo: "texto", Descripcion: "Nombre del servicio"}, + {Flag: "fase", Tipo: "entero", Valores: []any{0, 1, 2, 3}, Descripcion: "0 Auditoria, 1 Setup, 2 Publicidad, 3 Contenido/SEO"}, + {Flag: "tipo-pago", Tipo: "texto", Valores: []any{"unico", "mensual"}, Descripcion: "unico o mensual"}, + {Flag: "precio", Tipo: "numero", Descripcion: "Precio base en MXN, sin IVA (acepta 4500 o 4,500)"}, + {Flag: "descripcion", Tipo: "texto", Descripcion: `Descripcion (usa "" para borrarla)`}, + {Flag: "tiempo-entrega", Tipo: "texto", Descripcion: `Ej. "4 - 10 dias" (default al crear)`}, + {Flag: "entregable", Tipo: "texto", Repetible: true, Descripcion: "Un entregable; repite la flag para varios. En editar REEMPLAZA la lista"}, + {Flag: "categoria", Tipo: "texto", Descripcion: `Id o nombre de la categoria ("ninguna" para quitarla)`}, + {Flag: "variante", Tipo: "texto", Descripcion: "Ej. WooCommerce, Shopify"}, + {Flag: "nivel", Tipo: "texto", Valores: toAnySlice(nivelesServicio), Descripcion: `Nivel de cliente ("ninguno" para quitarlo)`}, + {Flag: "orden", Tipo: "entero", Descripcion: "Posicion dentro de su fase (default al crear: al final)"}, + {Flag: "datos", Tipo: "json", Descripcion: "Objeto JSON con los campos de la API (en linea, @archivo.json o - para stdin). Las flags tienen prioridad"}, +} + +func cuerpoServicio(c *apiClient, flags *parsedFlags, stdin io.Reader) (map[string]any, error) { + base, err := leerDatos(flags.Str("datos"), flags.Has("datos"), stdin) + if err != nil { + return nil, err + } + + // Admite categoria por nombre tambien dentro de --datos. + if catName, ok := base["categoria"].(string); ok { + if _, hasID := base["categoriaId"]; !hasID { + resolved, err := resolverCategoria(c, catName) + if err != nil { + return nil, err + } + base["categoriaId"] = resolved + delete(base, "categoria") + } + } + + desdeFlags := make(map[string]any) + if flags.Has("nombre") { + desdeFlags["nombre"] = flags.Str("nombre") + } + if flags.Has("fase") { + f, err := parseEntero(flags.Str("fase"), "fase") + if err != nil { + return nil, err + } + if f < 0 || f > 3 { + return nil, errorUso("--fase debe ser 0, 1, 2 o 3") + } + desdeFlags["fase"] = f + } + if flags.Has("tipoPago") { + tp, err := unoDe(flags.Str("tipoPago"), []string{"unico", "mensual"}, "tipo-pago") + if err != nil { + return nil, err + } + desdeFlags["tipoPago"] = tp + } + if flags.Has("precio") { + p, err := parseNumero(flags.Str("precio"), "precio") + if err != nil { + return nil, err + } + desdeFlags["precioBase"] = p + } + if flags.Has("descripcion") { + v, isNull := textoOpcional(flags.Str("descripcion")) + if isNull { + desdeFlags["descripcion"] = nil + } else { + desdeFlags["descripcion"] = v + } + } + if flags.Has("tiempoEntrega") { + desdeFlags["tiempoEntrega"] = flags.Str("tiempoEntrega") + } + if flags.Has("entregable") { + desdeFlags["entregablesDefault"] = flags.List("entregable") + } + if flags.Has("categoria") { + resolved, err := resolverCategoria(c, flags.Str("categoria")) + if err != nil { + return nil, err + } + desdeFlags["categoriaId"] = resolved + } + if flags.Has("variante") { + v, isNull := textoOpcional(flags.Str("variante")) + if isNull { + desdeFlags["variante"] = nil + } else { + desdeFlags["variante"] = v + } + } + if flags.Has("nivel") { + v, isNull := textoOpcional(flags.Str("nivel")) + if isNull { + desdeFlags["nivel"] = nil + } else { + nv, err := unoDe(v, nivelesServicio, "nivel") + if err != nil { + return nil, err + } + desdeFlags["nivel"] = nv + } + } + if flags.Has("orden") { + o, err := parseEntero(flags.Str("orden"), "orden") + if err != nil { + return nil, err + } + desdeFlags["orden"] = o + } + + out := make(map[string]any, len(base)+len(desdeFlags)) + for k, v := range base { + out[k] = v + } + for k, v := range desdeFlags { + out[k] = v + } + return out, nil +} + +func partidaDesdeCatalogo(s map[string]any, precio *float64) map[string]any { + p := s["precioBase"] + if precio != nil { + p = *precio + } + entregables := s["entregablesDefault"] + if entregables == nil { + entregables = []any{} + } + return map[string]any{ + "catalogoId": s["id"], + "nombre": s["nombre"], + "fase": s["fase"], + "tipoPago": s["tipoPago"], + "precio": p, + "tiempoEntrega": s["tiempoEntrega"], + "entregables": entregables, + } +} + +func partidaPorHoras(texto string) (map[string]any, error) { + parts := strings.Split(texto, "|") + var concepto, horasTxt, tarifaTxt string + if len(parts) > 0 { + concepto = strings.TrimSpace(parts[0]) + } + if len(parts) > 1 { + horasTxt = strings.TrimSpace(parts[1]) + } + if len(parts) > 2 { + tarifaTxt = strings.TrimSpace(parts[2]) + } + if concepto == "" || horasTxt == "" { + return nil, errorUso(fmt.Sprintf(`--partida-horas debe ser "Concepto|horas|tarifa" (tarifa opcional, default %.0f); recibi "%s"`, tarifaHoraDefault, texto)) + } + horas, err := parseNumero(horasTxt, "partida-horas") + if err != nil { + return nil, err + } + tarifa := tarifaHoraDefault + if tarifaTxt != "" { + tarifa, err = parseNumero(tarifaTxt, "partida-horas") + if err != nil { + return nil, err + } + } + return map[string]any{ + "catalogoId": "custom-" + uuid.NewString(), + "nombre": concepto, + "fase": 1, + "tipoPago": "unico", + "precio": math.Round(horas*tarifa*100) / 100, + "tiempoEntrega": "A convenir", + "entregables": []any{}, + "esPersonalizado": true, + "modeloCobro": "horas", + "horas": horas, + "tarifaHora": tarifa, + }, nil +} + +func resumenCotizacion(c map[string]any) map[string]any { + sliceDate := func(s string) any { + if len(s) >= 10 { + return s[:10] + } + if s == "" { + return nil + } + return s + } + cliente := asMap(c["cliente"]) + asesor := asMap(c["asesor"]) + plan := asMap(c["planBucefalo"]) + var planNivel any + if plan != nil && plan["nivel"] != nil { + planNivel = plan["nivel"] + } + return map[string]any{ + "id": c["id"], + "numero": c["numero"], + "estado": c["estado"], + "fecha": sliceDate(mapStr(c, "fecha")), + "vigencia": sliceDate(mapStr(c, "vigencia")), + "cliente": cliente["nombre"], + "empresa": cliente["empresa"], + "proyecto": c["proyecto"], + "moneda": c["moneda"], + "esDoble": c["esDoble"], + "partidas": len(asSlice(c["servicios"])), + "planBucefaloCRM": planNivel, + "asesor": asesor["name"], + } +} + +func exigirConfirmacion(flags *parsedFlags, accion string) error { + if !flags.Bool("confirmar") && !flags.Bool("dryRun") { + return errorUso(fmt.Sprintf("%s no se puede deshacer. Repite el comando con --confirmar si es lo que quieres.", accion)) + } + return nil +} + +func exigirPosicional(pos []string, i int, nombre, comando string) (string, error) { + if i >= len(pos) || pos[i] == "" { + return "", errorUso( + fmt.Sprintf("Falta el argumento <%s>", nombre), + fmt.Sprintf("Uso: cotizador %s <%s>", comando, nombre), + ) + } + return pos[i], nil +} + +// --------------------------------------------------------------------------- +// Command registry (all 30 commands matching cli/cotizador.mjs) +// --------------------------------------------------------------------------- + +func allCommands() []commandSpec { + return []commandSpec{ + // ----- sesion ----- + { + Comando: "login", + Descripcion: "Inicia sesion con una cuenta staff y guarda el token en ~/.cotizador-uj/sesiones.json (7 dias).", + Flags: []flagSpec{ + {Flag: "email", Tipo: "texto", Descripcion: "Correo (o $COTIZADOR_EMAIL)"}, + {Flag: "password", Tipo: "texto", Descripcion: "Contrasena (o $COTIZADOR_PASSWORD)"}, + {Flag: "password-stdin", Tipo: "booleano", Descripcion: "Lee la contrasena de stdin (no queda en el historial)"}, + }, + Ejemplos: []string{ + "cotizador login --email admin@urieljareth.com --password-stdin < pass.txt", + "COTIZADOR_EMAIL=... COTIZADOR_PASSWORD=... cotizador login", + }, + Endpoint: "POST /api/auth/login", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + email := ctx.Flags.Str("email") + if email == "" { + email = os.Getenv("COTIZADOR_EMAIL") + } + password := ctx.Flags.Str("password") + if password == "" { + password = os.Getenv("COTIZADOR_PASSWORD") + } + if ctx.Flags.Bool("passwordStdin") { + s, err := leerStdin(ctx.Stdin) + if err != nil { + return nil, false, err + } + password = strings.TrimSpace(s) + } + if email == "" || password == "" { + return nil, false, errorUso( + "Faltan credenciales", + "Pasa --email y --password (o --password-stdin), o define COTIZADOR_EMAIL y COTIZADOR_PASSWORD", + ) + } + usuario, err := ctx.Cliente.login(email, password) + if err != nil { + return nil, false, err + } + return map[string]any{"ok": true, "url": ctx.Cliente.base, "usuario": usuario}, true, nil + }, + }, + { + Comando: "logout", + Descripcion: "Borra la sesion guardada para la URL actual.", + Run: func(ctx *cmdContext) (any, bool, error) { + habia, err := ctx.Cliente.cerrarSesion() + if err != nil { + return nil, false, err + } + return map[string]any{"ok": true, "url": ctx.Cliente.base, "sesionBorrada": habia}, true, nil + }, + }, + { + Comando: "whoami", + Alias: []string{"yo"}, + Descripcion: "Muestra el usuario de la sesion actual.", + Endpoint: "GET /api/auth/me", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + raw, err := ctx.Cliente.api(http.MethodGet, "/api/auth/me") + if err != nil { + return nil, false, err + } + m := asMap(raw) + return map[string]any{"url": ctx.Cliente.base, "usuario": m["user"]}, true, nil + }, + }, + + // ----- servicios (catalogo) ----- + { + Comando: "servicios listar", + Alias: []string{"servicios", "servicios ls"}, + Descripcion: "Lista servicios del catalogo. Por defecto solo los activos.", + Flags: []flagSpec{ + {Flag: "q", Tipo: "texto", Descripcion: "Busca en nombre y descripcion"}, + {Flag: "fase", Tipo: "entero", Valores: []any{0, 1, 2, 3}, Descripcion: "Filtra por fase"}, + {Flag: "tipo-pago", Tipo: "texto", Valores: []any{"unico", "mensual"}, Descripcion: "Filtra por tipo de pago"}, + {Flag: "categoria", Tipo: "texto", Descripcion: "Id o nombre de categoria"}, + {Flag: "archivados", Tipo: "booleano", Descripcion: "Solo los archivados"}, + {Flag: "todos", Tipo: "booleano", Descripcion: "Activos y archivados"}, + }, + Ejemplos: []string{ + "cotizador servicios listar --fase 1 --campos id,nombre,precioBase", + `cotizador servicios listar --q "landing" --formato tabla`, + }, + Endpoint: "GET /api/catalogo", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + p := url.Values{} + if q := ctx.Flags.Str("q"); q != "" { + p.Set("q", q) + } + if ctx.Flags.Has("fase") { + f, err := parseEntero(ctx.Flags.Str("fase"), "fase") + if err != nil { + return nil, false, err + } + p.Set("fase", strconv.Itoa(f)) + } + if ctx.Flags.Has("tipoPago") { + tp, err := unoDe(ctx.Flags.Str("tipoPago"), []string{"unico", "mensual"}, "tipo-pago") + if err != nil { + return nil, false, err + } + p.Set("tipoPago", tp) + } + if ctx.Flags.Has("categoria") { + catID, err := resolverCategoria(ctx.Cliente, ctx.Flags.Str("categoria")) + if err != nil { + return nil, false, err + } + if s, ok := catID.(string); ok && s != "" { + p.Set("categoriaId", s) + } + } + if ctx.Flags.Bool("archivados") { + p.Set("activo", "false") + } else if !ctx.Flags.Bool("todos") { + p.Set("activo", "true") + } + res, err := ctx.Cliente.api(http.MethodGet, "/api/catalogo?"+p.Encode()) + return res, true, err + }, + }, + { + Comando: "servicios ver", + Descripcion: "Muestra un servicio del catalogo (por id o por nombre exacto).", + Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del servicio o su nombre"}}, + Ejemplos: []string{"cotizador servicios ver cmabc123...", `cotizador servicios ver "Landing Page"`}, + Endpoint: "GET /api/catalogo/{id}", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + ref, err := exigirPosicional(ctx.Pos, 0, "id", "servicios ver") + if err != nil { + return nil, false, err + } + res, err := resolverServicio(ctx.Cliente, ref) + return res, true, err + }, + }, + { + Comando: "servicios crear", + Alias: []string{"servicios nuevo"}, + Descripcion: "Crea un servicio en el catalogo. Obligatorios: --nombre, --fase, --tipo-pago, --precio. Queda activo y al final de su fase.", + Flags: flagsServicio, + Ejemplos: []string{ + `cotizador servicios crear --nombre "Auditoria SEO tecnica" --fase 0 --tipo-pago unico --precio 6500 --categoria SEO --entregable "Reporte PDF" --entregable "Sesion de 1 h"`, + `cotizador servicios crear --datos '{"nombre":"Gestion de Google Ads","fase":2,"tipoPago":"mensual","precioBase":5500}'`, + }, + Endpoint: "POST /api/catalogo", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + cuerpo, err := cuerpoServicio(ctx.Cliente, ctx.Flags, ctx.Stdin) + if err != nil { + return nil, false, err + } + required := []struct{ key, flag string }{ + {"nombre", "--nombre"}, + {"fase", "--fase"}, + {"tipoPago", "--tipo-pago"}, + {"precioBase", "--precio"}, + } + var faltan []string + for _, r := range required { + if _, ok := cuerpo[r.key]; !ok { + faltan = append(faltan, r.flag) + } + } + if len(faltan) > 0 { + return nil, false, errorUso( + "Faltan campos obligatorios: "+strings.Join(faltan, ", "), + `Ejemplo: cotizador servicios crear --nombre "Mi servicio" --fase 1 --tipo-pago unico --precio 5000`, + ) + } + res, err := ctx.Cliente.api(http.MethodPost, "/api/catalogo", apiOpts{Cuerpo: cuerpo, HasCuerpo: true}) + return res, true, err + }, + }, + { + Comando: "servicios editar", + Descripcion: "Edita un servicio: solo cambia los campos que pases. Las cotizaciones ya guardadas conservan su precio y entregables.", + Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del servicio o su nombre exacto"}}, + Flags: append(append([]flagSpec{}, flagsServicio...), + flagSpec{Flag: "agregar-entregable", Tipo: "texto", Repetible: true, Descripcion: "Agrega un entregable a la lista actual (sin reemplazarla)"}, + flagSpec{Flag: "quitar-entregable", Tipo: "texto", Repetible: true, Descripcion: "Quita un entregable de la lista actual (texto exacto)"}, + ), + Ejemplos: []string{ + "cotizador servicios editar cmabc123... --precio 7200", + `cotizador servicios editar "Landing Page" --agregar-entregable "Formulario conectado a Bucefalo CRM"`, + }, + Endpoint: "PATCH /api/catalogo/{id}", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + ref, err := exigirPosicional(ctx.Pos, 0, "id", "servicios editar") + if err != nil { + return nil, false, err + } + actual, err := resolverServicio(ctx.Cliente, ref) + if err != nil { + return nil, false, err + } + cuerpo, err := cuerpoServicio(ctx.Cliente, ctx.Flags, ctx.Stdin) + if err != nil { + return nil, false, err + } + if ctx.Flags.Has("agregarEntregable") || ctx.Flags.Has("quitarEntregable") { + var lista []string + if rawList, ok := cuerpo["entregablesDefault"]; ok { + switch x := rawList.(type) { + case []string: + lista = append(lista, x...) + case []any: + for _, item := range x { + lista = append(lista, fmt.Sprint(item)) + } + } + } else { + for _, item := range asSlice(actual["entregablesDefault"]) { + lista = append(lista, fmt.Sprint(item)) + } + } + if quitar := ctx.Flags.List("quitarEntregable"); len(quitar) > 0 { + var faltantes []string + for _, q := range quitar { + if !slices.Contains(lista, q) { + faltantes = append(faltantes, q) + } + } + if len(faltantes) > 0 { + actualStr := strings.Join(lista, "; ") + if actualStr == "" { + actualStr = "(ninguno)" + } + return nil, false, errorUso( + "No encontre estos entregables: "+strings.Join(faltantes, "; "), + "Entregables actuales: "+actualStr, + ) + } + var nueva []string + for _, e := range lista { + if !slices.Contains(quitar, e) { + nueva = append(nueva, e) + } + } + lista = nueva + } + if agregar := ctx.Flags.List("agregarEntregable"); len(agregar) > 0 { + lista = append(lista, agregar...) + } + if lista == nil { + lista = []string{} + } + cuerpo["entregablesDefault"] = lista + } + if len(cuerpo) == 0 { + return nil, false, errorUso("No pasaste ningun campo para cambiar", "Ejemplo: cotizador servicios editar --precio 5000") + } + res, err := ctx.Cliente.api(http.MethodPatch, "/api/catalogo/"+mapStr(actual, "id"), apiOpts{Cuerpo: cuerpo, HasCuerpo: true}) + return res, true, err + }, + }, + { + Comando: "servicios archivar", + Descripcion: "Oculta un servicio al cotizar (activo=false). Reversible con `servicios activar`.", + Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del servicio o su nombre exacto"}}, + Endpoint: "PATCH /api/catalogo/{id}", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + ref, err := exigirPosicional(ctx.Pos, 0, "id", "servicios archivar") + if err != nil { + return nil, false, err + } + s, err := resolverServicio(ctx.Cliente, ref) + if err != nil { + return nil, false, err + } + res, err := ctx.Cliente.api(http.MethodPatch, "/api/catalogo/"+mapStr(s, "id"), apiOpts{ + Cuerpo: map[string]any{"activo": false}, + HasCuerpo: true, + }) + return res, true, err + }, + }, + { + Comando: "servicios activar", + Descripcion: "Vuelve a mostrar un servicio archivado.", + Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del servicio"}}, + Endpoint: "PATCH /api/catalogo/{id}", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + id, err := exigirPosicional(ctx.Pos, 0, "id", "servicios activar") + if err != nil { + return nil, false, err + } + res, err := ctx.Cliente.api(http.MethodPatch, "/api/catalogo/"+url.PathEscape(id), apiOpts{ + Cuerpo: map[string]any{"activo": true}, + HasCuerpo: true, + }) + return res, true, err + }, + }, + { + Comando: "servicios eliminar", + Descripcion: "Borra un servicio. Si alguna cotizacion lo usa, el servidor lo ARCHIVA en vez de borrarlo (respuesta archived=true).", + Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del servicio"}}, + Flags: []flagSpec{flagConfirmar}, + Ejemplos: []string{"cotizador servicios eliminar cmabc123... --confirmar"}, + Endpoint: "DELETE /api/catalogo/{id}", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + id, err := exigirPosicional(ctx.Pos, 0, "id", "servicios eliminar") + if err != nil { + return nil, false, err + } + if err := exigirConfirmacion(ctx.Flags, "Eliminar un servicio"); err != nil { + return nil, false, err + } + res, err := ctx.Cliente.api(http.MethodDelete, "/api/catalogo/"+url.PathEscape(id)) + return res, true, err + }, + }, + + // ----- categorias y paquetes ----- + { + Comando: "categorias listar", + Alias: []string{"categorias"}, + Descripcion: "Lista las categorias del catalogo.", + Endpoint: "GET /api/categorias", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + res, err := ctx.Cliente.api(http.MethodGet, "/api/categorias") + return res, true, err + }, + }, + { + Comando: "categorias crear", + Descripcion: "Crea una categoria.", + Flags: []flagSpec{ + {Flag: "nombre", Tipo: "texto", Descripcion: "Nombre (unico)"}, + {Flag: "color", Tipo: "texto", Descripcion: "Color hex, ej. #2563eb"}, + {Flag: "descripcion", Tipo: "texto", Descripcion: "Descripcion"}, + }, + Ejemplos: []string{`cotizador categorias crear --nombre "Automatizacion" --color "#0ea5e9"`}, + Endpoint: "POST /api/categorias", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + if ctx.Flags.Str("nombre") == "" { + return nil, false, errorUso("Falta --nombre") + } + cuerpo := map[string]any{"nombre": ctx.Flags.Str("nombre")} + if ctx.Flags.Has("color") && ctx.Flags.Str("color") != "" { + if !colorHexRe.MatchString(ctx.Flags.Str("color")) { + return nil, false, errorUso("--color debe ser hex de 6 digitos, ej. #2563eb") + } + cuerpo["color"] = ctx.Flags.Str("color") + } + if ctx.Flags.Has("descripcion") { + cuerpo["descripcion"] = ctx.Flags.Str("descripcion") + } + res, err := ctx.Cliente.api(http.MethodPost, "/api/categorias", apiOpts{Cuerpo: cuerpo, HasCuerpo: true}) + return res, true, err + }, + }, + { + Comando: "paquetes listar", + Alias: []string{"paquetes"}, + Descripcion: "Lista los paquetes activos con sus fases y servicios (resumido; usa `paquetes ver` para el detalle).", + Endpoint: "GET /api/paquetes", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + raw, err := ctx.Cliente.api(http.MethodGet, "/api/paquetes") + if err != nil { + return nil, false, err + } + paquetes := asSlice(raw) + out := make([]map[string]any, 0, len(paquetes)) + for _, item := range paquetes { + p := asMap(item) + rawFases := asSlice(p["fases"]) + fases := make([]map[string]any, 0, len(rawFases)) + for _, fItem := range rawFases { + f := asMap(fItem) + rawServs := asSlice(f["servicios"]) + servs := make([]map[string]any, 0, len(rawServs)) + for _, spItem := range rawServs { + sp := asMap(spItem) + sv := asMap(sp["servicio"]) + servs = append(servs, map[string]any{ + "id": sv["id"], + "nombre": sv["nombre"], + "precioBase": sv["precioBase"], + "tipoPago": sv["tipoPago"], + }) + } + fases = append(fases, map[string]any{ + "nombre": f["nombre"], + "servicios": servs, + }) + } + out = append(out, map[string]any{ + "id": p["id"], + "nombre": p["nombre"], + "descripcion": p["descripcion"], + "fases": fases, + }) + } + return out, true, nil + }, + }, + { + Comando: "paquetes ver", + Descripcion: "Detalle completo de un paquete.", + Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del paquete"}}, + Endpoint: "GET /api/paquetes/{id}", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + id, err := exigirPosicional(ctx.Pos, 0, "id", "paquetes ver") + if err != nil { + return nil, false, err + } + res, err := ctx.Cliente.api(http.MethodGet, "/api/paquetes/"+url.PathEscape(id)) + return res, true, err + }, + }, + + // ----- clientes ----- + { + Comando: "clientes listar", + Alias: []string{"clientes"}, + Descripcion: "Lista clientes.", + Flags: []flagSpec{{Flag: "q", Tipo: "texto", Descripcion: "Busca en nombre, empresa, correo y RFC"}}, + Endpoint: "GET /api/clientes", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + ruta := "/api/clientes" + if q := ctx.Flags.Str("q"); q != "" { + ruta += "?q=" + url.QueryEscape(q) + } + res, err := ctx.Cliente.api(http.MethodGet, ruta) + return res, true, err + }, + }, + { + Comando: "clientes crear", + Descripcion: "Da de alta un cliente (nombre + empresa deben ser unicos).", + Flags: []flagSpec{ + {Flag: "nombre", Tipo: "texto", Descripcion: "Nombre del contacto (obligatorio)"}, + {Flag: "empresa", Tipo: "texto", Descripcion: "Empresa"}, + {Flag: "puesto", Tipo: "texto", Descripcion: "Puesto"}, + {Flag: "email", Tipo: "texto", Descripcion: "Correo"}, + {Flag: "telefono", Tipo: "texto", Descripcion: "Telefono"}, + {Flag: "rfc", Tipo: "texto", Descripcion: "RFC"}, + }, + Ejemplos: []string{`cotizador clientes crear --nombre "Ana Ruiz" --empresa "Panaderia Sol" --email ana@sol.mx`}, + Endpoint: "POST /api/clientes", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + if ctx.Flags.Str("nombre") == "" { + return nil, false, errorUso("Falta --nombre") + } + cuerpo := map[string]any{"nombre": ctx.Flags.Str("nombre")} + for _, k := range []string{"empresa", "puesto", "email", "telefono", "rfc"} { + if ctx.Flags.Has(k) { + cuerpo[k] = ctx.Flags.Str(k) + } + } + res, err := ctx.Cliente.api(http.MethodPost, "/api/clientes", apiOpts{Cuerpo: cuerpo, HasCuerpo: true}) + return res, true, err + }, + }, + { + Comando: "clientes editar", + Descripcion: "Edita un cliente (solo los campos que pases).", + Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id del cliente"}}, + Flags: []flagSpec{ + {Flag: "nombre", Tipo: "texto", Descripcion: "Nombre"}, + {Flag: "empresa", Tipo: "texto", Descripcion: `Empresa ("" para quitarla)`}, + {Flag: "puesto", Tipo: "texto", Descripcion: "Puesto"}, + {Flag: "email", Tipo: "texto", Descripcion: "Correo"}, + {Flag: "telefono", Tipo: "texto", Descripcion: "Telefono"}, + {Flag: "rfc", Tipo: "texto", Descripcion: "RFC"}, + }, + Endpoint: "PATCH /api/clientes/{id}", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + id, err := exigirPosicional(ctx.Pos, 0, "id", "clientes editar") + if err != nil { + return nil, false, err + } + cuerpo := map[string]any{} + for _, k := range []string{"nombre", "empresa", "puesto", "email", "telefono", "rfc"} { + if ctx.Flags.Has(k) { + cuerpo[k] = ctx.Flags.Str(k) + } + } + if len(cuerpo) == 0 { + return nil, false, errorUso("No pasaste ningun campo para cambiar") + } + res, err := ctx.Cliente.api(http.MethodPatch, "/api/clientes/"+url.PathEscape(id), apiOpts{Cuerpo: cuerpo, HasCuerpo: true}) + return res, true, err + }, + }, + + // ----- cotizaciones ----- + { + Comando: "cotizaciones listar", + Alias: []string{"cotizaciones", "cotizaciones ls"}, + Descripcion: "Lista cotizaciones resumidas, de la mas reciente a la mas antigua.", + Flags: []flagSpec{ + {Flag: "estado", Tipo: "texto", Valores: toAnySlice(estadosCotizacion), Descripcion: "Filtra por estado"}, + {Flag: "q", Tipo: "texto", Descripcion: "Busca en numero, proyecto, cliente y empresa"}, + {Flag: "cliente", Tipo: "texto", Descripcion: "Id del cliente"}, + {Flag: "limit", Tipo: "entero", Descripcion: "Maximo de resultados (default 50)"}, + {Flag: "completo", Tipo: "booleano", Descripcion: "Devuelve el registro completo (con partidas) en vez del resumen"}, + }, + Ejemplos: []string{"cotizador cotizaciones listar --estado enviada --formato tabla"}, + Endpoint: "GET /api/cotizaciones", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + p := url.Values{} + if ctx.Flags.Has("estado") { + e, err := unoDe(ctx.Flags.Str("estado"), estadosCotizacion, "estado") + if err != nil { + return nil, false, err + } + p.Set("estado", e) + } + if q := ctx.Flags.Str("q"); q != "" { + p.Set("q", q) + } + if cl := ctx.Flags.Str("cliente"); cl != "" { + p.Set("clienteId", cl) + } + limit := 50 + if ctx.Flags.Has("limit") { + var err error + limit, err = parseEntero(ctx.Flags.Str("limit"), "limit") + if err != nil { + return nil, false, err + } + } + p.Set("limit", strconv.Itoa(limit)) + raw, err := ctx.Cliente.api(http.MethodGet, "/api/cotizaciones?"+p.Encode()) + if err != nil { + return nil, false, err + } + if ctx.Flags.Bool("completo") { + return raw, true, nil + } + lista := asSlice(raw) + out := make([]map[string]any, 0, len(lista)) + for _, item := range lista { + out = append(out, resumenCotizacion(asMap(item))) + } + return out, true, nil + }, + }, + { + Comando: "cotizaciones ver", + Descripcion: "Detalle completo de una cotizacion (por id o por numero, ej. UJ2605AG001).", + Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id o numero de la cotizacion"}}, + Endpoint: "GET /api/cotizaciones/{id}", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + ref, err := exigirPosicional(ctx.Pos, 0, "id", "cotizaciones ver") + if err != nil { + return nil, false, err + } + id, err := resolverCotizacion(ctx.Cliente, ref) + if err != nil { + return nil, false, err + } + res, err := ctx.Cliente.api(http.MethodGet, "/api/cotizaciones/"+id) + return res, true, err + }, + }, + { + Comando: "cotizaciones crear", + Alias: []string{"cotizaciones nueva"}, + Descripcion: "Crea una cotizacion en borrador. El servidor asigna numero, asesor (tu usuario), fecha y vigencia (15 dias habiles). Si el cliente (nombre+empresa) no existe, se crea.", + Flags: []flagSpec{ + {Flag: "cliente", Tipo: "texto", Descripcion: "Nombre del cliente (obligatorio)"}, + {Flag: "empresa", Tipo: "texto", Descripcion: "Empresa del cliente"}, + {Flag: "email", Tipo: "texto", Descripcion: "Correo del cliente"}, + {Flag: "telefono", Tipo: "texto", Descripcion: "Telefono del cliente"}, + {Flag: "servicio", Tipo: "texto", Repetible: true, Descripcion: `Servicio del catalogo: "id", "nombre exacto" o "id=precio" para ajustar el precio. Repetible`}, + {Flag: "partida-horas", Tipo: "texto", Repetible: true, Descripcion: `Partida por horas: "Concepto|horas|tarifa" (tarifa opcional). Repetible`}, + {Flag: "proyecto", Tipo: "texto", Descripcion: `Nombre del proyecto (default "MKT Digital")`}, + {Flag: "moneda", Tipo: "texto", Valores: toAnySlice(monedasValidas), Descripcion: "MXN (default) o USD"}, + {Flag: "esquema-pago", Tipo: "texto", Valores: toAnySlice(esquemasPago), Descripcion: `Default "Pago Unico/Mensual"`}, + {Flag: "bucefalo", Tipo: "texto", Valores: toAnySlice(planesBucefaloCRM), Descripcion: "Agrega un plan de Bucefalo CRM (precio de lista)"}, + {Flag: "observaciones", Tipo: "texto", Descripcion: "Observaciones visibles para el cliente"}, + {Flag: "notas-internas", Tipo: "texto", Descripcion: "Observaciones internas (no salen en el PDF)"}, + {Flag: "sin-iva", Tipo: "booleano", Descripcion: "No sumar IVA"}, + {Flag: "bonos", Tipo: "booleano", Descripcion: "Incluir bonos"}, + {Flag: "financiamiento", Tipo: "booleano", Descripcion: "Incluir financiamiento"}, + {Flag: "fecha", Tipo: "fecha", Descripcion: "YYYY-MM-DD (default hoy)"}, + {Flag: "asesor", Tipo: "texto", Descripcion: "Id del asesor (default: el usuario de la sesion)"}, + {Flag: "datos", Tipo: "json", Descripcion: "Cuerpo JSON completo de POST /api/cotizaciones (ver `cotizador esquema`). Las flags tienen prioridad"}, + }, + Ejemplos: []string{ + `cotizador cotizaciones crear --cliente "Ana Ruiz" --empresa "Panaderia Sol" --servicio "Landing Page" --servicio cmabc123...=4500 --bucefalo estandar`, + `cotizador cotizaciones crear --cliente "Ana Ruiz" --partida-horas "Soporte tecnico|10|700"`, + }, + Endpoint: "POST /api/cotizaciones", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + base, err := leerDatos(ctx.Flags.Str("datos"), ctx.Flags.Has("datos"), ctx.Stdin) + if err != nil { + return nil, false, err + } + partidas := make([]any, 0) + if arr, ok := base["servicios"].([]any); ok { + partidas = append(partidas, arr...) + } + for _, ref := range ctx.Flags.List("servicio") { + nombreOId := ref + var precio *float64 + if m := servicioRefRe.FindStringSubmatch(ref); len(m) == 3 { + nombreOId = m[1] + p, err := parseNumero(m[2], "servicio") + if err != nil { + return nil, false, err + } + precio = &p + } + s, err := resolverServicio(ctx.Cliente, nombreOId) + if err != nil { + return nil, false, err + } + partidas = append(partidas, partidaDesdeCatalogo(s, precio)) + } + for _, txt := range ctx.Flags.List("partidaHoras") { + p, err := partidaPorHoras(txt) + if err != nil { + return nil, false, err + } + partidas = append(partidas, p) + } + + clienteBase := asMap(base["cliente"]) + datosCliente := make(map[string]any) + for k, v := range clienteBase { + datosCliente[k] = v + } + if ctx.Flags.Has("cliente") { + datosCliente["nombre"] = ctx.Flags.Str("cliente") + } + if ctx.Flags.Has("empresa") { + datosCliente["empresa"] = ctx.Flags.Str("empresa") + } + if ctx.Flags.Has("email") { + datosCliente["email"] = ctx.Flags.Str("email") + } + if ctx.Flags.Has("telefono") { + datosCliente["telefono"] = ctx.Flags.Str("telefono") + } + if mapStr(datosCliente, "nombre") == "" { + return nil, false, errorUso("Falta --cliente", `Ejemplo: cotizador cotizaciones crear --cliente "Ana Ruiz" --servicio "Landing Page"`) + } + if len(partidas) == 0 && !ctx.Flags.Has("bucefalo") && base["planBucefalo"] == nil { + return nil, false, errorUso( + "La cotizacion no tiene partidas", + "Agrega --servicio (busca con `cotizador servicios listar`), --partida-horas o --bucefalo", + ) + } + + cuerpo := make(map[string]any, len(base)+12) + for k, v := range base { + cuerpo[k] = v + } + if ctx.Flags.Has("proyecto") { + cuerpo["proyecto"] = ctx.Flags.Str("proyecto") + } + if ctx.Flags.Has("moneda") { + m, err := unoDe(ctx.Flags.Str("moneda"), monedasValidas, "moneda") + if err != nil { + return nil, false, err + } + cuerpo["moneda"] = m + } + if ctx.Flags.Has("esquemaPago") { + ep, err := unoDe(ctx.Flags.Str("esquemaPago"), esquemasPago, "esquema-pago") + if err != nil { + return nil, false, err + } + cuerpo["esquemaPago"] = ep + } + if ctx.Flags.Has("observaciones") { + cuerpo["observaciones"] = ctx.Flags.Str("observaciones") + } + if ctx.Flags.Has("notasInternas") { + cuerpo["observacionesInternas"] = ctx.Flags.Str("notasInternas") + } + if ctx.Flags.Bool("sinIva") { + cuerpo["incluirIva"] = false + } + if ctx.Flags.Has("bonos") { + cuerpo["incluirBonos"] = ctx.Flags.Bool("bonos") + } + if ctx.Flags.Has("financiamiento") { + cuerpo["incluirFinanciamiento"] = ctx.Flags.Bool("financiamiento") + } + if ctx.Flags.Has("fecha") { + f, err := validarFechaISO(ctx.Flags.Str("fecha"), "fecha") + if err != nil { + return nil, false, err + } + cuerpo["fecha"] = f + } + if ctx.Flags.Has("asesor") { + cuerpo["asesorId"] = ctx.Flags.Str("asesor") + } + if ctx.Flags.Has("bucefalo") { + niv, err := unoDe(ctx.Flags.Str("bucefalo"), planesBucefaloCRM, "bucefalo") + if err != nil { + return nil, false, err + } + cuerpo["planBucefalo"] = map[string]any{"nivel": niv} + } + cuerpo["cliente"] = datosCliente + cuerpo["servicios"] = partidas + + raw, err := ctx.Cliente.api(http.MethodPost, "/api/cotizaciones", apiOpts{Cuerpo: cuerpo, HasCuerpo: true}) + if err != nil { + return nil, false, err + } + creada := asMap(raw) + return map[string]any{ + "ok": true, + "id": creada["id"], + "numero": creada["numero"], + "estado": creada["estado"], + "url": fmt.Sprintf("%s/cotizaciones/%s", ctx.Cliente.base, mapStr(creada, "id")), + }, true, nil + }, + }, + { + Comando: "cotizaciones estado", + Descripcion: "Cambia el estado de una cotizacion.", + Argumentos: []argSpec{ + {Nombre: "id", Descripcion: "Id o numero de la cotizacion"}, + {Nombre: "estado", Descripcion: strings.Join(estadosCotizacion, " | ")}, + }, + Ejemplos: []string{"cotizador cotizaciones estado UJ2605AG001 enviada"}, + Endpoint: "PUT /api/cotizaciones/{id}", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + ref, err := exigirPosicional(ctx.Pos, 0, "id", "cotizaciones estado") + if err != nil { + return nil, false, err + } + rawEstado, err := exigirPosicional(ctx.Pos, 1, "estado", "cotizaciones estado ") + if err != nil { + return nil, false, err + } + estado, err := unoDe(rawEstado, estadosCotizacion, "estado") + if err != nil { + return nil, false, err + } + id, err := resolverCotizacion(ctx.Cliente, ref) + if err != nil { + return nil, false, err + } + raw, err := ctx.Cliente.api(http.MethodPut, "/api/cotizaciones/"+id, apiOpts{ + Cuerpo: map[string]any{"estado": estado}, + HasCuerpo: true, + }) + if err != nil { + return nil, false, err + } + r := asMap(raw) + return map[string]any{"ok": true, "id": r["id"], "numero": r["numero"], "estado": r["estado"]}, true, nil + }, + }, + { + Comando: "cotizaciones pdf", + Descripcion: "Descarga el PDF de una cotizacion.", + Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id o numero de la cotizacion"}}, + Flags: []flagSpec{{Flag: "salida", Tipo: "texto", Descripcion: "Ruta del archivo (default: nombre que da el servidor, en la carpeta actual)"}}, + Endpoint: "GET /api/export/pdf/{id}", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + ref, err := exigirPosicional(ctx.Pos, 0, "id", "cotizaciones pdf") + if err != nil { + return nil, false, err + } + id, err := resolverCotizacion(ctx.Cliente, ref) + if err != nil { + return nil, false, err + } + res, err := descargar(ctx.Cliente, "/api/export/pdf/"+id, ctx.Flags.Str("salida"), fmt.Sprintf("cotizacion-%s.pdf", id)) + return res, true, err + }, + }, + { + Comando: "cotizaciones excel", + Descripcion: "Descarga el Excel de una cotizacion.", + Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id o numero de la cotizacion"}}, + Flags: []flagSpec{{Flag: "salida", Tipo: "texto", Descripcion: "Ruta del archivo"}}, + Endpoint: "GET /api/export/excel/{id}", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + ref, err := exigirPosicional(ctx.Pos, 0, "id", "cotizaciones excel") + if err != nil { + return nil, false, err + } + id, err := resolverCotizacion(ctx.Cliente, ref) + if err != nil { + return nil, false, err + } + res, err := descargar(ctx.Cliente, "/api/export/excel/"+id, ctx.Flags.Str("salida"), fmt.Sprintf("cotizacion-%s.xlsx", id)) + return res, true, err + }, + }, + { + Comando: "cotizaciones eliminar", + Descripcion: "Borra una cotizacion y sus partidas.", + Argumentos: []argSpec{{Nombre: "id", Descripcion: "Id o numero de la cotizacion"}}, + Flags: []flagSpec{flagConfirmar}, + Endpoint: "DELETE /api/cotizaciones/{id}", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + ref, err := exigirPosicional(ctx.Pos, 0, "id", "cotizaciones eliminar") + if err != nil { + return nil, false, err + } + if err := exigirConfirmacion(ctx.Flags, "Eliminar una cotizacion"); err != nil { + return nil, false, err + } + id, err := resolverCotizacion(ctx.Cliente, ref) + if err != nil { + return nil, false, err + } + res, err := ctx.Cliente.api(http.MethodDelete, "/api/cotizaciones/"+id) + return res, true, err + }, + }, + + // ----- horas ----- + { + Comando: "horas listar", + Descripcion: "Registros de horas de una cotizacion por tiempo.", + Argumentos: []argSpec{{Nombre: "cotizacion", Descripcion: "Id o numero de la cotizacion"}}, + Flags: []flagSpec{ + {Flag: "desde", Tipo: "fecha", Descripcion: "YYYY-MM-DD"}, + {Flag: "hasta", Tipo: "fecha", Descripcion: "YYYY-MM-DD"}, + }, + Endpoint: "GET /api/cotizaciones/{id}/horas", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + ref, err := exigirPosicional(ctx.Pos, 0, "cotizacion", "horas listar") + if err != nil { + return nil, false, err + } + id, err := resolverCotizacion(ctx.Cliente, ref) + if err != nil { + return nil, false, err + } + p := url.Values{} + if ctx.Flags.Has("desde") { + d, err := validarFechaISO(ctx.Flags.Str("desde"), "desde") + if err != nil { + return nil, false, err + } + p.Set("from", d) + } + if ctx.Flags.Has("hasta") { + h, err := validarFechaISO(ctx.Flags.Str("hasta"), "hasta") + if err != nil { + return nil, false, err + } + p.Set("to", h) + } + qs := p.Encode() + ruta := "/api/cotizaciones/" + id + "/horas" + if qs != "" { + ruta += "?" + qs + } + res, err := ctx.Cliente.api(http.MethodGet, ruta) + return res, true, err + }, + }, + { + Comando: "horas registrar", + Descripcion: "Registra horas trabajadas (solo en cotizaciones con partidas por horas, retainer o demanda).", + Argumentos: []argSpec{{Nombre: "cotizacion", Descripcion: "Id o numero de la cotizacion"}}, + Flags: []flagSpec{ + {Flag: "fecha", Tipo: "fecha", Descripcion: "YYYY-MM-DD (obligatoria)"}, + {Flag: "inicio", Tipo: "texto", Descripcion: "HH:MM (obligatoria)"}, + {Flag: "fin", Tipo: "texto", Descripcion: "HH:MM (obligatoria)"}, + {Flag: "descripcion", Tipo: "texto", Descripcion: "Que se hizo (obligatoria)"}, + {Flag: "tarifa", Tipo: "numero", Descripcion: "Tarifa por hora (default: la de la cotizacion)"}, + }, + Ejemplos: []string{`cotizador horas registrar UJ2605AG001 --fecha 2026-11-20 --inicio 09:00 --fin 11:30 --descripcion "Ajustes de campanas"`}, + Endpoint: "POST /api/cotizaciones/{id}/horas", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + ref, err := exigirPosicional(ctx.Pos, 0, "cotizacion", "horas registrar") + if err != nil { + return nil, false, err + } + id, err := resolverCotizacion(ctx.Cliente, ref) + if err != nil { + return nil, false, err + } + var faltan []string + for _, k := range []string{"fecha", "inicio", "fin", "descripcion"} { + if ctx.Flags.Str(k) == "" { + faltan = append(faltan, "--"+k) + } + } + if len(faltan) > 0 { + return nil, false, errorUso("Faltan: " + strings.Join(faltan, ", ")) + } + fecha, err := validarFechaISO(ctx.Flags.Str("fecha"), "fecha") + if err != nil { + return nil, false, err + } + cuerpo := map[string]any{ + "fecha": fecha, + "horaInicio": ctx.Flags.Str("inicio"), + "horaFin": ctx.Flags.Str("fin"), + "descripcion": ctx.Flags.Str("descripcion"), + } + if ctx.Flags.Has("tarifa") { + t, err := parseNumero(ctx.Flags.Str("tarifa"), "tarifa") + if err != nil { + return nil, false, err + } + cuerpo["tarifaHora"] = t + } + res, err := ctx.Cliente.api(http.MethodPost, "/api/cotizaciones/"+id+"/horas", apiOpts{Cuerpo: cuerpo, HasCuerpo: true}) + return res, true, err + }, + }, + + // ----- utilidades ----- + { + Comando: "api", + Descripcion: "Llamada directa a cualquier endpoint de la API (escape para lo que no cubren los comandos). La ruta empieza con /api/.", + Argumentos: []argSpec{ + {Nombre: "metodo", Descripcion: "GET | POST | PUT | PATCH | DELETE"}, + {Nombre: "ruta", Descripcion: "Ej. /api/configuracion"}, + }, + Flags: []flagSpec{{Flag: "datos", Tipo: "json", Descripcion: "Cuerpo JSON (en linea, @archivo.json o -)"}}, + Ejemplos: []string{"cotizador api GET /api/configuracion", `cotizador api POST /api/cobros/recordatorios --datos '{}'`}, + Endpoint: "*", + HasEndpoint: true, + Run: func(ctx *cmdContext) (any, bool, error) { + rawMetodo, err := exigirPosicional(ctx.Pos, 0, "metodo", "api") + if err != nil { + return nil, false, err + } + metodo, err := unoDe(strings.ToUpper(rawMetodo), []string{"GET", "POST", "PUT", "PATCH", "DELETE"}, "metodo") + if err != nil { + return nil, false, err + } + rawRuta, err := exigirPosicional(ctx.Pos, 1, "ruta", "api ") + if err != nil { + return nil, false, err + } + ruta := strings.ReplaceAll(rawRuta, `\`, "/") + if corte := strings.Index(ruta, "/api/"); corte > 0 { + ruta = ruta[corte:] + } + if strings.HasPrefix(ruta, "api/") { + ruta = "/" + ruta + } + if !strings.HasPrefix(ruta, "/api/") { + return nil, false, errorUso("La ruta debe empezar con /api/ (ej. /api/configuracion)") + } + var opts apiOpts + if ctx.Flags.Has("datos") { + cuerpo, err := leerDatos(ctx.Flags.Str("datos"), true, ctx.Stdin) + if err != nil { + return nil, false, err + } + opts.Cuerpo = cuerpo + opts.HasCuerpo = true + } + res, err := ctx.Cliente.api(metodo, ruta, opts) + return res, true, err + }, + }, + { + Comando: "esquema", + Alias: []string{"schema"}, + Descripcion: "Describe en JSON todos los comandos, flags, tipos, ejemplos, codigos de salida y el dominio. Pensado para LLMs.", + SinServidor: true, + Run: func(ctx *cmdContext) (any, bool, error) { + return esquema(allCommands()), true, nil + }, + }, + { + Comando: "ayuda", + Alias: []string{"help"}, + Descripcion: "Ayuda legible. `cotizador ayuda ` para uno en particular.", + SinServidor: true, + Run: func(ctx *cmdContext) (any, bool, error) { + cmds := allCommands() + if len(ctx.Pos) > 0 { + cmd, _ := buscarComando(cmds, ctx.Pos) + if cmd == nil { + return nil, false, fallarComando(cmds, ctx.Pos) + } + _, _ = io.WriteString(ctx.Stdout, ayudaComando(cmd)) + return nil, false, nil + } + _, _ = io.WriteString(ctx.Stdout, ayudaGeneral(cmds)) + return nil, false, nil + }, + }, + { + Comando: "version", + SinServidor: true, + Descripcion: "Version del CLI.", + Run: func(ctx *cmdContext) (any, bool, error) { + return map[string]any{"version": Version}, true, nil + }, + }, + } +} + +// --------------------------------------------------------------------------- +// Command lookup, help, and self-describing schema +// --------------------------------------------------------------------------- + +func buscarComando(cmds []commandSpec, palabras []string) (*commandSpec, int) { + maxN := len(palabras) + if maxN > 3 { + maxN = 3 + } + for n := maxN; n >= 1; n-- { + clave := strings.ToLower(strings.Join(palabras[:n], " ")) + for i := range cmds { + if cmds[i].Comando == clave || slices.Contains(cmds[i].Alias, clave) { + return &cmds[i], n + } + } + } + return nil, 0 +} + +func fallarComando(cmds []commandSpec, palabras []string) error { + grupo := "" + if len(palabras) > 0 { + grupo = strings.ToLower(palabras[0]) + } + var delGrupo []string + for _, c := range cmds { + first := strings.SplitN(c.Comando, " ", 2)[0] + if first == grupo { + delGrupo = append(delGrupo, c.Comando) + } + } + sug := "Ejecuta `cotizador ayuda` o `cotizador esquema` para ver los comandos" + if len(delGrupo) > 0 { + sug = fmt.Sprintf(`Comandos de "%s": %s`, grupo, strings.Join(delGrupo, ", ")) + } + return errorUso("Comando desconocido: "+strings.Join(palabras, " "), sug) +} + +func describirFlag(f flagSpec) map[string]any { + m := map[string]any{ + "flag": "--" + f.Flag, + "tipo": f.Tipo, + "descripcion": f.Descripcion, + } + if len(f.Valores) > 0 { + m["valores"] = f.Valores + } + if f.Repetible { + m["repetible"] = true + } + return m +} + +func usoDe(c *commandSpec) string { + var args []string + for _, a := range c.Argumentos { + args = append(args, "<"+a.Nombre+">") + } + s := "cotizador " + c.Comando + if len(args) > 0 { + s += " " + strings.Join(args, " ") + } + if len(c.Flags) > 0 { + s += " [flags]" + } + return s +} + +func esquema(cmds []commandSpec) map[string]any { + glob := make([]map[string]any, len(flagsGlobales)) + for i, f := range flagsGlobales { + glob[i] = describirFlag(f) + } + cmdList := make([]map[string]any, len(cmds)) + for i := range cmds { + c := &cmds[i] + fl := make([]map[string]any, len(c.Flags)) + for j, f := range c.Flags { + fl[j] = describirFlag(f) + } + args := c.Argumentos + if args == nil { + args = []argSpec{} + } + ejemplos := c.Ejemplos + if ejemplos == nil { + ejemplos = []string{} + } + var ep any + if c.HasEndpoint { + ep = c.Endpoint + } + entry := map[string]any{ + "comando": c.Comando, + "descripcion": c.Descripcion, + "uso": usoDe(c), + "argumentos": args, + "flags": fl, + "ejemplos": ejemplos, + "endpoint": ep, + } + if len(c.Alias) > 0 { + entry["alias"] = c.Alias + } + cmdList[i] = entry + } + + return map[string]any{ + "nombre": "cotizador", + "version": Version, + "descripcion": "CLI del Cotizador — Uriel Jareth Consulting. Gestiona el catalogo de servicios, clientes, cotizaciones y horas a traves de la API REST de la plataforma.", + "convenciones": map[string]string{ + "salida": "JSON en stdout (usa --campos para recortar, --formato tabla para humanos)", + "errores": "JSON en stderr: { ok:false, error, codigo, status?, detalles?, sugerencia? }", + "entrada": "Flags --kebab-case; --datos acepta JSON en linea, @archivo.json o - (stdin). Las flags tienen prioridad sobre --datos", + "ids": "Donde se pide de servicio tambien vale su nombre exacto; para cotizaciones, el numero (UJ...)", + "escritura": "Usa --dry-run para ver la peticion sin enviarla. Borrar exige --confirmar", + "montos": "Precios en MXN sin IVA (IVA 16% se calcula al cotizar)", + }, + "configuracion": map[string]string{ + "COTIZADOR_URL": "URL base (default http://localhost:3000; produccion: https://cotizador.urieljareth.org)", + "COTIZADOR_EMAIL": "Correo para login automatico cuando no hay sesion o vencio", + "COTIZADOR_PASSWORD": "Contrasena para login automatico", + "COTIZADOR_TOKEN": "Token de sesion explicito (omite el archivo de sesiones)", + "COTIZADOR_HOME": "Carpeta de la sesion guardada (default ~/.cotizador-uj)", + }, + "codigosSalida": descripcionCodigos, + "dominio": dominioInfo(), + "formatos": map[string]any{ + "servicioCatalogo": map[string]string{ + "nombre": "texto (obligatorio)", + "fase": "0-3 (obligatorio)", + "tipoPago": "unico | mensual (obligatorio)", + "precioBase": "numero >= 0 (obligatorio)", + "descripcion": "texto | null", + "tiempoEntrega": `texto (default "4 - 10 dias")`, + "entregablesDefault": "texto[]", + "categoriaId": "id | null (en el CLI tambien `categoria`: nombre)", + "variante": "texto | null", + "nivel": strings.Join(nivelesServicio, " | ") + " | null", + "orden": "entero (default: al final de su fase)", + "activo": "booleano (default true)", + }, + "partidaCotizacion": map[string]string{ + "catalogoId": `id del servicio, o "custom-" si esPersonalizado`, + "nombre": "texto", + "fase": "0-3", + "tipoPago": "unico | mensual", + "precio": "numero: total autoritativo de la partida", + "tiempoEntrega": "texto", + "entregables": "texto[]", + "esPersonalizado": "booleano (partidas fuera del catalogo)", + "modeloCobro": "fijo | horas | retainer | demanda", + "horas": "numero (modelo horas)", + "tarifaHora": "numero", + "montoMinimo": "numero (retainer)", + "horasIncluidas": "numero (retainer)", + "opcion": `"1" | "2" | "ambas" (solo cotizaciones doble propuesta)`, + }, + }, + "flagsGlobales": glob, + "comandos": cmdList, + } +} + +func firstSentence(s string) string { + for i := 0; i < len(s)-2; i++ { + if s[i] == '.' && s[i+1] == ' ' { + next := s[i+2] + if (next >= 'A' && next <= 'Z') || next == '(' { + return s[:i] + } + } + } + return s +} + +func ayudaGeneral(cmds []commandSpec) string { + var groupOrder []string + grupos := make(map[string][]commandSpec) + ancho := 0 + for _, c := range cmds { + if len(c.Comando) > ancho { + ancho = len(c.Comando) + } + g := "general" + if idx := strings.IndexByte(c.Comando, ' '); idx >= 0 { + g = c.Comando[:idx] + } + if _, ok := grupos[g]; !ok { + groupOrder = append(groupOrder, g) + } + grupos[g] = append(grupos[g], c) + } + ancho += 2 + + var b strings.Builder + fmt.Fprintf(&b, "cotizador %s — CLI del Cotizador — Uriel Jareth Consulting\n\nUso: cotizador [argumentos] [flags]\n", Version) + for _, g := range groupOrder { + fmt.Fprintf(&b, "\n%s\n", strings.ToUpper(g)) + for _, c := range grupos[g] { + pad := strings.Repeat(" ", ancho-len(c.Comando)) + fmt.Fprintf(&b, " %s%s%s\n", c.Comando, pad, firstSentence(c.Descripcion)) + } + } + b.WriteString("\nFLAGS GLOBALES\n") + for _, f := range flagsGlobales { + padLen := ancho - 2 - len(f.Flag) + if padLen < 2 { + padLen = 2 + } + fmt.Fprintf(&b, " --%s%s%s\n", f.Flag, strings.Repeat(" ", padLen), f.Descripcion) + } + b.WriteString("\nPrimeros pasos:\n" + + " cotizador login --email --password-stdin\n" + + " cotizador servicios listar --formato tabla\n" + + " cotizador esquema (descripcion completa en JSON, para LLMs)\n" + + "\nMas: cotizador ayuda · docs/CLI.md\n") + return b.String() +} + +func ayudaComando(c *commandSpec) string { + var b strings.Builder + fmt.Fprintf(&b, "%s\n\n%s\n", usoDe(c), c.Descripcion) + if c.HasEndpoint && c.Endpoint != "" { + fmt.Fprintf(&b, "\nEndpoint: %s\n", c.Endpoint) + } + if len(c.Argumentos) > 0 { + b.WriteString("\nArgumentos:\n") + for _, a := range c.Argumentos { + fmt.Fprintf(&b, " <%s> %s\n", a.Nombre, a.Descripcion) + } + } + if len(c.Flags) > 0 { + b.WriteString("\nFlags:\n") + ancho := 0 + for _, f := range c.Flags { + if len(f.Flag) > ancho { + ancho = len(f.Flag) + } + } + ancho += 4 + for _, f := range c.Flags { + var extras []string + if len(f.Valores) > 0 { + vs := make([]string, len(f.Valores)) + for i, v := range f.Valores { + vs[i] = fmt.Sprint(v) + } + extras = append(extras, "valores: "+strings.Join(vs, ", ")) + } + if f.Repetible { + extras = append(extras, "repetible") + } + extra := "" + if len(extras) > 0 { + extra = " (" + strings.Join(extras, "; ") + ")" + } + fmt.Fprintf(&b, " --%s%s%s%s\n", f.Flag, strings.Repeat(" ", ancho-len(f.Flag)), f.Descripcion, extra) + } + } + if len(c.Ejemplos) > 0 { + b.WriteString("\nEjemplos:\n") + for _, e := range c.Ejemplos { + fmt.Fprintf(&b, " %s\n", e) + } + } + if len(c.Alias) > 0 { + fmt.Fprintf(&b, "\nAlias: %s\n", strings.Join(c.Alias, ", ")) + } + return b.String() +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..8dab129 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,145 @@ +package config + +import ( + "fmt" + "os" + "strconv" + "strings" + + "github.com/joho/godotenv" +) + +type Config struct { + Port string + Env string + + // PostgreSQL (individual params matching docker-compose & existing .env) + DBHost string + DBPort int + DBUser string + DBPassword string + DBName string + + // Auth + JWTSecret string + + // Public URL (used in emails & push links; runtime env) + AppURL string + + // Seed + RunSeed bool + SeedAdminEmail string + SeedAdminPassword string + SeedAdminName string + SeedAsesorEmail string + SeedAsesorPass string + SeedAsesorName string + + // MiniMax AI (Anthropic-compatible endpoint) + MinimaxAPIKey string + MinimaxBaseURL string + MinimaxModel string + + // Web Push (VAPID) + VAPIDPublicKey string + VAPIDPrivateKey string + VAPIDSubject string + + // SMTP + SMTPHost string + SMTPPort int + SMTPUser string + SMTPPass string + SMTPFrom string + SMTPFromName string + + // Cobros & Uploads + CobrosRecordatorioDias int + UploadDir string + + // Notifications & Webhooks + AdminNotifyEmail string + WebhookN8NURL string + WebhookN8NSecret string + WebhookWhatsAppSendURL string +} + +func Load() (*Config, error) { + _ = godotenv.Load() + + dbName := firstNonEmpty(os.Getenv("DB_DATABASE"), os.Getenv("DB_NAME"), "cotizador_e3") + dbPort := parseIntDefault(os.Getenv("DB_PORT"), 5432) + smtpPort := parseIntDefault(os.Getenv("SMTP_PORT"), 587) + recDias := parseIntDefault(os.Getenv("COBROS_RECORDATORIO_DIAS"), 3) + + cfg := &Config{ + Port: firstNonEmpty(os.Getenv("PORT"), "3000"), + Env: firstNonEmpty(os.Getenv("NODE_ENV"), os.Getenv("APP_ENV"), "production"), + DBHost: firstNonEmpty(os.Getenv("DB_HOST"), "localhost"), + DBPort: dbPort, + DBUser: firstNonEmpty(os.Getenv("DB_USER"), "postgres"), + DBPassword: firstNonEmpty(os.Getenv("DB_PASSWORD"), "postgres"), + DBName: dbName, + JWTSecret: strings.TrimSpace(os.Getenv("JWT_SECRET")), + AppURL: strings.TrimRight(firstNonEmpty(os.Getenv("APP_URL"), "http://localhost:3000"), "/"), + RunSeed: strings.EqualFold(strings.TrimSpace(os.Getenv("RUN_SEED")), "true"), + SeedAdminEmail: firstNonEmpty(os.Getenv("SEED_ADMIN_EMAIL"), "admin@urieljareth.com"), + SeedAdminPassword: os.Getenv("SEED_ADMIN_PASSWORD"), + SeedAdminName: firstNonEmpty(os.Getenv("SEED_ADMIN_NAME"), "Administrador"), + SeedAsesorEmail: strings.TrimSpace(os.Getenv("SEED_ASESOR_EMAIL")), + SeedAsesorPass: os.Getenv("SEED_ASESOR_PASSWORD"), + SeedAsesorName: firstNonEmpty(os.Getenv("SEED_ASESOR_NAME"), "Asesor"), + MinimaxAPIKey: strings.TrimSpace(os.Getenv("MINIMAX_API_KEY")), + MinimaxBaseURL: strings.TrimRight(firstNonEmpty(os.Getenv("MINIMAX_BASE_URL"), "https://api.minimax.io/anthropic"), "/"), + MinimaxModel: firstNonEmpty(os.Getenv("MINIMAX_MODEL"), "MiniMax-M3"), + VAPIDPublicKey: strings.TrimSpace(os.Getenv("VAPID_PUBLIC_KEY")), + VAPIDPrivateKey: strings.TrimSpace(os.Getenv("VAPID_PRIVATE_KEY")), + VAPIDSubject: firstNonEmpty(os.Getenv("VAPID_SUBJECT"), "mailto:contacto@urieljareth.com"), + SMTPHost: strings.TrimSpace(os.Getenv("SMTP_HOST")), + SMTPPort: smtpPort, + SMTPUser: strings.TrimSpace(os.Getenv("SMTP_USER")), + SMTPPass: os.Getenv("SMTP_PASS"), + SMTPFrom: firstNonEmpty(os.Getenv("SMTP_FROM"), os.Getenv("SMTP_USER")), + SMTPFromName: firstNonEmpty(os.Getenv("SMTP_FROM_NAME"), "Uriel Jareth Consulting"), + CobrosRecordatorioDias: recDias, + UploadDir: firstNonEmpty(os.Getenv("UPLOAD_DIR"), "./uploads"), + AdminNotifyEmail: strings.TrimSpace(os.Getenv("ADMIN_NOTIFY_EMAIL")), + WebhookN8NURL: strings.TrimSpace(os.Getenv("WEBHOOK_N8N_URL")), + WebhookN8NSecret: strings.TrimSpace(os.Getenv("WEBHOOK_N8N_SECRET")), + WebhookWhatsAppSendURL: strings.TrimSpace(os.Getenv("WEBHOOK_WHATSAPP_SEND_URL")), + } + + return cfg, nil +} + +func (c *Config) RequireJWTSecret() error { + if c.JWTSecret == "" { + return fmt.Errorf("JWT_SECRET es obligatorio y no esta configurado") + } + return nil +} + +func (c *Config) IsProduction() bool { + return strings.EqualFold(c.Env, "production") +} + +func firstNonEmpty(vals ...string) string { + for _, v := range vals { + if strings.TrimSpace(v) != "" { + return strings.TrimSpace(v) + } + } + return "" +} + +func parseIntDefault(s string, def int) int { + s = strings.TrimSpace(s) + if s == "" { + return def + } + n, err := strconv.Atoi(s) + if err != nil { + return def + } + return n +} diff --git a/internal/db/db.go b/internal/db/db.go new file mode 100644 index 0000000..aa30b2c --- /dev/null +++ b/internal/db/db.go @@ -0,0 +1,115 @@ +package db + +import ( + "context" + "crypto/rand" + "embed" + "encoding/hex" + "fmt" + "io/fs" + "sort" + "strconv" + "sync/atomic" + "time" + + "cotizador/internal/config" + + "github.com/jackc/pgx/v5/pgxpool" +) + +//go:embed migrations/*.sql +var migrationsFS embed.FS + +var idCounter uint64 + +// NewID generates a URL-safe, sortable, collision-resistant CUID-like identifier +// (e.g. "c" + base36 timestamp + counter + random hex, 25 chars). +func NewID() string { + ts := strconv.FormatInt(time.Now().UnixMilli(), 36) + cnt := strconv.FormatUint(atomic.AddUint64(&idCounter, 1)%1679616, 36) + var b [8]byte + _, _ = rand.Read(b[:]) + return "c" + ts + cnt + hex.EncodeToString(b[:])[:12] +} + +// Connect opens a pgxpool using individual connection parameters (matching the +// existing Docker/Coolify environment without SCRAM URL-encoding issues). +func Connect(ctx context.Context, cfg *config.Config) (*pgxpool.Pool, error) { + poolCfg, err := pgxpool.ParseConfig("") + if err != nil { + return nil, err + } + poolCfg.ConnConfig.Host = cfg.DBHost + poolCfg.ConnConfig.Port = uint16(cfg.DBPort) + poolCfg.ConnConfig.User = cfg.DBUser + poolCfg.ConnConfig.Password = cfg.DBPassword + poolCfg.ConnConfig.Database = cfg.DBName + poolCfg.MaxConns = 20 + poolCfg.MinConns = 2 + poolCfg.MaxConnLifetime = 30 * time.Minute + poolCfg.MaxConnIdleTime = 5 * time.Minute + + pool, err := pgxpool.NewWithConfig(ctx, poolCfg) + if err != nil { + return nil, fmt.Errorf("error conectando a PostgreSQL: %w", err) + } + if err := pool.Ping(ctx); err != nil { + pool.Close() + return nil, fmt.Errorf("error haciendo ping a PostgreSQL (%s:%d/%s): %w", cfg.DBHost, cfg.DBPort, cfg.DBName, err) + } + return pool, nil +} + +// Migrate runs embedded idempotent SQL migrations and tracks applied files in `_go_migrations`. +func Migrate(ctx context.Context, pool *pgxpool.Pool) error { + _, err := pool.Exec(ctx, ` + CREATE TABLE IF NOT EXISTS "_go_migrations" ( + "name" TEXT PRIMARY KEY, + "appliedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP + ) + `) + if err != nil { + return fmt.Errorf("error creando tabla _go_migrations: %w", err) + } + + entries, err := fs.ReadDir(migrationsFS, "migrations") + if err != nil { + return fmt.Errorf("error leyendo migraciones embebidas: %w", err) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() }) + + for _, e := range entries { + if e.IsDir() { + continue + } + name := e.Name() + var exists bool + if err := pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM "_go_migrations" WHERE "name" = $1)`, name).Scan(&exists); err != nil { + return fmt.Errorf("error verificando migracion %s: %w", name, err) + } + if exists { + continue + } + + sqlBytes, err := migrationsFS.ReadFile("migrations/" + name) + if err != nil { + return fmt.Errorf("error leyendo %s: %w", name, err) + } + tx, err := pool.Begin(ctx) + if err != nil { + return err + } + if _, err := tx.Exec(ctx, string(sqlBytes)); err != nil { + _ = tx.Rollback(ctx) + return fmt.Errorf("error ejecutando migracion %s: %w", name, err) + } + if _, err := tx.Exec(ctx, `INSERT INTO "_go_migrations" ("name") VALUES ($1)`, name); err != nil { + _ = tx.Rollback(ctx) + return fmt.Errorf("error registrando migracion %s: %w", name, err) + } + if err := tx.Commit(ctx); err != nil { + return err + } + } + return nil +} diff --git a/internal/db/migrations/001_initial_schema.sql b/internal/db/migrations/001_initial_schema.sql new file mode 100644 index 0000000..d4622ea --- /dev/null +++ b/internal/db/migrations/001_initial_schema.sql @@ -0,0 +1,478 @@ +-- Cotizador — Uriel Jareth Consulting +-- Consolidated idempotent PostgreSQL schema matching Prisma's exact 25-table schema. +-- Safe to run on both an empty database and an existing production database with live data. + +CREATE TABLE IF NOT EXISTS "Cliente" ( + "id" TEXT NOT NULL, + "nombre" TEXT NOT NULL, + "empresa" TEXT, + "puesto" TEXT, + "email" TEXT, + "telefono" TEXT, + "rfc" TEXT, + "archivado" BOOLEAN NOT NULL DEFAULT false, + "archivadoAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "Cliente_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "User" ( + "id" TEXT NOT NULL, + "email" TEXT NOT NULL, + "password" TEXT NOT NULL, + "name" TEXT NOT NULL, + "role" TEXT NOT NULL DEFAULT 'asesor', + "clienteId" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "User_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "Cotizacion" ( + "id" TEXT NOT NULL, + "numero" TEXT NOT NULL, + "fecha" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "vigencia" TIMESTAMP(3) NOT NULL, + "moneda" TEXT NOT NULL DEFAULT 'MXN', + "tipoCambio" TEXT NOT NULL DEFAULT 'NA', + "proyecto" TEXT NOT NULL DEFAULT 'MKT Digital', + "esquemaPago" TEXT NOT NULL DEFAULT 'Pago Unico/Mensual', + "estado" TEXT NOT NULL DEFAULT 'borrador', + "incluirBonos" BOOLEAN NOT NULL DEFAULT false, + "incluirFinanciamiento" BOOLEAN NOT NULL DEFAULT false, + "incluirIva" BOOLEAN NOT NULL DEFAULT true, + "esDoble" BOOLEAN NOT NULL DEFAULT false, + "opcionesMetadata" JSONB, + "observaciones" TEXT, + "observacionesInternas" TEXT, + "clienteId" TEXT NOT NULL, + "asesorId" TEXT NOT NULL, + "aprobadaPorId" TEXT, + "aprobadaAt" TIMESTAMP(3), + "aprobacionMetodo" TEXT, + "enviadaAt" TIMESTAMP(3), + "enviadaPor" TEXT, + "enviadaCanal" TEXT, + "enviadaDestino" TEXT, + "aceptadaAt" TIMESTAMP(3), + "rechazadaAt" TIMESTAMP(3), + "vencidaAt" TIMESTAMP(3), + "creadaPorAgente" TEXT, + "archivado" BOOLEAN NOT NULL DEFAULT false, + "archivadoAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "Cotizacion_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "Categoria" ( + "id" TEXT NOT NULL, + "nombre" TEXT NOT NULL, + "descripcion" TEXT, + "color" TEXT NOT NULL DEFAULT '#6b7280', + "activo" BOOLEAN NOT NULL DEFAULT true, + "orden" INTEGER NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "Categoria_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "Paquete" ( + "id" TEXT NOT NULL, + "nombre" TEXT NOT NULL, + "descripcion" TEXT, + "activo" BOOLEAN NOT NULL DEFAULT true, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "Paquete_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "FasePaquete" ( + "id" TEXT NOT NULL, + "paqueteId" TEXT NOT NULL, + "nombre" TEXT NOT NULL, + "orden" INTEGER NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "FasePaquete_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "ServicioCatalogo" ( + "id" TEXT NOT NULL, + "nombre" TEXT NOT NULL, + "descripcion" TEXT, + "fase" INTEGER NOT NULL DEFAULT 1, + "tipoPago" TEXT NOT NULL DEFAULT 'unico', + "precioBase" DOUBLE PRECISION NOT NULL, + "tiempoEntrega" TEXT NOT NULL DEFAULT '4 - 10 dias', + "entregablesDefault" JSONB NOT NULL DEFAULT '[]', + "categoriaId" TEXT, + "variante" TEXT, + "nivel" TEXT, + "activo" BOOLEAN NOT NULL DEFAULT true, + "soloAdmin" BOOLEAN NOT NULL DEFAULT false, + "orden" INTEGER NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "ServicioCatalogo_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "ServicioPaquete" ( + "id" TEXT NOT NULL, + "servicioCatalogoId" TEXT NOT NULL, + "fasePaqueteId" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "ServicioPaquete_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "ServicioCotizado" ( + "id" TEXT NOT NULL, + "cotizacionId" TEXT NOT NULL, + "servicioCatalogoId" TEXT, + "nombre" TEXT, + "esPersonalizado" BOOLEAN NOT NULL DEFAULT false, + "horas" DOUBLE PRECISION, + "tarifaHora" DOUBLE PRECISION, + "modeloCobro" TEXT NOT NULL DEFAULT 'fijo', + "montoMinimo" DOUBLE PRECISION, + "horasIncluidas" DOUBLE PRECISION, + "opcion" TEXT, + "fase" INTEGER NOT NULL, + "tipoPago" TEXT NOT NULL, + "precio" DOUBLE PRECISION NOT NULL, + "tiempoEntrega" TEXT NOT NULL, + "entregables" JSONB NOT NULL DEFAULT '[]', + "beneficios" JSONB NOT NULL DEFAULT '[]', + "notas" TEXT, + "seleccionado" BOOLEAN NOT NULL DEFAULT true, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "ServicioCotizado_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "PlanBucefaloCotizacion" ( + "id" TEXT NOT NULL, + "cotizacionId" TEXT NOT NULL, + "nivel" TEXT NOT NULL DEFAULT 'basico', + "precio" DOUBLE PRECISION NOT NULL, + "seleccionado" BOOLEAN NOT NULL DEFAULT true, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "PlanBucefaloCotizacion_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "RegistroHoras" ( + "id" TEXT NOT NULL, + "cotizacionId" TEXT NOT NULL, + "fecha" TIMESTAMP(3) NOT NULL, + "horaInicio" TEXT NOT NULL, + "horaFin" TEXT NOT NULL, + "horas" DOUBLE PRECISION NOT NULL, + "tarifaHora" DOUBLE PRECISION NOT NULL DEFAULT 0, + "descripcion" TEXT NOT NULL, + "estadoPago" TEXT NOT NULL DEFAULT 'por_pagar', + "fechaPago" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "RegistroHoras_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "PropuestaIA" ( + "id" TEXT NOT NULL, + "cotizacionId" TEXT NOT NULL, + "estado" TEXT NOT NULL DEFAULT 'borrador', + "contenidoIA" JSONB NOT NULL, + "contenidoEditado" JSONB, + "transcripcion" TEXT, + "traza" JSONB, + "avisos" JSONB NOT NULL DEFAULT '[]', + "modelo" TEXT NOT NULL, + "aprobadaPor" TEXT, + "aprobadaAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "PropuestaIA_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "Configuracion" ( + "id" TEXT NOT NULL, + "clave" TEXT NOT NULL, + "valor" TEXT NOT NULL, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "Configuracion_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "Bono" ( + "id" TEXT NOT NULL, + "numero" INTEGER NOT NULL, + "titulo" TEXT NOT NULL, + "descripcion" TEXT NOT NULL, + "activo" BOOLEAN NOT NULL DEFAULT true, + CONSTRAINT "Bono_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "FinanciamientoPlan" ( + "id" TEXT NOT NULL, + "meses" INTEGER NOT NULL, + "tasa" DOUBLE PRECISION NOT NULL, + "comision" DOUBLE PRECISION NOT NULL, + "montoMinimo" DOUBLE PRECISION NOT NULL, + "iva" DOUBLE PRECISION NOT NULL DEFAULT 0.16, + CONSTRAINT "FinanciamientoPlan_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "ProgramaPago" ( + "id" TEXT NOT NULL, + "clienteId" TEXT NOT NULL, + "cotizacionId" TEXT, + "concepto" TEXT NOT NULL, + "monto" DOUBLE PRECISION NOT NULL, + "moneda" TEXT NOT NULL DEFAULT 'MXN', + "frecuencia" TEXT NOT NULL DEFAULT 'semanal', + "diaSemana" INTEGER, + "diaMes" INTEGER, + "fechaInicio" TIMESTAMP(3) NOT NULL, + "fechaFin" TIMESTAMP(3), + "activo" BOOLEAN NOT NULL DEFAULT true, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "ProgramaPago_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "PagoRecurrente" ( + "id" TEXT NOT NULL, + "programaId" TEXT NOT NULL, + "fecha" TIMESTAMP(3) NOT NULL, + "monto" DOUBLE PRECISION NOT NULL, + "estado" TEXT NOT NULL DEFAULT 'pendiente', + "verificadoAt" TIMESTAMP(3), + "rechazadoAt" TIMESTAMP(3), + "rechazoMotivo" TEXT, + "ultimoRecordatorioAt" TIMESTAMP(3), + "recordatoriosEnviados" INTEGER NOT NULL DEFAULT 0, + "vencidoNotificadoAt" TIMESTAMP(3), + "nota" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "PagoRecurrente_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "ComprobantePago" ( + "id" TEXT NOT NULL, + "pagoId" TEXT NOT NULL, + "archivoRuta" TEXT NOT NULL, + "archivoNombre" TEXT NOT NULL, + "mime" TEXT NOT NULL, + "tamano" INTEGER NOT NULL, + "subidoAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "ComprobantePago_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "SuscripcionPush" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "endpoint" TEXT NOT NULL, + "p256dh" TEXT NOT NULL, + "auth" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "SuscripcionPush_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "AgentApiKey" ( + "id" TEXT NOT NULL, + "nombre" TEXT NOT NULL, + "prefijo" TEXT NOT NULL, + "keyHash" TEXT NOT NULL, + "scopes" TEXT[], + "rateLimitPerMin" INTEGER NOT NULL DEFAULT 60, + "activo" BOOLEAN NOT NULL DEFAULT true, + "revokedAt" TIMESTAMP(3), + "lastUsedAt" TIMESTAMP(3), + "createdById" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "AgentApiKey_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "AuditLog" ( + "id" TEXT NOT NULL, + "actorTipo" TEXT NOT NULL, + "actorId" TEXT, + "actorNombre" TEXT NOT NULL, + "accion" TEXT NOT NULL, + "recursoTipo" TEXT NOT NULL, + "recursoId" TEXT, + "ip" TEXT, + "requestId" TEXT, + "exito" BOOLEAN NOT NULL DEFAULT true, + "detalle" JSONB, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "ApprovalToken" ( + "id" TEXT NOT NULL, + "cotizacionId" TEXT NOT NULL, + "tokenHash" TEXT NOT NULL, + "expiraAt" TIMESTAMP(3) NOT NULL, + "usadoAt" TIMESTAMP(3), + "usadoIp" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "ApprovalToken_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "IdempotencyKey" ( + "id" TEXT NOT NULL, + "key" TEXT NOT NULL, + "method" TEXT NOT NULL, + "path" TEXT NOT NULL, + "requestHash" TEXT NOT NULL, + "statusCode" INTEGER NOT NULL, + "responseBody" JSONB NOT NULL, + "expiraAt" TIMESTAMP(3) NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "IdempotencyKey_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "WebhookEndpoint" ( + "id" TEXT NOT NULL, + "nombre" TEXT NOT NULL, + "url" TEXT NOT NULL, + "secret" TEXT NOT NULL, + "eventos" TEXT[], + "activo" BOOLEAN NOT NULL DEFAULT true, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "WebhookEndpoint_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE IF NOT EXISTS "WebhookDelivery" ( + "id" TEXT NOT NULL, + "endpointId" TEXT, + "url" TEXT NOT NULL, + "evento" TEXT NOT NULL, + "payload" JSONB NOT NULL, + "statusCode" INTEGER, + "exito" BOOLEAN NOT NULL DEFAULT false, + "intentos" INTEGER NOT NULL DEFAULT 1, + "error" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "WebhookDelivery_pkey" PRIMARY KEY ("id") +); + +-- Ensure additive columns exist on older production DBs +ALTER TABLE "Cliente" ADD COLUMN IF NOT EXISTS "puesto" TEXT; +ALTER TABLE "Cliente" ADD COLUMN IF NOT EXISTS "archivado" BOOLEAN NOT NULL DEFAULT false; +ALTER TABLE "Cliente" ADD COLUMN IF NOT EXISTS "archivadoAt" TIMESTAMP(3); + +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "observacionesInternas" TEXT; +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobadaPorId" TEXT; +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobadaAt" TIMESTAMP(3); +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobacionMetodo" TEXT; +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaAt" TIMESTAMP(3); +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaPor" TEXT; +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaCanal" TEXT; +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaDestino" TEXT; +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aceptadaAt" TIMESTAMP(3); +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "rechazadaAt" TIMESTAMP(3); +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "vencidaAt" TIMESTAMP(3); +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "creadaPorAgente" TEXT; +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "archivado" BOOLEAN NOT NULL DEFAULT false; +ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "archivadoAt" TIMESTAMP(3); + +ALTER TABLE "ServicioCatalogo" ADD COLUMN IF NOT EXISTS "soloAdmin" BOOLEAN NOT NULL DEFAULT false; +ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "ultimoRecordatorioAt" TIMESTAMP(3); +ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "recordatoriosEnviados" INTEGER NOT NULL DEFAULT 0; +ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "vencidoNotificadoAt" TIMESTAMP(3); +ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "nota" TEXT; + +-- Unique & regular indexes +CREATE UNIQUE INDEX IF NOT EXISTS "User_email_key" ON "User"("email"); +CREATE UNIQUE INDEX IF NOT EXISTS "User_clienteId_key" ON "User"("clienteId"); + +CREATE INDEX IF NOT EXISTS "Cliente_nombre_empresa_idx" ON "Cliente"("nombre", "empresa"); +CREATE INDEX IF NOT EXISTS "Cliente_archivado_idx" ON "Cliente"("archivado"); + +CREATE UNIQUE INDEX IF NOT EXISTS "Cotizacion_numero_key" ON "Cotizacion"("numero"); +CREATE INDEX IF NOT EXISTS "Cotizacion_clienteId_idx" ON "Cotizacion"("clienteId"); +CREATE INDEX IF NOT EXISTS "Cotizacion_asesorId_idx" ON "Cotizacion"("asesorId"); +CREATE INDEX IF NOT EXISTS "Cotizacion_estado_idx" ON "Cotizacion"("estado"); +CREATE INDEX IF NOT EXISTS "Cotizacion_archivado_idx" ON "Cotizacion"("archivado"); +CREATE INDEX IF NOT EXISTS "Cotizacion_createdAt_idx" ON "Cotizacion"("createdAt"); + +CREATE UNIQUE INDEX IF NOT EXISTS "Categoria_nombre_key" ON "Categoria"("nombre"); +CREATE INDEX IF NOT EXISTS "FasePaquete_paqueteId_idx" ON "FasePaquete"("paqueteId"); + +CREATE INDEX IF NOT EXISTS "ServicioCatalogo_categoriaId_idx" ON "ServicioCatalogo"("categoriaId"); +CREATE INDEX IF NOT EXISTS "ServicioCatalogo_activo_fase_orden_idx" ON "ServicioCatalogo"("activo", "fase", "orden"); + +CREATE UNIQUE INDEX IF NOT EXISTS "ServicioPaquete_servicioCatalogoId_fasePaqueteId_key" ON "ServicioPaquete"("servicioCatalogoId", "fasePaqueteId"); +CREATE INDEX IF NOT EXISTS "ServicioPaquete_fasePaqueteId_idx" ON "ServicioPaquete"("fasePaqueteId"); + +CREATE INDEX IF NOT EXISTS "ServicioCotizado_cotizacionId_idx" ON "ServicioCotizado"("cotizacionId"); +CREATE INDEX IF NOT EXISTS "ServicioCotizado_servicioCatalogoId_idx" ON "ServicioCotizado"("servicioCatalogoId"); + +CREATE UNIQUE INDEX IF NOT EXISTS "PlanBucefaloCotizacion_cotizacionId_key" ON "PlanBucefaloCotizacion"("cotizacionId"); + +CREATE INDEX IF NOT EXISTS "RegistroHoras_cotizacionId_idx" ON "RegistroHoras"("cotizacionId"); +CREATE INDEX IF NOT EXISTS "RegistroHoras_fecha_idx" ON "RegistroHoras"("fecha"); +CREATE INDEX IF NOT EXISTS "RegistroHoras_estadoPago_idx" ON "RegistroHoras"("estadoPago"); + +CREATE INDEX IF NOT EXISTS "PropuestaIA_cotizacionId_idx" ON "PropuestaIA"("cotizacionId"); + +CREATE UNIQUE INDEX IF NOT EXISTS "Configuracion_clave_key" ON "Configuracion"("clave"); +CREATE UNIQUE INDEX IF NOT EXISTS "FinanciamientoPlan_meses_key" ON "FinanciamientoPlan"("meses"); + +CREATE INDEX IF NOT EXISTS "ProgramaPago_clienteId_idx" ON "ProgramaPago"("clienteId"); +CREATE INDEX IF NOT EXISTS "ProgramaPago_activo_idx" ON "ProgramaPago"("activo"); + +CREATE UNIQUE INDEX IF NOT EXISTS "PagoRecurrente_programaId_fecha_key" ON "PagoRecurrente"("programaId", "fecha"); +CREATE INDEX IF NOT EXISTS "PagoRecurrente_estado_idx" ON "PagoRecurrente"("estado"); +CREATE INDEX IF NOT EXISTS "PagoRecurrente_fecha_idx" ON "PagoRecurrente"("fecha"); +CREATE INDEX IF NOT EXISTS "PagoRecurrente_vencidoNotificadoAt_idx" ON "PagoRecurrente"("vencidoNotificadoAt"); + +CREATE UNIQUE INDEX IF NOT EXISTS "ComprobantePago_pagoId_key" ON "ComprobantePago"("pagoId"); +CREATE UNIQUE INDEX IF NOT EXISTS "SuscripcionPush_endpoint_key" ON "SuscripcionPush"("endpoint"); +CREATE INDEX IF NOT EXISTS "SuscripcionPush_userId_idx" ON "SuscripcionPush"("userId"); + +CREATE UNIQUE INDEX IF NOT EXISTS "AgentApiKey_nombre_key" ON "AgentApiKey"("nombre"); +CREATE UNIQUE INDEX IF NOT EXISTS "AgentApiKey_keyHash_key" ON "AgentApiKey"("keyHash"); + +CREATE INDEX IF NOT EXISTS "AuditLog_createdAt_idx" ON "AuditLog"("createdAt"); +CREATE INDEX IF NOT EXISTS "AuditLog_accion_idx" ON "AuditLog"("accion"); +CREATE INDEX IF NOT EXISTS "AuditLog_recursoTipo_recursoId_idx" ON "AuditLog"("recursoTipo", "recursoId"); +CREATE INDEX IF NOT EXISTS "AuditLog_actorNombre_idx" ON "AuditLog"("actorNombre"); + +CREATE UNIQUE INDEX IF NOT EXISTS "ApprovalToken_tokenHash_key" ON "ApprovalToken"("tokenHash"); +CREATE INDEX IF NOT EXISTS "ApprovalToken_cotizacionId_idx" ON "ApprovalToken"("cotizacionId"); + +CREATE UNIQUE INDEX IF NOT EXISTS "IdempotencyKey_key_key" ON "IdempotencyKey"("key"); +CREATE INDEX IF NOT EXISTS "IdempotencyKey_expiraAt_idx" ON "IdempotencyKey"("expiraAt"); + +CREATE UNIQUE INDEX IF NOT EXISTS "WebhookEndpoint_nombre_key" ON "WebhookEndpoint"("nombre"); +CREATE INDEX IF NOT EXISTS "WebhookDelivery_evento_idx" ON "WebhookDelivery"("evento"); +CREATE INDEX IF NOT EXISTS "WebhookDelivery_createdAt_idx" ON "WebhookDelivery"("createdAt"); + +-- Foreign keys (idempotent) +DO $$ BEGIN ALTER TABLE "User" ADD CONSTRAINT "User_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "Cotizacion" ADD CONSTRAINT "Cotizacion_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE RESTRICT ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "Cotizacion" ADD CONSTRAINT "Cotizacion_asesorId_fkey" FOREIGN KEY ("asesorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "FasePaquete" ADD CONSTRAINT "FasePaquete_paqueteId_fkey" FOREIGN KEY ("paqueteId") REFERENCES "Paquete"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "ServicioCatalogo" ADD CONSTRAINT "ServicioCatalogo_categoriaId_fkey" FOREIGN KEY ("categoriaId") REFERENCES "Categoria"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "ServicioPaquete" ADD CONSTRAINT "ServicioPaquete_servicioCatalogoId_fkey" FOREIGN KEY ("servicioCatalogoId") REFERENCES "ServicioCatalogo"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "ServicioPaquete" ADD CONSTRAINT "ServicioPaquete_fasePaqueteId_fkey" FOREIGN KEY ("fasePaqueteId") REFERENCES "FasePaquete"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "ServicioCotizado" ADD CONSTRAINT "ServicioCotizado_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "ServicioCotizado" ADD CONSTRAINT "ServicioCotizado_servicioCatalogoId_fkey" FOREIGN KEY ("servicioCatalogoId") REFERENCES "ServicioCatalogo"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "PlanBucefaloCotizacion" ADD CONSTRAINT "PlanBucefaloCotizacion_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "RegistroHoras" ADD CONSTRAINT "RegistroHoras_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "PropuestaIA" ADD CONSTRAINT "PropuestaIA_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "ProgramaPago" ADD CONSTRAINT "ProgramaPago_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "ProgramaPago" ADD CONSTRAINT "ProgramaPago_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "PagoRecurrente" ADD CONSTRAINT "PagoRecurrente_programaId_fkey" FOREIGN KEY ("programaId") REFERENCES "ProgramaPago"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "ComprobantePago" ADD CONSTRAINT "ComprobantePago_pagoId_fkey" FOREIGN KEY ("pagoId") REFERENCES "PagoRecurrente"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "SuscripcionPush" ADD CONSTRAINT "SuscripcionPush_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "ApprovalToken" ADD CONSTRAINT "ApprovalToken_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; +DO $$ BEGIN ALTER TABLE "WebhookDelivery" ADD CONSTRAINT "WebhookDelivery_endpointId_fkey" FOREIGN KEY ("endpointId") REFERENCES "WebhookEndpoint"("id") ON DELETE SET NULL ON UPDATE CASCADE; EXCEPTION WHEN duplicate_object THEN NULL; END $$; diff --git a/internal/domain/aprobacion_core.go b/internal/domain/aprobacion_core.go new file mode 100644 index 0000000..5683d31 --- /dev/null +++ b/internal/domain/aprobacion_core.go @@ -0,0 +1,146 @@ +package domain + +import ( + "fmt" + "slices" + "strings" + "time" +) + +type ActorInfo struct { + Type string // "user" | "agent" | "enlace_firmado" + Role string // "admin" | "asesor" | "cliente" + Scopes []string +} + +type ValidarTransicionInput struct { + Actual string + Nuevo string + Actor ActorInfo + ViaEndpoint string // "aprobar" | "enlace_firmado" | "enviar" | "estado" | "put" + AprobadaAt *time.Time +} + +type ValidarTransicionResult struct { + OK bool + Status int + Error string +} + +func ValidarTransicionEstado(in ValidarTransicionInput) ValidarTransicionResult { + if !EsEstadoCotizacionValido(in.Nuevo) { + return ValidarTransicionResult{ + OK: false, + Status: 400, + Error: fmt.Sprintf("Estado invalido. Permitidos: %s", strings.Join(EstadosCotizacion, ", ")), + } + } + + if in.Actual == in.Nuevo { + return ValidarTransicionResult{OK: true} + } + + esAdminHumano := in.Actor.Type == "user" && in.Actor.Role == "admin" + esStaffHumano := in.Actor.Type == "user" && in.Actor.Role != "cliente" + esEnlaceFirmado := in.Actor.Type == "enlace_firmado" && in.ViaEndpoint == "enlace_firmado" + esAgente := in.Actor.Type == "agent" + + // REGLA DE HIERRO 1: Nadie salvo admin humano o enlace firmado de un solo uso puede aprobar. + if in.Nuevo == "aprobada" { + if !esAdminHumano && !esEnlaceFirmado { + return ValidarTransicionResult{ + OK: false, + Status: 403, + Error: "Solo un administrador humano o el enlace firmado puede aprobar una cotizacion", + } + } + if in.Actual != "borrador" { + return ValidarTransicionResult{ + OK: false, + Status: 409, + Error: fmt.Sprintf("Solo se puede aprobar una cotizacion en borrador (estado actual: %s)", in.Actual), + } + } + return ValidarTransicionResult{OK: true} + } + + // REGLA DE HIERRO 2: Nadie puede pasar a "enviada" sin estar previamente aprobada (con aprobadaAt). + if in.Nuevo == "enviada" { + if esAgente && in.ViaEndpoint != "enviar" { + return ValidarTransicionResult{ + OK: false, + Status: 403, + Error: "Los agentes solo pueden enviar cotizaciones mediante POST /api/cotizaciones/:id/enviar", + } + } + if in.Actual != "aprobada" || in.AprobadaAt == nil { + return ValidarTransicionResult{ + OK: false, + Status: 409, + Error: "La cotizacion debe estar aprobada por el administrador antes de enviarse", + } + } + if esAgente { + if !slices.Contains(in.Actor.Scopes, "cotizaciones:enviar") { + return ValidarTransicionResult{ + OK: false, + Status: 403, + Error: "El agente no tiene el alcance cotizaciones:enviar", + } + } + return ValidarTransicionResult{OK: true} + } + if !esStaffHumano { + return ValidarTransicionResult{ + OK: false, + Status: 403, + Error: "No autorizado para enviar cotizaciones", + } + } + return ValidarTransicionResult{OK: true} + } + + // Reabrir a borrador: solo admin humano desde aprobada, rechazada o vencida. + if in.Nuevo == "borrador" { + if !esAdminHumano { + return ValidarTransicionResult{ + OK: false, + Status: 403, + Error: "Solo un administrador humano puede regresar una cotizacion a borrador", + } + } + if in.Actual != "aprobada" && in.Actual != "rechazada" && in.Actual != "vencida" { + return ValidarTransicionResult{ + OK: false, + Status: 409, + Error: fmt.Sprintf("No se puede regresar a borrador desde el estado %s", in.Actual), + } + } + return ValidarTransicionResult{OK: true} + } + + // Estados de cierre post-envio: aceptada | rechazada | vencida + if in.Nuevo == "aceptada" || in.Nuevo == "rechazada" || in.Nuevo == "vencida" { + if !esStaffHumano { + return ValidarTransicionResult{ + OK: false, + Status: 403, + Error: "Solo el equipo humano puede marcar una cotizacion como aceptada, rechazada o vencida", + } + } + if in.Actual != "enviada" { + return ValidarTransicionResult{ + OK: false, + Status: 409, + Error: fmt.Sprintf("Solo se puede pasar a %s desde el estado enviada (estado actual: %s)", in.Nuevo, in.Actual), + } + } + return ValidarTransicionResult{OK: true} + } + + return ValidarTransicionResult{ + OK: false, + Status: 409, + Error: fmt.Sprintf("Transicion no permitida de %s a %s", in.Actual, in.Nuevo), + } +} diff --git a/internal/domain/calculators.go b/internal/domain/calculators.go new file mode 100644 index 0000000..bd4aecf --- /dev/null +++ b/internal/domain/calculators.go @@ -0,0 +1,540 @@ +package domain + +import ( + "fmt" + "math" + "regexp" + "strconv" + "strings" + "time" +) + +const ( + IVARate = 0.16 + TarifaHoraDefault = 700.0 +) + +var ModelosCobro = map[string]string{ + "fijo": "Precio fijo", + "horas": "Por horas", + "retainer": "Retainer (minimo + adicionales)", + "demanda": "Bajo demanda / por hora", +} + +var ModelosCobroTiempo = []string{"horas", "retainer", "demanda"} + +var Fases = map[int]string{ + 0: "FASE 0 - Auditoria / Acompanamiento", + 1: "FASE 1 - Setup e Infraestructura", + 2: "FASE 2 - Publicidad y Manejo", + 3: "FASE 3 - Contenido y SEO", +} + +var FasesShort = map[int]string{ + 0: "FASE 0 - Auditoria", + 1: "FASE 1 - Setup e Infraestructura", + 2: "FASE 2 - Publicidad y Manejo", + 3: "FASE 3 - Contenido y SEO", +} + +type PlanBucefaloDef struct { + Nivel string `json:"nivel"` + Label string `json:"label"` + Precio float64 `json:"precio"` +} + +var PlanesBucefalo = []PlanBucefaloDef{ + {Nivel: "basico", Label: "Basico", Precio: 1000}, + {Nivel: "estandar", Label: "Estandar", Precio: 3500}, + {Nivel: "premium", Label: "Premium", Precio: 4500}, + {Nivel: "empresarial", Label: "Empresarial", Precio: 7500}, +} + +var EstadosCotizacion = []string{"borrador", "aprobada", "enviada", "aceptada", "rechazada", "vencida"} + +var EstadosPagoHoras = []string{"por_pagar", "pagada"} + +var NivelesServicio = []string{"Emprendedor", "PYME", "Empresario", "Corporativo"} + +type MetaOpcion struct { + Titulo string `json:"titulo,omitempty"` + Descripcion string `json:"descripcion,omitempty"` + NoIncluye string `json:"noIncluye,omitempty"` +} + +type ServicioCalc struct { + Nombre string + ModeloCobro string + EsPersonalizado bool + Horas *float64 + TarifaHora *float64 + MontoMinimo *float64 + HorasIncluidas *float64 + Opcion *string + TipoPago string + Precio float64 + Seleccionado bool +} + +type TotalesOpcion struct { + TotalUnico float64 `json:"totalUnico"` + TotalMensual float64 `json:"totalMensual"` + Horas float64 `json:"horas"` +} + +type TotalesCotizacion struct { + SubtotalUnico float64 `json:"subtotalUnico"` + SubtotalMensual float64 `json:"subtotalMensual"` + IVAUnico float64 `json:"ivaUnico"` + IVAMensual float64 `json:"ivaMensual"` + TotalUnico float64 `json:"totalUnico"` + TotalMensual float64 `json:"totalMensual"` + TotalPrimerAnio float64 `json:"totalPrimerAnio"` + IncluyeIVA bool `json:"incluyeIva"` +} + +type FinanciamientoInput struct { + Monto float64 + Meses int + Tasa float64 + Comision float64 + IVA float64 +} + +type FinanciamientoResult struct { + PagoMensual float64 `json:"pagoMensual"` + IVAMensual float64 `json:"ivaMensual"` + TotalMensual float64 `json:"totalMensual"` + ComisionTotal float64 `json:"comisionTotal"` + GranTotal float64 `json:"granTotal"` +} + +type BucketHoras struct { + Horas float64 `json:"horas"` + Importe float64 `json:"importe"` + Count int `json:"count"` +} + +type ResumenPagoHoras struct { + PorPagar BucketHoras `json:"porPagar"` + Pagada BucketHoras `json:"pagada"` + Total BucketHoras `json:"total"` +} + +type RegistroHorasCalc struct { + Horas float64 + TarifaHora float64 + EstadoPago string +} + +type PeriodoAgrupacion struct { + Clave string `json:"clave"` + Etiqueta string `json:"etiqueta"` +} + +func Round2(n float64) float64 { + return math.Round(n*100) / 100 +} + +func CalcularPrecioHoras(horas, tarifaHora float64) float64 { + return Round2(horas * tarifaHora) +} + +func ConIVA(monto float64, incluirIVA bool) float64 { + if incluirIVA { + return Round2(monto * (1 + IVARate)) + } + return Round2(monto) +} + +func BucefaloPrecio(nivel string) float64 { + for _, p := range PlanesBucefalo { + if p.Nivel == nivel { + return p.Precio + } + } + return 0 +} + +func EsEstadoCotizacionValido(estado string) bool { + for _, e := range EstadosCotizacion { + if e == estado { + return true + } + } + return false +} + +func EsModeloTiempo(modelo string) bool { + for _, m := range ModelosCobroTiempo { + if m == modelo { + return true + } + } + return false +} + +func EsCotizacionPorTiempo(servicios []ServicioCalc) bool { + for _, s := range servicios { + if EsModeloTiempo(s.ModeloCobro) { + return true + } + } + return false +} + +func TarifaHoraSugerida(servicios []ServicioCalc) float64 { + for _, s := range servicios { + if EsModeloTiempo(s.ModeloCobro) && s.TarifaHora != nil && *s.TarifaHora > 0 { + return *s.TarifaHora + } + } + return TarifaHoraDefault +} + +func DescribirRetainer(montoMinimo, horasIncluidas, tarifaHora float64) string { + partes := []string{fmt.Sprintf("%s/mes", FormatCurrency(montoMinimo))} + if horasIncluidas != 0 { + partes = append(partes, fmt.Sprintf("incluye %s hr", formatTrimFloat(horasIncluidas))) + } + if tarifaHora != 0 { + partes = append(partes, fmt.Sprintf("adicional %s/hr (se factura aparte)", FormatCurrency(tarifaHora))) + } + return strings.Join(partes, " · ") +} + +func DetalleModelo(s ServicioCalc) string { + switch s.ModeloCobro { + case "retainer": + var mm, hi, th float64 + if s.MontoMinimo != nil { + mm = *s.MontoMinimo + } + if s.HorasIncluidas != nil { + hi = *s.HorasIncluidas + } + if s.TarifaHora != nil { + th = *s.TarifaHora + } + return DescribirRetainer(mm, hi, th) + case "demanda": + var th float64 + if s.TarifaHora != nil { + th = *s.TarifaHora + } + return fmt.Sprintf("%s/hr · segun consumo", FormatCurrency(th)) + default: + if (s.ModeloCobro == "horas" || s.EsPersonalizado) && s.Horas != nil && *s.Horas != 0 && s.TarifaHora != nil && *s.TarifaHora != 0 { + return fmt.Sprintf("%s h x %s/hr", formatTrimFloat(*s.Horas), FormatCurrency(*s.TarifaHora)) + } + return "" + } +} + +func PrecioDisplay(s ServicioCalc) string { + if s.ModeloCobro == "demanda" { + var th float64 + if s.TarifaHora != nil { + th = *s.TarifaHora + } + return fmt.Sprintf("%s/hr", FormatCurrency(th)) + } + return FormatCurrency(s.Precio) +} + +func NotaDemanda(servicios []ServicioCalc) string { + var partes []string + for _, s := range servicios { + if s.ModeloCobro == "demanda" { + nombre := strings.TrimSpace(s.Nombre) + if nombre == "" { + nombre = "Servicio" + } + var th float64 + if s.TarifaHora != nil { + th = *s.TarifaHora + } + partes = append(partes, fmt.Sprintf("%s a %s/hr", nombre, FormatCurrency(th))) + } + } + if len(partes) == 0 { + return "" + } + return fmt.Sprintf("+ Horas facturadas a fin de mes segun consumo (no incluidas en el total): %s.", strings.Join(partes, ", ")) +} + +func CalcularTotalesOpcion(servicios []ServicioCalc, opcion string) TotalesOpcion { + var totalUnico, totalMensual, horas float64 + for _, s := range servicios { + op := "" + if s.Opcion != nil { + op = *s.Opcion + } + if op != "ambas" && op != opcion { + continue + } + switch s.TipoPago { + case "unico": + totalUnico += s.Precio + case "mensual": + totalMensual += s.Precio + } + if s.Horas != nil { + horas += *s.Horas + } + } + return TotalesOpcion{ + TotalUnico: Round2(totalUnico), + TotalMensual: Round2(totalMensual), + Horas: Round2(horas), + } +} + +func CalcularTotalesCotizacion(servicios []ServicioCalc, incluirIVA bool) TotalesCotizacion { + var sumUnico, sumMensual float64 + for _, s := range servicios { + if !s.Seleccionado { + continue + } + switch s.TipoPago { + case "unico": + sumUnico += s.Precio + case "mensual": + sumMensual += s.Precio + } + } + subtotalUnico := Round2(sumUnico) + subtotalMensual := Round2(sumMensual) + + var ivaUnico, ivaMensual float64 + if incluirIVA { + ivaUnico = Round2(subtotalUnico * IVARate) + ivaMensual = Round2(subtotalMensual * IVARate) + } + totalUnico := Round2(subtotalUnico + ivaUnico) + totalMensual := Round2(subtotalMensual + ivaMensual) + + return TotalesCotizacion{ + SubtotalUnico: subtotalUnico, + SubtotalMensual: subtotalMensual, + IVAUnico: ivaUnico, + IVAMensual: ivaMensual, + TotalUnico: totalUnico, + TotalMensual: totalMensual, + TotalPrimerAnio: Round2(totalUnico + totalMensual*12), + IncluyeIVA: incluirIVA, + } +} + +func CalcularVigencia(fecha time.Time) time.Time { + vigencia := fecha + diasHabiles := 0 + for diasHabiles < 15 { + vigencia = vigencia.AddDate(0, 0, 1) + wd := vigencia.Weekday() + if wd != time.Sunday && wd != time.Saturday { + diasHabiles++ + } + } + return vigencia +} + +func CalcularFinanciamiento(input FinanciamientoInput) FinanciamientoResult { + comisionTotal := (input.Monto * input.Comision) / 100.0 + montoConComision := input.Monto + comisionTotal + pagoMensual := montoConComision * (1.0 + input.Tasa) / float64(input.Meses) + ivaMensual := pagoMensual * input.IVA + totalMensual := pagoMensual + ivaMensual + return FinanciamientoResult{ + PagoMensual: Round2(pagoMensual), + IVAMensual: Round2(ivaMensual), + TotalMensual: Round2(totalMensual), + ComisionTotal: Round2(comisionTotal), + GranTotal: Round2(totalMensual * float64(input.Meses)), + } +} + +func GenerarNumeroCotizacion(asesorIniciales string, secuencia int, now time.Time) string { + yy := fmt.Sprintf("%02d", now.Year()%100) + mm := fmt.Sprintf("%02d", int(now.Month())) + seq := fmt.Sprintf("%03d", secuencia) + return fmt.Sprintf("UJ%s%s%s%s", yy, mm, asesorIniciales, seq) +} + +var horaRe = regexp.MustCompile(`^(\d{1,2}):(\d{2})$`) + +func CalcularHorasRango(horaInicio, horaFin string) float64 { + a := horaRe.FindStringSubmatch(horaInicio) + b := horaRe.FindStringSubmatch(horaFin) + if a == nil || b == nil { + return 0 + } + ah, _ := strconv.Atoi(a[1]) + am, _ := strconv.Atoi(a[2]) + bh, _ := strconv.Atoi(b[1]) + bm, _ := strconv.Atoi(b[2]) + ini := ah*60 + am + fin := bh*60 + bm + if fin <= ini { + return 0 + } + return Round2(float64(fin-ini) / 60.0) +} + +func FechaRegistroDesdeISO(fechaISO string) (time.Time, error) { + t, err := time.Parse("2006-01-02", strings.TrimSpace(fechaISO)) + if err != nil { + return time.Time{}, err + } + return time.Date(t.Year(), t.Month(), t.Day(), 12, 0, 0, 0, time.UTC), nil +} + +func FormatFechaRegistro(date time.Time) string { + u := date.UTC() + return fmt.Sprintf("%02d/%02d/%04d", u.Day(), int(u.Month()), u.Year()) +} + +var mesesLargo = []string{ + "enero", "febrero", "marzo", "abril", "mayo", "junio", + "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre", +} + +func lunesDeSemanaUTC(d time.Time) time.Time { + u := d.UTC() + r := time.Date(u.Year(), u.Month(), u.Day(), 0, 0, 0, 0, time.UTC) + wd := int(r.Weekday()) // 0 = Sunday + offset := 1 - wd + if wd == 0 { + offset = -6 + } + return r.AddDate(0, 0, offset) +} + +func PeriodoAgrupacionDe(fecha time.Time, modo string) PeriodoAgrupacion { + u := fecha.UTC() + y, m, d := u.Year(), int(u.Month()), u.Day() + switch modo { + case "mes": + return PeriodoAgrupacion{ + Clave: fmt.Sprintf("%04d-%02d", y, m), + Etiqueta: fmt.Sprintf("%s %d", mesesLargo[m-1], y), + } + case "semana": + lunes := lunesDeSemanaUTC(u) + domingo := lunes.AddDate(0, 0, 6) + clave := fmt.Sprintf("%04d-%02d-%02d", lunes.Year(), int(lunes.Month()), lunes.Day()) + etiqueta := fmt.Sprintf("Semana %02d/%02d - %02d/%02d", lunes.Day(), int(lunes.Month()), domingo.Day(), int(domingo.Month())) + return PeriodoAgrupacion{Clave: clave, Etiqueta: etiqueta} + default: + return PeriodoAgrupacion{ + Clave: fmt.Sprintf("%04d-%02d-%02d", y, m, d), + Etiqueta: FormatFechaRegistro(u), + } + } +} + +func EsPagada(estadoPago string) bool { + return estadoPago == "pagada" +} + +func CalcularResumenPagoHoras(registros []RegistroHorasCalc) ResumenPagoHoras { + var r ResumenPagoHoras + for _, x := range registros { + importe := x.Horas * x.TarifaHora + if EsPagada(x.EstadoPago) { + r.Pagada.Horas += x.Horas + r.Pagada.Importe += importe + r.Pagada.Count++ + } else { + r.PorPagar.Horas += x.Horas + r.PorPagar.Importe += importe + r.PorPagar.Count++ + } + r.Total.Horas += x.Horas + r.Total.Importe += importe + r.Total.Count++ + } + r.PorPagar.Horas = Round2(r.PorPagar.Horas) + r.PorPagar.Importe = Round2(r.PorPagar.Importe) + r.Pagada.Horas = Round2(r.Pagada.Horas) + r.Pagada.Importe = Round2(r.Pagada.Importe) + r.Total.Horas = Round2(r.Total.Horas) + r.Total.Importe = Round2(r.Total.Importe) + return r +} + +var sanitizeFileRe = regexp.MustCompile(`[^\w\s.\-]`) +var multiSpaceRe = regexp.MustCompile(`\s+`) + +func SanitizeFilename(name string) string { + s := sanitizeFileRe.ReplaceAllString(name, "") + s = multiSpaceRe.ReplaceAllString(s, " ") + return strings.TrimSpace(s) +} + +// FormatCurrency formats MXN like Intl.NumberFormat("es-MX", {style:"currency", currency:"MXN", minFrac:0, maxFrac:2}). +func FormatCurrency(amount float64) string { + return FormatMonto(amount, "MXN") +} + +// FormatMonto formats currency matching es-MX formatting: "$4,500", "$4,500.50", "US$25" / "USD 25". +func FormatMonto(amount float64, moneda string) string { + neg := amount < 0 + abs := math.Abs(amount) + rounded := Round2(abs) + intPart := int64(rounded) + fracPart := int(math.Round((rounded - float64(intPart)) * 100)) + if fracPart == 100 { + intPart++ + fracPart = 0 + } + + intStr := addCommas(intPart) + numStr := intStr + if fracPart > 0 { + numStr = fmt.Sprintf("%s.%02d", intStr, fracPart) + } + + prefix := "$" + if moneda != "" && !strings.EqualFold(moneda, "MXN") { + prefix = strings.ToUpper(moneda) + " " + } + if neg { + return "-" + prefix + numStr + } + return prefix + numStr +} + +func FormatDateLongMX(d time.Time) string { + return fmt.Sprintf("%02d de %s de %d", d.Day(), mesesLargo[int(d.Month())-1], d.Year()) +} + +func FormatDateShort(d time.Time) string { + return fmt.Sprintf("%02d/%02d/%04d", d.Day(), int(d.Month()), d.Year()) +} + +func addCommas(n int64) string { + s := strconv.FormatInt(n, 10) + if len(s) <= 3 { + return s + } + var out strings.Builder + rem := len(s) % 3 + if rem > 0 { + out.WriteString(s[:rem]) + if len(s) > rem { + out.WriteByte(',') + } + } + for i := rem; i < len(s); i += 3 { + if i > rem { + out.WriteByte(',') + } + out.WriteString(s[i : i+3]) + } + return out.String() +} + +func formatTrimFloat(f float64) string { + return strconv.FormatFloat(Round2(f), 'f', -1, 64) +} diff --git a/internal/domain/cobros_fechas.go b/internal/domain/cobros_fechas.go new file mode 100644 index 0000000..aa4e646 --- /dev/null +++ b/internal/domain/cobros_fechas.go @@ -0,0 +1,239 @@ +package domain + +import ( + "fmt" + "math" + "regexp" + "sort" + "strconv" + "strings" + "time" +) + +const ( + ZonaHoraria = "America/Mexico_City" + RecordatorioDiasDef = 3 + HoraRecordatorios = 9 + EstadoPagoPendiente = "pendiente" + EstadoPagoEnRevision = "en_revision" + EstadoPagoVerificado = "verificado" + EstadoPagoRechazado = "rechazado" + EstadoPagoAnulado = "anulado" +) + +var EstadosPorPagar = []string{EstadoPagoPendiente, EstadoPagoRechazado} + +func EsPorPagar(estado string) bool { + return estado == EstadoPagoPendiente || estado == EstadoPagoRechazado +} + +func mexicoLocation() *time.Location { + loc, err := time.LoadLocation(ZonaHoraria) + if err != nil { + // Mexico City has been permanently UTC-6 since 2022 (no DST). + return time.FixedZone("America/Mexico_City", -6*3600) + } + return loc +} + +var fechaISORe = regexp.MustCompile(`^(\d{4})-(\d{2})-(\d{2})$`) + +// ParseFechaCalendario parses "YYYY-MM-DD" into UTC midnight calendar date. +func ParseFechaCalendario(iso string) (time.Time, error) { + m := fechaISORe.FindStringSubmatch(strings.TrimSpace(iso)) + if m == nil { + return time.Time{}, fmt.Errorf("Fecha invalida: %s (se espera YYYY-MM-DD)", iso) + } + y, _ := strconv.Atoi(m[1]) + mo, _ := strconv.Atoi(m[2]) + d, _ := strconv.Atoi(m[3]) + return time.Date(y, time.Month(mo), d, 0, 0, 0, 0, time.UTC), nil +} + +// ACalendario extracts calendar (year, month, day) from UTC parts. +func ACalendario(t time.Time) (int, time.Month, int) { + u := t.UTC() + return u.Year(), u.Month(), u.Day() +} + +// CalendarioDe converts a real timestamp to its America/Mexico_City calendar date (UTC midnight). +func CalendarioDe(instante time.Time) time.Time { + mx := instante.In(mexicoLocation()) + return time.Date(mx.Year(), mx.Month(), mx.Day(), 0, 0, 0, 0, time.UTC) +} + +func HoyCalendario() time.Time { + return CalendarioDe(time.Now()) +} + +func HoraMexico(instante time.Time) int { + return instante.In(mexicoLocation()).Hour() +} + +// InstanteDePago returns noon in Mexico City (18:00 UTC) so CalendarioDe() maps back to the same day. +func InstanteDePago(fecha time.Time) time.Time { + y, m, d := ACalendario(fecha) + return time.Date(y, m, d, 18, 0, 0, 0, time.UTC) +} + +func SumarDias(d time.Time, dias int) time.Time { + return d.UTC().AddDate(0, 0, dias) +} + +func DiasDeAtraso(fecha, hoy time.Time) int { + diff := math.Round(hoy.UTC().Sub(fecha.UTC()).Hours() / 24.0) + if diff < 0 { + return 0 + } + return int(diff) +} + +func DiasHasta(fecha, hoy time.Time) int { + return int(math.Round(fecha.UTC().Sub(hoy.UTC()).Hours() / 24.0)) +} + +func DescribirVencimiento(fecha, hoy time.Time) string { + d := DiasHasta(fecha, hoy) + switch { + case d == 0: + return "vence hoy" + case d == 1: + return "mañana" + case d > 1: + return fmt.Sprintf("en %d días", d) + case d == -1: + return "hace 1 día" + default: + return fmt.Sprintf("hace %d días", -d) + } +} + +var diasSemanaLargo = []string{ + "Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", +} + +var diasSemanaCorto = []string{ + "dom", "lun", "mar", "mié", "jue", "vie", "sáb", +} + +var mesesCorto = []string{ + "ene", "feb", "mar", "abr", "may", "jun", + "jul", "ago", "sep", "oct", "nov", "dic", +} + +func FormatFechaCobro(date time.Time) string { + u := date.UTC() + return fmt.Sprintf("%s, %02d de %s de %d", diasSemanaLargo[int(u.Weekday())], u.Day(), mesesLargo[int(u.Month())-1], u.Year()) +} + +func FormatFechaBreve(date, hoy time.Time) string { + u := date.UTC() + anio := "" + if u.Year() != hoy.UTC().Year() { + anio = fmt.Sprintf(" %d", u.Year()) + } + return fmt.Sprintf("%s %d %s%s", diasSemanaCorto[int(u.Weekday())], u.Day(), mesesCorto[int(u.Month())-1], anio) +} + +func FormatFechaCorta(date time.Time) string { + y, m, d := ACalendario(date) + return fmt.Sprintf("%02d/%02d/%04d", d, int(m), y) +} + +func FormatTotales(totales map[string]float64) string { + if len(totales) == 0 { + return "$0" + } + keys := make([]string, 0, len(totales)) + for k := range totales { + keys = append(keys, k) + } + sort.Strings(keys) + partes := make([]string, 0, len(keys)) + for _, k := range keys { + partes = append(partes, FormatMonto(totales[k], k)) + } + return strings.Join(partes, " + ") +} + +type ProgramaCalendario struct { + Frecuencia string + DiaSemana *int + DiaMes *int + FechaInicio time.Time + FechaFin *time.Time +} + +func FechasPeriodo(p ProgramaCalendario, hasta time.Time) []time.Time { + iy, im, id := ACalendario(p.FechaInicio) + inicioD := time.Date(iy, im, id, 0, 0, 0, 0, time.UTC) + limite := hasta.UTC() + if p.FechaFin != nil { + fy, fm, fd := ACalendario(*p.FechaFin) + finD := time.Date(fy, fm, fd, 0, 0, 0, 0, time.UTC) + if finD.Before(limite) { + limite = finD + } + } + if inicioD.After(limite) { + return nil + } + + var out []time.Time + switch p.Frecuencia { + case "semanal": + dia := int(inicioD.Weekday()) + if p.DiaSemana != nil { + dia = *p.DiaSemana + } + d := inicioD + for guard := 0; int(d.Weekday()) != dia && guard < 7; guard++ { + d = SumarDias(d, 1) + } + for !d.After(limite) { + out = append(out, d) + d = SumarDias(d, 7) + } + case "quincenal": + mes := time.Date(inicioD.Year(), inicioD.Month(), 1, 0, 0, 0, 0, time.UTC) + for !mes.After(limite) { + for _, dia := range []int{1, 15} { + d := time.Date(mes.Year(), mes.Month(), dia, 0, 0, 0, 0, time.UTC) + if !d.Before(inicioD) && !d.After(limite) { + out = append(out, d) + } + } + mes = time.Date(mes.Year(), mes.Month()+1, 1, 0, 0, 0, 0, time.UTC) + } + default: // mensual + diaMes := 1 + if p.DiaMes != nil { + diaMes = *p.DiaMes + } + mes := time.Date(inicioD.Year(), inicioD.Month(), 1, 0, 0, 0, 0, time.UTC) + for !mes.After(limite) { + ultimoDia := time.Date(mes.Year(), mes.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day() + dia := diaMes + if dia > ultimoDia { + dia = ultimoDia + } + d := time.Date(mes.Year(), mes.Month(), dia, 0, 0, 0, 0, time.UTC) + if !d.Before(inicioD) && !d.After(limite) { + out = append(out, d) + } + mes = time.Date(mes.Year(), mes.Month()+1, 1, 0, 0, 0, 0, time.UTC) + } + } + return out +} + +func ProximaFecha(p ProgramaCalendario, desde time.Time) *time.Time { + ventana := FechasPeriodo(p, SumarDias(desde, 366)) + for _, f := range ventana { + if !f.Before(desde) { + v := f + return &v + } + } + return nil +} diff --git a/internal/domain/domain_test.go b/internal/domain/domain_test.go new file mode 100644 index 0000000..37294ea --- /dev/null +++ b/internal/domain/domain_test.go @@ -0,0 +1,187 @@ +package domain + +import ( + "testing" + "time" +) + +func floatPtr(v float64) *float64 { return &v } +func strPtr(v string) *string { return &v } + +func TestCalculatorsParity(t *testing.T) { + if IVARate != 0.16 { + t.Fatalf("expected IVARate 0.16, got %v", IVARate) + } + if len(EstadosCotizacion) != 6 { + t.Fatalf("expected 6 estados, got %d", len(EstadosCotizacion)) + } + + // Financing plans (3, 6, 9, 12 months) + cases := []struct { + meses int + tasa float64 + monto float64 + wantComision float64 + wantPagoMes float64 + wantTotalMes float64 + }{ + {3, 0.077, 10000, 250, 3679.75, 4268.51}, + {6, 0.107, 10000, 250, 1891.13, 2193.71}, + {9, 0.137, 10000, 250, 1294.92, 1502.1}, + {12, 0.167, 10000, 250, 996.81, 1156.3}, + } + for _, tc := range cases { + res := CalcularFinanciamiento(FinanciamientoInput{ + Monto: tc.monto, Meses: tc.meses, Tasa: tc.tasa, Comision: 2.5, IVA: 0.16, + }) + if res.ComisionTotal != tc.wantComision { + t.Errorf("%dm comisionTotal=%v want %v", tc.meses, res.ComisionTotal, tc.wantComision) + } + if res.PagoMensual != tc.wantPagoMes { + t.Errorf("%dm pagoMensual=%v want %v", tc.meses, res.PagoMensual, tc.wantPagoMes) + } + if res.TotalMensual != tc.wantTotalMes { + t.Errorf("%dm totalMensual=%v want %v", tc.meses, res.TotalMensual, tc.wantTotalMes) + } + } + + // Totales cotizacion with mixed models & unselected item + svcs := []ServicioCalc{ + {TipoPago: "unico", Precio: 15000, Seleccionado: true, ModeloCobro: "fijo"}, + {TipoPago: "mensual", Precio: 5000, Seleccionado: true, ModeloCobro: "retainer"}, + {TipoPago: "mensual", Precio: 0, Seleccionado: true, ModeloCobro: "demanda", TarifaHora: floatPtr(700)}, + {TipoPago: "unico", Precio: 99999, Seleccionado: false}, + } + totCon := CalcularTotalesCotizacion(svcs, true) + if totCon.SubtotalUnico != 15000 || totCon.SubtotalMensual != 5000 || totCon.TotalUnico != 17400 || totCon.TotalMensual != 5800 || totCon.TotalPrimerAnio != 87000 { + t.Fatalf("unexpected totCon: %+v", totCon) + } + totSin := CalcularTotalesCotizacion(svcs, false) + if totSin.IVAUnico != 0 || totSin.TotalUnico != 15000 || totSin.TotalPrimerAnio != 75000 { + t.Fatalf("unexpected totSin: %+v", totSin) + } + + // Doble propuesta option totals + doble := []ServicioCalc{ + {Opcion: strPtr("1"), TipoPago: "unico", Precio: 10000, Horas: floatPtr(10)}, + {Opcion: strPtr("2"), TipoPago: "unico", Precio: 20000, Horas: floatPtr(20)}, + {Opcion: strPtr("ambas"), TipoPago: "mensual", Precio: 3000, Horas: floatPtr(5)}, + } + op1 := CalcularTotalesOpcion(doble, "1") + op2 := CalcularTotalesOpcion(doble, "2") + if op1.TotalUnico != 10000 || op1.TotalMensual != 3000 || op1.Horas != 15 { + t.Fatalf("unexpected op1: %+v", op1) + } + if op2.TotalUnico != 20000 || op2.TotalMensual != 3000 || op2.Horas != 25 { + t.Fatalf("unexpected op2: %+v", op2) + } + + // 15 business days vigencia: Mon 2026-06-01 -> Mon 2026-06-22 + start := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC) + vig := CalcularVigencia(start) + if vig.Format("2006-01-02") != "2026-06-22" { + t.Fatalf("expected vigencia 2026-06-22, got %s", vig.Format("2006-01-02")) + } + + // Hours range & summary + if h := CalcularHorasRango("09:00", "13:30"); h != 4.5 { + t.Fatalf("expected 4.5 hours, got %v", h) + } + resH := CalcularResumenPagoHoras([]RegistroHorasCalc{ + {Horas: 2, TarifaHora: 700, EstadoPago: "por_pagar"}, + {Horas: 3, TarifaHora: 700, EstadoPago: "pagada"}, + }) + if resH.PorPagar.Importe != 1400 || resH.Pagada.Importe != 2100 || resH.Total.Importe != 3500 { + t.Fatalf("unexpected resumen horas: %+v", resH) + } +} + +func TestApprovalGuard(t *testing.T) { + now := time.Now() + agent := ActorInfo{Type: "agent", Scopes: []string{"cotizaciones:borrador", "cotizaciones:enviar"}} + asesor := ActorInfo{Type: "user", Role: "asesor"} + admin := ActorInfo{Type: "user", Role: "admin"} + enlace := ActorInfo{Type: "enlace_firmado"} + + // Agent cannot approve + if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "aprobada", Actor: agent, ViaEndpoint: "aprobar"}); r.OK || r.Status != 403 { + t.Fatalf("agent approval should be 403, got %+v", r) + } + // Asesor cannot approve + if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "aprobada", Actor: asesor, ViaEndpoint: "aprobar"}); r.OK || r.Status != 403 { + t.Fatalf("asesor approval should be 403, got %+v", r) + } + // Admin can approve borrador + if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "aprobada", Actor: admin, ViaEndpoint: "aprobar"}); !r.OK { + t.Fatalf("admin approval should succeed, got %+v", r) + } + // Signed link can approve borrador + if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "aprobada", Actor: enlace, ViaEndpoint: "enlace_firmado"}); !r.OK { + t.Fatalf("signed link approval should succeed, got %+v", r) + } + // Cannot send borrador + if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "borrador", Nuevo: "enviada", Actor: agent, ViaEndpoint: "enviar"}); r.OK || r.Status != 409 { + t.Fatalf("sending draft should be 409, got %+v", r) + } + // Agent cannot set enviada via PUT + if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "aprobada", Nuevo: "enviada", Actor: agent, ViaEndpoint: "put", AprobadaAt: &now}); r.OK || r.Status != 403 { + t.Fatalf("agent PUT enviada should be 403, got %+v", r) + } + // Agent can send approved quote via enviar + if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "aprobada", Nuevo: "enviada", Actor: agent, ViaEndpoint: "enviar", AprobadaAt: &now}); !r.OK { + t.Fatalf("agent enviar approved should succeed, got %+v", r) + } + // Agent cannot mark aceptada + if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "enviada", Nuevo: "aceptada", Actor: agent, ViaEndpoint: "estado"}); r.OK || r.Status != 403 { + t.Fatalf("agent aceptada should be 403, got %+v", r) + } + // Staff can mark aceptada + if r := ValidarTransicionEstado(ValidarTransicionInput{Actual: "enviada", Nuevo: "aceptada", Actor: asesor, ViaEndpoint: "estado"}); !r.OK { + t.Fatalf("asesor aceptada should succeed, got %+v", r) + } +} + +func TestSoloAdminRestriction(t *testing.T) { + soloIDs := map[string]struct{}{"plan-mensual-crm-bucefalo-18": {}} + + // Human admin allowed everything + r1 := EvaluarRestriccionSoloAdmin(EvaluarSoloAdminInput{ + EsAgente: false, + HasPlanBucefalo: true, + Servicios: []ServicioDraftInput{{CatalogoID: "plan-mensual-crm-bucefalo-18", Nombre: "CRM Bucéfalo"}}, + SoloAdminCatalogIDs: soloIDs, + }) + if !r1.OK { + t.Fatalf("human admin should not be blocked: %+v", r1) + } + + // Agent blocked on planBucefalo, soloAdmin ID, bucefalo-* prefix, and custom name + r2 := EvaluarRestriccionSoloAdmin(EvaluarSoloAdminInput{ + EsAgente: true, + HasPlanBucefalo: true, + Servicios: []ServicioDraftInput{ + {CatalogoID: "plan-mensual-crm-bucefalo-18"}, + {CatalogoID: "bucefalo-pro"}, + {Nombre: "Implementacion Bucéfalo Custom"}, + }, + SoloAdminCatalogIDs: soloIDs, + }) + if r2.OK || len(r2.ItemsBloqueados) != 4 { + t.Fatalf("expected 4 blocked items, got %+v", r2) + } +} + +func TestFechasPeriodo(t *testing.T) { + ini, _ := ParseFechaCalendario("2026-07-01") + fin, _ := ParseFechaCalendario("2026-07-31") + sab := 6 + fechas := FechasPeriodo(ProgramaCalendario{ + Frecuencia: "semanal", + DiaSemana: &sab, + FechaInicio: ini, + FechaFin: &fin, + }, fin) + if len(fechas) != 4 || FormatFechaCorta(fechas[0]) != "04/07/2026" { + t.Fatalf("expected 4 saturdays starting 04/07/2026, got %d (%v)", len(fechas), fechas) + } +} diff --git a/internal/domain/solo_admin_core.go b/internal/domain/solo_admin_core.go new file mode 100644 index 0000000..d3fc82f --- /dev/null +++ b/internal/domain/solo_admin_core.go @@ -0,0 +1,71 @@ +package domain + +import ( + "fmt" + "regexp" + "strings" +) + +type ServicioDraftInput struct { + CatalogoID string + Nombre string + EsPersonalizado bool +} + +type EvaluarSoloAdminInput struct { + EsAgente bool + HasPlanBucefalo bool + Servicios []ServicioDraftInput + SoloAdminCatalogIDs map[string]struct{} +} + +type EvaluarSoloAdminResult struct { + OK bool + Motivos []string + ItemsBloqueados []string +} + +var bucefaloRe = regexp.MustCompile(`(?i)buc[eé]falo`) +var bucefaloPrefixRe = regexp.MustCompile(`(?i)^bucefalo-`) + +func EvaluarRestriccionSoloAdmin(in EvaluarSoloAdminInput) EvaluarSoloAdminResult { + if !in.EsAgente { + return EvaluarSoloAdminResult{OK: true} + } + + var motivos []string + var bloqueados []string + + if in.HasPlanBucefalo { + motivos = append(motivos, "planBucefalo esta reservado al administrador humano") + bloqueados = append(bloqueados, "planBucefalo") + } + + for _, svc := range in.Servicios { + cid := strings.TrimSpace(svc.CatalogoID) + nombre := strings.TrimSpace(svc.Nombre) + + if cid != "" && bucefaloPrefixRe.MatchString(cid) { + motivos = append(motivos, fmt.Sprintf("catalogoId restringido (%s)", cid)) + bloqueados = append(bloqueados, cid) + continue + } + if cid != "" { + if _, ok := in.SoloAdminCatalogIDs[cid]; ok { + motivos = append(motivos, fmt.Sprintf("servicio marcado soloAdmin (%s)", cid)) + bloqueados = append(bloqueados, cid) + continue + } + } + if nombre != "" && bucefaloRe.MatchString(nombre) { + motivos = append(motivos, fmt.Sprintf("servicio restringido por marca soloAdmin (%s)", nombre)) + bloqueados = append(bloqueados, nombre) + } + } + + return EvaluarSoloAdminResult{ + OK: len(motivos) == 0, + Motivos: motivos, + ItemsBloqueados: bloqueados, + } +} diff --git a/internal/excel/catalogo_csv.go b/internal/excel/catalogo_csv.go new file mode 100644 index 0000000..a09576e --- /dev/null +++ b/internal/excel/catalogo_csv.go @@ -0,0 +1,253 @@ +package excel + +import ( + "bytes" + "encoding/csv" + "errors" + "fmt" + "io" + "math" + "strconv" + "strings" +) + +type CatalogoCSVRow struct { + Nombre string + Categoria string + Fase int + TipoPago string + PrecioBase float64 + TiempoEntrega string + Entregables []string + Variante string +} + +var fasesExportCSV = map[int]string{ + 0: "Auditoria", + 1: "Setup e Infraestructura", + 2: "Publicidad y Manejo", + 3: "Contenido y SEO", +} + +var fasesImportCSV = map[string]int{ + "0": 0, + "fase 0": 0, + "auditoria": 0, + "auditoría": 0, + "1": 1, + "fase 1": 1, + "setup e infraestructura": 1, + "setup": 1, + "infraestructura": 1, + "2": 2, + "fase 2": 2, + "publicidad y manejo": 2, + "publicidad": 2, + "manejo": 2, + "3": 3, + "fase 3": 3, + "contenido y seo": 3, + "contenido": 3, + "seo": 3, +} + +func ExportCatalogoCSV(rows []CatalogoCSVRow) ([]byte, error) { + var buf bytes.Buffer + w := csv.NewWriter(&buf) + + if err := w.Write([]string{ + "Nombre", + "Categoria", + "Fase", + "Tipo de Pago", + "Precio Base", + "Tiempo de Entrega", + "Entregables", + "Variante", + }); err != nil { + return nil, err + } + + for _, r := range rows { + faseLabel, ok := fasesExportCSV[r.Fase] + if !ok { + faseLabel = fmt.Sprintf("Fase %d", r.Fase) + } + tipoLabel := "Mensual" + if strings.EqualFold(strings.TrimSpace(r.TipoPago), "unico") { + tipoLabel = "Pago Unico" + } + rec := []string{ + r.Nombre, + r.Categoria, + faseLabel, + tipoLabel, + strconv.FormatFloat(r.PrecioBase, 'f', -1, 64), + r.TiempoEntrega, + strings.Join(r.Entregables, " | "), + r.Variante, + } + if err := w.Write(rec); err != nil { + return nil, err + } + } + + w.Flush() + if err := w.Error(); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func PlantillaCatalogoCSV() []byte { + const tpl = `Nombre,Categoria,Fase,Tipo de Pago,Precio Base,Tiempo de Entrega,Entregables,Variante +"SEO On-Page Basico","SEO","Setup e Infraestructura","unico",5000,"7 - 14 dias","Auditoria SEO | Optimizacion de meta tags | Mapa del sitio", +"Manejo de Redes Sociales","Marketing","Publicidad y Manejo","mensual",8000,"Mensual","Publicaciones semanales | Reporte mensual | Gestion de comunidad","Basico" +"Gestion de Google Ads","Paid Media","Publicidad y Manejo","mensual",5000,"Mensual","Configuracion de campanas | Reporte semanal", +"Sitio Web Informativo","Desarrollo Web","Setup e Infraestructura","unico",15000,"15 - 30 dias","Diseno responsivo | Hasta 5 secciones | Formulario de contacto", +"Automatizacion Email Marketing","Automatizaciones","Publicidad y Manejo","unico",8000,"10 - 15 dias","Configuracion de flujos | Plantillas de correo | Integracion CRM", +"CRM Basico","CRM","Publicidad y Manejo","mensual",1000,"Mensual","CRM completo segun plan contratado","basico" + +,,,, +"CATEGORIAS DISPONIBLES: SEO / Marketing / Paid Media / Desarrollo Web / Automatizaciones / CRM",,,,, +"FASES: Auditoria / Setup e Infraestructura / Publicidad y Manejo / Contenido y SEO",,,,, +"TIPOS DE PAGO: unico / mensual",,,,, +"ENTREGABLES: separar con | (pipe)",,,,, +"VARIANTE: opcional (ej: Basico, Estandar, Premium)",,,,, +` + return []byte(tpl) +} + +func isInstructionLine(line string) bool { + trimmed := strings.TrimSpace(line) + if trimmed == "" { + return true + } + unquoted := strings.ToUpper(strings.TrimPrefix(trimmed, `"`)) + for _, prefix := range []string{ + "CATEGORIAS", + "CATEGORÍAS", + "FASES:", + "TIPOS DE PAGO", + "TIPOS", + "ENTREGABLES:", + "VARIANTE:", + } { + if strings.HasPrefix(unquoted, prefix) { + return true + } + } + return false +} + +func ParseCatalogoCSV(raw []byte) ([]CatalogoCSVRow, error) { + // Strip UTF-8 BOM if present. + raw = bytes.TrimPrefix(raw, []byte{0xEF, 0xBB, 0xBF}) + + text := strings.ReplaceAll(string(raw), "\r\n", "\n") + rawLines := strings.Split(text, "\n") + var kept []string + for _, l := range rawLines { + if isInstructionLine(l) { + continue + } + kept = append(kept, l) + } + if len(kept) < 2 { + return nil, errors.New("el CSV esta vacio o no tiene datos") + } + + r := csv.NewReader(strings.NewReader(strings.Join(kept, "\n"))) + r.FieldsPerRecord = -1 + r.LazyQuotes = true + r.TrimLeadingSpace = true + + // Skip header row. + if _, err := r.Read(); err != nil { + return nil, fmt.Errorf("error leyendo encabezado CSV: %w", err) + } + + var rows []CatalogoCSVRow + for { + rec, err := r.Read() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return nil, fmt.Errorf("error leyendo CSV: %w", err) + } + if len(rec) < 5 { + continue + } + + get := func(i int) string { + if i >= len(rec) { + return "" + } + return strings.TrimSpace(rec[i]) + } + + nombre := get(0) + categoria := get(1) + faseStr := strings.ToLower(get(2)) + tipoStr := strings.ToLower(get(3)) + precioStr := get(4) + tiempoEntrega := get(5) + entregablesStr := get(6) + variante := get(7) + + if nombre == "" || categoria == "" || tipoStr == "" || precioStr == "" { + continue + } + + fase, ok := fasesImportCSV[faseStr] + if !ok { + continue + } + + var tipoPago string + switch tipoStr { + case "unico", "único", "pago unico", "pago único": + tipoPago = "unico" + case "mensual": + tipoPago = "mensual" + default: + continue + } + + cleanedPrecio := strings.NewReplacer("$", "", ",", "", " ", "").Replace(precioStr) + precioBase, err := strconv.ParseFloat(cleanedPrecio, 64) + if err != nil || math.IsNaN(precioBase) || math.IsInf(precioBase, 0) || precioBase < 0 { + continue + } + + if tiempoEntrega == "" { + tiempoEntrega = "7 - 14 dias" + } + + var entregables []string + if entregablesStr != "" { + for _, part := range strings.Split(entregablesStr, "|") { + if p := strings.TrimSpace(part); p != "" { + entregables = append(entregables, p) + } + } + } + + rows = append(rows, CatalogoCSVRow{ + Nombre: nombre, + Categoria: categoria, + Fase: fase, + TipoPago: tipoPago, + PrecioBase: precioBase, + TiempoEntrega: tiempoEntrega, + Entregables: entregables, + Variante: variante, + }) + } + + if len(rows) == 0 { + return nil, errors.New("no se encontraron filas validas. Verifica el formato del CSV") + } + return rows, nil +} diff --git a/internal/excel/cotizacion.go b/internal/excel/cotizacion.go new file mode 100644 index 0000000..5f535a1 --- /dev/null +++ b/internal/excel/cotizacion.go @@ -0,0 +1,769 @@ +package excel + +import ( + "fmt" + "math" + "regexp" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/xuri/excelize/v2" + + "cotizador/internal/domain" +) + +type ServicioExcel struct { + Nombre string + Fase int + TipoPago string + Precio float64 + TiempoEntrega string + Entregables []string + EsPersonalizado bool + Horas *float64 + TarifaHora *float64 + ModeloCobro string + MontoMinimo *float64 + HorasIncluidas *float64 + Opcion *string +} + +// CotizacionExcelData holds client-facing quotation data for Excel export. +// ObservacionesInternas is intentionally NOT declared here so internal notes +// can never leak into a client workbook. +type CotizacionExcelData struct { + RazonSocial string + DomicilioFiscal string + Numero string + ClienteNombre string + ClienteEmpresa string + AsesorNombre string + Fecha time.Time + Vigencia time.Time + Moneda string + TipoCambio string + Proyecto string + EsquemaPago string + Servicios []ServicioExcel + EsDoble bool + OpcionesMetadata map[string]domain.MetaOpcion + PlanBucefaloNivel *string + PlanBucefaloPrecio *float64 + ColorPrimario string + ColorSecundario string + IncluirIVA bool + Observaciones *string +} + +var ( + hexRe = regexp.MustCompile(`^#?[0-9a-fA-F]{6}$`) + invalidTabRe = regexp.MustCompile(`[/\\*?\[\]:]`) + fasesExcelMap = map[int]string{ + 0: "FASE 0", + 1: "FASE 1", + 2: "FASE 2", + 3: "FASE 3", + } +) + +func cleanHex(v, fallback string) string { + v = strings.TrimSpace(v) + if !hexRe.MatchString(v) { + v = fallback + } + return strings.ToUpper(strings.TrimPrefix(v, "#")) +} + +// tintLight blends ~10% of hex color onto white (#FFFFFF) for crisp light fills in Excel. +func tintLight(hex6 string) string { + r, _ := strconv.ParseInt(hex6[0:2], 16, 64) + g, _ := strconv.ParseInt(hex6[2:4], 16, 64) + b, _ := strconv.ParseInt(hex6[4:6], 16, 64) + blend := func(c int64) int64 { + return int64(math.Round(float64(c)*0.10 + 255.0*0.90)) + } + return fmt.Sprintf("%02X%02X%02X", blend(r), blend(g), blend(b)) +} + +func capitalize(s string) string { + s = strings.TrimSpace(s) + if s == "" { + return "" + } + r := []rune(s) + r[0] = unicode.ToUpper(r[0]) + return string(r) +} + +func servicioExcelToCalc(s ServicioExcel) domain.ServicioCalc { + return domain.ServicioCalc{ + Nombre: s.Nombre, + ModeloCobro: s.ModeloCobro, + EsPersonalizado: s.EsPersonalizado, + Horas: s.Horas, + TarifaHora: s.TarifaHora, + MontoMinimo: s.MontoMinimo, + HorasIncluidas: s.HorasIncluidas, + Opcion: s.Opcion, + TipoPago: s.TipoPago, + Precio: s.Precio, + Seleccionado: true, + } +} + +func serviciosExcelToCalc(list []ServicioExcel) []domain.ServicioCalc { + out := make([]domain.ServicioCalc, len(list)) + for i, s := range list { + out[i] = servicioExcelToCalc(s) + } + return out +} + +func estimateRowHeight(text string, widthChars float64, fontSize float64) float64 { + cpl := int(math.Floor(widthChars)) + if cpl < 8 { + cpl = 8 + } + lineH := 14.0 + switch { + case fontSize <= 10: + lineH = 14 + case fontSize <= 11: + lineH = 15.5 + case fontSize <= 12: + lineH = 17 + default: + lineH = 20 + } + lines := 0 + for _, seg := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") { + n := utf8.RuneCountInString(seg) + l := int(math.Ceil(float64(n) / float64(cpl))) + if l < 1 { + l = 1 + } + lines += l + } + h := math.Round(float64(lines)*lineH + 4) + if h < 16 { + return 16 + } + return h +} + +func sanitizeSheetName(name string, used map[string]bool) string { + cleaned := strings.TrimSpace(invalidTabRe.ReplaceAllString(name, "")) + cleaned = strings.Trim(cleaned, "'") + if cleaned == "" { + cleaned = "Servicio" + } + runes := []rune(cleaned) + if len(runes) > 31 { + runes = runes[:31] + } + base := string(runes) + candidate := base + n := 2 + for used[strings.ToLower(candidate)] { + suffix := fmt.Sprintf(" (%d)", n) + maxBase := 31 - utf8.RuneCountInString(suffix) + br := []rune(base) + if len(br) > maxBase { + br = br[:maxBase] + } + candidate = string(br) + suffix + n++ + } + used[strings.ToLower(candidate)] = true + return candidate +} + +type styleSpec struct { + bold bool + italic bool + size float64 + fontColor string + fillColor string + borderClr string + horiz string + vert string + wrap bool + numFmt string +} + +type wbHelper struct { + f *excelize.File + styles map[styleSpec]int +} + +func newWBHelper() *wbHelper { + return &wbHelper{ + f: excelize.NewFile(), + styles: make(map[styleSpec]int), + } +} + +func (h *wbHelper) styleID(s styleSpec) int { + if id, ok := h.styles[s]; ok { + return id + } + size := s.size + if size <= 0 { + size = 10 + } + st := &excelize.Style{ + Font: &excelize.Font{ + Family: "Calibri", + Size: size, + Bold: s.bold, + Italic: s.italic, + Color: s.fontColor, + }, + Alignment: &excelize.Alignment{ + Horizontal: s.horiz, + Vertical: s.vert, + WrapText: s.wrap, + }, + } + if s.fillColor != "" { + st.Fill = excelize.Fill{ + Type: "pattern", + Pattern: 1, + Color: []string{s.fillColor}, + } + } + if s.borderClr != "" { + st.Border = []excelize.Border{ + {Type: "top", Color: s.borderClr, Style: 1}, + {Type: "bottom", Color: s.borderClr, Style: 1}, + {Type: "left", Color: s.borderClr, Style: 1}, + {Type: "right", Color: s.borderClr, Style: 1}, + } + } + if s.numFmt != "" { + nf := s.numFmt + st.CustomNumFmt = &nf + } + id, err := h.f.NewStyle(st) + if err != nil { + return 0 + } + h.styles[s] = id + return id +} + +func (h *wbHelper) hideGrid(sheet string) { + show := false + _ = h.f.SetSheetView(sheet, 0, &excelize.ViewOptions{ShowGridLines: &show}) +} + +func (h *wbHelper) setColWidths(sheet string, widths map[string]float64) { + for col, w := range widths { + _ = h.f.SetColWidth(sheet, col, col, w) + } +} + +func (h *wbHelper) ensureRowHeight(sheet string, row int, minH float64) { + cur, _ := h.f.GetRowHeight(sheet, row) + if cur < minH { + _ = h.f.SetRowHeight(sheet, row, minH) + } +} + +func sumWidths(widths map[string]float64, cols ...string) float64 { + total := 0.0 + for _, c := range cols { + if w, ok := widths[c]; ok { + total += w + } else { + total += 8 + } + } + return total +} + +func BuildCotizacionExcel(data CotizacionExcelData) ([]byte, error) { + primary := cleanHex(data.ColorPrimario, "0400C4") + primaryLight := tintLight(primary) + secondary := cleanHex(data.ColorSecundario, "0F172A") + white := "FFFFFF" + lightBG := "F8FAFC" + muted := "64748B" + borderColor := "E2E8F0" + + wb := newWBHelper() + defer wb.f.Close() + + _ = wb.f.SetDocProps(&excelize.DocProperties{ + Creator: "Cotizador — Uriel Jareth Consulting", + Created: time.Now().UTC().Format(time.RFC3339), + }) + + const resumenSheet = "HOJA RESUMEN" + _ = wb.f.SetSheetName("Sheet1", resumenSheet) + resumenWidths := map[string]float64{ + "A": 3, "B": 18, "C": 26, "D": 13, "E": 16, "F": 22, + "G": 6, "H": 6, "I": 6, "J": 6, "K": 16, + } + wb.setColWidths(resumenSheet, resumenWidths) + wb.hideGrid(resumenSheet) + + // Common styles. + stBanner1 := wb.styleID(styleSpec{bold: true, size: 16, fontColor: white, fillColor: primary, vert: "center"}) + stBanner2 := wb.styleID(styleSpec{bold: true, size: 11, fontColor: white, fillColor: secondary, vert: "center"}) + stLabel := wb.styleID(styleSpec{bold: true, size: 10, fontColor: muted, vert: "top"}) + stValueWrap := wb.styleID(styleSpec{size: 10, vert: "top", wrap: true}) + stDate := wb.styleID(styleSpec{size: 10, vert: "top", numFmt: "DD/MM/YYYY"}) + stHeaderL := wb.styleID(styleSpec{bold: true, size: 10, fontColor: white, fillColor: primary, borderClr: primary, horiz: "left", vert: "center"}) + stHeaderR := wb.styleID(styleSpec{bold: true, size: 10, fontColor: white, fillColor: primary, borderClr: primary, horiz: "right", vert: "center"}) + stFase := wb.styleID(styleSpec{bold: true, size: 11, fontColor: primary, fillColor: primaryLight, vert: "center"}) + stSmall := wb.styleID(styleSpec{italic: true, size: 9, fontColor: muted, vert: "top", wrap: true}) + stIvaNote := wb.styleID(styleSpec{size: 9, fontColor: muted}) + stObsTitle := wb.styleID(styleSpec{bold: true, size: 10, fontColor: primary}) + stOpBanner := wb.styleID(styleSpec{bold: true, size: 12, fontColor: white, fillColor: secondary, vert: "center"}) + stCompBanner := wb.styleID(styleSpec{bold: true, size: 12, fontColor: white, fillColor: primary, vert: "center"}) + + // ── Banner ── + _ = wb.f.MergeCell(resumenSheet, "B2", "K2") + _ = wb.f.SetCellValue(resumenSheet, "B2", data.RazonSocial) + _ = wb.f.SetCellStyle(resumenSheet, "A2", "K2", stBanner1) + _ = wb.f.SetRowHeight(resumenSheet, 2, 28) + + _ = wb.f.MergeCell(resumenSheet, "B3", "K3") + _ = wb.f.SetCellValue(resumenSheet, "B3", data.Numero) + _ = wb.f.SetCellStyle(resumenSheet, "A3", "K3", stBanner2) + _ = wb.f.SetRowHeight(resumenSheet, 3, 20) + + // ── Info cliente / proyecto ── + infoStart := 5 + empresa := data.ClienteEmpresa + if strings.TrimSpace(empresa) == "" { + empresa = "—" + } + type infoPair struct{ l1, v1, l2, v2 string } + infoRows := []infoPair{ + {"En atención a:", data.ClienteNombre, "Empresa:", empresa}, + {"Proyecto:", data.Proyecto, "Moneda:", data.Moneda}, + {"Asesor:", data.AsesorNombre, "Tipo de Cambio:", data.TipoCambio}, + {"Fecha:", "", "Esquema de Pago:", data.EsquemaPago}, + } + for i, ip := range infoRows { + r := infoStart + i + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", r), ip.l1) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel) + if ip.v1 != "" { + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", r), ip.v1) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("C%d", r), fmt.Sprintf("C%d", r), stValueWrap) + wb.ensureRowHeight(resumenSheet, r, estimateRowHeight(ip.v1, resumenWidths["C"], 10)) + } + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("E%d", r), ip.l2) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("E%d", r), fmt.Sprintf("E%d", r), stLabel) + if ip.v2 != "" { + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("F%d", r), ip.v2) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("F%d", r), fmt.Sprintf("F%d", r), stValueWrap) + wb.ensureRowHeight(resumenSheet, r, estimateRowHeight(ip.v2, resumenWidths["F"], 10)) + } + } + + if !data.Fecha.IsZero() { + fUTC := time.Date(data.Fecha.Year(), data.Fecha.Month(), data.Fecha.Day(), 0, 0, 0, 0, time.UTC) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", infoStart+3), fUTC) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("C%d", infoStart+3), fmt.Sprintf("C%d", infoStart+3), stDate) + } + + vigRow := infoStart + 4 + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", vigRow), "Vigencia:") + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", vigRow), fmt.Sprintf("B%d", vigRow), stLabel) + if !data.Vigencia.IsZero() { + vUTC := time.Date(data.Vigencia.Year(), data.Vigencia.Month(), data.Vigencia.Day(), 0, 0, 0, 0, time.UTC) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", vigRow), vUTC) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("C%d", vigRow), fmt.Sprintf("C%d", vigRow), stDate) + } + + // ── Tabla de servicios ── + tableStart := infoStart + 6 + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("D%d", tableStart), fmt.Sprintf("J%d", tableStart)) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", tableStart), fmt.Sprintf("J%d", tableStart), stHeaderL) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("K%d", tableStart), fmt.Sprintf("K%d", tableStart), stHeaderR) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", tableStart), "Fase") + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", tableStart), "Tipo de Pago") + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("D%d", tableStart), "Servicio") + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("K%d", tableStart), "Precio") + _ = wb.f.SetRowHeight(resumenSheet, tableStart, 24) + + var unicos, mensuales []ServicioExcel + for _, s := range data.Servicios { + if s.TipoPago == "mensual" { + mensuales = append(mensuales, s) + } else { + unicos = append(unicos, s) + } + } + + servWidth := sumWidths(resumenWidths, "D", "E", "F", "G", "H", "I", "J") + fullWidth := sumWidths(resumenWidths, "B", "C", "D", "E", "F", "G", "H", "I", "J", "K") + row := tableStart + 1 + + writeTotalRow := func(label string, amount float64, fontSize float64) { + stLbl := wb.styleID(styleSpec{bold: true, size: fontSize, fillColor: primaryLight, borderClr: primary, horiz: "left", vert: "center"}) + stAmt := wb.styleID(styleSpec{bold: true, size: fontSize, fillColor: primaryLight, borderClr: primary, horiz: "right", vert: "center", numFmt: "$#,##0.00"}) + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row)) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), label) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row), stLbl) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("K%d", row), amount) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("K%d", row), fmt.Sprintf("K%d", row), stAmt) + _ = wb.f.SetRowHeight(resumenSheet, row, 20) + row++ + } + + writeIvaNote := func() { + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row)) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), "(+ IVA)") + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("J%d", row), stIvaNote) + row++ + } + + drawServiceRows := func(servs []ServicioExcel) { + currentFase := -1 + for _, serv := range servs { + if serv.Fase != currentFase { + currentFase = serv.Fase + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) + fLbl := fasesExcelMap[serv.Fase] + if fLbl == "" { + fLbl = fmt.Sprintf("FASE %d", serv.Fase) + } + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), fLbl) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stFase) + _ = wb.f.SetRowHeight(resumenSheet, row, 20) + row++ + } + bg := white + if row%2 == 0 { + bg = lightBG + } + stCell := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "left", vert: "top"}) + stCellWrap := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "left", vert: "top", wrap: true}) + stPrice := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "right", vert: "top", numFmt: "$#,##0.00"}) + + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("D%d", row), fmt.Sprintf("J%d", row)) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("C%d", row), stCell) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("D%d", row), fmt.Sprintf("J%d", row), stCellWrap) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("K%d", row), fmt.Sprintf("K%d", row), stPrice) + + tipo := "Único" + if serv.TipoPago == "mensual" { + tipo = "Mensual" + } + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("C%d", row), tipo) + + detalle := domain.DetalleModelo(servicioExcelToCalc(serv)) + servText := serv.Nombre + if detalle != "" { + servText = fmt.Sprintf("%s — %s", serv.Nombre, detalle) + } + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("D%d", row), servText) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("K%d", row), serv.Precio) + wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(servText, servWidth, 10)) + row++ + } + } + + writeOpcionBanner := func(op string) { + meta := data.OpcionesMetadata[op] + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) + tit := "OPCIÓN " + op + if strings.TrimSpace(meta.Titulo) != "" { + tit += ": " + meta.Titulo + } + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), tit) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stOpBanner) + _ = wb.f.SetRowHeight(resumenSheet, row, 22) + row++ + if strings.TrimSpace(meta.Descripcion) != "" { + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), meta.Descripcion) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stValueWrap) + wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(meta.Descripcion, fullWidth, 10)) + row++ + } + if strings.TrimSpace(meta.NoIncluye) != "" { + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) + txt := "No incluye: " + meta.NoIncluye + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), txt) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stSmall) + wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(txt, fullWidth, 9)) + row++ + } + } + + sumPrices := func(list []ServicioExcel) float64 { + tot := 0.0 + for _, s := range list { + tot += s.Precio + } + return domain.Round2(tot) + } + + if data.EsDoble { + filterOp := func(list []ServicioExcel, op string) []ServicioExcel { + var out []ServicioExcel + for _, s := range list { + if s.Opcion != nil && (*s.Opcion == op || *s.Opcion == "ambas") { + out = append(out, s) + } + } + return out + } + + for _, op := range []string{"1", "2"} { + u := filterOp(unicos, op) + me := filterOp(mensuales, op) + writeOpcionBanner(op) + combined := make([]ServicioExcel, 0, len(u)+len(me)) + combined = append(combined, u...) + combined = append(combined, me...) + drawServiceRows(combined) + row++ + writeTotalRow(fmt.Sprintf("Total Pago Único - Opción %s", op), sumPrices(u), 11) + writeIvaNote() + writeTotalRow(fmt.Sprintf("Total Pago Mensual - Opción %s", op), sumPrices(me), 11) + writeIvaNote() + row++ + } + + calcs := serviciosExcelToCalc(data.Servicios) + t1 := domain.CalcularTotalesOpcion(calcs, "1") + t2 := domain.CalcularTotalesOpcion(calcs, "2") + + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), "COMPARATIVA DE OPCIONES") + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stCompBanner) + _ = wb.f.SetRowHeight(resumenSheet, row, 22) + row++ + + compRow := func(lab, v1, v2 string, bold bool) { + stL := wb.styleID(styleSpec{bold: bold, size: 10, borderClr: borderColor, horiz: "left", vert: "center"}) + stR := wb.styleID(styleSpec{bold: bold, size: 10, borderClr: borderColor, horiz: "right", vert: "center"}) + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("F%d", row)) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), lab) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("F%d", row), stL) + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("G%d", row), fmt.Sprintf("H%d", row)) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("G%d", row), v1) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("G%d", row), fmt.Sprintf("H%d", row), stR) + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("I%d", row), fmt.Sprintf("K%d", row)) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("I%d", row), v2) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("I%d", row), fmt.Sprintf("K%d", row), stR) + row++ + } + + t1Tit := data.OpcionesMetadata["1"].Titulo + t2Tit := data.OpcionesMetadata["2"].Titulo + op1Lbl := "Opción 1" + if t1Tit != "" { + op1Lbl += " - " + t1Tit + } + op2Lbl := "Opción 2" + if t2Tit != "" { + op2Lbl += " - " + t2Tit + } + compRow("Concepto", op1Lbl, op2Lbl, true) + ivaLbl := "" + if data.IncluirIVA { + ivaLbl = " (c/IVA)" + } + compRow("Total único"+ivaLbl, domain.FormatCurrency(domain.ConIVA(t1.TotalUnico, data.IncluirIVA)), domain.FormatCurrency(domain.ConIVA(t2.TotalUnico, data.IncluirIVA)), false) + compRow("Total mensual"+ivaLbl, domain.FormatCurrency(domain.ConIVA(t1.TotalMensual, data.IncluirIVA)), domain.FormatCurrency(domain.ConIVA(t2.TotalMensual, data.IncluirIVA)), false) + compRow("Horas estimadas", fmt.Sprintf("%g h", t1.Horas), fmt.Sprintf("%g h", t2.Horas), false) + row++ + } else { + combined := make([]ServicioExcel, 0, len(unicos)+len(mensuales)) + combined = append(combined, unicos...) + combined = append(combined, mensuales...) + drawServiceRows(combined) + row++ + writeTotalRow("Total Pago Único", sumPrices(unicos), 11) + writeIvaNote() + writeTotalRow("Total Pago Mensual", sumPrices(mensuales), 11) + writeIvaNote() + row++ + } + + if data.PlanBucefaloNivel != nil && strings.TrimSpace(*data.PlanBucefaloNivel) != "" { + nivel := strings.TrimSpace(*data.PlanBucefaloNivel) + precio := domain.BucefaloPrecio(strings.ToLower(nivel)) + if data.PlanBucefaloPrecio != nil { + precio = *data.PlanBucefaloPrecio + } + writeTotalRow("CRM Bucéfalo - "+capitalize(nivel), precio, 10) + row++ + } + + notaResumen := "Todos los precios son en Moneda Nacional (MX), los precios no incluyen IVA. Vigencia de 15 días hábiles." + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), notaResumen) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stSmall) + wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(notaResumen, fullWidth, 9)) + + // Observaciones del cliente (solo cliente, nunca observaciones internas). + if data.Observaciones != nil && strings.TrimSpace(*data.Observaciones) != "" { + row += 2 + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), "OBSERVACIONES") + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stObsTitle) + row++ + texto := strings.TrimSpace(*data.Observaciones) + _ = wb.f.MergeCell(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row)) + _ = wb.f.SetCellValue(resumenSheet, fmt.Sprintf("B%d", row), texto) + _ = wb.f.SetCellStyle(resumenSheet, fmt.Sprintf("B%d", row), fmt.Sprintf("K%d", row), stSmall) + wb.ensureRowHeight(resumenSheet, row, estimateRowHeight(texto, fullWidth, 9)) + } + + // ═══════════════════════════════════════════════════════════════════════════ + // HOJAS DETALLADAS POR SERVICIO + // ═══════════════════════════════════════════════════════════════════════════ + usedNames := map[string]bool{ + strings.ToLower(resumenSheet): true, + } + detailWidths := map[string]float64{ + "A": 3, "B": 16, "C": 30, "D": 8, "E": 4, + "F": 18, "G": 22, "H": 6, "I": 6, "J": 16, + } + stDetBanner := wb.styleID(styleSpec{bold: true, size: 14, fontColor: white, fillColor: primary, vert: "center", wrap: true}) + stBoldWrap := wb.styleID(styleSpec{bold: true, size: 10, vert: "top", wrap: true}) + stServTit := wb.styleID(styleSpec{bold: true, size: 12, fontColor: primary, vert: "top", wrap: true}) + stEntHead := wb.styleID(styleSpec{bold: true, size: 10, fontColor: white, fillColor: primary, vert: "center"}) + stTotLbl := wb.styleID(styleSpec{bold: true, size: 11, fillColor: primaryLight, borderClr: primary, horiz: "left", vert: "center"}) + stTotVal := wb.styleID(styleSpec{bold: true, size: 11, fillColor: primaryLight, borderClr: primary, horiz: "right", vert: "center", numFmt: "$#,##0.00"}) + stRazon := wb.styleID(styleSpec{bold: true, size: 10, fontColor: primary}) + + for _, serv := range data.Servicios { + tabName := sanitizeSheetName(serv.Nombre, usedNames) + _, _ = wb.f.NewSheet(tabName) + wb.setColWidths(tabName, detailWidths) + wb.hideGrid(tabName) + + fLbl := fasesExcelMap[serv.Fase] + if fLbl == "" { + fLbl = fmt.Sprintf("FASE %d", serv.Fase) + } + bannerText := fmt.Sprintf("%s — %s", fLbl, serv.Nombre) + _ = wb.f.MergeCell(tabName, "B1", "J1") + _ = wb.f.SetCellValue(tabName, "B1", bannerText) + _ = wb.f.SetCellStyle(tabName, "A1", "J1", stDetBanner) + bh := estimateRowHeight(bannerText, sumWidths(detailWidths, "B", "C", "D", "E", "F", "G", "H", "I", "J"), 14) + if bh < 30 { + bh = 30 + } + _ = wb.f.SetRowHeight(tabName, 1, bh) + + cValW := sumWidths(detailWidths, "C", "D") + gValW := sumWidths(detailWidths, "G", "H") + entW := sumWidths(detailWidths, "B", "C", "D", "E", "F", "G", "H", "I", "J") + + r := 3 + clienteDisp := data.ClienteEmpresa + if strings.TrimSpace(clienteDisp) == "" { + clienteDisp = data.ClienteNombre + } + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Cliente:") + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel) + _ = wb.f.MergeCell(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r)) + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("C%d", r), clienteDisp) + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r), stBoldWrap) + wb.ensureRowHeight(tabName, r, estimateRowHeight(clienteDisp, cValW, 10)) + + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("F%d", r), "No. Cotización:") + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("F%d", r), fmt.Sprintf("F%d", r), stLabel) + _ = wb.f.MergeCell(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r)) + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("G%d", r), data.Numero) + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r), stBoldWrap) + r += 2 + + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Servicio:") + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel) + _ = wb.f.MergeCell(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r)) + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("C%d", r), serv.Nombre) + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("D%d", r), stServTit) + wb.ensureRowHeight(tabName, r, estimateRowHeight(serv.Nombre, cValW, 12)) + + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("F%d", r), "Tiempo de Entrega:") + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("F%d", r), fmt.Sprintf("F%d", r), stLabel) + _ = wb.f.MergeCell(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r)) + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("G%d", r), serv.TiempoEntrega) + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("G%d", r), fmt.Sprintf("H%d", r), stValueWrap) + wb.ensureRowHeight(tabName, r, estimateRowHeight(serv.TiempoEntrega, gValW, 10)) + r += 2 + + detalleServ := domain.DetalleModelo(servicioExcelToCalc(serv)) + if detalleServ != "" { + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Detalle:") + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stLabel) + _ = wb.f.MergeCell(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("J%d", r)) + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("C%d", r), detalleServ) + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("C%d", r), fmt.Sprintf("J%d", r), stValueWrap) + wb.ensureRowHeight(tabName, r, estimateRowHeight(detalleServ, sumWidths(detailWidths, "C", "D", "E", "F", "G", "H", "I", "J"), 10)) + r += 2 + } + + // Entregables header + _ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r)) + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Entregables") + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r), stEntHead) + _ = wb.f.SetRowHeight(tabName, r, 22) + r++ + + for i, ent := range serv.Entregables { + er := r + i + bg := white + if i%2 == 1 { + bg = lightBG + } + stEnt := wb.styleID(styleSpec{size: 10, fillColor: bg, borderClr: borderColor, horiz: "left", vert: "top", wrap: true}) + txt := fmt.Sprintf("%d. %s", i+1, ent) + _ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", er), fmt.Sprintf("J%d", er)) + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", er), txt) + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", er), fmt.Sprintf("J%d", er), stEnt) + wb.ensureRowHeight(tabName, er, estimateRowHeight(txt, entW, 10)) + } + r += len(serv.Entregables) + 1 + + tipoTot := "Único" + if serv.TipoPago == "mensual" { + tipoTot = "Mensual" + } + _ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("H%d", r)) + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "Total Pago "+tipoTot) + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("H%d", r), stTotLbl) + _ = wb.f.MergeCell(tabName, fmt.Sprintf("I%d", r), fmt.Sprintf("J%d", r)) + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("I%d", r), serv.Precio) + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("I%d", r), fmt.Sprintf("J%d", r), stTotVal) + _ = wb.f.SetRowHeight(tabName, r, 20) + r++ + + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), "(+ IVA)") + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("B%d", r), stIvaNote) + r += 2 + + notaDetalle := "Esta cotización tiene una vigencia de 15 días hábiles. Todos los precios en MXN, precios + IVA." + _ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r)) + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), notaDetalle) + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r), stSmall) + wb.ensureRowHeight(tabName, r, estimateRowHeight(notaDetalle, entW, 9)) + r += 2 + + // Brand decision: never print domicilio fiscal in generated documents. + _ = wb.f.MergeCell(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r)) + _ = wb.f.SetCellValue(tabName, fmt.Sprintf("B%d", r), data.RazonSocial) + _ = wb.f.SetCellStyle(tabName, fmt.Sprintf("B%d", r), fmt.Sprintf("J%d", r), stRazon) + } + + buf, err := wb.f.WriteToBuffer() + if err != nil { + return nil, err + } + return buf.Bytes(), nil +} diff --git a/internal/excel/excel_test.go b/internal/excel/excel_test.go new file mode 100644 index 0000000..b285541 --- /dev/null +++ b/internal/excel/excel_test.go @@ -0,0 +1,276 @@ +package excel + +import ( + "bytes" + "reflect" + "strings" + "testing" + "time" + + "github.com/xuri/excelize/v2" + + "cotizador/internal/domain" +) + +func f64(v float64) *float64 { return &v } +func str(v string) *string { return &v } + +func TestCotizacionExcelDataHasNoObservacionesInternas(t *testing.T) { + rt := reflect.TypeOf(CotizacionExcelData{}) + for i := 0; i < rt.NumField(); i++ { + name := strings.ToLower(rt.Field(i).Name) + if strings.Contains(name, "interna") { + t.Fatalf("CotizacionExcelData must never declare internal observations field, found %q", rt.Field(i).Name) + } + } +} + +func sheetContains(t *testing.T, f *excelize.File, sheet, substr string) bool { + t.Helper() + rows, err := f.GetRows(sheet) + if err != nil { + t.Fatalf("GetRows(%s): %v", sheet, err) + } + for _, row := range rows { + for _, cell := range row { + if strings.Contains(cell, substr) { + return true + } + } + } + return false +} + +func TestBuildCotizacionExcelSingle(t *testing.T) { + fecha := time.Date(2026, 5, 10, 0, 0, 0, 0, time.UTC) + vigencia := domain.CalcularVigencia(fecha) + obs := "Nota visible para el cliente con acentos: diseño y año." + + raw, err := BuildCotizacionExcel(CotizacionExcelData{ + RazonSocial: "URIEL JARETH CONSULTING", + DomicilioFiscal: "DOMICILIO_SECRETO_NO_IMPRIMIR 123", + Numero: "UJ2605UR001", + ClienteNombre: "Sofía Ramírez", + ClienteEmpresa: "Ramírez Diseño S.A.", + AsesorNombre: "Uriel Jareth", + Fecha: fecha, + Vigencia: vigencia, + Moneda: "MXN", + TipoCambio: "N/A", + Proyecto: "Sitio Web y Campañas", + EsquemaPago: "50/50", + Servicios: []ServicioExcel{ + { + Nombre: "Auditoría SEO / Técnica: [2026]*?", + Fase: 0, + TipoPago: "unico", + Precio: 6000, + TiempoEntrega: "7 días", + Entregables: []string{"Diagnóstico técnico", "Roadmap SEO"}, + ModeloCobro: "fijo", + }, + { + Nombre: "Desarrollo Custom", + Fase: 1, + TipoPago: "unico", + Precio: 14000, + TiempoEntrega: "15 días", + Entregables: []string{"Frontend", "Backend"}, + ModeloCobro: "horas", + EsPersonalizado: true, + Horas: f64(20), + TarifaHora: f64(700), + }, + { + Nombre: "Retainer Mensual", + Fase: 2, + TipoPago: "mensual", + Precio: 7500, + TiempoEntrega: "Mensual", + Entregables: []string{"Soporte", "Reportes"}, + ModeloCobro: "retainer", + MontoMinimo: f64(7500), + HorasIncluidas: f64(10), + TarifaHora: f64(700), + }, + { + Nombre: "Desarrollo Custom", // duplicate tab name test + Fase: 3, + TipoPago: "mensual", + Precio: 0, + TiempoEntrega: "Bajo demanda", + ModeloCobro: "demanda", + TarifaHora: f64(700), + }, + }, + PlanBucefaloNivel: str("premium"), // nil price -> falls back to domain.BucefaloPrecio (4500) + ColorPrimario: "#0400C4", + ColorSecundario: "#0F172A", + IncluirIVA: true, + Observaciones: &obs, + }) + if err != nil { + t.Fatalf("BuildCotizacionExcel error: %v", err) + } + + f, err := excelize.OpenReader(bytes.NewReader(raw)) + if err != nil { + t.Fatalf("excelize.OpenReader error: %v", err) + } + defer f.Close() + + sheets := f.GetSheetList() + if len(sheets) != 5 { + t.Fatalf("expected 5 sheets (1 resumen + 4 services), got %d: %v", len(sheets), sheets) + } + if sheets[0] != "HOJA RESUMEN" { + t.Fatalf("expected first sheet HOJA RESUMEN, got %q", sheets[0]) + } + + // Verify key values in HOJA RESUMEN + if v, _ := f.GetCellValue("HOJA RESUMEN", "B2"); v != "URIEL JARETH CONSULTING" { + t.Errorf("B2 = %q, want URIEL JARETH CONSULTING", v) + } + if v, _ := f.GetCellValue("HOJA RESUMEN", "B3"); v != "UJ2605UR001" { + t.Errorf("B3 = %q, want UJ2605UR001", v) + } + if !sheetContains(t, f, "HOJA RESUMEN", "20 h x $700/hr") { + t.Errorf("HOJA RESUMEN missing horas DetalleModelo") + } + if !sheetContains(t, f, "HOJA RESUMEN", "segun consumo") { + t.Errorf("HOJA RESUMEN missing demanda DetalleModelo") + } + if !sheetContains(t, f, "HOJA RESUMEN", "CRM Bucéfalo - Premium") { + t.Errorf("HOJA RESUMEN missing Plan Bucéfalo row") + } + if !sheetContains(t, f, "HOJA RESUMEN", obs) { + t.Errorf("HOJA RESUMEN missing Observaciones") + } + + // Verify DomicilioFiscal is NEVER printed on any sheet. + for _, s := range sheets { + if sheetContains(t, f, s, "DOMICILIO_SECRETO_NO_IMPRIMIR") { + t.Fatalf("sheet %q leaked DomicilioFiscal", s) + } + } +} + +func TestBuildCotizacionExcelDoblePropuesta(t *testing.T) { + fecha := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC) + raw, err := BuildCotizacionExcel(CotizacionExcelData{ + RazonSocial: "URIEL JARETH CONSULTING", + Numero: "UJ2606UR002", + ClienteNombre: "Luis Torres", + ClienteEmpresa: "Torres Corp", + AsesorNombre: "Uriel Jareth", + Fecha: fecha, + Vigencia: domain.CalcularVigencia(fecha), + Moneda: "MXN", + Proyecto: "Escalamiento", + EsquemaPago: "Mensual", + EsDoble: true, + IncluirIVA: true, + OpcionesMetadata: map[string]domain.MetaOpcion{ + "1": {Titulo: "Básico", Descripcion: "Plan inicial", NoIncluye: "Video"}, + "2": {Titulo: "Pro", Descripcion: "Plan avanzado", NoIncluye: "Pauta"}, + }, + Servicios: []ServicioExcel{ + {Nombre: "HOJA RESUMEN", Fase: 0, TipoPago: "unico", Precio: 5000, TiempoEntrega: "5 días", Opcion: str("ambas"), Horas: f64(5)}, + {Nombre: "Landing", Fase: 1, TipoPago: "unico", Precio: 10000, TiempoEntrega: "10 días", Opcion: str("1"), Horas: f64(10)}, + {Nombre: "Web Pro", Fase: 1, TipoPago: "unico", Precio: 20000, TiempoEntrega: "20 días", Opcion: str("2"), Horas: f64(25)}, + {Nombre: "Ads", Fase: 2, TipoPago: "mensual", Precio: 8000, TiempoEntrega: "Mensual", Opcion: str("ambas")}, + }, + PlanBucefaloNivel: str("basico"), + PlanBucefaloPrecio: f64(1200), + }) + if err != nil { + t.Fatalf("BuildCotizacionExcel doble error: %v", err) + } + + f, err := excelize.OpenReader(bytes.NewReader(raw)) + if err != nil { + t.Fatalf("OpenReader error: %v", err) + } + defer f.Close() + + if !sheetContains(t, f, "HOJA RESUMEN", "OPCIÓN 1: Básico") { + t.Errorf("missing OPCIÓN 1 banner") + } + if !sheetContains(t, f, "HOJA RESUMEN", "OPCIÓN 2: Pro") { + t.Errorf("missing OPCIÓN 2 banner") + } + if !sheetContains(t, f, "HOJA RESUMEN", "COMPARATIVA DE OPCIONES") { + t.Errorf("missing COMPARATIVA DE OPCIONES") + } + // Opción 1 único = (5000+10000)*1.16 = $17,400; Opción 2 único = (5000+20000)*1.16 = $29,000 + if !sheetContains(t, f, "HOJA RESUMEN", "$17,400") || !sheetContains(t, f, "HOJA RESUMEN", "$29,000") { + t.Errorf("expected IVA-adjusted comparative totals $17,400 and $29,000") + } + if !sheetContains(t, f, "HOJA RESUMEN", "15 h") || !sheetContains(t, f, "HOJA RESUMEN", "30 h") { + t.Errorf("expected comparative hours 15 h and 30 h") + } +} + +func TestCatalogoCSVExportPlantillaAndParse(t *testing.T) { + // 1. Plantilla parses cleanly into 6 rows. + tpl := PlantillaCatalogoCSV() + parsedTpl, err := ParseCatalogoCSV(tpl) + if err != nil { + t.Fatalf("ParseCatalogoCSV(PlantillaCatalogoCSV()) error: %v", err) + } + if len(parsedTpl) != 6 { + t.Fatalf("expected 6 rows from plantilla, got %d", len(parsedTpl)) + } + if parsedTpl[0].Nombre != "SEO On-Page Basico" || parsedTpl[0].Fase != 1 || parsedTpl[0].TipoPago != "unico" || parsedTpl[0].PrecioBase != 5000 { + t.Errorf("unexpected first plantilla row: %+v", parsedTpl[0]) + } + if len(parsedTpl[0].Entregables) != 3 { + t.Errorf("expected 3 entregables in first row, got %v", parsedTpl[0].Entregables) + } + + // 2. Round-trip ExportCatalogoCSV -> ParseCatalogoCSV (including commas, quotes, BOM). + orig := []CatalogoCSVRow{ + { + Nombre: `Auditoría "Pro", Web & SEO`, + Categoria: "SEO", + Fase: 0, + TipoPago: "unico", + PrecioBase: 4500.5, + TiempoEntrega: "5 - 7 días", + Entregables: []string{"Informe técnico", "Sesión de entrega"}, + Variante: "Premium", + }, + { + Nombre: "Gestión de Redes", + Categoria: "Marketing", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 8000, + TiempoEntrega: "Mensual", + Entregables: []string{"Calendario editorial", "Reporte mensual"}, + Variante: "", + }, + } + exported, err := ExportCatalogoCSV(orig) + if err != nil { + t.Fatalf("ExportCatalogoCSV error: %v", err) + } + + // Prepend UTF-8 BOM to verify BOM stripping too. + withBOM := append([]byte{0xEF, 0xBB, 0xBF}, exported...) + roundTrip, err := ParseCatalogoCSV(withBOM) + if err != nil { + t.Fatalf("ParseCatalogoCSV round-trip error: %v", err) + } + if !reflect.DeepEqual(roundTrip, orig) { + t.Fatalf("round-trip mismatch:\ngot: %+v\nwant: %+v", roundTrip, orig) + } + + // 3. Error cases. + if _, err := ParseCatalogoCSV([]byte("Nombre,Categoria,Fase,Tipo de Pago,Precio Base\n")); err == nil { + t.Errorf("expected error for header-only CSV") + } + if _, err := ParseCatalogoCSV([]byte("Nombre,Categoria,Fase,Tipo de Pago,Precio Base\nFoo,Bar,Invalida,unico,-5\n")); err == nil { + t.Errorf("expected error when no valid rows exist") + } +} diff --git a/internal/httpapi/admin_control_handlers.go b/internal/httpapi/admin_control_handlers.go new file mode 100644 index 0000000..57ea04d --- /dev/null +++ b/internal/httpapi/admin_control_handlers.go @@ -0,0 +1,497 @@ +package httpapi + +import ( + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "cotizador/internal/audit" + "cotizador/internal/auth" + "cotizador/internal/db" + "cotizador/internal/webhooks" + + "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5" +) + +func (s *Server) handleAgentKeysList(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"}); !ok { + return + } + rows, err := s.Pool.Query(r.Context(), ` + SELECT "id", "nombre", "prefijo", "scopes", "rateLimitPerMin", "activo", "revokedAt", "lastUsedAt", "createdById", "createdAt", "updatedAt" + FROM "AgentApiKey" + ORDER BY "createdAt" DESC + `) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error listando claves de agente") + return + } + defer rows.Close() + + keys := []map[string]any{} + for rows.Next() { + var id, nombre, prefijo string + var scopes []string + var rateLimit int + var activo bool + var revokedAt, lastUsedAt *time.Time + var createdByID *string + var createdAt, updatedAt time.Time + if rows.Scan(&id, &nombre, &prefijo, &scopes, &rateLimit, &activo, &revokedAt, &lastUsedAt, &createdByID, &createdAt, &updatedAt) == nil { + keys = append(keys, map[string]any{ + "id": id, + "nombre": nombre, + "prefijo": prefijo, + "scopes": scopes, + "rateLimitPerMin": rateLimit, + "activo": activo, + "revokedAt": revokedAt, + "lastUsedAt": lastUsedAt, + "createdById": createdByID, + "createdAt": createdAt, + "updatedAt": updatedAt, + }) + } + } + writeJSON(w, http.StatusOK, map[string]any{"data": keys, "scopesDisponibles": auth.AgentScopes}) +} + +func (s *Server) handleAgentKeysCreate(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"}) + if !ok { + return + } + var body struct { + Nombre string `json:"nombre"` + Scopes []string `json:"scopes"` + RateLimitPerMin *int `json:"rateLimitPerMin"` + } + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + nombre := strings.TrimSpace(body.Nombre) + if nombre == "" || len(body.Scopes) == 0 { + writeError(w, http.StatusBadRequest, "nombre y scopes son requeridos") + return + } + for _, sc := range body.Scopes { + if !auth.IsValidScope(sc) { + writeError(w, http.StatusBadRequest, fmt.Sprintf("Scope invalido o no permitido: %s", sc)) + return + } + } + rl := 60 + if body.RateLimitPerMin != nil { + rl = *body.RateLimitPerMin + if rl < 1 || rl > 1000 { + writeError(w, http.StatusBadRequest, "rateLimitPerMin debe estar entre 1 y 1000") + return + } + } + + rawKey, prefijo, keyHash := auth.GenerateAPIKey() + id := db.NewID() + _, err := s.Pool.Exec(r.Context(), ` + INSERT INTO "AgentApiKey" ("id", "nombre", "prefijo", "keyHash", "scopes", "rateLimitPerMin", "activo", "createdById", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, $5, $6, true, $7, NOW(), NOW()) + `, id, nombre, prefijo, keyHash, body.Scopes, rl, actor.UserID) + if err != nil { + if strings.Contains(err.Error(), "duplicate") || strings.Contains(err.Error(), "23505") { + writeError(w, http.StatusConflict, "Ya existe una clave con ese nombre") + return + } + writeError(w, http.StatusInternalServerError, "Error creando clave de agente") + return + } + + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "agent_key.crear", RecursoTipo: "agent_key", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + Detalle: map[string]any{"nombre": nombre, "scopes": body.Scopes, "rateLimitPerMin": rl}, + }) + + writeJSON(w, http.StatusCreated, map[string]any{ + "id": id, + "nombre": nombre, + "prefijo": prefijo, + "rawKey": rawKey, + "scopes": body.Scopes, + "rateLimitPerMin": rl, + "activo": true, + }) +} + +func (s *Server) handleAgentKeysRotate(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"}) + if !ok { + return + } + id := chi.URLParam(r, "id") + rawKey, prefijo, keyHash := auth.GenerateAPIKey() + + var nombre string + err := s.Pool.QueryRow(r.Context(), ` + UPDATE "AgentApiKey" + SET "prefijo" = $1, "keyHash" = $2, "activo" = true, "revokedAt" = NULL, "updatedAt" = NOW() + WHERE "id" = $3 + RETURNING "nombre" + `, prefijo, keyHash, id).Scan(&nombre) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + writeError(w, http.StatusNotFound, "Clave no encontrada") + return + } + writeError(w, http.StatusInternalServerError, "Error rotando clave") + return + } + + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "agent_key.rotar", RecursoTipo: "agent_key", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + Detalle: map[string]any{"nombre": nombre, "prefijo": prefijo}, + }) + + writeJSON(w, http.StatusOK, map[string]any{ + "id": id, + "nombre": nombre, + "prefijo": prefijo, + "rawKey": rawKey, + "activo": true, + }) +} + +func (s *Server) handleAgentKeysRevoke(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "agent_key"}) + if !ok { + return + } + id := chi.URLParam(r, "id") + var nombre string + err := s.Pool.QueryRow(r.Context(), ` + UPDATE "AgentApiKey" + SET "activo" = false, "revokedAt" = NOW(), "updatedAt" = NOW() + WHERE "id" = $1 + RETURNING "nombre" + `, id).Scan(&nombre) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + writeError(w, http.StatusNotFound, "Clave no encontrada") + return + } + writeError(w, http.StatusInternalServerError, "Error revocando clave") + return + } + + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "agent_key.revocar", RecursoTipo: "agent_key", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + Detalle: map[string]any{"nombre": nombre}, + }) + + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "activo": false}) +} + +func (s *Server) handleAuditLogs(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "audit_log"}); !ok { + return + } + q := r.URL.Query() + page := parseIntQuery(r, "page", 1, 1, 10000) + limit := parseIntQuery(r, "limit", 50, 1, 200) + offset := (page - 1) * limit + + conds := []string{"1=1"} + args := []any{} + addArg := func(v any) string { + args = append(args, v) + return fmt.Sprintf("$%d", len(args)) + } + if v := strings.TrimSpace(q.Get("accion")); v != "" { + conds = append(conds, `"accion" = `+addArg(v)) + } + if v := strings.TrimSpace(q.Get("actorNombre")); v != "" { + conds = append(conds, `"actorNombre" ILIKE `+addArg("%"+v+"%")) + } + if v := strings.TrimSpace(q.Get("recursoId")); v != "" { + conds = append(conds, `"recursoId" = `+addArg(v)) + } + whereSQL := strings.Join(conds, " AND ") + + var total int + _ = s.Pool.QueryRow(r.Context(), `SELECT COUNT(*) FROM "AuditLog" WHERE `+whereSQL, args...).Scan(&total) + + limArg := addArg(limit) + offArg := addArg(offset) + rows, err := s.Pool.Query(r.Context(), ` + SELECT "id", "actorTipo", "actorId", "actorNombre", "accion", "recursoTipo", "recursoId", "ip", "requestId", "exito", "detalle", "createdAt" + FROM "AuditLog" + WHERE `+whereSQL+` + ORDER BY "createdAt" DESC + LIMIT `+limArg+` OFFSET `+offArg, args...) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error consultando auditoria") + return + } + defer rows.Close() + + data := []map[string]any{} + for rows.Next() { + var id, actorTipo, actorNombre, accion, recursoTipo string + var actorID, recursoID, ip, reqID *string + var exito bool + var detalle []byte + var createdAt time.Time + if rows.Scan(&id, &actorTipo, &actorID, &actorNombre, &accion, &recursoTipo, &recursoID, &ip, &reqID, &exito, &detalle, &createdAt) == nil { + var det any + if len(detalle) > 0 { + _ = json.Unmarshal(detalle, &det) + } + data = append(data, map[string]any{ + "id": id, "actorTipo": actorTipo, "actorId": actorID, "actorNombre": actorNombre, + "accion": accion, "recursoTipo": recursoTipo, "recursoId": recursoID, + "ip": ip, "requestId": reqID, "exito": exito, "detalle": det, "createdAt": createdAt, + }) + } + } + writeJSON(w, http.StatusOK, map[string]any{ + "data": data, + "meta": map[string]any{"total": total, "page": page, "limit": limit}, + }) +} + +func (s *Server) handleWebhooksList(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"}); !ok { + return + } + rows, err := s.Pool.Query(r.Context(), ` + SELECT "id", "nombre", "url", "eventos", "activo", "createdAt", "updatedAt" + FROM "WebhookEndpoint" + ORDER BY "createdAt" DESC + `) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error listando webhooks") + return + } + defer rows.Close() + + list := []map[string]any{} + for rows.Next() { + var id, nombre, urlStr string + var eventos []string + var activo bool + var createdAt, updatedAt time.Time + if rows.Scan(&id, &nombre, &urlStr, &eventos, &activo, &createdAt, &updatedAt) == nil { + list = append(list, map[string]any{ + "id": id, "nombre": nombre, "url": urlStr, "eventos": eventos, + "activo": activo, "createdAt": createdAt, "updatedAt": updatedAt, + }) + } + } + writeJSON(w, http.StatusOK, map[string]any{"data": list, "eventosDisponibles": webhooks.EventosOficiales}) +} + +func (s *Server) handleWebhooksCreate(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"}) + if !ok { + return + } + var body struct { + Nombre string `json:"nombre"` + URL string `json:"url"` + Secret string `json:"secret"` + Eventos []string `json:"eventos"` + } + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + nombre := strings.TrimSpace(body.Nombre) + urlStr := strings.TrimSpace(body.URL) + if nombre == "" || urlStr == "" || len(body.Eventos) == 0 { + writeError(w, http.StatusBadRequest, "nombre, url y eventos son requeridos") + return + } + for _, ev := range body.Eventos { + if !webhooks.EsEventoValido(ev) { + writeError(w, http.StatusBadRequest, fmt.Sprintf("Evento invalido: %s", ev)) + return + } + } + secret := strings.TrimSpace(body.Secret) + if secret == "" { + var b [24]byte + _, _ = rand.Read(b[:]) + secret = "whsec_" + hex.EncodeToString(b[:]) + } + + id := db.NewID() + _, err := s.Pool.Exec(r.Context(), ` + INSERT INTO "WebhookEndpoint" ("id", "nombre", "url", "secret", "eventos", "activo", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, $5, true, NOW(), NOW()) + `, id, nombre, urlStr, secret, body.Eventos) + if err != nil { + if strings.Contains(err.Error(), "23505") || strings.Contains(err.Error(), "duplicate") { + writeError(w, http.StatusConflict, "Ya existe un webhook con ese nombre") + return + } + writeError(w, http.StatusInternalServerError, "Error creando webhook") + return + } + + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "webhook.crear", RecursoTipo: "webhook", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + Detalle: map[string]any{"nombre": nombre, "url": urlStr, "eventos": body.Eventos}, + }) + + writeJSON(w, http.StatusCreated, map[string]any{ + "id": id, "nombre": nombre, "url": urlStr, "secret": secret, "eventos": body.Eventos, "activo": true, + }) +} + +func (s *Server) handleWebhooksDelete(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"}) + if !ok { + return + } + id := chi.URLParam(r, "id") + tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "WebhookEndpoint" WHERE "id" = $1`, id) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Webhook no encontrado") + return + } + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "webhook.eliminar", RecursoTipo: "webhook", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + }) + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +func (s *Server) handleWebhooksDeliveries(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{AdminOnly: true, RecursoTipo: "webhook"}); !ok { + return + } + q := r.URL.Query() + limit := parseIntQuery(r, "limit", 50, 1, 200) + conds := []string{"1=1"} + args := []any{} + if ev := strings.TrimSpace(q.Get("evento")); ev != "" { + args = append(args, ev) + conds = append(conds, fmt.Sprintf(`"evento" = $%d`, len(args))) + } + if eid := strings.TrimSpace(q.Get("endpointId")); eid != "" { + args = append(args, eid) + conds = append(conds, fmt.Sprintf(`"endpointId" = $%d`, len(args))) + } + args = append(args, limit) + rows, err := s.Pool.Query(r.Context(), fmt.Sprintf(` + SELECT "id", "endpointId", "url", "evento", "payload", "statusCode", "exito", "intentos", "error", "createdAt" + FROM "WebhookDelivery" + WHERE %s + ORDER BY "createdAt" DESC + LIMIT $%d + `, strings.Join(conds, " AND "), len(args)), args...) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error consultando entregas de webhooks") + return + } + defer rows.Close() + + list := []map[string]any{} + for rows.Next() { + var id, urlStr, evento string + var endpointID, errStr *string + var payload []byte + var statusCode *int + var exito bool + var intentos int + var createdAt time.Time + if rows.Scan(&id, &endpointID, &urlStr, &evento, &payload, &statusCode, &exito, &intentos, &errStr, &createdAt) == nil { + var p any + _ = json.Unmarshal(payload, &p) + list = append(list, map[string]any{ + "id": id, "endpointId": endpointID, "url": urlStr, "evento": evento, + "payload": p, "statusCode": statusCode, "exito": exito, "intentos": intentos, + "error": errStr, "createdAt": createdAt, + }) + } + } + writeJSON(w, http.StatusOK, map[string]any{"data": list}) +} + +var configAllowedKeys = map[string]bool{ + "razon_social": true, + "rfc": true, + "domicilio_fiscal": true, + "banco_nacional": true, + "cuenta_nacional": true, + "clabe_interbancaria": true, + "clabe_nacional": true, + "banco_internacional": true, + "cuenta_internacional": true, + "cuenta_internacional_swift": true, + "swift": true, + "routing_number": true, + "hora_centinela": true, + "anualidad_hosting": true, + "iva": true, + "terminos_condiciones": true, + "no_incluye": true, + "notas_adicionales": true, + "nota_legal": true, + "color_primario": true, + "color_secundario": true, + "logo_base64": true, + "email_facturacion": true, + "telefono_contacto": true, +} + +func (s *Server) handleConfiguracionGet(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "configuracion"}); !ok { + return + } + writeJSON(w, http.StatusOK, s.getAllConfigMap(r.Context())) +} + +func (s *Server) handleConfiguracionPut(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "configuracion"}); !ok { + return + } + var body map[string]string + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + for k, v := range body { + if !configAllowedKeys[k] { + continue + } + _, err := s.Pool.Exec(r.Context(), ` + INSERT INTO "Configuracion" ("id", "clave", "valor", "updatedAt") + VALUES ($1, $2, $3, NOW()) + ON CONFLICT ("clave") DO UPDATE SET "valor" = EXCLUDED."valor", "updatedAt" = NOW() + `, db.NewID(), k, v) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error guardando configuracion") + return + } + } + writeJSON(w, http.StatusOK, s.getAllConfigMap(r.Context())) +} diff --git a/internal/httpapi/auth_handlers.go b/internal/httpapi/auth_handlers.go new file mode 100644 index 0000000..7420da3 --- /dev/null +++ b/internal/httpapi/auth_handlers.go @@ -0,0 +1,540 @@ +package httpapi + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "time" + + "cotizador/internal/audit" + "cotizador/internal/auth" + "cotizador/internal/domain" + "cotizador/internal/webhooks" + + "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5" +) + +func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second) + defer cancel() + var one int + if err := s.Pool.QueryRow(ctx, "SELECT 1").Scan(&one); err != nil { + writeJSON(w, http.StatusServiceUnavailable, map[string]any{ + "status": "error", + "db": "disconnected", + "version": "3.0.0-go", + }) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "status": "ok", + "db": "connected", + "runtime": "go", + "version": "3.0.0-go", + }) +} + +func (s *Server) handleOpenAPI(w http.ResponseWriter, r *http.Request) { + serverURL := s.Cfg.AppURL + if serverURL == "" { + serverURL = "https://cotizador.urieljareth.org" + } + spec := map[string]any{ + "openapi": "3.1.0", + "info": map[string]any{ + "title": "Cotizador — Uriel Jareth Consulting API", + "version": "3.0.0", + "description": "API unificada en Go para agentes de IA y operacion comercial de Uriel Jareth Consulting. " + + "Autenticacion por cookie JWT (usuarios humanos) o X-API-Key / Bearer ujc_live_* (agentes con alcances granulares). " + + "Ningun agente puede aprobar cotizaciones: la aprobacion es exclusivamente humana (panel admin o enlace firmado de un solo uso).", + }, + "servers": []map[string]any{{"url": serverURL}}, + "components": map[string]any{ + "securitySchemes": map[string]any{ + "ApiKeyAuth": map[string]any{"type": "apiKey", "in": "header", "name": "X-API-Key"}, + "BearerAuth": map[string]any{"type": "http", "scheme": "bearer"}, + "CookieAuth": map[string]any{"type": "apiKey", "in": "cookie", "name": auth.SessionCookieName}, + }, + "schemas": map[string]any{ + "AgentScope": map[string]any{"type": "string", "enum": auth.AgentScopes}, + "EstadoCotizacion": map[string]any{"type": "string", "enum": domain.EstadosCotizacion}, + "WebhookEvent": map[string]any{"type": "string", "enum": webhooks.EventosOficiales}, + }, + }, + "security": []map[string]any{{"ApiKeyAuth": []any{}}, {"BearerAuth": []any{}}, {"CookieAuth": []any{}}}, + "paths": map[string]any{ + "/api/health": map[string]any{"get": map[string]any{"summary": "Estado de salud del servicio y BD", "security": []any{}}}, + "/api/catalogo": map[string]any{"get": map[string]any{"summary": "Listar catalogo de servicios (scope: catalogo:leer)"}, "post": map[string]any{"summary": "Crear servicio (staff)"}}, + "/api/catalogo/{id}": map[string]any{"get": map[string]any{"summary": "Detalle de servicio (scope: catalogo:leer; 403 si soloAdmin para agentes)"}}, + "/api/categorias": map[string]any{"get": map[string]any{"summary": "Listar categorias (scope: catalogo:leer)"}}, + "/api/paquetes": map[string]any{"get": map[string]any{"summary": "Listar paquetes activos (scope: catalogo:leer)"}}, + "/api/clientes": map[string]any{"get": map[string]any{"summary": "Listar clientes (scope: clientes:leer)"}, "post": map[string]any{"summary": "Crear cliente (scope: clientes:escribir, idempotente)"}}, + "/api/clientes/{id}": map[string]any{"patch": map[string]any{"summary": "Actualizar cliente (scope: clientes:escribir)"}}, + "/api/clientes/{id}/archivar": map[string]any{"post": map[string]any{"summary": "Archivar/desarchivar cliente (staff)"}}, + "/api/cotizaciones": map[string]any{"get": map[string]any{"summary": "Listar cotizaciones (cotizaciones:leer | cotizaciones:leer_aceptadas)"}, "post": map[string]any{"summary": "Crear borrador (cotizaciones:borrador, idempotente)"}}, + "/api/cotizaciones/{id}": map[string]any{"get": map[string]any{"summary": "Detalle cotizacion (?verificarContacto=...)"}, "put": map[string]any{"summary": "Editar borrador"}, "delete": map[string]any{"summary": "Eliminar cotizacion (staff)"}}, + "/api/cotizaciones/{id}/solicitar-aprobacion": map[string]any{"post": map[string]any{"summary": "Reenviar enlace de aprobacion a Jareth"}}, + "/api/cotizaciones/{id}/aprobar": map[string]any{"post": map[string]any{"summary": "Aprobar cotizacion (EXCLUSIVO admin humano)"}}, + "/api/cotizaciones/{id}/enviar": map[string]any{"post": map[string]any{"summary": "Enviar cotizacion aprobada (cotizaciones:enviar, idempotente)"}}, + "/api/cotizaciones/{id}/estado": map[string]any{"patch": map[string]any{"summary": "Cambiar estado (staff)"}}, + "/api/cotizaciones/{id}/precio": map[string]any{"patch": map[string]any{"summary": "Actualizar precio de partida"}}, + "/api/aprobar/{token}": map[string]any{"get": map[string]any{"summary": "Resumen de aprobacion firmado", "security": []any{}}, "post": map[string]any{"summary": "Confirmar aprobacion de un solo uso", "security": []any{}}}, + "/api/cobros/programas": map[string]any{"get": map[string]any{"summary": "Listar programas recurrentes (cobros:leer)"}}, + "/api/cobros/pagos": map[string]any{"get": map[string]any{"summary": "Listar cobros recurrentes (cobros:leer)"}}, + "/api/cobros/pagos/{id}/registrar": map[string]any{"post": map[string]any{"summary": "Registrar pago manual (cobros:registrar, idempotente)"}}, + "/api/export/pdf/{id}": map[string]any{"get": map[string]any{"summary": "Exportar PDF de cotizacion"}}, + "/api/agent-keys": map[string]any{"get": map[string]any{"summary": "Listar claves de agente (admin)"}, "post": map[string]any{"summary": "Crear clave de agente (admin)"}}, + "/api/audit-logs": map[string]any{"get": map[string]any{"summary": "Consultar auditoria (admin)"}}, + "/api/webhooks": map[string]any{"get": map[string]any{"summary": "Listar webhooks (admin)"}, "post": map[string]any{"summary": "Registrar webhook (admin)"}}, + }, + } + writeJSON(w, http.StatusOK, spec) +} + +func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { + var body struct { + Email string `json:"email"` + Password string `json:"password"` + } + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "Datos de acceso invalidos") + return + } + email := strings.ToLower(strings.TrimSpace(body.Email)) + if email == "" || body.Password == "" { + writeError(w, http.StatusBadRequest, "Email y contrasena requeridos") + return + } + + var id, dbEmail, passHash, name, role string + var clienteID *string + err := s.Pool.QueryRow(r.Context(), ` + SELECT "id", "email", "password", "name", "role", "clienteId" + FROM "User" + WHERE LOWER("email") = $1 + LIMIT 1 + `, email).Scan(&id, &dbEmail, &passHash, &name, &role, &clienteID) + if err != nil || !auth.ComparePassword(passHash, body.Password) { + writeError(w, http.StatusUnauthorized, "Credenciales invalidas") + return + } + if role == "" { + role = "asesor" + } + cid := "" + if clienteID != nil { + cid = *clienteID + } + + payload := auth.SessionPayload{ + UserID: id, + Email: dbEmail, + Name: name, + Role: role, + ClienteID: cid, + } + tok, err := s.Auth.SignSession(payload) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error generando sesion") + return + } + s.Auth.SetSessionCookie(w, tok) + + respUser := map[string]any{ + "id": id, + "userId": id, + "email": dbEmail, + "name": name, + "role": role, + } + if cid != "" { + respUser["clienteId"] = cid + } + writeJSON(w, http.StatusOK, map[string]any{"user": respUser}) +} + +func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { + s.Auth.ClearSessionCookie(w) + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +// handleMe returns the authenticated cookie session user (for both staff and cliente). +func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) { + sess, ok := s.Auth.SessionFromRequest(r) + if !ok { + writeError(w, http.StatusUnauthorized, "No autenticado") + return + } + user := map[string]any{ + "userId": sess.UserID, + "email": sess.Email, + "name": sess.Name, + "role": sess.Role, + } + if sess.ClienteID != "" { + user["clienteId"] = sess.ClienteID + if s.Pool != nil { + var clienteNombre string + if err := s.Pool.QueryRow(r.Context(), `SELECT "nombre" FROM "Cliente" WHERE "id" = $1`, sess.ClienteID).Scan(&clienteNombre); err == nil { + user["clienteNombre"] = clienteNombre + } + } + } + writeJSON(w, http.StatusOK, map[string]any{"user": user}) +} + +// handleAsesores returns safe staff user list + next quote sequence for CotizacionForm. +func (s *Server) handleAsesores(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "asesor"}); !ok { + return + } + rows, err := s.Pool.Query(r.Context(), ` + SELECT "id", "name", "email", "role" + FROM "User" + WHERE "role" <> 'cliente' + ORDER BY "name" ASC + `) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error cargando asesores") + return + } + defer rows.Close() + asesores := []map[string]any{} + for rows.Next() { + var id, name, email, role string + if rows.Scan(&id, &name, &email, &role) == nil { + asesores = append(asesores, map[string]any{ + "id": id, + "name": name, + "email": email, + "role": role, + "iniciales": asesorInitials(name), + }) + } + } + writeJSON(w, http.StatusOK, map[string]any{ + "asesores": asesores, + "nextSeq": s.nextCotizacionSeq(r.Context()), + }) +} + +// handleDashboard provides summary counts + 10 recent quotes for the SPA dashboard. +func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "dashboard"}); !ok { + return + } + ctx := r.Context() + var totalCot, totalCli, totalSvc int + _ = s.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM "Cotizacion" WHERE "archivado" = false`).Scan(&totalCot) + _ = s.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM "Cliente" WHERE "archivado" = false`).Scan(&totalCli) + _ = s.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM "ServicioCatalogo" WHERE "activo" = true`).Scan(&totalSvc) + + rows, err := s.Pool.Query(ctx, ` + SELECT q."id", q."numero", q."fecha", q."vigencia", q."proyecto", q."estado", + q."moneda", q."esDoble", q."incluirIva", + c."id", c."nombre", COALESCE(c."empresa", '') + FROM "Cotizacion" q + JOIN "Cliente" c ON c."id" = q."clienteId" + WHERE q."archivado" = false + ORDER BY q."createdAt" DESC + LIMIT 10 + `) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error cargando dashboard") + return + } + defer rows.Close() + + recientes := []map[string]any{} + var cotIDs []string + for rows.Next() { + var id, numero, proyecto, estado, moneda, cid, cnombre, cempresa string + var fecha, vigencia time.Time + var esDoble, incluirIva bool + if rows.Scan(&id, &numero, &fecha, &vigencia, &proyecto, &estado, &moneda, &esDoble, &incluirIva, &cid, &cnombre, &cempresa) == nil { + cotIDs = append(cotIDs, id) + recientes = append(recientes, map[string]any{ + "id": id, + "numero": numero, + "fecha": fecha, + "vigencia": vigencia, + "proyecto": proyecto, + "estado": estado, + "moneda": moneda, + "esDoble": esDoble, + "incluirIva": incluirIva, + "cliente": map[string]any{ + "id": cid, + "nombre": cnombre, + "empresa": nullableStr(cempresa), + }, + "servicios": []any{}, + }) + } + } + + if len(cotIDs) > 0 { + svcRows, err := s.Pool.Query(ctx, ` + SELECT "cotizacionId", "tipoPago", "precio", "seleccionado", "opcion" + FROM "ServicioCotizado" + WHERE "cotizacionId" = ANY($1) + `, cotIDs) + if err == nil { + defer svcRows.Close() + byCot := map[string][]map[string]any{} + for svcRows.Next() { + var qid, tipoPago string + var precio float64 + var sel bool + var opcion *string + if svcRows.Scan(&qid, &tipoPago, &precio, &sel, &opcion) == nil { + byCot[qid] = append(byCot[qid], map[string]any{ + "tipoPago": tipoPago, + "precio": precio, + "seleccionado": sel, + "opcion": opcion, + }) + } + } + for _, item := range recientes { + if svcs, ok := byCot[item["id"].(string)]; ok { + item["servicios"] = svcs + } + } + } + } + + writeJSON(w, http.StatusOK, map[string]any{ + "totalCotizaciones": totalCot, + "totalClientes": totalCli, + "totalServicios": totalSvc, + "cotizacionesRecientes": recientes, + }) +} + +func (s *Server) handleAprobarTokenGet(w http.ResponseWriter, r *http.Request) { + rawToken := strings.TrimSpace(chi.URLParam(r, "token")) + if rawToken == "" { + writeError(w, http.StatusNotFound, "Enlace invalido") + return + } + tokenHash := auth.HashSecret(rawToken) + + var tokID, cotID, numero, proyecto, estado, moneda, cNombre string + var cEmpresa, cEmail, creadaPorAgente *string + var expiraAt time.Time + var usadoAt *time.Time + var incluirIva, esDoble bool + var fecha, vigencia time.Time + + err := s.Pool.QueryRow(r.Context(), ` + SELECT t."id", t."cotizacionId", t."expiraAt", t."usadoAt", + q."numero", q."proyecto", q."estado", q."moneda", q."incluirIva", q."esDoble", q."fecha", q."vigencia", q."creadaPorAgente", + c."nombre", c."empresa", c."email" + FROM "ApprovalToken" t + JOIN "Cotizacion" q ON q."id" = t."cotizacionId" + JOIN "Cliente" c ON c."id" = q."clienteId" + WHERE t."tokenHash" = $1 + `, tokenHash).Scan(&tokID, &cotID, &expiraAt, &usadoAt, &numero, &proyecto, &estado, &moneda, &incluirIva, &esDoble, &fecha, &vigencia, &creadaPorAgente, &cNombre, &cEmpresa, &cEmail) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + writeError(w, http.StatusNotFound, "Enlace de aprobacion no encontrado") + return + } + writeError(w, http.StatusInternalServerError, "Error consultando enlace") + return + } + + if usadoAt != nil { + writeJSON(w, http.StatusGone, map[string]any{"error": "Este enlace ya fue utilizado", "usado": true}) + return + } + if time.Now().After(expiraAt) { + writeJSON(w, http.StatusGone, map[string]any{"error": "Este enlace ha expirado", "expirado": true}) + return + } + + svcRows, _ := s.Pool.Query(r.Context(), ` + SELECT s."id", COALESCE(s."nombre", sc."nombre", 'Servicio'), s."fase", s."tipoPago", s."precio", s."tiempoEntrega", s."seleccionado", s."modeloCobro", s."opcion" + FROM "ServicioCotizado" s + LEFT JOIN "ServicioCatalogo" sc ON sc."id" = s."servicioCatalogoId" + WHERE s."cotizacionId" = $1 + ORDER BY s."fase" ASC, s."createdAt" ASC + `, cotID) + partidas := []map[string]any{} + var calcSvcs []domain.ServicioCalc + if svcRows != nil { + defer svcRows.Close() + for svcRows.Next() { + var sid, nom, tp, te, mc string + var fase int + var precio float64 + var sel bool + var op *string + if svcRows.Scan(&sid, &nom, &fase, &tp, &precio, &te, &sel, &mc, &op) == nil { + partidas = append(partidas, map[string]any{ + "id": sid, "nombre": nom, "fase": fase, "tipoPago": tp, "precio": precio, + "tiempoEntrega": te, "seleccionado": sel, "modeloCobro": mc, "opcion": op, + }) + calcSvcs = append(calcSvcs, domain.ServicioCalc{ + Nombre: nom, TipoPago: tp, Precio: precio, Seleccionado: sel, ModeloCobro: mc, Opcion: op, + }) + } + } + } + totales := domain.CalcularTotalesCotizacion(calcSvcs, incluirIva) + + writeJSON(w, http.StatusOK, map[string]any{ + "cotizacion": map[string]any{ + "id": cotID, + "numero": numero, + "proyecto": proyecto, + "estado": estado, + "moneda": moneda, + "incluirIva": incluirIva, + "esDoble": esDoble, + "fecha": fecha, + "vigencia": vigencia, + "creadaPorAgente": creadaPorAgente, + "cliente": map[string]any{ + "nombre": cNombre, + "empresa": cEmpresa, + "email": cEmail, + }, + "totales": totales, + "partidas": partidas, + "servicios": partidas, + }, + "puedeAprobar": estado == "borrador", + "totales": totales, + "expiraAt": expiraAt, + }) +} + +func (s *Server) handleAprobarTokenPost(w http.ResponseWriter, r *http.Request) { + rawToken := strings.TrimSpace(chi.URLParam(r, "token")) + var body struct { + Confirmar bool `json:"confirmar"` + } + if err := decodeJSON(r, &body); err != nil || !body.Confirmar { + writeError(w, http.StatusBadRequest, "Se requiere confirmar: true para aprobar la cotizacion") + return + } + tokenHash := auth.HashSecret(rawToken) + ip := audit.ClientIP(r) + + tx, err := s.Pool.Begin(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error iniciando transaccion") + return + } + defer tx.Rollback(r.Context()) + + var tokID, cotID, estado, numero string + var expiraAt time.Time + var usadoAt *time.Time + err = tx.QueryRow(r.Context(), ` + SELECT t."id", t."cotizacionId", t."expiraAt", t."usadoAt", q."estado", q."numero" + FROM "ApprovalToken" t + JOIN "Cotizacion" q ON q."id" = t."cotizacionId" + WHERE t."tokenHash" = $1 + FOR UPDATE OF t, q + `, tokenHash).Scan(&tokID, &cotID, &expiraAt, &usadoAt, &estado, &numero) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + writeError(w, http.StatusNotFound, "Enlace de aprobacion no encontrado") + return + } + writeError(w, http.StatusInternalServerError, "Error validando enlace") + return + } + if usadoAt != nil || time.Now().After(expiraAt) { + writeError(w, http.StatusGone, "El enlace de aprobacion ya fue usado o expiro") + return + } + + tr := domain.ValidarTransicionEstado(domain.ValidarTransicionInput{ + Actual: estado, + Nuevo: "aprobada", + Actor: domain.ActorInfo{Type: "enlace_firmado"}, + ViaEndpoint: "enlace_firmado", + }) + if !tr.OK { + writeError(w, tr.Status, tr.Error) + return + } + + now := time.Now() + if _, err := tx.Exec(r.Context(), ` + UPDATE "ApprovalToken" SET "usadoAt" = $1, "usadoIp" = $2 WHERE "id" = $3 + `, now, ip, tokID); err != nil { + writeError(w, http.StatusInternalServerError, "Error consumiendo enlace") + return + } + // Invalidate sibling open tokens + _, _ = tx.Exec(r.Context(), ` + UPDATE "ApprovalToken" SET "usadoAt" = $1 WHERE "cotizacionId" = $2 AND "usadoAt" IS NULL + `, now, cotID) + + if _, err := tx.Exec(r.Context(), ` + UPDATE "Cotizacion" + SET "estado" = 'aprobada', "aprobadaAt" = $1, "aprobacionMetodo" = 'enlace_firmado', "updatedAt" = NOW() + WHERE "id" = $2 + `, now, cotID); err != nil { + writeError(w, http.StatusInternalServerError, "Error aprobando cotizacion") + return + } + if err := tx.Commit(r.Context()); err != nil { + writeError(w, http.StatusInternalServerError, "Error confirmando aprobacion") + return + } + + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: "system", + ActorNombre: "enlace_firmado", + Accion: "cotizacion.aprobar", + RecursoTipo: "cotizacion", + RecursoID: cotID, + IP: ip, + RequestID: audit.RequestID(r), + Exito: true, + Detalle: map[string]any{"numero": numero, "metodo": "enlace_firmado"}, + }) + + go s.Webhooks.Emitir(context.Background(), "cotizacion.aprobada", map[string]any{ + "cotizacionId": cotID, + "numero": numero, + "estado": "aprobada", + "aprobacionMetodo": "enlace_firmado", + "aprobadaAt": now.UTC().Format(time.RFC3339), + }) + + writeJSON(w, http.StatusOK, map[string]any{ + "ok": true, + "cotizacionId": cotID, + "numero": numero, + "estado": "aprobada", + "aprobadaAt": now, + }) +} + +func nullableStr(s string) *string { + if s == "" { + return nil + } + return &s +} + +func parseJSONRawOrEmptyArray(raw []byte) any { + if len(raw) == 0 { + return []any{} + } + var v any + if err := json.Unmarshal(raw, &v); err != nil { + return []any{} + } + return v +} diff --git a/internal/httpapi/catalogo_handlers.go b/internal/httpapi/catalogo_handlers.go new file mode 100644 index 0000000..d375ed0 --- /dev/null +++ b/internal/httpapi/catalogo_handlers.go @@ -0,0 +1,979 @@ +package httpapi + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "strings" + + "cotizador/internal/audit" + "cotizador/internal/auth" + "cotizador/internal/db" + "cotizador/internal/excel" + + "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5" +) + +func (s *Server) queryServicioCatalogo(ctx context.Context, whereSQL string, args ...any) ([]map[string]any, error) { + rows, err := s.Pool.Query(ctx, ` + SELECT sc."id", sc."nombre", sc."descripcion", sc."fase", sc."tipoPago", sc."precioBase", + sc."tiempoEntrega", sc."entregablesDefault", sc."categoriaId", sc."variante", sc."nivel", + sc."activo", sc."soloAdmin", sc."orden", + c."nombre", c."color", + (SELECT COUNT(*) FROM "ServicioCotizado" cot WHERE cot."servicioCatalogoId" = sc."id") AS en_cotizaciones + FROM "ServicioCatalogo" sc + LEFT JOIN "Categoria" c ON c."id" = sc."categoriaId" + WHERE `+whereSQL+` + ORDER BY sc."fase" ASC, sc."orden" ASC, sc."nombre" ASC + `, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + out := []map[string]any{} + for rows.Next() { + var id, nombre, tipoPago, tiempoEntrega string + var descripcion, categoriaID, variante, nivel, catNombre, catColor *string + var fase, orden, enCot int + var precioBase float64 + var entregablesRaw []byte + var activo, soloAdmin bool + if err := rows.Scan( + &id, &nombre, &descripcion, &fase, &tipoPago, &precioBase, + &tiempoEntrega, &entregablesRaw, &categoriaID, &variante, &nivel, + &activo, &soloAdmin, &orden, + &catNombre, &catColor, &enCot, + ); err != nil { + continue + } + var entregables []string + _ = json.Unmarshal(entregablesRaw, &entregables) + if entregables == nil { + entregables = []string{} + } + var catRel any + if categoriaID != nil && catNombre != nil { + catRel = map[string]any{"id": *categoriaID, "nombre": *catNombre, "color": catColor} + } + out = append(out, map[string]any{ + "id": id, + "nombre": nombre, + "descripcion": descripcion, + "fase": fase, + "tipoPago": tipoPago, + "precioBase": precioBase, + "tiempoEntrega": tiempoEntrega, + "entregablesDefault": entregables, + "categoriaId": categoriaID, + "categoriaNombre": catNombre, + "categoriaColor": catColor, + "categoriaRel": catRel, + "variante": variante, + "nivel": nivel, + "activo": activo, + "soloAdmin": soloAdmin, + "orden": orden, + "enCotizaciones": enCot, + }) + } + return out, nil +} + +func (s *Server) handleCatalogoList(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "catalogo"}) + if !ok { + return + } + q := r.URL.Query() + conds := []string{"1=1"} + args := []any{} + add := func(v any) string { + args = append(args, v) + return fmt.Sprintf("$%d", len(args)) + } + + if actor.IsAgent() { + conds = append(conds, `sc."soloAdmin" = false`) + } + if v := strings.TrimSpace(q.Get("q")); v != "" { + p := add("%" + v + "%") + conds = append(conds, fmt.Sprintf(`(sc."nombre" ILIKE %s OR COALESCE(sc."descripcion", '') ILIKE %s OR COALESCE(sc."variante", '') ILIKE %s)`, p, p, p)) + } + if v := strings.TrimSpace(q.Get("fase")); v != "" { + if f, err := strconv.Atoi(v); err == nil { + conds = append(conds, `sc."fase" = `+add(f)) + } + } + if v := strings.TrimSpace(q.Get("tipoPago")); v != "" { + conds = append(conds, `sc."tipoPago" = `+add(v)) + } + if v := strings.TrimSpace(q.Get("categoriaId")); v != "" { + conds = append(conds, `sc."categoriaId" = `+add(v)) + } + if v := strings.TrimSpace(q.Get("activo")); v == "true" || v == "false" { + conds = append(conds, `sc."activo" = `+add(v == "true")) + } + + list, err := s.queryServicioCatalogo(r.Context(), strings.Join(conds, " AND "), args...) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error listando catalogo") + return + } + writeJSON(w, http.StatusOK, list) +} + +func (s *Server) handleCatalogoGet(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "catalogo"}) + if !ok { + return + } + id := chi.URLParam(r, "id") + list, err := s.queryServicioCatalogo(r.Context(), `sc."id" = $1`, id) + if err != nil || len(list) == 0 { + writeError(w, http.StatusNotFound, "Servicio no encontrado") + return + } + svc := list[0] + if actor.IsAgent() && svc["soloAdmin"] == true { + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "catalogo.solo_admin_bloqueado", RecursoTipo: "catalogo", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + }) + writeError(w, http.StatusForbidden, "Servicio restringido para administradores") + return + } + writeJSON(w, http.StatusOK, svc) +} + +func (s *Server) handleCatalogoCreate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok { + return + } + var raw map[string]any + if err := decodeJSON(r, &raw); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + + var detalles []ValidationDetail + nombre := strings.TrimSpace(asString(raw["nombre"])) + if nombre == "" { + detalles = append(detalles, ValidationDetail{Campo: "nombre", Mensaje: "El nombre es obligatorio"}) + } + fase, faseOK := asInt(raw["fase"]) + if !faseOK || fase < 0 || fase > 3 { + detalles = append(detalles, ValidationDetail{Campo: "fase", Mensaje: "La fase debe ser 0, 1, 2 o 3"}) + } + tipoPago := strings.TrimSpace(asString(raw["tipoPago"])) + if tipoPago != "unico" && tipoPago != "mensual" { + detalles = append(detalles, ValidationDetail{Campo: "tipoPago", Mensaje: "tipoPago debe ser unico o mensual"}) + } + precioBase, precioOK := asFloat(raw["precioBase"]) + if !precioOK || precioBase < 0 { + detalles = append(detalles, ValidationDetail{Campo: "precioBase", Mensaje: "precioBase debe ser >= 0"}) + } + if len(detalles) > 0 { + writeValidationError(w, detalles) + return + } + + var categoriaID *string + if cid := strings.TrimSpace(asString(raw["categoriaId"])); cid != "" { + var exists bool + _ = s.Pool.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM "Categoria" WHERE "id" = $1)`, cid).Scan(&exists) + if !exists { + writeValidationError(w, []ValidationDetail{{Campo: "categoriaId", Mensaje: "La categoria no existe"}}) + return + } + categoriaID = &cid + } + + orden, hasOrden := asInt(raw["orden"]) + if !hasOrden { + var maxOrden int + _ = s.Pool.QueryRow(r.Context(), `SELECT COALESCE(MAX("orden"), 0) FROM "ServicioCatalogo" WHERE "fase" = $1`, fase).Scan(&maxOrden) + orden = maxOrden + 1 + } + + tiempoEntrega := firstNonEmptyStr(asString(raw["tiempoEntrega"]), "4 - 10 dias") + entregables := asStringSlice(raw["entregablesDefault"]) + entJSON, _ := json.Marshal(entregables) + + activo := true + if v, ok := raw["activo"].(bool); ok { + activo = v + } + soloAdmin := false + if v, ok := raw["soloAdmin"].(bool); ok { + soloAdmin = v + } + + id := db.NewID() + _, err := s.Pool.Exec(r.Context(), ` + INSERT INTO "ServicioCatalogo" ( + "id", "nombre", "descripcion", "fase", "tipoPago", "precioBase", + "tiempoEntrega", "entregablesDefault", "categoriaId", "variante", "nivel", + "activo", "soloAdmin", "orden", "createdAt", "updatedAt" + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,NOW(),NOW()) + `, id, nombre, nullableTrim(asString(raw["descripcion"])), fase, tipoPago, precioBase, + tiempoEntrega, entJSON, categoriaID, nullableTrim(asString(raw["variante"])), nullableTrim(asString(raw["nivel"])), + activo, soloAdmin, orden) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error creando servicio") + return + } + + list, _ := s.queryServicioCatalogo(r.Context(), `sc."id" = $1`, id) + if len(list) == 1 { + writeJSON(w, http.StatusCreated, list[0]) + return + } + writeJSON(w, http.StatusCreated, map[string]any{"id": id}) +} + +func (s *Server) handleCatalogoPatch(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok { + return + } + id := chi.URLParam(r, "id") + var exists bool + _ = s.Pool.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM "ServicioCatalogo" WHERE "id" = $1)`, id).Scan(&exists) + if !exists { + writeError(w, http.StatusNotFound, "Servicio no encontrado") + return + } + + var raw map[string]any + if err := decodeJSON(r, &raw); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + + sets := []string{`"updatedAt" = NOW()`} + args := []any{} + add := func(col string, val any) { + args = append(args, val) + sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args))) + } + + if v, ok := raw["nombre"]; ok { + nom := strings.TrimSpace(asString(v)) + if nom == "" { + writeValidationError(w, []ValidationDetail{{Campo: "nombre", Mensaje: "El nombre no puede estar vacio"}}) + return + } + add("nombre", nom) + } + if v, ok := raw["descripcion"]; ok { + add("descripcion", nullableTrim(asString(v))) + } + if v, ok := raw["fase"]; ok { + f, okInt := asInt(v) + if !okInt || f < 0 || f > 3 { + writeValidationError(w, []ValidationDetail{{Campo: "fase", Mensaje: "Fase invalida"}}) + return + } + add("fase", f) + } + if v, ok := raw["tipoPago"]; ok { + tp := strings.TrimSpace(asString(v)) + if tp != "unico" && tp != "mensual" { + writeValidationError(w, []ValidationDetail{{Campo: "tipoPago", Mensaje: "tipoPago invalido"}}) + return + } + add("tipoPago", tp) + } + if v, ok := raw["precioBase"]; ok { + pb, okF := asFloat(v) + if !okF || pb < 0 { + writeValidationError(w, []ValidationDetail{{Campo: "precioBase", Mensaje: "precioBase invalido"}}) + return + } + add("precioBase", pb) + } + if v, ok := raw["tiempoEntrega"]; ok { + add("tiempoEntrega", firstNonEmptyStr(asString(v), "4 - 10 dias")) + } + if v, ok := raw["entregablesDefault"]; ok { + entJSON, _ := json.Marshal(asStringSlice(v)) + add("entregablesDefault", entJSON) + } + if v, ok := raw["categoriaId"]; ok { + cid := strings.TrimSpace(asString(v)) + if cid == "" { + add("categoriaId", nil) + } else { + var catOK bool + _ = s.Pool.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM "Categoria" WHERE "id" = $1)`, cid).Scan(&catOK) + if !catOK { + writeValidationError(w, []ValidationDetail{{Campo: "categoriaId", Mensaje: "La categoria no existe"}}) + return + } + add("categoriaId", cid) + } + } + if v, ok := raw["variante"]; ok { + add("variante", nullableTrim(asString(v))) + } + if v, ok := raw["nivel"]; ok { + add("nivel", nullableTrim(asString(v))) + } + if v, ok := raw["activo"].(bool); ok { + add("activo", v) + } + if v, ok := raw["soloAdmin"].(bool); ok { + add("soloAdmin", v) + } + if v, ok := raw["orden"]; ok { + if ord, okInt := asInt(v); okInt { + add("orden", ord) + } + } + + args = append(args, id) + _, err := s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "ServicioCatalogo" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error actualizando servicio") + return + } + + list, _ := s.queryServicioCatalogo(r.Context(), `sc."id" = $1`, id) + if len(list) == 1 { + writeJSON(w, http.StatusOK, list[0]) + return + } + writeJSON(w, http.StatusOK, map[string]any{"id": id}) +} + +func (s *Server) handleCatalogoDelete(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok { + return + } + id := chi.URLParam(r, "id") + var enCot int + if err := s.Pool.QueryRow(r.Context(), `SELECT COUNT(*) FROM "ServicioCotizado" WHERE "servicioCatalogoId" = $1`, id).Scan(&enCot); err != nil { + writeError(w, http.StatusInternalServerError, "Error verificando uso del servicio") + return + } + if enCot > 0 { + tag, err := s.Pool.Exec(r.Context(), `UPDATE "ServicioCatalogo" SET "activo" = false, "updatedAt" = NOW() WHERE "id" = $1`, id) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Servicio no encontrado") + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "archivado": true, "enCotizaciones": enCot}) + return + } + tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "ServicioCatalogo" WHERE "id" = $1`, id) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Servicio no encontrado") + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "eliminado": true}) +} + +func (s *Server) handleCategoriasList(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "categoria"}); !ok { + return + } + rows, err := s.Pool.Query(r.Context(), ` + SELECT c."id", c."nombre", c."descripcion", c."color", c."activo", c."orden", + (SELECT COUNT(*) FROM "ServicioCatalogo" sc WHERE sc."categoriaId" = c."id") AS servicios_count + FROM "Categoria" c + ORDER BY c."orden" ASC, c."nombre" ASC + `) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error listando categorias") + return + } + defer rows.Close() + list := []map[string]any{} + for rows.Next() { + var id, nombre, color string + var desc *string + var activo bool + var orden, cnt int + if rows.Scan(&id, &nombre, &desc, &color, &activo, &orden, &cnt) == nil { + list = append(list, map[string]any{ + "id": id, "nombre": nombre, "descripcion": desc, "color": color, "activo": activo, "orden": orden, + "_count": map[string]any{"servicios": cnt}, + }) + } + } + writeJSON(w, http.StatusOK, list) +} + +func (s *Server) handleCategoriasCreate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "categoria"}); !ok { + return + } + var body struct { + Nombre string `json:"nombre"` + Descripcion *string `json:"descripcion"` + Color string `json:"color"` + Orden *int `json:"orden"` + } + if err := decodeJSON(r, &body); err != nil || strings.TrimSpace(body.Nombre) == "" { + writeError(w, http.StatusBadRequest, "El nombre es obligatorio") + return + } + color := firstNonEmptyStr(body.Color, "#6b7280") + orden := 0 + if body.Orden != nil { + orden = *body.Orden + } else { + _ = s.Pool.QueryRow(r.Context(), `SELECT COALESCE(MAX("orden"), 0) + 1 FROM "Categoria"`).Scan(&orden) + } + id := db.NewID() + _, err := s.Pool.Exec(r.Context(), ` + INSERT INTO "Categoria" ("id", "nombre", "descripcion", "color", "activo", "orden", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, true, $5, NOW(), NOW()) + `, id, strings.TrimSpace(body.Nombre), body.Descripcion, color, orden) + if err != nil { + if strings.Contains(err.Error(), "23505") { + writeError(w, http.StatusConflict, "Ya existe una categoria con ese nombre") + return + } + writeError(w, http.StatusInternalServerError, "Error creando categoria") + return + } + writeJSON(w, http.StatusCreated, map[string]any{ + "id": id, "nombre": strings.TrimSpace(body.Nombre), "descripcion": body.Descripcion, "color": color, "activo": true, "orden": orden, + }) +} + +func (s *Server) handleCategoriasUpdate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "categoria"}); !ok { + return + } + id := chi.URLParam(r, "id") + var body struct { + Nombre *string `json:"nombre"` + Descripcion *string `json:"descripcion"` + Color *string `json:"color"` + Activo *bool `json:"activo"` + Orden *int `json:"orden"` + } + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + sets := []string{`"updatedAt" = NOW()`} + args := []any{} + add := func(col string, val any) { + args = append(args, val) + sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args))) + } + if body.Nombre != nil { + add("nombre", strings.TrimSpace(*body.Nombre)) + } + if body.Descripcion != nil { + add("descripcion", *body.Descripcion) + } + if body.Color != nil { + add("color", *body.Color) + } + if body.Activo != nil { + add("activo", *body.Activo) + } + if body.Orden != nil { + add("orden", *body.Orden) + } + args = append(args, id) + var nombre, color string + var desc *string + var activo bool + var orden int + err := s.Pool.QueryRow(r.Context(), fmt.Sprintf(` + UPDATE "Categoria" SET %s WHERE "id" = $%d + RETURNING "nombre", "descripcion", "color", "activo", "orden" + `, strings.Join(sets, ", "), len(args)), args...).Scan(&nombre, &desc, &color, &activo, &orden) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + writeError(w, http.StatusNotFound, "Categoria no encontrada") + return + } + writeError(w, http.StatusInternalServerError, "Error actualizando categoria") + return + } + writeJSON(w, http.StatusOK, map[string]any{"id": id, "nombre": nombre, "descripcion": desc, "color": color, "activo": activo, "orden": orden}) +} + +func (s *Server) handleCategoriasDelete(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "categoria"}); !ok { + return + } + id := chi.URLParam(r, "id") + var cnt int + _ = s.Pool.QueryRow(r.Context(), `SELECT COUNT(*) FROM "ServicioCatalogo" WHERE "categoriaId" = $1`, id).Scan(&cnt) + if cnt > 0 { + writeError(w, http.StatusConflict, "No se puede eliminar una categoria con servicios asociados") + return + } + tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "Categoria" WHERE "id" = $1`, id) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Categoria no encontrada") + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +func (s *Server) loadPaqueteFull(ctx context.Context, paqueteID string, hideSoloAdmin bool) (map[string]any, error) { + var id, nombre string + var desc *string + var activo bool + err := s.Pool.QueryRow(ctx, `SELECT "id", "nombre", "descripcion", "activo" FROM "Paquete" WHERE "id" = $1`, paqueteID).Scan(&id, &nombre, &desc, &activo) + if err != nil { + return nil, err + } + + faseRows, err := s.Pool.Query(ctx, `SELECT "id", "nombre", "orden" FROM "FasePaquete" WHERE "paqueteId" = $1 ORDER BY "orden" ASC`, id) + if err != nil { + return nil, err + } + defer faseRows.Close() + + fases := []map[string]any{} + for faseRows.Next() { + var fid, fnom string + var forden int + if faseRows.Scan(&fid, &fnom, &forden) != nil { + continue + } + filterAdmin := "" + if hideSoloAdmin { + filterAdmin = ` AND sc."soloAdmin" = false` + } + sRows, _ := s.Pool.Query(ctx, ` + SELECT sp."id", sp."servicioCatalogoId", sc."nombre", sc."descripcion", sc."fase", sc."tipoPago", + sc."precioBase", sc."tiempoEntrega", sc."entregablesDefault", sc."categoriaId", sc."variante", sc."nivel", sc."soloAdmin", + c."nombre", c."color" + FROM "ServicioPaquete" sp + JOIN "ServicioCatalogo" sc ON sc."id" = sp."servicioCatalogoId" + LEFT JOIN "Categoria" c ON c."id" = sc."categoriaId" + WHERE sp."fasePaqueteId" = $1 AND sc."activo" = true`+filterAdmin+` + ORDER BY sc."orden" ASC, sc."nombre" ASC + `, fid) + svcs := []map[string]any{} + if sRows != nil { + for sRows.Next() { + var spid, scid, snom, tp, te string + var sdesc, cid, vari, niv, cnom, ccol *string + var sfase int + var pb float64 + var entRaw []byte + var sadmin bool + if sRows.Scan(&spid, &scid, &snom, &sdesc, &sfase, &tp, &pb, &te, &entRaw, &cid, &vari, &niv, &sadmin, &cnom, &ccol) == nil { + var ent []string + _ = json.Unmarshal(entRaw, &ent) + if ent == nil { + ent = []string{} + } + svcs = append(svcs, map[string]any{ + "id": spid, + "servicioCatalogoId": scid, + "fasePaqueteId": fid, + "servicio": map[string]any{ + "id": scid, "nombre": snom, "descripcion": sdesc, "fase": sfase, + "tipoPago": tp, "precioBase": pb, "tiempoEntrega": te, + "entregablesDefault": ent, "categoriaId": cid, "variante": vari, "nivel": niv, + "soloAdmin": sadmin, "categoriaNombre": cnom, "categoriaColor": ccol, + }, + }) + } + } + sRows.Close() + } + fases = append(fases, map[string]any{ + "id": fid, "paqueteId": id, "nombre": fnom, "orden": forden, "servicios": svcs, + }) + } + return map[string]any{ + "id": id, "nombre": nombre, "descripcion": desc, "activo": activo, "fases": fases, + }, nil +} + +func (s *Server) handlePaquetesList(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "paquete"}) + if !ok { + return + } + rows, err := s.Pool.Query(r.Context(), `SELECT "id" FROM "Paquete" WHERE "activo" = true ORDER BY "createdAt" ASC`) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error listando paquetes") + return + } + defer rows.Close() + var ids []string + for rows.Next() { + var id string + if rows.Scan(&id) == nil { + ids = append(ids, id) + } + } + list := []map[string]any{} + for _, id := range ids { + if p, err := s.loadPaqueteFull(r.Context(), id, actor.IsAgent()); err == nil { + list = append(list, p) + } + } + writeJSON(w, http.StatusOK, list) +} + +func (s *Server) handlePaquetesGet(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"catalogo:leer"}, RecursoTipo: "paquete"}) + if !ok { + return + } + id := chi.URLParam(r, "id") + p, err := s.loadPaqueteFull(r.Context(), id, actor.IsAgent()) + if err != nil { + writeError(w, http.StatusNotFound, "Paquete no encontrado") + return + } + writeJSON(w, http.StatusOK, p) +} + +func (s *Server) handlePaquetesCreate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "paquete"}); !ok { + return + } + var body struct { + Nombre string `json:"nombre"` + Descripcion *string `json:"descripcion"` + Fases []struct { + Nombre string `json:"nombre"` + Orden int `json:"orden"` + } `json:"fases"` + } + if err := decodeJSON(r, &body); err != nil || strings.TrimSpace(body.Nombre) == "" { + writeError(w, http.StatusBadRequest, "El nombre del paquete es obligatorio") + return + } + id := db.NewID() + _, err := s.Pool.Exec(r.Context(), ` + INSERT INTO "Paquete" ("id", "nombre", "descripcion", "activo", "createdAt", "updatedAt") + VALUES ($1, $2, $3, true, NOW(), NOW()) + `, id, strings.TrimSpace(body.Nombre), body.Descripcion) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error creando paquete") + return + } + for i, f := range body.Fases { + ord := f.Orden + if ord == 0 { + ord = i + } + _, _ = s.Pool.Exec(r.Context(), ` + INSERT INTO "FasePaquete" ("id", "paqueteId", "nombre", "orden", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, NOW(), NOW()) + `, db.NewID(), id, strings.TrimSpace(f.Nombre), ord) + } + p, _ := s.loadPaqueteFull(r.Context(), id, false) + writeJSON(w, http.StatusCreated, p) +} + +func (s *Server) handlePaquetesUpdate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "paquete"}); !ok { + return + } + id := chi.URLParam(r, "id") + var body struct { + Nombre *string `json:"nombre"` + Descripcion *string `json:"descripcion"` + Activo *bool `json:"activo"` + } + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + sets := []string{`"updatedAt" = NOW()`} + args := []any{} + add := func(col string, val any) { + args = append(args, val) + sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args))) + } + if body.Nombre != nil { + add("nombre", strings.TrimSpace(*body.Nombre)) + } + if body.Descripcion != nil { + add("descripcion", *body.Descripcion) + } + if body.Activo != nil { + add("activo", *body.Activo) + } + args = append(args, id) + tag, err := s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "Paquete" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Paquete no encontrado") + return + } + p, _ := s.loadPaqueteFull(r.Context(), id, false) + writeJSON(w, http.StatusOK, p) +} + +func (s *Server) handlePaquetesDelete(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "paquete"}); !ok { + return + } + id := chi.URLParam(r, "id") + tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "Paquete" WHERE "id" = $1`, id) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Paquete no encontrado") + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +func (s *Server) handlePaquetesManage(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "paquete"}); !ok { + return + } + paqueteID := chi.URLParam(r, "id") + var body struct { + Action string `json:"action"` + FaseID string `json:"faseId"` + FasePaqueteID string `json:"fasePaqueteId"` + Nombre string `json:"nombre"` + Orden *int `json:"orden"` + ServicioCatalogoID string `json:"servicioCatalogoId"` + } + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + fid := firstNonEmptyStr(body.FasePaqueteID, body.FaseID) + + switch body.Action { + case "addFase": + ord := 0 + if body.Orden != nil { + ord = *body.Orden + } else { + _ = s.Pool.QueryRow(r.Context(), `SELECT COALESCE(MAX("orden"), -1) + 1 FROM "FasePaquete" WHERE "paqueteId" = $1`, paqueteID).Scan(&ord) + } + _, err := s.Pool.Exec(r.Context(), ` + INSERT INTO "FasePaquete" ("id", "paqueteId", "nombre", "orden", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, NOW(), NOW()) + `, db.NewID(), paqueteID, strings.TrimSpace(body.Nombre), ord) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error agregando fase") + return + } + case "updateFase": + if body.Nombre != "" { + _, _ = s.Pool.Exec(r.Context(), `UPDATE "FasePaquete" SET "nombre" = $1, "updatedAt" = NOW() WHERE "id" = $2`, strings.TrimSpace(body.Nombre), fid) + } + if body.Orden != nil { + _, _ = s.Pool.Exec(r.Context(), `UPDATE "FasePaquete" SET "orden" = $1, "updatedAt" = NOW() WHERE "id" = $2`, *body.Orden, fid) + } + case "deleteFase": + _, _ = s.Pool.Exec(r.Context(), `DELETE FROM "FasePaquete" WHERE "id" = $1`, fid) + case "addServicio": + _, _ = s.Pool.Exec(r.Context(), ` + INSERT INTO "ServicioPaquete" ("id", "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt") + VALUES ($1, $2, $3, NOW(), NOW()) + ON CONFLICT ("servicioCatalogoId", "fasePaqueteId") DO NOTHING + `, db.NewID(), body.ServicioCatalogoID, fid) + case "removeServicio": + _, _ = s.Pool.Exec(r.Context(), ` + DELETE FROM "ServicioPaquete" WHERE "servicioCatalogoId" = $1 AND "fasePaqueteId" = $2 + `, body.ServicioCatalogoID, fid) + default: + writeError(w, http.StatusBadRequest, "Accion invalida") + return + } + + p, err := s.loadPaqueteFull(r.Context(), paqueteID, false) + if err != nil { + writeError(w, http.StatusNotFound, "Paquete no encontrado") + return + } + writeJSON(w, http.StatusOK, p) +} + +func (s *Server) handleExportCatalogoCSV(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok { + return + } + list, err := s.queryServicioCatalogo(r.Context(), `sc."activo" = true`) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error exportando catalogo") + return + } + rows := make([]excel.CatalogoCSVRow, 0, len(list)) + for _, it := range list { + cat := "" + if c, ok := it["categoriaNombre"].(*string); ok && c != nil { + cat = *c + } + vari := "" + if v, ok := it["variante"].(*string); ok && v != nil { + vari = *v + } + ent, _ := it["entregablesDefault"].([]string) + rows = append(rows, excel.CatalogoCSVRow{ + Nombre: asString(it["nombre"]), + Categoria: cat, + Fase: it["fase"].(int), + TipoPago: asString(it["tipoPago"]), + PrecioBase: it["precioBase"].(float64), + TiempoEntrega: asString(it["tiempoEntrega"]), + Entregables: ent, + Variante: vari, + }) + } + csvBytes, err := excel.ExportCatalogoCSV(rows) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error generando CSV") + return + } + w.Header().Set("Content-Type", "text/csv; charset=utf-8") + w.Header().Set("Content-Disposition", `attachment; filename="catalogo-servicios.csv"`) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(csvBytes) +} + +func (s *Server) handleExportCatalogoPlantilla(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok { + return + } + w.Header().Set("Content-Type", "text/csv; charset=utf-8") + w.Header().Set("Content-Disposition", `attachment; filename="plantilla-catalogo.csv"`) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(excel.PlantillaCatalogoCSV()) +} + +func (s *Server) handleImportCatalogoCSV(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "catalogo"}); !ok { + return + } + if err := r.ParseMultipartForm(10 << 20); err != nil { + writeError(w, http.StatusBadRequest, "Error leyendo archivo multipart") + return + } + file, _, err := r.FormFile("file") + if err != nil { + writeError(w, http.StatusBadRequest, "Se requiere el archivo en el campo 'file'") + return + } + defer file.Close() + raw, err := io.ReadAll(io.LimitReader(file, 10<<20)) + if err != nil { + writeError(w, http.StatusBadRequest, "No se pudo leer el archivo") + return + } + rows, err := excel.ParseCatalogoCSV(raw) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + + catMap := map[string]string{} + cRows, _ := s.Pool.Query(r.Context(), `SELECT "id", LOWER("nombre") FROM "Categoria" WHERE "activo" = true`) + if cRows != nil { + for cRows.Next() { + var cid, cnom string + if cRows.Scan(&cid, &cnom) == nil { + catMap[cnom] = cid + } + } + cRows.Close() + } + + imported := 0 + for i, row := range rows { + var catID *string + if id, ok := catMap[strings.ToLower(strings.TrimSpace(row.Categoria))]; ok { + cid := id + catID = &cid + } + entJSON, _ := json.Marshal(row.Entregables) + _, err := s.Pool.Exec(r.Context(), ` + INSERT INTO "ServicioCatalogo" ( + "id", "nombre", "fase", "tipoPago", "precioBase", "tiempoEntrega", + "entregablesDefault", "categoriaId", "variante", "activo", "soloAdmin", "orden", "createdAt", "updatedAt" + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,true,false,$10,NOW(),NOW()) + `, db.NewID(), row.Nombre, row.Fase, row.TipoPago, row.PrecioBase, firstNonEmptyStr(row.TiempoEntrega, "4 - 10 dias"), + entJSON, catID, nullableTrim(row.Variante), i+1) + if err == nil { + imported++ + } + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "importados": imported}) +} + +func asString(v any) string { + if v == nil { + return "" + } + s, ok := v.(string) + if ok { + return s + } + return fmt.Sprintf("%v", v) +} + +func nullableTrim(s string) *string { + t := strings.TrimSpace(s) + if t == "" { + return nil + } + return &t +} + +func asInt(v any) (int, bool) { + switch x := v.(type) { + case float64: + return int(x), true + case int: + return x, true + case string: + n, err := strconv.Atoi(strings.TrimSpace(x)) + return n, err == nil + default: + return 0, false + } +} + +func asFloat(v any) (float64, bool) { + switch x := v.(type) { + case float64: + return x, true + case int: + return float64(x), true + case string: + f, err := strconv.ParseFloat(strings.TrimSpace(x), 64) + return f, err == nil + default: + return 0, false + } +} + +func asStringSlice(v any) []string { + if v == nil { + return []string{} + } + switch arr := v.(type) { + case []string: + return arr + case []any: + out := make([]string, 0, len(arr)) + for _, item := range arr { + if s := strings.TrimSpace(asString(item)); s != "" { + out = append(out, s) + } + } + return out + default: + return []string{} + } +} diff --git a/internal/httpapi/cliente_portal_handlers.go b/internal/httpapi/cliente_portal_handlers.go new file mode 100644 index 0000000..0e82b99 --- /dev/null +++ b/internal/httpapi/cliente_portal_handlers.go @@ -0,0 +1,438 @@ +package httpapi + +import ( + "context" + "errors" + "io" + "net/http" + "strings" + "time" + + "cotizador/internal/db" + "cotizador/internal/domain" + "cotizador/internal/uploads" + + "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5" +) + +func (s *Server) handleClienteResumen(w http.ResponseWriter, r *http.Request) { + sess, ok := s.Auth.RequireCliente(w, r) + if !ok { + return + } + ctx := r.Context() + cid := sess.ClienteID + hoy := domain.HoyCalendario() + inicioMes := time.Date(hoy.Year(), hoy.Month(), 1, 0, 0, 0, 0, time.UTC) + + var nombre string + var empresa, email *string + if err := s.Pool.QueryRow(ctx, `SELECT "nombre", "empresa", "email" FROM "Cliente" WHERE "id" = $1`, cid).Scan(&nombre, &empresa, &email); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + writeError(w, http.StatusNotFound, "Cliente no encontrado") + return + } + writeError(w, http.StatusInternalServerError, "Error cargando perfil") + return + } + + var totalCot, pagosPendientes, pagosEnRevision, pagosVerificadosMes int + _ = s.Pool.QueryRow(ctx, `SELECT COUNT(*) FROM "Cotizacion" WHERE "clienteId" = $1 AND "archivado" = false`, cid).Scan(&totalCot) + _ = s.Pool.QueryRow(ctx, ` + SELECT COUNT(*) FROM "PagoRecurrente" p JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + WHERE pr."clienteId" = $1 AND p."estado" IN ('pendiente', 'rechazado') + `, cid).Scan(&pagosPendientes) + _ = s.Pool.QueryRow(ctx, ` + SELECT COUNT(*) FROM "PagoRecurrente" p JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + WHERE pr."clienteId" = $1 AND p."estado" = 'en_revision' + `, cid).Scan(&pagosEnRevision) + _ = s.Pool.QueryRow(ctx, ` + SELECT COUNT(*) FROM "PagoRecurrente" p JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + WHERE pr."clienteId" = $1 AND p."estado" = 'verificado' AND COALESCE(p."verificadoAt", p."fecha") >= $2 + `, cid, inicioMes).Scan(&pagosVerificadosMes) + + // Pending balance + oldest unpaid date + saldoPendiente := map[string]float64{} + var masAntiguo *time.Time + pendRows, _ := s.Pool.Query(ctx, ` + SELECT p."fecha", p."monto", pr."moneda" + FROM "PagoRecurrente" p + JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + WHERE pr."clienteId" = $1 AND p."estado" IN ('pendiente', 'rechazado') + ORDER BY p."fecha" ASC + `, cid) + if pendRows != nil { + for pendRows.Next() { + var fecha time.Time + var monto float64 + var mon string + if pendRows.Scan(&fecha, &monto, &mon) == nil { + saldoPendiente[mon] = domain.Round2(saldoPendiente[mon] + monto) + if masAntiguo == nil || fecha.Before(*masAntiguo) { + t := fecha + masAntiguo = &t + } + } + } + pendRows.Close() + } + + // Upcoming scheduled charges from active programs + proximos := []map[string]any{} + progRows, _ := s.Pool.Query(ctx, ` + SELECT "concepto", "monto", "moneda", "frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin" + FROM "ProgramaPago" + WHERE "clienteId" = $1 AND "activo" = true + ORDER BY "createdAt" DESC + `, cid) + if progRows != nil { + for progRows.Next() { + var conc, mon, frec string + var monto float64 + var ds, dm *int + var fIni time.Time + var fFin *time.Time + if progRows.Scan(&conc, &monto, &mon, &frec, &ds, &dm, &fIni, &fFin) == nil { + if prox := domain.ProximaFecha(domain.ProgramaCalendario{ + Frecuencia: frec, DiaSemana: ds, DiaMes: dm, FechaInicio: fIni, FechaFin: fFin, + }, hoy); prox != nil { + proximos = append(proximos, map[string]any{ + "fecha": *prox, + "monto": monto, + "moneda": mon, + "concepto": conc, + }) + } + } + } + progRows.Close() + } + + // Recent cotizaciones + cRows, _ := s.Pool.Query(ctx, ` + SELECT "id", "numero", "proyecto", "estado", "fecha", "vigencia", "moneda", "esDoble", "incluirIva" + FROM "Cotizacion" + WHERE "clienteId" = $1 AND "archivado" = false + ORDER BY "createdAt" DESC + LIMIT 5 + `, cid) + cotRecientes := []map[string]any{} + if cRows != nil { + for cRows.Next() { + var qid, num, proy, est, mon string + var fecha, vig time.Time + var esDoble, incIva bool + if cRows.Scan(&qid, &num, &proy, &est, &fecha, &vig, &mon, &esDoble, &incIva) == nil { + cotRecientes = append(cotRecientes, s.enrichClienteCotSummary(ctx, qid, num, proy, est, mon, fecha, vig, esDoble, incIva)) + } + } + cRows.Close() + } + + writeJSON(w, http.StatusOK, map[string]any{ + "cliente": map[string]any{"id": cid, "nombre": nombre, "empresa": empresa, "email": email}, + "cotizacionesActivas": totalCot, + "cotizaciones": cotRecientes, + "pagos": map[string]any{ + "pendientes": pagosPendientes, + "saldoPendiente": saldoPendiente, + "masAntiguo": masAntiguo, + "enRevision": pagosEnRevision, + "verificadosMes": pagosVerificadosMes, + "proximos": proximos, + }, + }) +} + +func (s *Server) enrichClienteCotSummary(ctx context.Context, qid, num, proy, est, mon string, fecha, vig time.Time, esDoble, incIva bool) map[string]any { + full, _, err := s.loadCotizacionFull(ctx, qid, true) + var tot domain.TotalesCotizacion + var totalesOpciones map[string]any + if err == nil { + tot = domain.CalcularTotalesCotizacion(full.ServiciosCalc, incIva) + if esDoble { + o1 := domain.CalcularTotalesOpcion(full.ServiciosCalc, "1") + o2 := domain.CalcularTotalesOpcion(full.ServiciosCalc, "2") + totalesOpciones = map[string]any{"1": o1, "2": o2} + } + } + return map[string]any{ + "id": qid, "numero": num, "proyecto": proy, "estado": est, "moneda": mon, + "fecha": fecha, "vigencia": vig, "esDoble": esDoble, "incluirIva": incIva, + "totales": tot, "totalesOpciones": totalesOpciones, + } +} + +func (s *Server) handleClienteCotizacionesList(w http.ResponseWriter, r *http.Request) { + sess, ok := s.Auth.RequireCliente(w, r) + if !ok { + return + } + rows, err := s.Pool.Query(r.Context(), ` + SELECT "id", "numero", "proyecto", "estado", "fecha", "vigencia", "moneda", "esDoble", "incluirIva" + FROM "Cotizacion" + WHERE "clienteId" = $1 AND "archivado" = false + ORDER BY "createdAt" DESC + `, sess.ClienteID) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error cargando cotizaciones") + return + } + defer rows.Close() + list := []map[string]any{} + for rows.Next() { + var qid, num, proy, est, mon string + var fecha, vig time.Time + var esDoble, incIva bool + if rows.Scan(&qid, &num, &proy, &est, &fecha, &vig, &mon, &esDoble, &incIva) == nil { + list = append(list, s.enrichClienteCotSummary(r.Context(), qid, num, proy, est, mon, fecha, vig, esDoble, incIva)) + } + } + writeJSON(w, http.StatusOK, list) +} + +func (s *Server) handleClienteCotizacionGet(w http.ResponseWriter, r *http.Request) { + sess, ok := s.Auth.RequireCliente(w, r) + if !ok { + return + } + id := chi.URLParam(r, "id") + full, jsonMap, err := s.loadCotizacionFull(r.Context(), id, true) + if err != nil || full.ClienteID != sess.ClienteID { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + // Never expose internal notes or registrosHoras to client view + jsonMap["observacionesInternas"] = nil + writeJSON(w, http.StatusOK, jsonMap) +} + +func (s *Server) handleClientePagosList(w http.ResponseWriter, r *http.Request) { + sess, ok := s.Auth.RequireCliente(w, r) + if !ok { + return + } + ctx := r.Context() + + // Load programs belonging to client + progRows, err := s.Pool.Query(ctx, ` + SELECT "id", "concepto", "monto", "moneda", "frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin", "activo" + FROM "ProgramaPago" + WHERE "clienteId" = $1 + ORDER BY "activo" DESC, "createdAt" DESC + `, sess.ClienteID) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error cargando pagos") + return + } + defer progRows.Close() + + programas := []map[string]any{} + progByID := map[string]map[string]any{} + for progRows.Next() { + var pid, conc, mon, frec string + var monto float64 + var ds, dm *int + var fIni time.Time + var fFin *time.Time + var activo bool + if progRows.Scan(&pid, &conc, &monto, &mon, &frec, &ds, &dm, &fIni, &fFin, &activo) == nil { + pm := map[string]any{ + "id": pid, "concepto": conc, "monto": monto, "moneda": mon, + "frecuencia": frec, "diaSemana": ds, "diaMes": dm, + "fechaInicio": fIni, "fechaFin": fFin, "activo": activo, + "pagos": []map[string]any{}, + } + programas = append(programas, pm) + progByID[pid] = pm + } + } + + // Load payments (omitting internal `nota` for clients!) + pRows, _ := s.Pool.Query(ctx, ` + SELECT p."id", p."programaId", p."fecha", p."monto", p."estado", + p."verificadoAt", p."rechazadoAt", p."rechazoMotivo", + pr."concepto", pr."moneda", pr."frecuencia", + c."id", c."archivoNombre", c."mime", c."tamano", c."subidoAt" + FROM "PagoRecurrente" p + JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + LEFT JOIN "ComprobantePago" c ON c."pagoId" = p."id" + WHERE pr."clienteId" = $1 + ORDER BY p."fecha" DESC + `, sess.ClienteID) + pagos := []map[string]any{} + if pRows != nil { + defer pRows.Close() + for pRows.Next() { + var id, progID, est, conc, mon, frec string + var rmot, compID, compNom, compMime *string + var fecha time.Time + var monto float64 + var verifAt, rechAt, compSub *time.Time + var compTam *int + if pRows.Scan(&id, &progID, &fecha, &monto, &est, &verifAt, &rechAt, &rmot, + &conc, &mon, &frec, &compID, &compNom, &compMime, &compTam, &compSub) == nil { + var comp any + if compID != nil { + comp = map[string]any{ + "id": *compID, "pagoId": id, "archivoNombre": compNom, "mime": compMime, "tamano": compTam, "subidoAt": compSub, + } + } + row := map[string]any{ + "id": id, "programaId": progID, "fecha": fecha, "monto": monto, "estado": est, + "verificadoAt": verifAt, "rechazadoAt": rechAt, "rechazoMotivo": rmot, + "programa": map[string]any{"id": progID, "concepto": conc, "moneda": mon, "frecuencia": frec}, + "comprobante": comp, + } + pagos = append(pagos, row) + if pm, ok := progByID[progID]; ok { + pm["pagos"] = append(pm["pagos"].([]map[string]any), row) + } + } + } + } + + writeJSON(w, http.StatusOK, map[string]any{ + "pagos": pagos, + "programas": programas, + "bancaria": s.getConfigBancaria(ctx), + }) +} + +func (s *Server) handleClienteComprobanteUpload(w http.ResponseWriter, r *http.Request) { + sess, ok := s.Auth.RequireCliente(w, r) + if !ok { + return + } + pagoID := chi.URLParam(r, "id") + + var estado, ownerClienteID string + err := s.Pool.QueryRow(r.Context(), ` + SELECT p."estado", pr."clienteId" + FROM "PagoRecurrente" p + JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + WHERE p."id" = $1 + `, pagoID).Scan(&estado, &ownerClienteID) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + writeError(w, http.StatusNotFound, "Cobro no encontrado") + return + } + writeError(w, http.StatusInternalServerError, "Error verificando cobro") + return + } + if ownerClienteID != sess.ClienteID { + writeError(w, http.StatusForbidden, "No tienes acceso a este cobro") + return + } + if estado != domain.EstadoPagoPendiente && estado != domain.EstadoPagoRechazado { + writeError(w, http.StatusConflict, "Solo puedes subir comprobante para cobros pendientes o rechazados") + return + } + + if err := r.ParseMultipartForm(uploads.MaxFileSizeBytes + (1 << 20)); err != nil { + writeError(w, http.StatusBadRequest, "Error leyendo formulario de archivo") + return + } + file, header, err := r.FormFile("file") + if err != nil { + writeError(w, http.StatusBadRequest, "Se requiere el archivo en el campo 'file'") + return + } + defer file.Close() + + raw, err := io.ReadAll(io.LimitReader(file, uploads.MaxFileSizeBytes+1)) + if err != nil { + writeError(w, http.StatusBadRequest, "Error leyendo archivo") + return + } + saved, err := uploads.GuardarComprobante(s.Cfg.UploadDir, pagoID, header.Filename, header.Header.Get("Content-Type"), raw) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + + // Remove previous comprobante if any + var oldRuta string + _ = s.Pool.QueryRow(r.Context(), `SELECT "archivoRuta" FROM "ComprobantePago" WHERE "pagoId" = $1`, pagoID).Scan(&oldRuta) + if oldRuta != "" { + _ = uploads.EliminarComprobante(s.Cfg.UploadDir, oldRuta) + _, _ = s.Pool.Exec(r.Context(), `DELETE FROM "ComprobantePago" WHERE "pagoId" = $1`, pagoID) + } + + compID := db.NewID() + _, err = s.Pool.Exec(r.Context(), ` + INSERT INTO "ComprobantePago" ("id", "pagoId", "archivoRuta", "archivoNombre", "mime", "tamano", "subidoAt") + VALUES ($1, $2, $3, $4, $5, $6, NOW()) + `, compID, pagoID, saved.ArchivoRuta, saved.ArchivoNombre, saved.Mime, saved.Tamano) + if err != nil { + _ = uploads.EliminarComprobante(s.Cfg.UploadDir, saved.ArchivoRuta) + writeError(w, http.StatusInternalServerError, "Error registrando comprobante") + return + } + _, _ = s.Pool.Exec(r.Context(), ` + UPDATE "PagoRecurrente" SET "estado"='en_revision', "rechazoMotivo"=NULL, "updatedAt"=NOW() WHERE "id" = $1 + `, pagoID) + + writeJSON(w, http.StatusCreated, map[string]any{ + "ok": true, "id": compID, "pagoId": pagoID, "estado": "en_revision", + "archivoNombre": saved.ArchivoNombre, "mime": saved.Mime, "tamano": saved.Tamano, + }) +} + +func (s *Server) handleClientePushConfig(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireCliente(w, r); !ok { + return + } + if !s.Notify.VAPIDConfigured() { + writeError(w, http.StatusNotImplemented, "Notificaciones push no configuradas") + return + } + writeJSON(w, http.StatusOK, map[string]any{"publicKey": s.Cfg.VAPIDPublicKey}) +} + +func (s *Server) handleClientePushSubscribe(w http.ResponseWriter, r *http.Request) { + sess, ok := s.Auth.RequireCliente(w, r) + if !ok { + return + } + var body struct { + Endpoint string `json:"endpoint"` + Keys struct { + P256dh string `json:"p256dh"` + Auth string `json:"auth"` + } `json:"keys"` + } + if err := decodeJSON(r, &body); err != nil || strings.TrimSpace(body.Endpoint) == "" || body.Keys.P256dh == "" || body.Keys.Auth == "" { + writeError(w, http.StatusBadRequest, "Suscripcion push invalida") + return + } + _, err := s.Pool.Exec(r.Context(), ` + INSERT INTO "SuscripcionPush" ("id", "userId", "endpoint", "p256dh", "auth", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, $5, NOW(), NOW()) + ON CONFLICT ("endpoint") DO UPDATE SET "userId" = EXCLUDED."userId", "p256dh" = EXCLUDED."p256dh", "auth" = EXCLUDED."auth", "updatedAt" = NOW() + `, db.NewID(), sess.UserID, strings.TrimSpace(body.Endpoint), body.Keys.P256dh, body.Keys.Auth) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error guardando suscripcion push") + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +func (s *Server) handleClientePushUnsubscribe(w http.ResponseWriter, r *http.Request) { + sess, ok := s.Auth.RequireCliente(w, r) + if !ok { + return + } + var body struct { + Endpoint string `json:"endpoint"` + } + _ = decodeJSON(r, &body) + if strings.TrimSpace(body.Endpoint) != "" { + _, _ = s.Pool.Exec(r.Context(), `DELETE FROM "SuscripcionPush" WHERE "userId" = $1 AND "endpoint" = $2`, sess.UserID, strings.TrimSpace(body.Endpoint)) + } else { + _, _ = s.Pool.Exec(r.Context(), `DELETE FROM "SuscripcionPush" WHERE "userId" = $1`, sess.UserID) + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} diff --git a/internal/httpapi/clientes_handlers.go b/internal/httpapi/clientes_handlers.go new file mode 100644 index 0000000..276b789 --- /dev/null +++ b/internal/httpapi/clientes_handlers.go @@ -0,0 +1,418 @@ +package httpapi + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "cotizador/internal/audit" + "cotizador/internal/auth" + "cotizador/internal/db" + "cotizador/internal/idempotency" + + "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5" +) + +func (s *Server) queryClientes(ctx context.Context, whereSQL string, args ...any) ([]map[string]any, error) { + rows, err := s.Pool.Query(ctx, ` + SELECT c."id", c."nombre", c."empresa", c."puesto", c."email", c."telefono", c."rfc", + c."archivado", c."archivadoAt", c."createdAt", c."updatedAt", + u."id", u."email", + (SELECT COUNT(*) FROM "Cotizacion" q WHERE q."clienteId" = c."id" AND q."archivado" = false) AS cot_count, + (SELECT COUNT(*) FROM "ProgramaPago" p WHERE p."clienteId" = c."id" AND p."activo" = true) AS prog_count + FROM "Cliente" c + LEFT JOIN "User" u ON u."clienteId" = c."id" + WHERE `+whereSQL+` + ORDER BY c."nombre" ASC + `, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + list := []map[string]any{} + for rows.Next() { + var id, nombre string + var empresa, puesto, email, telefono, rfc, uid, uemail *string + var archivado bool + var archivadoAt *time.Time + var createdAt, updatedAt time.Time + var cotCount, progCount int + if rows.Scan(&id, &nombre, &empresa, &puesto, &email, &telefono, &rfc, &archivado, &archivadoAt, &createdAt, &updatedAt, &uid, &uemail, &cotCount, &progCount) == nil { + var usuario any + if uid != nil { + usuario = map[string]any{"id": *uid, "email": uemail} + } + list = append(list, map[string]any{ + "id": id, + "nombre": nombre, + "empresa": empresa, + "puesto": puesto, + "email": email, + "telefono": telefono, + "rfc": rfc, + "archivado": archivado, + "archivadoAt": archivadoAt, + "createdAt": createdAt, + "updatedAt": updatedAt, + "usuario": usuario, + "_count": map[string]any{ + "cotizaciones": cotCount, + "programasPago": progCount, + }, + }) + } + } + return list, nil +} + +func (s *Server) clienteDuplicadoExiste(ctx context.Context, nombre, empresa, excludeID string) (bool, error) { + empNorm := strings.ToLower(strings.TrimSpace(empresa)) + var exists bool + err := s.Pool.QueryRow(ctx, ` + SELECT EXISTS( + SELECT 1 FROM "Cliente" + WHERE "archivado" = false + AND LOWER(TRIM("nombre")) = LOWER(TRIM($1)) + AND LOWER(TRIM(COALESCE("empresa", ''))) = $2 + AND ($3 = '' OR "id" <> $3) + ) + `, nombre, empNorm, excludeID).Scan(&exists) + return exists, err +} + +func (s *Server) handleClientesList(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"clientes:leer"}, RecursoTipo: "cliente"}) + if !ok { + return + } + q := r.URL.Query() + conds := []string{"1=1"} + args := []any{} + add := func(v any) string { + args = append(args, v) + return fmt.Sprintf("$%d", len(args)) + } + + incluirArchivados := !actor.IsAgent() && q.Get("incluirArchivados") == "true" + if !incluirArchivados { + conds = append(conds, `c."archivado" = false`) + } + if search := strings.TrimSpace(q.Get("q")); search != "" { + p := add("%" + search + "%") + conds = append(conds, fmt.Sprintf(`(c."nombre" ILIKE %s OR COALESCE(c."empresa", '') ILIKE %s OR COALESCE(c."email", '') ILIKE %s OR COALESCE(c."rfc", '') ILIKE %s)`, p, p, p, p)) + } + + list, err := s.queryClientes(r.Context(), strings.Join(conds, " AND "), args...) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error listando clientes") + return + } + writeJSON(w, http.StatusOK, list) +} + +func (s *Server) handleClientesCreate(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"clientes:escribir"}, RecursoTipo: "cliente"}) + if !ok { + return + } + idempotency.Execute(r.Context(), s.Pool, w, r, actor, func(rawBody []byte) (int, any) { + var body struct { + Nombre string `json:"nombre"` + Empresa *string `json:"empresa"` + Puesto *string `json:"puesto"` + Email *string `json:"email"` + Telefono *string `json:"telefono"` + RFC *string `json:"rfc"` + } + if err := json.Unmarshal(rawBody, &body); err != nil { + return http.StatusBadRequest, map[string]any{"error": "JSON invalido"} + } + nombre := strings.TrimSpace(body.Nombre) + if nombre == "" { + return http.StatusBadRequest, map[string]any{ + "error": "Datos invalidos", + "detalles": []ValidationDetail{{Campo: "nombre", Mensaje: "El nombre del cliente es obligatorio"}}, + } + } + empStr := "" + if body.Empresa != nil { + empStr = strings.TrimSpace(*body.Empresa) + } + dup, err := s.clienteDuplicadoExiste(r.Context(), nombre, empStr, "") + if err != nil { + return http.StatusInternalServerError, map[string]any{"error": "Error validando duplicado"} + } + if dup { + return http.StatusConflict, map[string]any{"error": "Ya existe un cliente con el mismo nombre y empresa"} + } + + id := db.NewID() + _, err = s.Pool.Exec(r.Context(), ` + INSERT INTO "Cliente" ("id", "nombre", "empresa", "puesto", "email", "telefono", "rfc", "archivado", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, $5, $6, $7, false, NOW(), NOW()) + `, id, nombre, nullableTrim(empStr), trimPtr(body.Puesto), trimPtr(body.Email), trimPtr(body.Telefono), trimPtr(body.RFC)) + if err != nil { + return http.StatusInternalServerError, map[string]any{"error": "Error creando cliente"} + } + + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cliente.crear", RecursoTipo: "cliente", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + Detalle: map[string]any{"nombre": nombre, "empresa": empStr}, + }) + + list, _ := s.queryClientes(r.Context(), `c."id" = $1`, id) + if len(list) == 1 { + return http.StatusCreated, list[0] + } + return http.StatusCreated, map[string]any{"id": id, "nombre": nombre} + }) +} + +func (s *Server) handleClientesUpdate(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"clientes:escribir"}, RecursoTipo: "cliente"}) + if !ok { + return + } + id := chi.URLParam(r, "id") + var curNombre string + var curEmpresa *string + err := s.Pool.QueryRow(r.Context(), `SELECT "nombre", "empresa" FROM "Cliente" WHERE "id" = $1`, id).Scan(&curNombre, &curEmpresa) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + writeError(w, http.StatusNotFound, "Cliente no encontrado") + return + } + writeError(w, http.StatusInternalServerError, "Error consultando cliente") + return + } + + var raw map[string]any + if err := decodeJSON(r, &raw); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + + newNombre := curNombre + if v, ok := raw["nombre"]; ok { + newNombre = strings.TrimSpace(asString(v)) + if newNombre == "" { + writeValidationError(w, []ValidationDetail{{Campo: "nombre", Mensaje: "El nombre no puede estar vacio"}}) + return + } + } + newEmpresa := "" + if curEmpresa != nil { + newEmpresa = *curEmpresa + } + if v, ok := raw["empresa"]; ok { + newEmpresa = strings.TrimSpace(asString(v)) + } + + if dup, _ := s.clienteDuplicadoExiste(r.Context(), newNombre, newEmpresa, id); dup { + writeError(w, http.StatusConflict, "Ya existe otro cliente con el mismo nombre y empresa") + return + } + + sets := []string{`"updatedAt" = NOW()`} + args := []any{} + add := func(col string, val any) { + args = append(args, val) + sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args))) + } + if _, ok := raw["nombre"]; ok { + add("nombre", newNombre) + } + if _, ok := raw["empresa"]; ok { + add("empresa", nullableTrim(newEmpresa)) + } + if v, ok := raw["puesto"]; ok { + add("puesto", nullableTrim(asString(v))) + } + if v, ok := raw["email"]; ok { + add("email", nullableTrim(asString(v))) + } + if v, ok := raw["telefono"]; ok { + add("telefono", nullableTrim(asString(v))) + } + if v, ok := raw["rfc"]; ok { + add("rfc", nullableTrim(asString(v))) + } + args = append(args, id) + _, err = s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "Cliente" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error actualizando cliente") + return + } + + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cliente.actualizar", RecursoTipo: "cliente", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + }) + + list, _ := s.queryClientes(r.Context(), `c."id" = $1`, id) + if len(list) == 1 { + writeJSON(w, http.StatusOK, list[0]) + return + } + writeJSON(w, http.StatusOK, map[string]any{"id": id}) +} + +func (s *Server) handleClienteAccesoCreate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cliente_acceso"}); !ok { + return + } + clienteID := chi.URLParam(r, "id") + var cliNombre string + if err := s.Pool.QueryRow(r.Context(), `SELECT "nombre" FROM "Cliente" WHERE "id" = $1`, clienteID).Scan(&cliNombre); err != nil { + writeError(w, http.StatusNotFound, "Cliente no encontrado") + return + } + + var body struct { + Email string `json:"email"` + Password string `json:"password"` + } + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + email := strings.ToLower(strings.TrimSpace(body.Email)) + if email == "" || len(body.Password) < 6 { + writeError(w, http.StatusBadRequest, "Email y contrasena (minimo 6 caracteres) requeridos") + return + } + + hash, err := auth.HashPassword(body.Password) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error encriptando contrasena") + return + } + + // Check if another user owns this email + var conflict bool + _ = s.Pool.QueryRow(r.Context(), ` + SELECT EXISTS(SELECT 1 FROM "User" WHERE LOWER("email") = $1 AND ("clienteId" IS NULL OR "clienteId" <> $2)) + `, email, clienteID).Scan(&conflict) + if conflict { + writeError(w, http.StatusConflict, "Ese correo ya esta en uso por otra cuenta") + return + } + + var existingID string + err = s.Pool.QueryRow(r.Context(), `SELECT "id" FROM "User" WHERE "clienteId" = $1`, clienteID).Scan(&existingID) + if err == nil && existingID != "" { + _, err = s.Pool.Exec(r.Context(), ` + UPDATE "User" SET "email" = $1, "password" = $2, "name" = $3, "role" = 'cliente', "updatedAt" = NOW() + WHERE "id" = $4 + `, email, hash, cliNombre, existingID) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error actualizando acceso") + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": existingID, "email": email, "actualizado": true}) + return + } + + uid := db.NewID() + _, err = s.Pool.Exec(r.Context(), ` + INSERT INTO "User" ("id", "email", "password", "name", "role", "clienteId", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, 'cliente', $5, NOW(), NOW()) + `, uid, email, hash, cliNombre, clienteID) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error creando cuenta de cliente") + return + } + writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "id": uid, "email": email}) +} + +func (s *Server) handleClienteAccesoDelete(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cliente_acceso"}); !ok { + return + } + clienteID := chi.URLParam(r, "id") + _, _ = s.Pool.Exec(r.Context(), `DELETE FROM "User" WHERE "clienteId" = $1 AND "role" = 'cliente'`, clienteID) + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +func (s *Server) handleClienteArchivar(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{ + StaffOnly: true, + AccionBloqueo: "cliente.archivar_bloqueado", + RecursoTipo: "cliente", + }) + if !ok { + return + } + clienteID := chi.URLParam(r, "id") + var body struct { + Archivado *bool `json:"archivado"` + IncluirCotizaciones *bool `json:"incluirCotizaciones"` + } + _ = decodeJSON(r, &body) + archivado := true + if body.Archivado != nil { + archivado = *body.Archivado + } + incluirCot := true + if body.IncluirCotizaciones != nil { + incluirCot = *body.IncluirCotizaciones + } + + var archAt *time.Time + if archivado { + now := time.Now() + archAt = &now + } + + tag, err := s.Pool.Exec(r.Context(), ` + UPDATE "Cliente" SET "archivado" = $1, "archivadoAt" = $2, "updatedAt" = NOW() WHERE "id" = $3 + `, archivado, archAt, clienteID) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Cliente no encontrado") + return + } + var cotAfectadas int64 + if incluirCot { + ctag, _ := s.Pool.Exec(r.Context(), ` + UPDATE "Cotizacion" SET "archivado" = $1, "archivadoAt" = $2, "updatedAt" = NOW() WHERE "clienteId" = $3 + `, archivado, archAt, clienteID) + cotAfectadas = ctag.RowsAffected() + } + + accion := "cliente.archivar" + if !archivado { + accion = "cliente.desarchivar" + } + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: accion, RecursoTipo: "cliente", RecursoID: clienteID, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + Detalle: map[string]any{"archivado": archivado, "cotizacionesAfectadas": cotAfectadas}, + }) + + writeJSON(w, http.StatusOK, map[string]any{ + "ok": true, + "id": clienteID, + "archivado": archivado, + "cotizacionesAfectadas": cotAfectadas, + }) +} + +func trimPtr(p *string) *string { + if p == nil { + return nil + } + return nullableTrim(*p) +} diff --git a/internal/httpapi/cobros_handlers.go b/internal/httpapi/cobros_handlers.go new file mode 100644 index 0000000..a7ab849 --- /dev/null +++ b/internal/httpapi/cobros_handlers.go @@ -0,0 +1,701 @@ +package httpapi + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "strings" + "time" + + "cotizador/internal/audit" + "cotizador/internal/auth" + "cotizador/internal/db" + "cotizador/internal/domain" + "cotizador/internal/idempotency" + "cotizador/internal/scheduler" + "cotizador/internal/uploads" + + "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5" +) + +func (s *Server) queryProgramas(ctx context.Context) ([]map[string]any, error) { + rows, err := s.Pool.Query(ctx, ` + SELECT p."id", p."clienteId", p."cotizacionId", p."concepto", p."monto", p."moneda", + p."frecuencia", p."diaSemana", p."diaMes", p."fechaInicio", p."fechaFin", p."activo", + p."createdAt", p."updatedAt", + c."nombre", c."empresa", c."email", + (SELECT COUNT(*) FROM "PagoRecurrente" pr WHERE pr."programaId" = p."id") AS pagos_count + FROM "ProgramaPago" p + JOIN "Cliente" c ON c."id" = p."clienteId" + ORDER BY p."activo" DESC, p."createdAt" DESC + `) + if err != nil { + return nil, err + } + defer rows.Close() + + hoy := domain.HoyCalendario() + list := []map[string]any{} + for rows.Next() { + var id, clienteID, concepto, moneda, frecuencia, cNombre string + var cotID, cEmpresa, cEmail *string + var monto float64 + var diaSemana, diaMes *int + var fechaInicio, createdAt, updatedAt time.Time + var fechaFin *time.Time + var activo bool + var pagosCount int + if rows.Scan(&id, &clienteID, &cotID, &concepto, &monto, &moneda, &frecuencia, &diaSemana, &diaMes, + &fechaInicio, &fechaFin, &activo, &createdAt, &updatedAt, &cNombre, &cEmpresa, &cEmail, &pagosCount) == nil { + var prox *time.Time + if activo { + prox = domain.ProximaFecha(domain.ProgramaCalendario{ + Frecuencia: frecuencia, DiaSemana: diaSemana, DiaMes: diaMes, + FechaInicio: fechaInicio, FechaFin: fechaFin, + }, hoy) + } + list = append(list, map[string]any{ + "id": id, "clienteId": clienteID, "cotizacionId": cotID, + "concepto": concepto, "monto": monto, "moneda": moneda, + "frecuencia": frecuencia, "diaSemana": diaSemana, "diaMes": diaMes, + "fechaInicio": fechaInicio, "fechaFin": fechaFin, "activo": activo, + "proximaFecha": prox, "createdAt": createdAt, "updatedAt": updatedAt, + "cliente": map[string]any{"id": clienteID, "nombre": cNombre, "empresa": cEmpresa, "email": cEmail}, + "pagosCount": pagosCount, + "_count": map[string]any{"pagos": pagosCount}, + }) + } + } + return list, nil +} + +func (s *Server) handleCobrosResumen(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cobros"}); !ok { + return + } + ctx := r.Context() + hoy := domain.HoyCalendario() + + programas, err := s.queryProgramas(ctx) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error cargando programas") + return + } + + // Clientes for dropdown + cRows, _ := s.Pool.Query(ctx, `SELECT "id", "nombre", "empresa" FROM "Cliente" WHERE "archivado" = false ORDER BY "nombre" ASC`) + clientes := []map[string]any{} + if cRows != nil { + for cRows.Next() { + var cid, cnom string + var cemp *string + if cRows.Scan(&cid, &cnom, &cemp) == nil { + clientes = append(clientes, map[string]any{"id": cid, "nombre": cnom, "empresa": cemp}) + } + } + cRows.Close() + } + + // Pagos en revision + revPagos, _ := s.queryPagos(ctx, `p."estado" = 'en_revision'`, nil) + + // Pagos por cobrar (pendiente | rechazado, fecha <= hoy, including inactive programs) + porCobrarRows, _ := s.Pool.Query(ctx, ` + SELECT p."id", p."programaId", p."fecha", p."monto", p."estado", p."ultimoRecordatorioAt", p."recordatoriosEnviados", + pr."concepto", pr."moneda", + c."id", c."nombre", c."empresa", c."email", + (SELECT COUNT(*) FROM "SuscripcionPush" sp JOIN "User" u ON u."id" = sp."userId" WHERE u."clienteId" = c."id") AS push_count + FROM "PagoRecurrente" p + JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + JOIN "Cliente" c ON c."id" = pr."clienteId" + WHERE p."estado" IN ('pendiente', 'rechazado') AND p."fecha" <= $1 + ORDER BY c."nombre" ASC, p."fecha" ASC + `, hoy) + + type saldoClient struct { + ClienteID string + ClienteNombre string + ClienteEmpresa *string + ClienteEmail *string + Contactable bool + Totales map[string]float64 + MasAntigua time.Time + UltimoRecordatorio *time.Time + PagosCount int + } + saldoMap := map[string]*saldoClient{} + var saldoOrder []string + if porCobrarRows != nil { + for porCobrarRows.Next() { + var pid, prid, estado, concepto, moneda, cid, cnom string + var cemp, cemail *string + var fecha time.Time + var monto float64 + var ultRec *time.Time + var recCnt, pushCnt int + if porCobrarRows.Scan(&pid, &prid, &fecha, &monto, &estado, &ultRec, &recCnt, &concepto, &moneda, &cid, &cnom, &cemp, &cemail, &pushCnt) == nil { + sc, ok := saldoMap[cid] + if !ok { + sc = &saldoClient{ + ClienteID: cid, ClienteNombre: cnom, ClienteEmpresa: cemp, ClienteEmail: cemail, + Contactable: (cemail != nil && strings.TrimSpace(*cemail) != "") || pushCnt > 0, + Totales: map[string]float64{}, + MasAntigua: fecha, + } + saldoMap[cid] = sc + saldoOrder = append(saldoOrder, cid) + } + if fecha.Before(sc.MasAntigua) { + sc.MasAntigua = fecha + } + sc.Totales[moneda] = domain.Round2(sc.Totales[moneda] + monto) + if ultRec != nil && (sc.UltimoRecordatorio == nil || ultRec.After(*sc.UltimoRecordatorio)) { + t := *ultRec + sc.UltimoRecordatorio = &t + } + sc.PagosCount++ + } + } + porCobrarRows.Close() + } + + saldos := make([]map[string]any, 0, len(saldoOrder)) + for _, cid := range saldoOrder { + sc := saldoMap[cid] + saldos = append(saldos, map[string]any{ + "clienteId": sc.ClienteID, + "nombre": sc.ClienteNombre, + "empresa": sc.ClienteEmpresa, + "pagos": sc.PagosCount, + "totales": sc.Totales, + "masAntigua": sc.MasAntigua, + "diasAtraso": domain.DiasDeAtraso(sc.MasAntigua, hoy), + "ultimoRecordatorio": sc.UltimoRecordatorio, + "contactable": sc.Contactable, + }) + } + + writeJSON(w, http.StatusOK, map[string]any{ + "programas": programas, + "clientes": clientes, + "pagosEnRevision": revPagos, + "saldos": saldos, + "diasRecordatorio": s.Cfg.CobrosRecordatorioDias, + }) +} + +func (s *Server) handleProgramasList(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"cobros:leer"}, RecursoTipo: "programa_pago"}); !ok { + return + } + list, err := s.queryProgramas(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error listando programas") + return + } + writeJSON(w, http.StatusOK, list) +} + +func (s *Server) handleProgramasCreate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "programa_pago"}); !ok { + return + } + var body struct { + ClienteID string `json:"clienteId"` + CotizacionID *string `json:"cotizacionId"` + Concepto string `json:"concepto"` + Monto float64 `json:"monto"` + Moneda string `json:"moneda"` + Frecuencia string `json:"frecuencia"` + DiaSemana *int `json:"diaSemana"` + DiaMes *int `json:"diaMes"` + FechaInicio string `json:"fechaInicio"` + FechaFin *string `json:"fechaFin"` + } + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + if body.ClienteID == "" || strings.TrimSpace(body.Concepto) == "" || body.Monto <= 0 { + writeError(w, http.StatusBadRequest, "clienteId, concepto y monto > 0 son obligatorios") + return + } + fIni, err := domain.ParseFechaCalendario(body.FechaInicio) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + var fFin *time.Time + if body.FechaFin != nil && strings.TrimSpace(*body.FechaFin) != "" { + t, err := domain.ParseFechaCalendario(*body.FechaFin) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + fFin = &t + } + frec := firstNonEmptyStr(body.Frecuencia, "semanal") + mon := firstNonEmptyStr(body.Moneda, "MXN") + + id := db.NewID() + _, err = s.Pool.Exec(r.Context(), ` + INSERT INTO "ProgramaPago" ( + "id", "clienteId", "cotizacionId", "concepto", "monto", "moneda", + "frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin", "activo", "createdAt", "updatedAt" + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,true,NOW(),NOW()) + `, id, body.ClienteID, trimPtr(body.CotizacionID), strings.TrimSpace(body.Concepto), body.Monto, mon, + frec, body.DiaSemana, body.DiaMes, fIni, fFin) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error creando programa de pago") + return + } + + // Generate initial due charges right away + if nuevos, err := scheduler.GenerarCobros(r.Context(), s.Pool, id, nil); err == nil && len(nuevos) > 0 { + go s.Notify.NotificarCobrosNuevos(context.Background(), nuevos) + } + + writeJSON(w, http.StatusCreated, map[string]any{"id": id, "ok": true}) +} + +func (s *Server) handleProgramasUpdate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "programa_pago"}); !ok { + return + } + id := chi.URLParam(r, "id") + var raw map[string]any + if err := decodeJSON(r, &raw); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + sets := []string{`"updatedAt" = NOW()`} + args := []any{} + add := func(col string, val any) { + args = append(args, val) + sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args))) + } + if v, ok := raw["concepto"]; ok { + add("concepto", strings.TrimSpace(asString(v))) + } + if v, ok := raw["monto"]; ok { + if m, okF := asFloat(v); okF && m > 0 { + add("monto", m) + } + } + if v, ok := raw["moneda"]; ok { + add("moneda", strings.TrimSpace(asString(v))) + } + if v, ok := raw["frecuencia"]; ok { + add("frecuencia", strings.TrimSpace(asString(v))) + } + if v, ok := raw["diaSemana"]; ok { + if n, okI := asInt(v); okI { + add("diaSemana", n) + } else { + add("diaSemana", nil) + } + } + if v, ok := raw["diaMes"]; ok { + if n, okI := asInt(v); okI { + add("diaMes", n) + } else { + add("diaMes", nil) + } + } + if v, ok := raw["fechaFin"]; ok { + sVal := strings.TrimSpace(asString(v)) + if sVal == "" { + add("fechaFin", nil) + } else if t, err := domain.ParseFechaCalendario(sVal); err == nil { + add("fechaFin", t) + } + } + if v, ok := raw["activo"].(bool); ok { + add("activo", v) + } + args = append(args, id) + tag, err := s.Pool.Exec(r.Context(), fmt.Sprintf(`UPDATE "ProgramaPago" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Programa no encontrado") + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id}) +} + +func (s *Server) handleCobrosGenerar(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cobros"}); !ok { + return + } + var body struct { + ProgramaID string `json:"programaId"` + Hasta string `json:"hasta"` + } + _ = decodeJSON(r, &body) + var hasta *time.Time + if strings.TrimSpace(body.Hasta) != "" { + t, err := domain.ParseFechaCalendario(body.Hasta) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + hasta = &t + } + nuevos, err := scheduler.GenerarCobros(r.Context(), s.Pool, body.ProgramaID, hasta) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error generando cobros") + return + } + if len(nuevos) > 0 { + go s.Notify.NotificarCobrosNuevos(context.Background(), nuevos) + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "generados": len(nuevos), "ids": nuevos}) +} + +func (s *Server) queryPagos(ctx context.Context, whereSQL string, args []any) ([]map[string]any, error) { + rows, err := s.Pool.Query(ctx, ` + SELECT p."id", p."programaId", p."fecha", p."monto", p."estado", + p."verificadoAt", p."rechazadoAt", p."rechazoMotivo", + p."ultimoRecordatorioAt", p."recordatoriosEnviados", p."nota", + pr."concepto", pr."moneda", pr."frecuencia", pr."clienteId", + c."nombre", c."empresa", c."email", + comp."id", comp."archivoNombre", comp."mime", comp."tamano", comp."subidoAt" + FROM "PagoRecurrente" p + JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + JOIN "Cliente" c ON c."id" = pr."clienteId" + LEFT JOIN "ComprobantePago" comp ON comp."pagoId" = p."id" + WHERE `+whereSQL+` + ORDER BY p."fecha" DESC + `, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + list := []map[string]any{} + for rows.Next() { + var id, progID, estado, concepto, moneda, frec, cid, cnom string + var rechazoMotivo, nota, cemp, cemail, compID, compNom, compMime *string + var fecha time.Time + var monto float64 + var verifAt, rechAt, ultRec, compSub *time.Time + var recCnt int + var compTam *int + if rows.Scan(&id, &progID, &fecha, &monto, &estado, &verifAt, &rechAt, &rechazoMotivo, + &ultRec, &recCnt, ¬a, &concepto, &moneda, &frec, &cid, &cnom, &cemp, &cemail, + &compID, &compNom, &compMime, &compTam, &compSub) == nil { + var comp any + if compID != nil { + comp = map[string]any{ + "id": *compID, "pagoId": id, "archivoNombre": compNom, "mime": compMime, "tamano": compTam, "subidoAt": compSub, + } + } + list = append(list, map[string]any{ + "id": id, "programaId": progID, "fecha": fecha, "monto": monto, "estado": estado, + "verificadoAt": verifAt, "rechazadoAt": rechAt, "rechazoMotivo": rechazoMotivo, + "ultimoRecordatorioAt": ultRec, "recordatoriosEnviados": recCnt, "nota": nota, + "programa": map[string]any{ + "id": progID, "concepto": concepto, "moneda": moneda, "frecuencia": frec, "clienteId": cid, + "cliente": map[string]any{"id": cid, "nombre": cnom, "empresa": cemp, "email": cemail}, + }, + "comprobante": comp, + }) + } + } + return list, nil +} + +func (s *Server) handlePagosList(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"cobros:leer"}, RecursoTipo: "pago"}); !ok { + return + } + q := r.URL.Query() + conds := []string{"1=1"} + args := []any{} + add := func(v any) string { + args = append(args, v) + return fmt.Sprintf("$%d", len(args)) + } + if est := strings.TrimSpace(q.Get("estado")); est != "" { + if est == "por_pagar" { + conds = append(conds, `p."estado" IN ('pendiente', 'rechazado')`) + } else { + conds = append(conds, `p."estado" = `+add(est)) + } + } + if cid := strings.TrimSpace(q.Get("clienteId")); cid != "" { + conds = append(conds, `pr."clienteId" = `+add(cid)) + } + if pid := strings.TrimSpace(q.Get("programaId")); pid != "" { + conds = append(conds, `p."programaId" = `+add(pid)) + } + if d := strings.TrimSpace(q.Get("desde")); d != "" { + if t, err := domain.ParseFechaCalendario(d); err == nil { + conds = append(conds, `p."fecha" >= `+add(t)) + } + } + if h := strings.TrimSpace(q.Get("hasta")); h != "" { + if t, err := domain.ParseFechaCalendario(h); err == nil { + conds = append(conds, `p."fecha" <= `+add(t)) + } + } + list, err := s.queryPagos(r.Context(), strings.Join(conds, " AND "), args) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error listando pagos") + return + } + writeJSON(w, http.StatusOK, list) +} + +func (s *Server) handlePagoAprobar(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}) + if !ok { + return + } + id := chi.URLParam(r, "id") + var estado string + var monto float64 + if err := s.Pool.QueryRow(r.Context(), `SELECT "estado", "monto" FROM "PagoRecurrente" WHERE "id" = $1`, id).Scan(&estado, &monto); err != nil { + writeError(w, http.StatusNotFound, "Cobro no encontrado") + return + } + if estado != domain.EstadoPagoEnRevision { + writeError(w, http.StatusConflict, "Solo se pueden aprobar cobros en revision") + return + } + now := time.Now() + _, err := s.Pool.Exec(r.Context(), ` + UPDATE "PagoRecurrente" SET "estado"='verificado', "verificadoAt"=$1, "rechazadoAt"=NULL, "rechazoMotivo"=NULL, "updatedAt"=NOW() + WHERE "id" = $2 + `, now, id) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error aprobando comprobante") + return + } + + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "pago.aprobar_comprobante", RecursoTipo: "pago", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + }) + go s.Notify.NotificarVerificacion(context.Background(), id) + go s.Webhooks.Emitir(context.Background(), "pago.registrado", map[string]any{ + "pagoId": id, "monto": monto, "metodo": "comprobante_verificado", "verificadoAt": now.UTC().Format(time.RFC3339), + }) + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "verificado", "verificadoAt": now}) +} + +func (s *Server) handlePagoRechazar(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}); !ok { + return + } + id := chi.URLParam(r, "id") + var body struct { + Motivo string `json:"motivo"` + } + _ = decodeJSON(r, &body) + motivo := strings.TrimSpace(body.Motivo) + if motivo == "" { + writeError(w, http.StatusBadRequest, "El motivo del rechazo es obligatorio") + return + } + + var ruta string + _ = s.Pool.QueryRow(r.Context(), `SELECT "archivoRuta" FROM "ComprobantePago" WHERE "pagoId" = $1`, id).Scan(&ruta) + if ruta != "" { + _ = uploads.EliminarComprobante(s.Cfg.UploadDir, ruta) + _, _ = s.Pool.Exec(r.Context(), `DELETE FROM "ComprobantePago" WHERE "pagoId" = $1`, id) + } + + tag, err := s.Pool.Exec(r.Context(), ` + UPDATE "PagoRecurrente" SET "estado"='rechazado', "rechazadoAt"=NOW(), "rechazoMotivo"=$1, "updatedAt"=NOW() + WHERE "id" = $2 + `, motivo, id) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Cobro no encontrado") + return + } + go s.Notify.NotificarRechazo(context.Background(), id, motivo) + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "rechazado"}) +} + +func (s *Server) handlePagoRegistrar(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{Scopes: []string{"cobros:registrar"}, RecursoTipo: "pago"}) + if !ok { + return + } + id := chi.URLParam(r, "id") + idempotency.Execute(r.Context(), s.Pool, w, r, actor, func(rawBody []byte) (int, any) { + var body struct { + Fecha string `json:"fecha"` + Nota *string `json:"nota"` + } + if err := json.Unmarshal(rawBody, &body); err != nil { + return http.StatusBadRequest, map[string]any{"error": "JSON invalido"} + } + hoy := domain.HoyCalendario() + fPago := hoy + if strings.TrimSpace(body.Fecha) != "" { + t, err := domain.ParseFechaCalendario(body.Fecha) + if err != nil { + return http.StatusBadRequest, map[string]any{"error": err.Error()} + } + if t.After(hoy) { + return http.StatusBadRequest, map[string]any{"error": "La fecha de pago no puede ser futura"} + } + fPago = t + } + + var estado string + var monto float64 + if err := s.Pool.QueryRow(r.Context(), `SELECT "estado", "monto" FROM "PagoRecurrente" WHERE "id" = $1`, id).Scan(&estado, &monto); err != nil { + return http.StatusNotFound, map[string]any{"error": "Cobro no encontrado"} + } + if estado != domain.EstadoPagoPendiente && estado != domain.EstadoPagoRechazado { + return http.StatusConflict, map[string]any{"error": "Solo se pueden registrar cobros pendientes o rechazados"} + } + + verifAt := domain.InstanteDePago(fPago) + _, err := s.Pool.Exec(r.Context(), ` + UPDATE "PagoRecurrente" + SET "estado"='verificado', "verificadoAt"=$1, "nota"=$2, "rechazadoAt"=NULL, "rechazoMotivo"=NULL, "updatedAt"=NOW() + WHERE "id" = $3 + `, verifAt, trimPtr(body.Nota), id) + if err != nil { + return http.StatusInternalServerError, map[string]any{"error": "Error registrando pago"} + } + + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "pago.registrar", RecursoTipo: "pago", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + Detalle: map[string]any{"fecha": fPago.Format("2006-01-02"), "nota": body.Nota}, + }) + go s.Notify.NotificarVerificacion(context.Background(), id) + go s.Webhooks.Emitir(context.Background(), "pago.registrado", map[string]any{ + "pagoId": id, "monto": monto, "metodo": "registro_manual", "verificadoAt": verifAt.UTC().Format(time.RFC3339), + }) + return http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "verificado", "verificadoAt": verifAt} + }) +} + +func (s *Server) handlePagoAnular(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}); !ok { + return + } + id := chi.URLParam(r, "id") + var body struct { + Motivo string `json:"motivo"` + } + _ = decodeJSON(r, &body) + motivo := strings.TrimSpace(body.Motivo) + if motivo == "" { + writeError(w, http.StatusBadRequest, "El motivo es obligatorio") + return + } + var estado string + if err := s.Pool.QueryRow(r.Context(), `SELECT "estado" FROM "PagoRecurrente" WHERE "id" = $1`, id).Scan(&estado); err != nil { + writeError(w, http.StatusNotFound, "Cobro no encontrado") + return + } + if estado != domain.EstadoPagoPendiente && estado != domain.EstadoPagoRechazado { + writeError(w, http.StatusConflict, "Solo se pueden anular cobros pendientes o rechazados") + return + } + _, _ = s.Pool.Exec(r.Context(), `UPDATE "PagoRecurrente" SET "estado"='anulado', "nota"=$1, "updatedAt"=NOW() WHERE "id" = $2`, motivo, id) + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "anulado"}) +} + +func (s *Server) handlePagoReabrir(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "pago"}); !ok { + return + } + id := chi.URLParam(r, "id") + var estado string + var hasComp bool + err := s.Pool.QueryRow(r.Context(), ` + SELECT p."estado", EXISTS(SELECT 1 FROM "ComprobantePago" c WHERE c."pagoId" = p."id") + FROM "PagoRecurrente" p WHERE p."id" = $1 + `, id).Scan(&estado, &hasComp) + if err != nil { + writeError(w, http.StatusNotFound, "Cobro no encontrado") + return + } + if estado == domain.EstadoPagoVerificado && hasComp { + writeError(w, http.StatusConflict, "No se puede reabrir un cobro verificado con comprobante") + return + } + if estado != domain.EstadoPagoVerificado && estado != domain.EstadoPagoAnulado { + writeError(w, http.StatusConflict, "Solo se pueden reabrir cobros anulados o registrados manualmente") + return + } + _, _ = s.Pool.Exec(r.Context(), ` + UPDATE "PagoRecurrente" SET "estado"='pendiente', "verificadoAt"=NULL, "nota"=NULL, "updatedAt"=NOW() WHERE "id" = $1 + `, id) + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id, "estado": "pendiente"}) +} + +func (s *Server) handleCobrosRecordatorios(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cobros"}); !ok { + return + } + var body struct { + ClienteID string `json:"clienteId"` + } + _ = decodeJSON(r, &body) + res, err := s.Notify.EnviarRecordatoriosPendientes(r.Context(), strings.TrimSpace(body.ClienteID), true) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error enviando recordatorios") + return + } + writeJSON(w, http.StatusOK, res) +} + +func (s *Server) handleComprobanteGet(w http.ResponseWriter, r *http.Request) { + sess, ok := s.Auth.SessionFromRequest(r) + if !ok { + writeError(w, http.StatusUnauthorized, "No autenticado") + return + } + pagoID := chi.URLParam(r, "pagoId") + var ruta, nombre, mime, ownerClienteID string + err := s.Pool.QueryRow(r.Context(), ` + SELECT c."archivoRuta", c."archivoNombre", c."mime", pr."clienteId" + FROM "ComprobantePago" c + JOIN "PagoRecurrente" p ON p."id" = c."pagoId" + JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + WHERE c."pagoId" = $1 + `, pagoID).Scan(&ruta, &nombre, &mime, &ownerClienteID) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + writeError(w, http.StatusNotFound, "Comprobante no encontrado") + return + } + writeError(w, http.StatusInternalServerError, "Error consultando comprobante") + return + } + if sess.Role == "cliente" && sess.ClienteID != ownerClienteID { + writeError(w, http.StatusForbidden, "No tienes acceso a este comprobante") + return + } + absPath, err := uploads.RutaAbsoluta(s.Cfg.UploadDir, ruta) + if err != nil { + writeError(w, http.StatusForbidden, "Ruta invalida") + return + } + data, err := os.ReadFile(absPath) + if err != nil { + writeError(w, http.StatusNotFound, "Archivo no encontrado en disco") + return + } + w.Header().Set("Content-Type", mime) + w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, domain.SanitizeFilename(nombre))) + w.Header().Set("Cache-Control", "private, no-store") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(data) +} diff --git a/internal/httpapi/cotizaciones_handlers.go b/internal/httpapi/cotizaciones_handlers.go new file mode 100644 index 0000000..6c582bb --- /dev/null +++ b/internal/httpapi/cotizaciones_handlers.go @@ -0,0 +1,1742 @@ +package httpapi + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "cotizador/internal/audit" + "cotizador/internal/auth" + "cotizador/internal/db" + "cotizador/internal/domain" + "cotizador/internal/idempotency" + "cotizador/internal/pdf" + + "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5" +) + +type cotizacionFull struct { + ID string + Numero string + Fecha time.Time + Vigencia time.Time + Moneda string + TipoCambio string + Proyecto string + EsquemaPago string + Estado string + IncluirBonos bool + IncluirFinanciamiento bool + IncluirIVA bool + EsDoble bool + OpcionesMetadata map[string]domain.MetaOpcion + Observaciones *string + ObservacionesInternas *string + ClienteID string + AsesorID string + AprobadaPorID *string + AprobadaAt *time.Time + AprobacionMetodo *string + EnviadaAt *time.Time + EnviadaPor *string + EnviadaCanal *string + EnviadaDestino *string + AceptadaAt *time.Time + RechazadaAt *time.Time + VencidaAt *time.Time + CreadaPorAgente *string + Archivado bool + ArchivadoAt *time.Time + CreatedAt time.Time + UpdatedAt time.Time + + ClienteNombre string + ClienteEmpresa *string + ClientePuesto *string + ClienteEmail *string + ClienteTelefono *string + ClienteRFC *string + + AsesorName string + AsesorEmail string + AsesorRole string + + Servicios []map[string]any + ServiciosCalc []domain.ServicioCalc + ServiciosPDF []pdf.ServicioPDF + PlanBucefalo map[string]any + PlanBucefaloNv *string + PlanBucefaloPr float64 + RegistrosHoras []map[string]any +} + +func (s *Server) loadCotizacionFull(ctx context.Context, id string, redactInternas bool) (*cotizacionFull, map[string]any, error) { + var c cotizacionFull + var opMetaRaw []byte + err := s.Pool.QueryRow(ctx, ` + SELECT q."id", q."numero", q."fecha", q."vigencia", q."moneda", q."tipoCambio", q."proyecto", + q."esquemaPago", q."estado", q."incluirBonos", q."incluirFinanciamiento", q."incluirIva", + q."esDoble", q."opcionesMetadata", q."observaciones", q."observacionesInternas", + q."clienteId", q."asesorId", q."aprobadaPorId", q."aprobadaAt", q."aprobacionMetodo", + q."enviadaAt", q."enviadaPor", q."enviadaCanal", q."enviadaDestino", + q."aceptadaAt", q."rechazadaAt", q."vencidaAt", q."creadaPorAgente", + q."archivado", q."archivadoAt", q."createdAt", q."updatedAt", + cl."nombre", cl."empresa", cl."puesto", cl."email", cl."telefono", cl."rfc", + u."name", u."email", u."role" + FROM "Cotizacion" q + JOIN "Cliente" cl ON cl."id" = q."clienteId" + JOIN "User" u ON u."id" = q."asesorId" + WHERE q."id" = $1 + `, id).Scan( + &c.ID, &c.Numero, &c.Fecha, &c.Vigencia, &c.Moneda, &c.TipoCambio, &c.Proyecto, + &c.EsquemaPago, &c.Estado, &c.IncluirBonos, &c.IncluirFinanciamiento, &c.IncluirIVA, + &c.EsDoble, &opMetaRaw, &c.Observaciones, &c.ObservacionesInternas, + &c.ClienteID, &c.AsesorID, &c.AprobadaPorID, &c.AprobadaAt, &c.AprobacionMetodo, + &c.EnviadaAt, &c.EnviadaPor, &c.EnviadaCanal, &c.EnviadaDestino, + &c.AceptadaAt, &c.RechazadaAt, &c.VencidaAt, &c.CreadaPorAgente, + &c.Archivado, &c.ArchivadoAt, &c.CreatedAt, &c.UpdatedAt, + &c.ClienteNombre, &c.ClienteEmpresa, &c.ClientePuesto, &c.ClienteEmail, &c.ClienteTelefono, &c.ClienteRFC, + &c.AsesorName, &c.AsesorEmail, &c.AsesorRole, + ) + if err != nil { + return nil, nil, err + } + if len(opMetaRaw) > 0 { + _ = json.Unmarshal(opMetaRaw, &c.OpcionesMetadata) + } + + // Load ServiciosCotizados + sRows, _ := s.Pool.Query(ctx, ` + SELECT s."id", s."cotizacionId", s."servicioCatalogoId", s."nombre", s."esPersonalizado", + s."horas", s."tarifaHora", s."modeloCobro", s."montoMinimo", s."horasIncluidas", + s."opcion", s."fase", s."tipoPago", s."precio", s."tiempoEntrega", + s."entregables", s."beneficios", s."notas", s."seleccionado", + sc."nombre", sc."precioBase" + FROM "ServicioCotizado" s + LEFT JOIN "ServicioCatalogo" sc ON sc."id" = s."servicioCatalogoId" + WHERE s."cotizacionId" = $1 + ORDER BY s."fase" ASC, s."createdAt" ASC + `, id) + c.Servicios = []map[string]any{} + if sRows != nil { + defer sRows.Close() + for sRows.Next() { + var sid, qid, modeloCobro, tipoPago, tiempoEntrega string + var scid, nombre, opcion, notas, scNombre *string + var esPers, sel bool + var horas, tarifaHora, montoMin, horasInc, scPrecioBase *float64 + var fase int + var precio float64 + var entRaw, benRaw []byte + if sRows.Scan(&sid, &qid, &scid, &nombre, &esPers, &horas, &tarifaHora, &modeloCobro, &montoMin, &horasInc, + &opcion, &fase, &tipoPago, &precio, &tiempoEntrega, &entRaw, &benRaw, ¬as, &sel, &scNombre, &scPrecioBase) == nil { + var ent, ben []string + _ = json.Unmarshal(entRaw, &ent) + _ = json.Unmarshal(benRaw, &ben) + if ent == nil { + ent = []string{} + } + if ben == nil { + ben = []string{} + } + effName := "Servicio" + if nombre != nil && strings.TrimSpace(*nombre) != "" { + effName = *nombre + } else if scNombre != nil && strings.TrimSpace(*scNombre) != "" { + effName = *scNombre + } + var scObj any + if scid != nil { + scObj = map[string]any{"id": *scid, "nombre": scNombre, "precioBase": scPrecioBase} + } + c.Servicios = append(c.Servicios, map[string]any{ + "id": sid, "cotizacionId": qid, "servicioCatalogoId": scid, + "nombre": effName, "esPersonalizado": esPers, "horas": horas, "tarifaHora": tarifaHora, + "modeloCobro": modeloCobro, "montoMinimo": montoMin, "horasIncluidas": horasInc, + "opcion": opcion, "fase": fase, "tipoPago": tipoPago, "precio": precio, + "tiempoEntrega": tiempoEntrega, "entregables": ent, "beneficios": ben, + "notas": notas, "seleccionado": sel, "servicioCatalogo": scObj, + }) + c.ServiciosCalc = append(c.ServiciosCalc, domain.ServicioCalc{ + Nombre: effName, ModeloCobro: modeloCobro, EsPersonalizado: esPers, + Horas: horas, TarifaHora: tarifaHora, MontoMinimo: montoMin, HorasIncluidas: horasInc, + Opcion: opcion, TipoPago: tipoPago, Precio: precio, Seleccionado: sel, + }) + if sel { + c.ServiciosPDF = append(c.ServiciosPDF, pdf.ServicioPDF{ + Nombre: effName, Fase: fase, TipoPago: tipoPago, Precio: precio, + TiempoEntrega: tiempoEntrega, Entregables: ent, EsPersonalizado: esPers, + Horas: horas, TarifaHora: tarifaHora, ModeloCobro: modeloCobro, + MontoMinimo: montoMin, HorasIncluidas: horasInc, Opcion: opcion, + }) + } + } + } + } + + // Plan Bucefalo + var pbid, pbnivel string + var pbprecio float64 + var pbsel bool + if err := s.Pool.QueryRow(ctx, ` + SELECT "id", "nivel", "precio", "seleccionado" FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1 + `, id).Scan(&pbid, &pbnivel, &pbprecio, &pbsel); err == nil { + c.PlanBucefalo = map[string]any{ + "id": pbid, "cotizacionId": id, "nivel": pbnivel, "precio": pbprecio, "seleccionado": pbsel, + } + if pbsel { + nv := pbnivel + c.PlanBucefaloNv = &nv + c.PlanBucefaloPr = pbprecio + } + } + + // RegistrosHoras + hRows, _ := s.Pool.Query(ctx, ` + SELECT "id", "cotizacionId", "fecha", "horaInicio", "horaFin", "horas", "tarifaHora", "descripcion", "estadoPago", "fechaPago", "createdAt" + FROM "RegistroHoras" + WHERE "cotizacionId" = $1 + ORDER BY "fecha" DESC, "horaInicio" DESC + `, id) + c.RegistrosHoras = []map[string]any{} + if hRows != nil { + defer hRows.Close() + for hRows.Next() { + var hid, qid, hi, hf, desc, ep string + var fecha, createdAt time.Time + var fechaPago *time.Time + var hrs, th float64 + if hRows.Scan(&hid, &qid, &fecha, &hi, &hf, &hrs, &th, &desc, &ep, &fechaPago, &createdAt) == nil { + c.RegistrosHoras = append(c.RegistrosHoras, map[string]any{ + "id": hid, "cotizacionId": qid, "fecha": fecha, "horaInicio": hi, "horaFin": hf, + "horas": hrs, "tarifaHora": th, "descripcion": desc, "estadoPago": ep, + "fechaPago": fechaPago, "createdAt": createdAt, + }) + } + } + } + + obsInt := c.ObservacionesInternas + if redactInternas { + obsInt = nil + } + + jsonMap := map[string]any{ + "id": c.ID, "numero": c.Numero, "fecha": c.Fecha, "vigencia": c.Vigencia, + "moneda": c.Moneda, "tipoCambio": c.TipoCambio, "proyecto": c.Proyecto, + "esquemaPago": c.EsquemaPago, "estado": c.Estado, + "incluirBonos": c.IncluirBonos, "incluirFinanciamiento": c.IncluirFinanciamiento, + "incluirIva": c.IncluirIVA, "esDoble": c.EsDoble, "opcionesMetadata": c.OpcionesMetadata, + "observaciones": c.Observaciones, "observacionesInternas": obsInt, + "clienteId": c.ClienteID, "asesorId": c.AsesorID, + "aprobadaPorId": c.AprobadaPorID, "aprobadaAt": c.AprobadaAt, "aprobacionMetodo": c.AprobacionMetodo, + "enviadaAt": c.EnviadaAt, "enviadaPor": c.EnviadaPor, "enviadaCanal": c.EnviadaCanal, "enviadaDestino": c.EnviadaDestino, + "aceptadaAt": c.AceptadaAt, "rechazadaAt": c.RechazadaAt, "vencidaAt": c.VencidaAt, + "creadaPorAgente": c.CreadaPorAgente, "archivado": c.Archivado, "archivadoAt": c.ArchivadoAt, + "createdAt": c.CreatedAt, "updatedAt": c.UpdatedAt, + "cliente": map[string]any{ + "id": c.ClienteID, "nombre": c.ClienteNombre, "empresa": c.ClienteEmpresa, + "puesto": c.ClientePuesto, "email": c.ClienteEmail, "telefono": c.ClienteTelefono, "rfc": c.ClienteRFC, + }, + "asesor": map[string]any{ + "id": c.AsesorID, "name": c.AsesorName, "email": c.AsesorEmail, "role": c.AsesorRole, + }, + "servicios": c.Servicios, + "planBucefalo": c.PlanBucefalo, + "registrosHoras": c.RegistrosHoras, + } + return &c, jsonMap, nil +} + +func (s *Server) soloAdminCatalogIDs(ctx context.Context) map[string]struct{} { + out := map[string]struct{}{} + rows, err := s.Pool.Query(ctx, `SELECT "id" FROM "ServicioCatalogo" WHERE "soloAdmin" = true`) + if err != nil { + return out + } + defer rows.Close() + for rows.Next() { + var id string + if rows.Scan(&id) == nil { + out[id] = struct{}{} + } + } + return out +} + +func (s *Server) crearEnlaceAprobacion(ctx context.Context, cotID string) (string, error) { + // Invalidate previous unused tokens for this quote + _, _ = s.Pool.Exec(ctx, `UPDATE "ApprovalToken" SET "usadoAt" = NOW() WHERE "cotizacionId" = $1 AND "usadoAt" IS NULL`, cotID) + rawToken, tokHash := auth.GenerateRandomToken(32) + expiraAt := time.Now().Add(72 * time.Hour) + _, err := s.Pool.Exec(ctx, ` + INSERT INTO "ApprovalToken" ("id", "cotizacionId", "tokenHash", "expiraAt", "createdAt") + VALUES ($1, $2, $3, $4, NOW()) + `, db.NewID(), cotID, tokHash, expiraAt) + if err != nil { + return "", err + } + return fmt.Sprintf("%s/aprobar/%s", s.Cfg.AppURL, rawToken), nil +} + +func (s *Server) handleCotizacionesList(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{ + Scopes: []string{"cotizaciones:leer", "cotizaciones:leer_aceptadas"}, + RecursoTipo: "cotizacion", + }) + if !ok { + return + } + q := r.URL.Query() + soloAceptadas := actor.EsAgenteSoloAceptadas() + + estado := strings.TrimSpace(q.Get("estado")) + if soloAceptadas { + if estado != "" && estado != "aceptada" { + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.leer_bloqueado", RecursoTipo: "cotizacion", + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + Detalle: map[string]any{"estadoSolicitado": estado}, + }) + writeError(w, http.StatusForbidden, "Esta clave solo puede consultar cotizaciones aceptadas") + return + } + estado = "aceptada" + } + + conds := []string{"1=1"} + args := []any{} + add := func(v any) string { + args = append(args, v) + return fmt.Sprintf("$%d", len(args)) + } + + if actor.IsAgent() || q.Get("incluirArchivados") != "true" { + conds = append(conds, `q."archivado" = false`) + } + if estado != "" { + conds = append(conds, `q."estado" = `+add(estado)) + } + if v := strings.TrimSpace(q.Get("clienteId")); v != "" { + conds = append(conds, `q."clienteId" = `+add(v)) + } + if v := strings.TrimSpace(q.Get("q")); v != "" { + p := add("%" + v + "%") + conds = append(conds, fmt.Sprintf(`(q."numero" ILIKE %s OR q."proyecto" ILIKE %s OR cl."nombre" ILIKE %s OR COALESCE(cl."empresa", '') ILIKE %s)`, p, p, p, p)) + } + if v := strings.TrimSpace(q.Get("clienteEmail")); v != "" { + conds = append(conds, `LOWER(COALESCE(cl."email", '')) = LOWER(`+add(v)+`)`) + } + if v := strings.TrimSpace(q.Get("clienteTelefono")); v != "" { + conds = append(conds, `COALESCE(cl."telefono", '') ILIKE `+add("%"+v+"%")) + } + if v := strings.TrimSpace(q.Get("desde")); v != "" { + if t, err := time.Parse("2006-01-02", v); err == nil { + conds = append(conds, `q."fecha" >= `+add(t)) + } + } + if v := strings.TrimSpace(q.Get("hasta")); v != "" { + if t, err := time.Parse("2006-01-02", v); err == nil { + conds = append(conds, `q."fecha" <= `+add(t.Add(24*time.Hour))) + } + } + + limit := parseIntQuery(r, "limit", 200, 1, 200) + page := parseIntQuery(r, "page", 1, 1, 10000) + offset := (page - 1) * limit + limArg := add(limit) + offArg := add(offset) + + rows, err := s.Pool.Query(r.Context(), ` + SELECT q."id", q."numero", q."fecha", q."vigencia", q."moneda", q."proyecto", q."estado", + q."esDoble", q."incluirIva", q."observaciones", q."observacionesInternas", + q."archivado", q."createdAt", q."aprobadaAt", q."enviadaAt", + cl."id", cl."nombre", cl."empresa", cl."email", cl."telefono", + u."id", u."name", u."email" + FROM "Cotizacion" q + JOIN "Cliente" cl ON cl."id" = q."clienteId" + JOIN "User" u ON u."id" = q."asesorId" + WHERE `+strings.Join(conds, " AND ")+` + ORDER BY q."createdAt" DESC + LIMIT `+limArg+` OFFSET `+offArg, args...) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error listando cotizaciones") + return + } + defer rows.Close() + + list := []map[string]any{} + var ids []string + for rows.Next() { + var id, numero, moneda, proyecto, estadoRow, cid, cnom, uid, uname, uemail string + var cemp, cemail, ctel, obs, obsInt *string + var fecha, vigencia, createdAt time.Time + var aprobadaAt, enviadaAt *time.Time + var esDoble, incluirIva, archivado bool + if rows.Scan(&id, &numero, &fecha, &vigencia, &moneda, &proyecto, &estadoRow, &esDoble, &incluirIva, + &obs, &obsInt, &archivado, &createdAt, &aprobadaAt, &enviadaAt, + &cid, &cnom, &cemp, &cemail, &ctel, &uid, &uname, &uemail) == nil { + ids = append(ids, id) + if soloAceptadas { + obsInt = nil + } + list = append(list, map[string]any{ + "id": id, "numero": numero, "fecha": fecha, "vigencia": vigencia, + "moneda": moneda, "proyecto": proyecto, "estado": estadoRow, + "esDoble": esDoble, "incluirIva": incluirIva, + "observaciones": obs, "observacionesInternas": obsInt, + "archivado": archivado, "createdAt": createdAt, "aprobadaAt": aprobadaAt, "enviadaAt": enviadaAt, + "cliente": map[string]any{"id": cid, "nombre": cnom, "empresa": cemp, "email": cemail, "telefono": ctel}, + "asesor": map[string]any{"id": uid, "name": uname, "email": uemail}, + "servicios": []any{}, + }) + } + } + + if len(ids) > 0 { + sRows, err := s.Pool.Query(r.Context(), ` + SELECT "id", "cotizacionId", "nombre", "fase", "tipoPago", "precio", "seleccionado", "modeloCobro", "opcion" + FROM "ServicioCotizado" + WHERE "cotizacionId" = ANY($1) + ORDER BY "fase" ASC, "createdAt" ASC + `, ids) + if err == nil { + defer sRows.Close() + byCot := map[string][]map[string]any{} + for sRows.Next() { + var sid, qid, tp, mc string + var nom, op *string + var fase int + var precio float64 + var sel bool + if sRows.Scan(&sid, &qid, &nom, &fase, &tp, &precio, &sel, &mc, &op) == nil { + byCot[qid] = append(byCot[qid], map[string]any{ + "id": sid, "nombre": nom, "fase": fase, "tipoPago": tp, "precio": precio, + "seleccionado": sel, "modeloCobro": mc, "opcion": op, + }) + } + } + for _, it := range list { + if svcs, ok := byCot[it["id"].(string)]; ok { + it["servicios"] = svcs + } + } + } + } + + writeJSON(w, http.StatusOK, list) +} + +type servicioInputDTO struct { + ServicioCatalogoID *string `json:"servicioCatalogoId"` + CatalogoID *string `json:"catalogoId"` + Nombre *string `json:"nombre"` + EsPersonalizado bool `json:"esPersonalizado"` + Horas *float64 `json:"horas"` + TarifaHora *float64 `json:"tarifaHora"` + ModeloCobro string `json:"modeloCobro"` + MontoMinimo *float64 `json:"montoMinimo"` + HorasIncluidas *float64 `json:"horasIncluidas"` + Opcion *string `json:"opcion"` + Fase int `json:"fase"` + TipoPago string `json:"tipoPago"` + Precio float64 `json:"precio"` + TiempoEntrega string `json:"tiempoEntrega"` + Entregables []string `json:"entregables"` + Beneficios []string `json:"beneficios"` + Notas *string `json:"notas"` + Seleccionado *bool `json:"seleccionado"` +} + +func (s *Server) handleCotizacionesCreate(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{ + Scopes: []string{"cotizaciones:borrador"}, + RecursoTipo: "cotizacion", + }) + if !ok { + return + } + + idempotency.Execute(r.Context(), s.Pool, w, r, actor, func(rawBody []byte) (int, any) { + var body struct { + Numero string `json:"numero"` + Fecha string `json:"fecha"` + Vigencia string `json:"vigencia"` + Moneda string `json:"moneda"` + TipoCambio string `json:"tipoCambio"` + Proyecto string `json:"proyecto"` + EsquemaPago string `json:"esquemaPago"` + IncluirBonos bool `json:"incluirBonos"` + IncluirFinanciamiento bool `json:"incluirFinanciamiento"` + IncluirIVA *bool `json:"incluirIva"` + EsDoble bool `json:"esDoble"` + OpcionesMetadata map[string]domain.MetaOpcion `json:"opcionesMetadata"` + Observaciones *string `json:"observaciones"` + ObservacionesInternas *string `json:"observacionesInternas"` + ClienteID string `json:"clienteId"` + Cliente *struct { + Nombre string `json:"nombre"` + Empresa *string `json:"empresa"` + Puesto *string `json:"puesto"` + Email *string `json:"email"` + Telefono *string `json:"telefono"` + RFC *string `json:"rfc"` + } `json:"cliente"` + AsesorID string `json:"asesorId"` + Servicios []servicioInputDTO `json:"servicios"` + PlanBucefalo *struct { + Nivel string `json:"nivel"` + Precio *float64 `json:"precio"` + Seleccionado *bool `json:"seleccionado"` + } `json:"planBucefalo"` + } + if err := json.Unmarshal(rawBody, &body); err != nil { + return http.StatusBadRequest, map[string]any{"error": "JSON invalido"} + } + + // SoloAdmin check for agents + draftSvcs := make([]domain.ServicioDraftInput, 0, len(body.Servicios)) + for _, sv := range body.Servicios { + cid := firstNonEmptyStr(derefStr(sv.ServicioCatalogoID), derefStr(sv.CatalogoID)) + draftSvcs = append(draftSvcs, domain.ServicioDraftInput{ + CatalogoID: cid, Nombre: derefStr(sv.Nombre), EsPersonalizado: sv.EsPersonalizado, + }) + } + soloCheck := domain.EvaluarRestriccionSoloAdmin(domain.EvaluarSoloAdminInput{ + EsAgente: actor.IsAgent(), + HasPlanBucefalo: body.PlanBucefalo != nil, + Servicios: draftSvcs, + SoloAdminCatalogIDs: s.soloAdminCatalogIDs(r.Context()), + }) + if !soloCheck.OK { + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.servicio_solo_admin_bloqueado", RecursoTipo: "cotizacion", + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + Detalle: map[string]any{"items": soloCheck.ItemsBloqueados, "motivos": soloCheck.Motivos}, + }) + return http.StatusForbidden, map[string]any{ + "error": "Uno o mas servicios solicitados son exclusivos de administrador", + "reason": "solo_admin_restricted", + "itemsBloqueados": soloCheck.ItemsBloqueados, + } + } + + // Resolve or upsert Cliente + clienteID := strings.TrimSpace(body.ClienteID) + var clienteNombre, clienteEmpresa string + if clienteID == "" { + if body.Cliente == nil || strings.TrimSpace(body.Cliente.Nombre) == "" { + return http.StatusBadRequest, map[string]any{"error": "Se requiere clienteId o datos de cliente"} + } + cNom := strings.TrimSpace(body.Cliente.Nombre) + cEmp := strings.TrimSpace(derefStr(body.Cliente.Empresa)) + err := s.Pool.QueryRow(r.Context(), ` + SELECT "id", "nombre", COALESCE("empresa", '') + FROM "Cliente" + WHERE "archivado" = false + AND LOWER(TRIM("nombre")) = LOWER($1) + AND LOWER(TRIM(COALESCE("empresa", ''))) = LOWER($2) + LIMIT 1 + `, cNom, cEmp).Scan(&clienteID, &clienteNombre, &clienteEmpresa) + if err != nil { + clienteID = db.NewID() + clienteNombre = cNom + clienteEmpresa = cEmp + _, err = s.Pool.Exec(r.Context(), ` + INSERT INTO "Cliente" ("id", "nombre", "empresa", "puesto", "email", "telefono", "rfc", "archivado", "createdAt", "updatedAt") + VALUES ($1,$2,$3,$4,$5,$6,$7,false,NOW(),NOW()) + `, clienteID, cNom, nullableTrim(cEmp), trimPtr(body.Cliente.Puesto), trimPtr(body.Cliente.Email), trimPtr(body.Cliente.Telefono), trimPtr(body.Cliente.RFC)) + if err != nil { + return http.StatusInternalServerError, map[string]any{"error": "Error creando cliente"} + } + } else { + // Update optional contact fields if supplied + if body.Cliente.Email != nil || body.Cliente.Telefono != nil || body.Cliente.RFC != nil || body.Cliente.Puesto != nil { + _, _ = s.Pool.Exec(r.Context(), ` + UPDATE "Cliente" + SET "email" = COALESCE($1, "email"), + "telefono" = COALESCE($2, "telefono"), + "rfc" = COALESCE($3, "rfc"), + "puesto" = COALESCE($4, "puesto"), + "updatedAt" = NOW() + WHERE "id" = $5 + `, trimPtr(body.Cliente.Email), trimPtr(body.Cliente.Telefono), trimPtr(body.Cliente.RFC), trimPtr(body.Cliente.Puesto), clienteID) + } + } + } else { + if err := s.Pool.QueryRow(r.Context(), `SELECT "nombre", COALESCE("empresa", '') FROM "Cliente" WHERE "id" = $1`, clienteID).Scan(&clienteNombre, &clienteEmpresa); err != nil { + return http.StatusNotFound, map[string]any{"error": "Cliente no encontrado"} + } + } + + // Resolve Asesor + asesorID := strings.TrimSpace(body.AsesorID) + var asesorName string + if asesorID == "" { + if actor.IsStaff() { + asesorID = actor.UserID + asesorName = actor.Name + } else { + _ = s.Pool.QueryRow(r.Context(), `SELECT "id", "name" FROM "User" WHERE "role" = 'admin' ORDER BY "createdAt" ASC LIMIT 1`).Scan(&asesorID, &asesorName) + } + } else { + _ = s.Pool.QueryRow(r.Context(), `SELECT "name" FROM "User" WHERE "id" = $1`, asesorID).Scan(&asesorName) + } + if asesorID == "" { + return http.StatusBadRequest, map[string]any{"error": "No se encontro un asesor valido"} + } + + // Dates & folio + fecha := time.Now() + if body.Fecha != "" { + if t, err := parseFlexibleDate(body.Fecha); err == nil { + fecha = t + } + } + vigencia := domain.CalcularVigencia(fecha) + if body.Vigencia != "" { + if t, err := parseFlexibleDate(body.Vigencia); err == nil { + vigencia = t + } + } + numero := strings.TrimSpace(body.Numero) + if numero == "" { + numero = s.siguienteNumeroCotizacion(r.Context(), asesorName) + } + incluirIVA := true + if body.IncluirIVA != nil { + incluirIVA = *body.IncluirIVA + } + var opMetaJSON []byte + if body.OpcionesMetadata != nil { + opMetaJSON, _ = json.Marshal(body.OpcionesMetadata) + } + var creadaPorAgente *string + if actor.IsAgent() { + n := actor.KeyNombre + creadaPorAgente = &n + } + + tx, err := s.Pool.Begin(r.Context()) + if err != nil { + return http.StatusInternalServerError, map[string]any{"error": "Error iniciando transaccion"} + } + defer tx.Rollback(r.Context()) + + cotID := db.NewID() + _, err = tx.Exec(r.Context(), ` + INSERT INTO "Cotizacion" ( + "id", "numero", "fecha", "vigencia", "moneda", "tipoCambio", "proyecto", + "esquemaPago", "estado", "incluirBonos", "incluirFinanciamiento", "incluirIva", + "esDoble", "opcionesMetadata", "observaciones", "observacionesInternas", + "clienteId", "asesorId", "creadaPorAgente", "archivado", "createdAt", "updatedAt" + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'borrador',$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,false,NOW(),NOW()) + `, cotID, numero, fecha, vigencia, + firstNonEmptyStr(body.Moneda, "MXN"), + firstNonEmptyStr(body.TipoCambio, "NA"), + firstNonEmptyStr(body.Proyecto, "MKT Digital"), + firstNonEmptyStr(body.EsquemaPago, "Pago Unico/Mensual"), + body.IncluirBonos, body.IncluirFinanciamiento, incluirIVA, + body.EsDoble, opMetaJSON, body.Observaciones, body.ObservacionesInternas, + clienteID, asesorID, creadaPorAgente) + if err != nil { + if strings.Contains(err.Error(), "23505") { + return http.StatusConflict, map[string]any{"error": "Ya existe una cotizacion con ese numero"} + } + return http.StatusInternalServerError, map[string]any{"error": "Error guardando cotizacion: " + err.Error()} + } + + var calcSvcs []domain.ServicioCalc + for _, sv := range body.Servicios { + scid := nullableTrim(firstNonEmptyStr(derefStr(sv.ServicioCatalogoID), derefStr(sv.CatalogoID))) + sel := true + if sv.Seleccionado != nil { + sel = *sv.Seleccionado + } + mc := firstNonEmptyStr(sv.ModeloCobro, "fijo") + tp := firstNonEmptyStr(sv.TipoPago, "unico") + te := firstNonEmptyStr(sv.TiempoEntrega, "4 - 10 dias") + ent := sv.Entregables + if ent == nil { + ent = []string{} + } + ben := sv.Beneficios + if ben == nil { + ben = []string{} + } + entJSON, _ := json.Marshal(ent) + benJSON, _ := json.Marshal(ben) + _, err = tx.Exec(r.Context(), ` + INSERT INTO "ServicioCotizado" ( + "id", "cotizacionId", "servicioCatalogoId", "nombre", "esPersonalizado", + "horas", "tarifaHora", "modeloCobro", "montoMinimo", "horasIncluidas", + "opcion", "fase", "tipoPago", "precio", "tiempoEntrega", + "entregables", "beneficios", "notas", "seleccionado", "createdAt", "updatedAt" + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,NOW(),NOW()) + `, db.NewID(), cotID, scid, sv.Nombre, sv.EsPersonalizado, + sv.Horas, sv.TarifaHora, mc, sv.MontoMinimo, sv.HorasIncluidas, + sv.Opcion, sv.Fase, tp, sv.Precio, te, entJSON, benJSON, sv.Notas, sel) + if err != nil { + return http.StatusInternalServerError, map[string]any{"error": "Error guardando servicios"} + } + calcSvcs = append(calcSvcs, domain.ServicioCalc{TipoPago: tp, Precio: sv.Precio, Seleccionado: sel}) + } + + if body.PlanBucefalo != nil { + nivel := firstNonEmptyStr(body.PlanBucefalo.Nivel, "basico") + precio := domain.BucefaloPrecio(nivel) + if body.PlanBucefalo.Precio != nil { + precio = *body.PlanBucefalo.Precio + } + sel := true + if body.PlanBucefalo.Seleccionado != nil { + sel = *body.PlanBucefalo.Seleccionado + } + _, err = tx.Exec(r.Context(), ` + INSERT INTO "PlanBucefaloCotizacion" ("id", "cotizacionId", "nivel", "precio", "seleccionado", "createdAt", "updatedAt") + VALUES ($1,$2,$3,$4,$5,NOW(),NOW()) + `, db.NewID(), cotID, nivel, precio, sel) + if err != nil { + return http.StatusInternalServerError, map[string]any{"error": "Error guardando plan Bucefalo"} + } + } + + if err := tx.Commit(r.Context()); err != nil { + return http.StatusInternalServerError, map[string]any{"error": "Error confirmando cotizacion"} + } + + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.crear", RecursoTipo: "cotizacion", RecursoID: cotID, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + Detalle: map[string]any{"numero": numero, "clienteId": clienteID}, + }) + + tot := domain.CalcularTotalesCotizacion(calcSvcs, incluirIVA) + if actor.IsAgent() { + if approvalURL, err := s.crearEnlaceAprobacion(r.Context(), cotID); err == nil { + go s.Notify.NotificarJarethBorrador(context.Background(), cotID, numero, clienteNombre, clienteEmpresa, firstNonEmptyStr(body.Proyecto, "MKT Digital"), actor.KeyNombre, approvalURL, tot.TotalUnico, tot.TotalMensual) + } + } + + go s.Webhooks.Emitir(context.Background(), "cotizacion.creada", map[string]any{ + "cotizacionId": cotID, "numero": numero, "estado": "borrador", + "clienteId": clienteID, "clienteNombre": clienteNombre, "totalUnico": tot.TotalUnico, "totalMensual": tot.TotalMensual, + }) + + _, respMap, err := s.loadCotizacionFull(r.Context(), cotID, false) + if err != nil { + return http.StatusCreated, map[string]any{"id": cotID, "numero": numero, "estado": "borrador"} + } + return http.StatusCreated, respMap + }) +} + +func (s *Server) handleCotizacionesGet(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{ + Scopes: []string{"cotizaciones:leer", "cotizaciones:leer_aceptadas"}, + RecursoTipo: "cotizacion", + }) + if !ok { + return + } + id := chi.URLParam(r, "id") + soloAceptadas := actor.EsAgenteSoloAceptadas() + + full, jsonMap, err := s.loadCotizacionFull(r.Context(), id, soloAceptadas) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + writeError(w, http.StatusInternalServerError, "Error cargando cotizacion") + return + } + + if soloAceptadas && full.Estado != "aceptada" { + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.leer_bloqueado", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + }) + writeError(w, http.StatusForbidden, "Esta clave solo puede leer cotizaciones aceptadas") + return + } + + if verif := strings.TrimSpace(r.URL.Query().Get("verificarContacto")); verif != "" { + if !auth.CoincideContacto(verif, derefStr(full.ClienteEmail), derefStr(full.ClienteTelefono)) { + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.verificar_contacto_fallo", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + }) + writeError(w, http.StatusForbidden, "El contacto proporcionado no coincide con el cliente de esta cotizacion") + return + } + } + + writeJSON(w, http.StatusOK, jsonMap) +} + +func (s *Server) handleCotizacionesUpdate(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{ + Scopes: []string{"cotizaciones:borrador"}, + RecursoTipo: "cotizacion", + }) + if !ok { + return + } + id := chi.URLParam(r, "id") + full, _, err := s.loadCotizacionFull(r.Context(), id, false) + if err != nil { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + + var raw map[string]any + if err := decodeJSON(r, &raw); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + + // Single-key { estado } shortcut + if len(raw) == 1 { + if nuevoEstado, ok := raw["estado"].(string); ok { + s.transitionEstado(w, r, actor, full, nuevoEstado, "put") + return + } + } + + if actor.IsAgent() && full.Estado != "borrador" { + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.editar_bloqueado", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + }) + writeError(w, http.StatusForbidden, "Los agentes solo pueden editar cotizaciones en borrador") + return + } + + rawBytes, _ := json.Marshal(raw) + var body struct { + Fecha string `json:"fecha"` + Vigencia string `json:"vigencia"` + Moneda *string `json:"moneda"` + TipoCambio *string `json:"tipoCambio"` + Proyecto *string `json:"proyecto"` + EsquemaPago *string `json:"esquemaPago"` + Estado *string `json:"estado"` + IncluirBonos *bool `json:"incluirBonos"` + IncluirFinanciamiento *bool `json:"incluirFinanciamiento"` + IncluirIVA *bool `json:"incluirIva"` + EsDoble *bool `json:"esDoble"` + OpcionesMetadata map[string]domain.MetaOpcion `json:"opcionesMetadata"` + Observaciones *string `json:"observaciones"` + ObservacionesInternas *string `json:"observacionesInternas"` + AsesorID *string `json:"asesorId"` + Cliente *struct { + Nombre string `json:"nombre"` + Empresa *string `json:"empresa"` + Puesto *string `json:"puesto"` + Email *string `json:"email"` + Telefono *string `json:"telefono"` + RFC *string `json:"rfc"` + } `json:"cliente"` + Servicios []servicioInputDTO `json:"servicios"` + PlanBucefalo *struct { + Nivel string `json:"nivel"` + Precio *float64 `json:"precio"` + Seleccionado *bool `json:"seleccionado"` + } `json:"planBucefalo"` + } + _ = json.Unmarshal(rawBytes, &body) + + if body.Estado != nil && *body.Estado != full.Estado { + tr := domain.ValidarTransicionEstado(domain.ValidarTransicionInput{ + Actual: full.Estado, Nuevo: *body.Estado, Actor: actor.ToDomainActor(), ViaEndpoint: "put", AprobadaAt: full.AprobadaAt, + }) + if !tr.OK { + writeError(w, tr.Status, tr.Error) + return + } + } + + // SoloAdmin guard + _, hasPlanKey := raw["planBucefalo"] + draftSvcs := make([]domain.ServicioDraftInput, 0, len(body.Servicios)) + for _, sv := range body.Servicios { + cid := firstNonEmptyStr(derefStr(sv.ServicioCatalogoID), derefStr(sv.CatalogoID)) + draftSvcs = append(draftSvcs, domain.ServicioDraftInput{CatalogoID: cid, Nombre: derefStr(sv.Nombre), EsPersonalizado: sv.EsPersonalizado}) + } + soloCheck := domain.EvaluarRestriccionSoloAdmin(domain.EvaluarSoloAdminInput{ + EsAgente: actor.IsAgent(), + HasPlanBucefalo: hasPlanKey && body.PlanBucefalo != nil, + Servicios: draftSvcs, + SoloAdminCatalogIDs: s.soloAdminCatalogIDs(r.Context()), + }) + if !soloCheck.OK { + writeJSON(w, http.StatusForbidden, map[string]any{ + "error": "Servicios exclusivos de administrador bloqueados", "reason": "solo_admin_restricted", "itemsBloqueados": soloCheck.ItemsBloqueados, + }) + return + } + + tx, err := s.Pool.Begin(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error iniciando transaccion") + return + } + defer tx.Rollback(r.Context()) + + if body.Cliente != nil && strings.TrimSpace(body.Cliente.Nombre) != "" { + _, _ = tx.Exec(r.Context(), ` + UPDATE "Cliente" SET "nombre"=$1, "empresa"=$2, "puesto"=$3, "email"=$4, "telefono"=$5, "rfc"=$6, "updatedAt"=NOW() + WHERE "id" = $7 + `, strings.TrimSpace(body.Cliente.Nombre), trimPtr(body.Cliente.Empresa), trimPtr(body.Cliente.Puesto), + trimPtr(body.Cliente.Email), trimPtr(body.Cliente.Telefono), trimPtr(body.Cliente.RFC), full.ClienteID) + } + + sets := []string{`"updatedAt" = NOW()`} + args := []any{} + add := func(col string, val any) { + args = append(args, val) + sets = append(sets, fmt.Sprintf(`"%s" = $%d`, col, len(args))) + } + if body.Fecha != "" { + if t, err := parseFlexibleDate(body.Fecha); err == nil { + add("fecha", t) + } + } + if body.Vigencia != "" { + if t, err := parseFlexibleDate(body.Vigencia); err == nil { + add("vigencia", t) + } + } + if body.Moneda != nil { + add("moneda", *body.Moneda) + } + if body.TipoCambio != nil { + add("tipoCambio", *body.TipoCambio) + } + if body.Proyecto != nil { + add("proyecto", *body.Proyecto) + } + if body.EsquemaPago != nil { + add("esquemaPago", *body.EsquemaPago) + } + if body.IncluirBonos != nil { + add("incluirBonos", *body.IncluirBonos) + } + if body.IncluirFinanciamiento != nil { + add("incluirFinanciamiento", *body.IncluirFinanciamiento) + } + if body.IncluirIVA != nil { + add("incluirIva", *body.IncluirIVA) + } + if body.EsDoble != nil { + add("esDoble", *body.EsDoble) + } + if _, ok := raw["opcionesMetadata"]; ok { + b, _ := json.Marshal(body.OpcionesMetadata) + add("opcionesMetadata", b) + } + if _, ok := raw["observaciones"]; ok { + add("observaciones", body.Observaciones) + } + if _, ok := raw["observacionesInternas"]; ok { + add("observacionesInternas", body.ObservacionesInternas) + } + if body.AsesorID != nil && *body.AsesorID != "" { + add("asesorId", *body.AsesorID) + } + if body.Estado != nil { + add("estado", *body.Estado) + } + + args = append(args, id) + if _, err := tx.Exec(r.Context(), fmt.Sprintf(`UPDATE "Cotizacion" SET %s WHERE "id" = $%d`, strings.Join(sets, ", "), len(args)), args...); err != nil { + writeError(w, http.StatusInternalServerError, "Error actualizando cotizacion") + return + } + + if _, hasSvcs := raw["servicios"]; hasSvcs { + _, _ = tx.Exec(r.Context(), `DELETE FROM "ServicioCotizado" WHERE "cotizacionId" = $1`, id) + for _, sv := range body.Servicios { + scid := nullableTrim(firstNonEmptyStr(derefStr(sv.ServicioCatalogoID), derefStr(sv.CatalogoID))) + sel := true + if sv.Seleccionado != nil { + sel = *sv.Seleccionado + } + entJSON, _ := json.Marshal(nonNilSlice(sv.Entregables)) + benJSON, _ := json.Marshal(nonNilSlice(sv.Beneficios)) + _, err = tx.Exec(r.Context(), ` + INSERT INTO "ServicioCotizado" ( + "id", "cotizacionId", "servicioCatalogoId", "nombre", "esPersonalizado", + "horas", "tarifaHora", "modeloCobro", "montoMinimo", "horasIncluidas", + "opcion", "fase", "tipoPago", "precio", "tiempoEntrega", + "entregables", "beneficios", "notas", "seleccionado", "createdAt", "updatedAt" + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,NOW(),NOW()) + `, db.NewID(), id, scid, sv.Nombre, sv.EsPersonalizado, + sv.Horas, sv.TarifaHora, firstNonEmptyStr(sv.ModeloCobro, "fijo"), sv.MontoMinimo, sv.HorasIncluidas, + sv.Opcion, sv.Fase, firstNonEmptyStr(sv.TipoPago, "unico"), sv.Precio, firstNonEmptyStr(sv.TiempoEntrega, "4 - 10 dias"), + entJSON, benJSON, sv.Notas, sel) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error actualizando servicios") + return + } + } + } + + if hasPlanKey { + _, _ = tx.Exec(r.Context(), `DELETE FROM "PlanBucefaloCotizacion" WHERE "cotizacionId" = $1`, id) + if body.PlanBucefalo != nil { + nivel := firstNonEmptyStr(body.PlanBucefalo.Nivel, "basico") + precio := domain.BucefaloPrecio(nivel) + if body.PlanBucefalo.Precio != nil { + precio = *body.PlanBucefalo.Precio + } + sel := true + if body.PlanBucefalo.Seleccionado != nil { + sel = *body.PlanBucefalo.Seleccionado + } + _, _ = tx.Exec(r.Context(), ` + INSERT INTO "PlanBucefaloCotizacion" ("id", "cotizacionId", "nivel", "precio", "seleccionado", "createdAt", "updatedAt") + VALUES ($1,$2,$3,$4,$5,NOW(),NOW()) + `, db.NewID(), id, nivel, precio, sel) + } + } + + if err := tx.Commit(r.Context()); err != nil { + writeError(w, http.StatusInternalServerError, "Error confirmando cambios") + return + } + + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.actualizar", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + }) + + _, updatedMap, _ := s.loadCotizacionFull(r.Context(), id, false) + writeJSON(w, http.StatusOK, updatedMap) +} + +func (s *Server) handleCotizacionesDelete(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{ + StaffOnly: true, + AccionBloqueo: "cotizacion.eliminar_bloqueado", + RecursoTipo: "cotizacion", + }) + if !ok { + return + } + id := chi.URLParam(r, "id") + tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "Cotizacion" WHERE "id" = $1`, id) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.eliminar", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + }) + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +func (s *Server) handleCotizacionSolicitarAprobacion(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{ + Scopes: []string{"cotizaciones:borrador"}, + RecursoTipo: "cotizacion", + }) + if !ok { + return + } + id := chi.URLParam(r, "id") + full, _, err := s.loadCotizacionFull(r.Context(), id, false) + if err != nil { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + if full.Estado != "borrador" { + writeError(w, http.StatusConflict, "Solo se puede solicitar aprobacion para cotizaciones en borrador") + return + } + approvalURL, err := s.crearEnlaceAprobacion(r.Context(), id) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error generando enlace de aprobacion") + return + } + + tot := domain.CalcularTotalesCotizacion(full.ServiciosCalc, full.IncluirIVA) + _, _, anom := actor.AuditActor() + go s.Notify.NotificarJarethBorrador(context.Background(), id, full.Numero, full.ClienteNombre, derefStr(full.ClienteEmpresa), full.Proyecto, anom, approvalURL, tot.TotalUnico, tot.TotalMensual) + + tipo, aid, _ := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.solicitar_aprobacion", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + }) + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mensaje": "Solicitud de aprobacion enviada al administrador"}) +} + +func (s *Server) handleCotizacionAprobar(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{ + AdminOnly: true, + AccionBloqueo: "cotizacion.aprobar_bloqueado", + RecursoTipo: "cotizacion", + }) + if !ok { + return + } + // Redundant iron-clad human admin check + if !actor.IsAdmin() { + writeError(w, http.StatusForbidden, "Solo un administrador humano puede aprobar cotizaciones") + return + } + id := chi.URLParam(r, "id") + full, _, err := s.loadCotizacionFull(r.Context(), id, false) + if err != nil { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + s.transitionEstado(w, r, actor, full, "aprobada", "aprobar") +} + +func (s *Server) handleCotizacionEstado(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{ + StaffOnly: true, + AccionBloqueo: "cotizacion.estado_bloqueado", + RecursoTipo: "cotizacion", + }) + if !ok { + return + } + id := chi.URLParam(r, "id") + full, _, err := s.loadCotizacionFull(r.Context(), id, false) + if err != nil { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + var body struct { + Estado string `json:"estado"` + } + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + s.transitionEstado(w, r, actor, full, body.Estado, "estado") +} + +func (s *Server) transitionEstado(w http.ResponseWriter, r *http.Request, actor *auth.Actor, full *cotizacionFull, nuevo, via string) { + tr := domain.ValidarTransicionEstado(domain.ValidarTransicionInput{ + Actual: full.Estado, Nuevo: nuevo, Actor: actor.ToDomainActor(), ViaEndpoint: via, AprobadaAt: full.AprobadaAt, + }) + tipo, aid, anom := actor.AuditActor() + if !tr.OK { + acc := "cotizacion.estado_bloqueado" + if nuevo == "aprobada" { + acc = "cotizacion.aprobar_bloqueado" + } + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: acc, RecursoTipo: "cotizacion", RecursoID: full.ID, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + Detalle: map[string]any{"actual": full.Estado, "nuevo": nuevo, "error": tr.Error}, + }) + writeError(w, tr.Status, tr.Error) + return + } + + now := time.Now() + switch nuevo { + case "aprobada": + _, _ = s.Pool.Exec(r.Context(), `UPDATE "ApprovalToken" SET "usadoAt" = $1 WHERE "cotizacionId" = $2 AND "usadoAt" IS NULL`, now, full.ID) + _, _ = s.Pool.Exec(r.Context(), ` + UPDATE "Cotizacion" SET "estado"='aprobada', "aprobadaAt"=$1, "aprobadaPorId"=$2, "aprobacionMetodo"='web_admin', "updatedAt"=NOW() + WHERE "id" = $3 + `, now, actor.UserID, full.ID) + case "enviada": + _, _ = s.Pool.Exec(r.Context(), ` + UPDATE "Cotizacion" SET "estado"='enviada', "enviadaAt"=$1, "enviadaPor"=$2, "updatedAt"=NOW() WHERE "id" = $3 + `, now, anom, full.ID) + case "aceptada": + _, _ = s.Pool.Exec(r.Context(), `UPDATE "Cotizacion" SET "estado"='aceptada', "aceptadaAt"=$1, "updatedAt"=NOW() WHERE "id" = $2`, now, full.ID) + case "rechazada": + _, _ = s.Pool.Exec(r.Context(), `UPDATE "Cotizacion" SET "estado"='rechazada', "rechazadaAt"=$1, "updatedAt"=NOW() WHERE "id" = $2`, now, full.ID) + case "vencida": + _, _ = s.Pool.Exec(r.Context(), `UPDATE "Cotizacion" SET "estado"='vencida', "vencidaAt"=$1, "updatedAt"=NOW() WHERE "id" = $2`, now, full.ID) + case "borrador": + _, _ = s.Pool.Exec(r.Context(), ` + UPDATE "Cotizacion" SET "estado"='borrador', "aprobadaAt"=NULL, "aprobadaPorId"=NULL, "aprobacionMetodo"=NULL, "updatedAt"=NOW() WHERE "id" = $1 + `, full.ID) + } + + acc := "cotizacion.estado_" + nuevo + if nuevo == "aprobada" { + acc = "cotizacion.aprobar" + } + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: acc, RecursoTipo: "cotizacion", RecursoID: full.ID, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + Detalle: map[string]any{"anterior": full.Estado, "nuevo": nuevo}, + }) + + if nuevo != "borrador" && nuevo != full.Estado { + go s.Webhooks.Emitir(context.Background(), "cotizacion."+nuevo, map[string]any{ + "cotizacionId": full.ID, "numero": full.Numero, "estado": nuevo, + }) + } + + _, updatedMap, _ := s.loadCotizacionFull(r.Context(), full.ID, false) + writeJSON(w, http.StatusOK, updatedMap) +} + +func (s *Server) handleCotizacionEnviar(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{ + Scopes: []string{"cotizaciones:enviar"}, + AccionBloqueo: "cotizacion.enviar_bloqueado", + RecursoTipo: "cotizacion", + }) + if !ok { + return + } + id := chi.URLParam(r, "id") + idempotency.Execute(r.Context(), s.Pool, w, r, actor, func(rawBody []byte) (int, any) { + var body struct { + Canal string `json:"canal"` + Destino string `json:"destino"` + VerificarContacto string `json:"verificarContacto"` + FallbackEmail *bool `json:"fallbackEmail"` + Mensaje string `json:"mensaje"` + } + _ = json.Unmarshal(rawBody, &body) + canal := firstNonEmptyStr(body.Canal, "whatsapp_chatwoot") + fallbackEmail := true + if body.FallbackEmail != nil { + fallbackEmail = *body.FallbackEmail + } + + full, _, err := s.loadCotizacionFull(r.Context(), id, false) + if err != nil { + return http.StatusNotFound, map[string]any{"error": "Cotizacion no encontrada"} + } + + tipo, aid, anom := actor.AuditActor() + // Hard approval guard + tr := domain.ValidarTransicionEstado(domain.ValidarTransicionInput{ + Actual: full.Estado, Nuevo: "enviada", Actor: actor.ToDomainActor(), ViaEndpoint: "enviar", AprobadaAt: full.AprobadaAt, + }) + if !tr.OK { + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.enviar_bloqueado", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + Detalle: map[string]any{"estado": full.Estado, "error": tr.Error}, + }) + return tr.Status, map[string]any{"error": tr.Error} + } + + if canal == "manual" && !actor.IsAdmin() { + return http.StatusForbidden, map[string]any{"error": "El canal manual es exclusivo del administrador humano"} + } + + if strings.TrimSpace(body.VerificarContacto) != "" { + if !auth.CoincideContacto(body.VerificarContacto, derefStr(full.ClienteEmail), derefStr(full.ClienteTelefono)) { + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.enviar_contacto_bloqueado", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + }) + return http.StatusForbidden, map[string]any{"error": "El contacto no coincide con el cliente de la cotizacion"} + } + } + + pdfBytes, err := s.buildQuotePDFBytes(r.Context(), full) + if err != nil { + return http.StatusInternalServerError, map[string]any{"error": "Error generando PDF de cotizacion"} + } + + canalFinal := canal + destinoFinal := strings.TrimSpace(body.Destino) + + switch canal { + case "whatsapp_chatwoot": + if destinoFinal == "" { + destinoFinal = derefStr(full.ClienteTelefono) + } + waRes := s.Webhooks.InvocarEnvioWhatsAppN8n(r.Context(), map[string]any{ + "cotizacionId": full.ID, + "numero": full.Numero, + "clienteNombre": full.ClienteNombre, + "telefono": destinoFinal, + "email": derefStr(full.ClienteEmail), + "mensaje": body.Mensaje, + "pdfFilename": fmt.Sprintf("Cotizacion_%s.pdf", domain.SanitizeFilename(full.Numero)), + "pdfBase64": base64.StdEncoding.EncodeToString(pdfBytes), + }) + if !waRes.OK { + if waRes.Outside24h { + if fallbackEmail && derefStr(full.ClienteEmail) != "" { + sent := s.Notify.EnviarCotizacionPorCorreo(derefStr(full.ClienteEmail), full.ClienteNombre, full.Numero, full.Proyecto, pdfBytes) + if sent { + canalFinal = "email" + destinoFinal = derefStr(full.ClienteEmail) + } else { + return http.StatusBadGateway, map[string]any{"error": "WhatsApp fuera de ventana 24h y fallo el envio por correo"} + } + } else { + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.enviar_fuera_ventana", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + }) + go s.Notify.NotificarJarethWhatsAppFueraVentana(context.Background(), full.Numero, full.ClienteNombre, destinoFinal) + return http.StatusConflict, map[string]any{ + "error": "WhatsApp fuera de ventana de 24 horas", + "reason": "outside_24h_window", + } + } + } else { + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.enviar_error", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + Detalle: map[string]any{"error": waRes.ErrorMessage}, + }) + return http.StatusBadGateway, map[string]any{"error": "Error enviando por WhatsApp: " + waRes.ErrorMessage} + } + } + case "email": + if destinoFinal == "" { + destinoFinal = derefStr(full.ClienteEmail) + } + if destinoFinal == "" { + return http.StatusBadRequest, map[string]any{"error": "El cliente no tiene correo electronico configurado"} + } + if !s.Notify.EnviarCotizacionPorCorreo(destinoFinal, full.ClienteNombre, full.Numero, full.Proyecto, pdfBytes) { + return http.StatusBadGateway, map[string]any{"error": "No se pudo enviar el correo (verifica configuracion SMTP)"} + } + case "manual": + if destinoFinal == "" { + destinoFinal = firstNonEmptyStr(derefStr(full.ClienteEmail), derefStr(full.ClienteTelefono), "manual") + } + default: + return http.StatusBadRequest, map[string]any{"error": "Canal invalido (usa whatsapp_chatwoot, email o manual)"} + } + + now := time.Now() + _, _ = s.Pool.Exec(r.Context(), ` + UPDATE "Cotizacion" + SET "estado"='enviada', "enviadaAt"=$1, "enviadaPor"=$2, "enviadaCanal"=$3, "enviadaDestino"=$4, "updatedAt"=NOW() + WHERE "id" = $5 + `, now, anom, canalFinal, destinoFinal, id) + + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.enviar", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + Detalle: map[string]any{"canal": canalFinal, "destino": destinoFinal}, + }) + go s.Webhooks.Emitir(context.Background(), "cotizacion.enviada", map[string]any{ + "cotizacionId": id, "numero": full.Numero, "canal": canalFinal, "destino": destinoFinal, "enviadaAt": now.UTC().Format(time.RFC3339), + }) + + return http.StatusOK, map[string]any{ + "ok": true, "cotizacionId": id, "numero": full.Numero, "estado": "enviada", + "canal": canalFinal, "destino": destinoFinal, "enviadaAt": now, + } + }) +} + +func (s *Server) handleCotizacionPrecio(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{ + Scopes: []string{"cotizaciones:borrador"}, + RecursoTipo: "cotizacion", + }) + if !ok { + return + } + id := chi.URLParam(r, "id") + var estado string + if err := s.Pool.QueryRow(r.Context(), `SELECT "estado" FROM "Cotizacion" WHERE "id" = $1`, id).Scan(&estado); err != nil { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + if actor.IsAgent() && estado != "borrador" { + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.editar_precio_bloqueado", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + }) + writeError(w, http.StatusForbidden, "Los agentes solo pueden editar precios en borrador") + return + } + var body struct { + ServicioID string `json:"servicioId"` + Precio float64 `json:"precio"` + } + if err := decodeJSON(r, &body); err != nil || body.ServicioID == "" || body.Precio < 0 { + writeError(w, http.StatusBadRequest, "servicioId y precio >= 0 son requeridos") + return + } + tag, err := s.Pool.Exec(r.Context(), ` + UPDATE "ServicioCotizado" SET "precio" = $1, "updatedAt" = NOW() + WHERE "id" = $2 AND "cotizacionId" = $3 + `, body.Precio, body.ServicioID, id) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Partida no encontrada") + return + } + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.actualizar_precio", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: true, + Detalle: map[string]any{"servicioId": body.ServicioID, "precio": body.Precio}, + }) + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "servicioId": body.ServicioID, "precio": body.Precio}) +} + +// ── Registro de Horas & Nota de Horas PDF ──────────────────────────────────── + +func (s *Server) handleHorasList(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "horas"}); !ok { + return + } + cotID := chi.URLParam(r, "id") + q := r.URL.Query() + conds := []string{`"cotizacionId" = $1`} + args := []any{cotID} + if from := strings.TrimSpace(q.Get("from")); from != "" { + if t, err := time.Parse("2006-01-02", from); err == nil { + args = append(args, t) + conds = append(conds, fmt.Sprintf(`"fecha" >= $%d`, len(args))) + } + } + if to := strings.TrimSpace(q.Get("to")); to != "" { + if t, err := time.Parse("2006-01-02", to); err == nil { + args = append(args, t.Add(24*time.Hour)) + conds = append(conds, fmt.Sprintf(`"fecha" < $%d`, len(args))) + } + } + rows, err := s.Pool.Query(r.Context(), ` + SELECT "id", "cotizacionId", "fecha", "horaInicio", "horaFin", "horas", "tarifaHora", "descripcion", "estadoPago", "fechaPago", "createdAt" + FROM "RegistroHoras" + WHERE `+strings.Join(conds, " AND ")+` + ORDER BY "fecha" DESC, "horaInicio" DESC + `, args...) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error listando horas") + return + } + defer rows.Close() + list := []map[string]any{} + for rows.Next() { + var id, qid, hi, hf, desc, ep string + var fecha, createdAt time.Time + var fechaPago *time.Time + var hrs, th float64 + if rows.Scan(&id, &qid, &fecha, &hi, &hf, &hrs, &th, &desc, &ep, &fechaPago, &createdAt) == nil { + list = append(list, map[string]any{ + "id": id, "cotizacionId": qid, "fecha": fecha, "horaInicio": hi, "horaFin": hf, + "horas": hrs, "tarifaHora": th, "descripcion": desc, "estadoPago": ep, + "fechaPago": fechaPago, "createdAt": createdAt, + }) + } + } + writeJSON(w, http.StatusOK, list) +} + +func (s *Server) handleHorasCreate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "horas"}); !ok { + return + } + cotID := chi.URLParam(r, "id") + full, _, err := s.loadCotizacionFull(r.Context(), cotID, false) + if err != nil { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + if !domain.EsCotizacionPorTiempo(full.ServiciosCalc) { + writeError(w, http.StatusBadRequest, "Esta cotizacion no tiene servicios cobrados por tiempo") + return + } + var body struct { + Fecha string `json:"fecha"` + HoraInicio string `json:"horaInicio"` + HoraFin string `json:"horaFin"` + TarifaHora *float64 `json:"tarifaHora"` + Descripcion string `json:"descripcion"` + } + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + fecha, err := domain.FechaRegistroDesdeISO(body.Fecha) + if err != nil { + writeError(w, http.StatusBadRequest, "Fecha invalida (YYYY-MM-DD)") + return + } + horas := domain.CalcularHorasRango(body.HoraInicio, body.HoraFin) + if horas <= 0 { + writeError(w, http.StatusBadRequest, "Rango horario invalido (horaFin debe ser mayor a horaInicio)") + return + } + desc := strings.TrimSpace(body.Descripcion) + if desc == "" { + writeError(w, http.StatusBadRequest, "La descripcion es obligatoria") + return + } + tarifa := domain.TarifaHoraSugerida(full.ServiciosCalc) + if body.TarifaHora != nil && *body.TarifaHora >= 0 { + tarifa = *body.TarifaHora + } + id := db.NewID() + _, err = s.Pool.Exec(r.Context(), ` + INSERT INTO "RegistroHoras" ("id", "cotizacionId", "fecha", "horaInicio", "horaFin", "horas", "tarifaHora", "descripcion", "estadoPago", "createdAt", "updatedAt") + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,'por_pagar',NOW(),NOW()) + `, id, cotID, fecha, body.HoraInicio, body.HoraFin, horas, tarifa, desc) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error registrando horas") + return + } + writeJSON(w, http.StatusCreated, map[string]any{ + "id": id, "cotizacionId": cotID, "fecha": fecha, "horaInicio": body.HoraInicio, "horaFin": body.HoraFin, + "horas": horas, "tarifaHora": tarifa, "descripcion": desc, "estadoPago": "por_pagar", "fechaPago": nil, + }) +} + +func (s *Server) handleHorasUpdate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "horas"}); !ok { + return + } + cotID := chi.URLParam(r, "id") + regID := chi.URLParam(r, "registroId") + var body struct { + Fecha string `json:"fecha"` + HoraInicio string `json:"horaInicio"` + HoraFin string `json:"horaFin"` + TarifaHora *float64 `json:"tarifaHora"` + Descripcion string `json:"descripcion"` + } + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + fecha, err := domain.FechaRegistroDesdeISO(body.Fecha) + if err != nil { + writeError(w, http.StatusBadRequest, "Fecha invalida") + return + } + horas := domain.CalcularHorasRango(body.HoraInicio, body.HoraFin) + if horas <= 0 { + writeError(w, http.StatusBadRequest, "Rango horario invalido") + return + } + tarifa := 0.0 + if body.TarifaHora != nil { + tarifa = *body.TarifaHora + } + tag, err := s.Pool.Exec(r.Context(), ` + UPDATE "RegistroHoras" + SET "fecha"=$1, "horaInicio"=$2, "horaFin"=$3, "horas"=$4, "tarifaHora"=$5, "descripcion"=$6, "updatedAt"=NOW() + WHERE "id"=$7 AND "cotizacionId"=$8 + `, fecha, body.HoraInicio, body.HoraFin, horas, tarifa, strings.TrimSpace(body.Descripcion), regID, cotID) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Registro no encontrado") + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "id": regID, "cotizacionId": cotID, "fecha": fecha, "horaInicio": body.HoraInicio, "horaFin": body.HoraFin, + "horas": horas, "tarifaHora": tarifa, "descripcion": strings.TrimSpace(body.Descripcion), + }) +} + +func (s *Server) handleHorasEstadoPago(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "horas"}); !ok { + return + } + cotID := chi.URLParam(r, "id") + regID := chi.URLParam(r, "registroId") + var body struct { + EstadoPago string `json:"estadoPago"` + } + if err := decodeJSON(r, &body); err != nil || (body.EstadoPago != "por_pagar" && body.EstadoPago != "pagada") { + writeError(w, http.StatusBadRequest, "estadoPago debe ser por_pagar o pagada") + return + } + var fp *time.Time + if body.EstadoPago == "pagada" { + now := time.Now() + fp = &now + } + tag, err := s.Pool.Exec(r.Context(), ` + UPDATE "RegistroHoras" SET "estadoPago"=$1, "fechaPago"=$2, "updatedAt"=NOW() + WHERE "id"=$3 AND "cotizacionId"=$4 + `, body.EstadoPago, fp, regID, cotID) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Registro no encontrado") + return + } + writeJSON(w, http.StatusOK, map[string]any{"id": regID, "estadoPago": body.EstadoPago, "fechaPago": fp}) +} + +func (s *Server) handleHorasDelete(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "horas"}); !ok { + return + } + cotID := chi.URLParam(r, "id") + regID := chi.URLParam(r, "registroId") + tag, err := s.Pool.Exec(r.Context(), `DELETE FROM "RegistroHoras" WHERE "id"=$1 AND "cotizacionId"=$2`, regID, cotID) + if err != nil || tag.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "Registro no encontrado") + return + } + writeJSON(w, http.StatusOK, map[string]any{"ok": true}) +} + +func (s *Server) handleNotaHorasPDF(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "horas"}); !ok { + return + } + cotID := chi.URLParam(r, "id") + full, _, err := s.loadCotizacionFull(r.Context(), cotID, false) + if err != nil { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + var body struct { + Estado string `json:"estado"` // por_pagar | pagada | todas + Modo string `json:"modo"` // detalle | dia | semana | mes + From string `json:"from"` + To string `json:"to"` + } + _ = decodeJSON(r, &body) + estado := firstNonEmptyStr(body.Estado, "por_pagar") + modo := firstNonEmptyStr(body.Modo, "detalle") + + conds := []string{`"cotizacionId" = $1`} + args := []any{cotID} + if estado == "por_pagar" || estado == "pagada" { + args = append(args, estado) + conds = append(conds, fmt.Sprintf(`"estadoPago" = $%d`, len(args))) + } + if body.From != "" { + if t, err := time.Parse("2006-01-02", body.From); err == nil { + args = append(args, t) + conds = append(conds, fmt.Sprintf(`"fecha" >= $%d`, len(args))) + } + } + if body.To != "" { + if t, err := time.Parse("2006-01-02", body.To); err == nil { + args = append(args, t.Add(24*time.Hour)) + conds = append(conds, fmt.Sprintf(`"fecha" < $%d`, len(args))) + } + } + + rows, err := s.Pool.Query(r.Context(), ` + SELECT "fecha", "horaInicio", "horaFin", "horas", "tarifaHora", "descripcion", "estadoPago" + FROM "RegistroHoras" + WHERE `+strings.Join(conds, " AND ")+` + ORDER BY "fecha" ASC, "horaInicio" ASC + `, args...) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error cargando registros") + return + } + defer rows.Close() + + var regs []pdf.RegistroHoraPDF + for rows.Next() { + var rpdf pdf.RegistroHoraPDF + if rows.Scan(&rpdf.Fecha, &rpdf.HoraInicio, &rpdf.HoraFin, &rpdf.Horas, &rpdf.TarifaHora, &rpdf.Descripcion, &rpdf.EstadoPago) == nil { + regs = append(regs, rpdf) + } + } + if len(regs) == 0 { + writeError(w, http.StatusBadRequest, "No hay registros de horas para emitir la nota") + return + } + + titulo := "Nota de Pago — Registro de Horas" + if estado == "pagada" { + titulo = "Recibo — Horas Pagadas" + } else if estado == "todas" { + titulo = "Estado de Cuenta — Registro de Horas" + } + + branding := s.getConfigBranding(r.Context()) + pdfBytes, err := pdf.GenerateNotaHorasPDF(pdf.NotaHorasPDFData{ + Titulo: titulo, + Numero: full.Numero, + ClienteNombre: full.ClienteNombre, + ClienteEmpresa: derefStr(full.ClienteEmpresa), + Proyecto: full.Proyecto, + AsesorNombre: full.AsesorName, + Moneda: full.Moneda, + IncluirIVA: full.IncluirIVA, + Modo: modo, + MostrarEstado: estado == "todas", + MostrarBancarios: estado != "pagada", + Registros: regs, + ConfigBancaria: s.getConfigBancaria(r.Context()), + ColorPrimario: branding.ColorPrimario, + ColorSecundario: branding.ColorSecundario, + LogoBase64: branding.LogoBase64, + LogoMime: branding.LogoMime, + FechaEmision: time.Now(), + }) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error generando nota de horas PDF") + return + } + + w.Header().Set("Content-Type", "application/pdf") + w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="NotaHoras_%s.pdf"`, domain.SanitizeFilename(full.Numero))) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(pdfBytes) +} + +func derefStr(p *string) string { + if p == nil { + return "" + } + return *p +} + +func nonNilSlice(s []string) []string { + if s == nil { + return []string{} + } + return s +} + +func parseFlexibleDate(s string) (time.Time, error) { + s = strings.TrimSpace(s) + for _, layout := range []string{time.RFC3339, "2006-01-02T15:04:05.000Z", "2006-01-02"} { + if t, err := time.Parse(layout, s); err == nil { + return t, nil + } + } + return time.Time{}, fmt.Errorf("fecha invalida: %s", s) +} diff --git a/internal/httpapi/export_propuesta_handlers.go b/internal/httpapi/export_propuesta_handlers.go new file mode 100644 index 0000000..b6d09ec --- /dev/null +++ b/internal/httpapi/export_propuesta_handlers.go @@ -0,0 +1,649 @@ +package httpapi + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "cotizador/internal/audit" + "cotizador/internal/auth" + "cotizador/internal/db" + "cotizador/internal/domain" + "cotizador/internal/excel" + "cotizador/internal/pdf" + "cotizador/internal/propuesta" + + "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5" +) + +func (s *Server) loadBonosPDF(ctx context.Context) []pdf.BonoPDF { + rows, err := s.Pool.Query(ctx, `SELECT "numero", "descripcion" FROM "Bono" WHERE "activo" = true ORDER BY "numero" ASC`) + if err != nil { + return nil + } + defer rows.Close() + var out []pdf.BonoPDF + for rows.Next() { + var b pdf.BonoPDF + if rows.Scan(&b.Numero, &b.Descripcion) == nil { + out = append(out, b) + } + } + return out +} + +func (s *Server) buildQuotePDFBytes(ctx context.Context, full *cotizacionFull) ([]byte, error) { + branding := s.getConfigBranding(ctx) + var bonos []pdf.BonoPDF + if full.IncluirBonos { + bonos = s.loadBonosPDF(ctx) + } + return pdf.GenerateCotizacionPDF(pdf.CotizacionPDFData{ + Numero: full.Numero, + ClienteNombre: full.ClienteNombre, + ClienteEmpresa: derefStr(full.ClienteEmpresa), + AsesorNombre: full.AsesorName, + Fecha: full.Fecha, + Vigencia: full.Vigencia, + Moneda: full.Moneda, + TipoCambio: full.TipoCambio, + Proyecto: full.Proyecto, + EsquemaPago: full.EsquemaPago, + Servicios: full.ServiciosPDF, + EsDoble: full.EsDoble, + OpcionesMetadata: full.OpcionesMetadata, + PlanBucefaloNivel: full.PlanBucefaloNv, + PlanBucefaloPrecio: full.PlanBucefaloPr, + IncluirBonos: full.IncluirBonos, + Bonos: bonos, + IncluirIVA: full.IncluirIVA, + Observaciones: full.Observaciones, + ConfigBancaria: s.getConfigBancaria(ctx), + ColorPrimario: branding.ColorPrimario, + ColorSecundario: branding.ColorSecundario, + LogoBase64: branding.LogoBase64, + LogoMime: branding.LogoMime, + }) +} + +func (s *Server) handleExportPDFByID(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{ + AllowCliente: true, + Scopes: []string{"cotizaciones:leer", "cotizaciones:enviar", "cotizaciones:leer_aceptadas"}, + RecursoTipo: "cotizacion_pdf", + }) + if !ok { + return + } + id := chi.URLParam(r, "id") + full, _, err := s.loadCotizacionFull(r.Context(), id, true) + if err != nil { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + if actor.IsCliente() && full.ClienteID != actor.ClienteID { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + if actor.EsAgenteSoloAceptadas() && full.Estado != "aceptada" { + tipo, aid, anom := actor.AuditActor() + audit.Registrar(r.Context(), s.Pool, audit.Entry{ + ActorTipo: tipo, ActorID: aid, ActorNombre: anom, + Accion: "cotizacion.export_pdf_bloqueado", RecursoTipo: "cotizacion", RecursoID: id, + IP: audit.ClientIP(r), RequestID: audit.RequestID(r), Exito: false, + }) + writeError(w, http.StatusForbidden, "Solo puedes exportar PDF de cotizaciones aceptadas") + return + } + + pdfBytes, err := s.buildQuotePDFBytes(r.Context(), full) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error generando PDF: "+err.Error()) + return + } + + w.Header().Set("Content-Type", "application/pdf") + w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Cotizacion_%s.pdf"`, domain.SanitizeFilename(full.Numero))) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(pdfBytes) +} + +type draftExportBody struct { + Draft *draftExportPayload `json:"draft"` + draftExportPayload +} + +type draftExportPayload struct { + Numero string `json:"numero"` + ClienteNombre string `json:"clienteNombre"` + ClienteEmpresa string `json:"clienteEmpresa"` + AsesorNombre string `json:"asesorNombre"` + Fecha string `json:"fecha"` + Vigencia string `json:"vigencia"` + Moneda string `json:"moneda"` + TipoCambio string `json:"tipoCambio"` + Proyecto string `json:"proyecto"` + EsquemaPago string `json:"esquemaPago"` + IncluirBonos bool `json:"incluirBonos"` + IncluirIVA *bool `json:"incluirIva"` + EsDoble bool `json:"esDoble"` + OpcionesMetadata map[string]domain.MetaOpcion `json:"opcionesMetadata"` + Observaciones *string `json:"observaciones"` + PlanBucefaloNivel *string `json:"planBucefaloNivel"` + PlanBucefaloPrecio *float64 `json:"planBucefaloPrecio"` + PlanBucefalo *struct { + Nivel string `json:"nivel"` + Precio *float64 `json:"precio"` + Seleccionado *bool `json:"seleccionado"` + } `json:"planBucefalo"` + Servicios []servicioInputDTO `json:"servicios"` +} + +func (s *Server) handleExportPDFDraft(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cotizacion_pdf"}); !ok { + return + } + var wrap draftExportBody + if err := decodeJSON(r, &wrap); err != nil { + writeError(w, http.StatusBadRequest, "Borrador invalido") + return + } + d := wrap.draftExportPayload + if wrap.Draft != nil { + d = *wrap.Draft + } + fecha := time.Now() + if t, err := parseFlexibleDate(d.Fecha); err == nil { + fecha = t + } + vigencia := domain.CalcularVigencia(fecha) + if t, err := parseFlexibleDate(d.Vigencia); err == nil { + vigencia = t + } + incluirIVA := true + if d.IncluirIVA != nil { + incluirIVA = *d.IncluirIVA + } + svcs := make([]pdf.ServicioPDF, 0, len(d.Servicios)) + for _, sv := range d.Servicios { + if sv.Seleccionado != nil && !*sv.Seleccionado { + continue + } + svcs = append(svcs, pdf.ServicioPDF{ + Nombre: firstNonEmptyStr(derefStr(sv.Nombre), "Servicio"), Fase: sv.Fase, + TipoPago: firstNonEmptyStr(sv.TipoPago, "unico"), Precio: sv.Precio, + TiempoEntrega: firstNonEmptyStr(sv.TiempoEntrega, "4 - 10 dias"), + Entregables: nonNilSlice(sv.Entregables), EsPersonalizado: sv.EsPersonalizado, + Horas: sv.Horas, TarifaHora: sv.TarifaHora, ModeloCobro: firstNonEmptyStr(sv.ModeloCobro, "fijo"), + MontoMinimo: sv.MontoMinimo, HorasIncluidas: sv.HorasIncluidas, Opcion: sv.Opcion, + }) + } + pbNivel, pbPrecio := resolveDraftBucefalo(d) + branding := s.getConfigBranding(r.Context()) + var bonos []pdf.BonoPDF + if d.IncluirBonos { + bonos = s.loadBonosPDF(r.Context()) + } + pdfBytes, err := pdf.GenerateCotizacionPDF(pdf.CotizacionPDFData{ + Numero: firstNonEmptyStr(d.Numero, "BORRADOR"), + ClienteNombre: firstNonEmptyStr(d.ClienteNombre, "Cliente"), + ClienteEmpresa: d.ClienteEmpresa, + AsesorNombre: firstNonEmptyStr(d.AsesorNombre, "Asesor"), + Fecha: fecha, + Vigencia: vigencia, + Moneda: firstNonEmptyStr(d.Moneda, "MXN"), + TipoCambio: firstNonEmptyStr(d.TipoCambio, "NA"), + Proyecto: firstNonEmptyStr(d.Proyecto, "MKT Digital"), + EsquemaPago: firstNonEmptyStr(d.EsquemaPago, "Pago Unico/Mensual"), + Servicios: svcs, + EsDoble: d.EsDoble, + OpcionesMetadata: d.OpcionesMetadata, + PlanBucefaloNivel: pbNivel, + PlanBucefaloPrecio: pbPrecio, + IncluirBonos: d.IncluirBonos, + Bonos: bonos, + IncluirIVA: incluirIVA, + Observaciones: d.Observaciones, + ConfigBancaria: s.getConfigBancaria(r.Context()), + ColorPrimario: branding.ColorPrimario, + ColorSecundario: branding.ColorSecundario, + LogoBase64: branding.LogoBase64, + LogoMime: branding.LogoMime, + }) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error generando PDF de borrador") + return + } + w.Header().Set("Content-Type", "application/pdf") + w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Cotizacion_%s.pdf"`, domain.SanitizeFilename(firstNonEmptyStr(d.Numero, "BORRADOR")))) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(pdfBytes) +} + +func (s *Server) handleExportExcelByID(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cotizacion_excel"}); !ok { + return + } + id := chi.URLParam(r, "id") + full, _, err := s.loadCotizacionFull(r.Context(), id, true) + if err != nil { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + cfgMap := s.getAllConfigMap(r.Context()) + svcs := make([]excel.ServicioExcel, 0, len(full.ServiciosPDF)) + for _, sv := range full.ServiciosPDF { + svcs = append(svcs, excel.ServicioExcel{ + Nombre: sv.Nombre, Fase: sv.Fase, TipoPago: sv.TipoPago, Precio: sv.Precio, + TiempoEntrega: sv.TiempoEntrega, Entregables: sv.Entregables, + EsPersonalizado: sv.EsPersonalizado, Horas: sv.Horas, TarifaHora: sv.TarifaHora, + ModeloCobro: sv.ModeloCobro, MontoMinimo: sv.MontoMinimo, HorasIncluidas: sv.HorasIncluidas, Opcion: sv.Opcion, + }) + } + var pbPrecio *float64 + if full.PlanBucefaloNv != nil { + p := full.PlanBucefaloPr + pbPrecio = &p + } + xlsxBytes, err := excel.BuildCotizacionExcel(excel.CotizacionExcelData{ + RazonSocial: firstNonEmptyStr(cfgMap["razon_social"], "Uriel Jareth Consulting"), + DomicilioFiscal: cfgMap["domicilio_fiscal"], + Numero: full.Numero, + ClienteNombre: full.ClienteNombre, + ClienteEmpresa: derefStr(full.ClienteEmpresa), + AsesorNombre: full.AsesorName, + Fecha: full.Fecha, + Vigencia: full.Vigencia, + Moneda: full.Moneda, + TipoCambio: full.TipoCambio, + Proyecto: full.Proyecto, + EsquemaPago: full.EsquemaPago, + Servicios: svcs, + EsDoble: full.EsDoble, + OpcionesMetadata: full.OpcionesMetadata, + PlanBucefaloNivel: full.PlanBucefaloNv, + PlanBucefaloPrecio: pbPrecio, + ColorPrimario: firstNonEmptyStr(cfgMap["color_primario"], "#0400C4"), + ColorSecundario: firstNonEmptyStr(cfgMap["color_secundario"], "#0F172A"), + IncluirIVA: full.IncluirIVA, + Observaciones: full.Observaciones, + }) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error generando Excel") + return + } + w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") + w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Cotizacion_%s.xlsx"`, domain.SanitizeFilename(full.Numero))) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(xlsxBytes) +} + +func (s *Server) handleExportExcelDraft(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "cotizacion_excel"}); !ok { + return + } + var wrap draftExportBody + if err := decodeJSON(r, &wrap); err != nil { + writeError(w, http.StatusBadRequest, "Borrador invalido") + return + } + d := wrap.draftExportPayload + if wrap.Draft != nil { + d = *wrap.Draft + } + fecha := time.Now() + if t, err := parseFlexibleDate(d.Fecha); err == nil { + fecha = t + } + vigencia := domain.CalcularVigencia(fecha) + if t, err := parseFlexibleDate(d.Vigencia); err == nil { + vigencia = t + } + incluirIVA := true + if d.IncluirIVA != nil { + incluirIVA = *d.IncluirIVA + } + svcs := make([]excel.ServicioExcel, 0, len(d.Servicios)) + for _, sv := range d.Servicios { + if sv.Seleccionado != nil && !*sv.Seleccionado { + continue + } + svcs = append(svcs, excel.ServicioExcel{ + Nombre: firstNonEmptyStr(derefStr(sv.Nombre), "Servicio"), Fase: sv.Fase, + TipoPago: firstNonEmptyStr(sv.TipoPago, "unico"), Precio: sv.Precio, + TiempoEntrega: firstNonEmptyStr(sv.TiempoEntrega, "4 - 10 dias"), + Entregables: nonNilSlice(sv.Entregables), EsPersonalizado: sv.EsPersonalizado, + Horas: sv.Horas, TarifaHora: sv.TarifaHora, ModeloCobro: firstNonEmptyStr(sv.ModeloCobro, "fijo"), + MontoMinimo: sv.MontoMinimo, HorasIncluidas: sv.HorasIncluidas, Opcion: sv.Opcion, + }) + } + pbNivel, pbPrecioVal := resolveDraftBucefalo(d) + var pbPrecio *float64 + if pbNivel != nil { + pbPrecio = &pbPrecioVal + } + cfgMap := s.getAllConfigMap(r.Context()) + xlsxBytes, err := excel.BuildCotizacionExcel(excel.CotizacionExcelData{ + RazonSocial: firstNonEmptyStr(cfgMap["razon_social"], "Uriel Jareth Consulting"), + DomicilioFiscal: cfgMap["domicilio_fiscal"], + Numero: firstNonEmptyStr(d.Numero, "BORRADOR"), + ClienteNombre: firstNonEmptyStr(d.ClienteNombre, "Cliente"), + ClienteEmpresa: d.ClienteEmpresa, + AsesorNombre: firstNonEmptyStr(d.AsesorNombre, "Asesor"), + Fecha: fecha, + Vigencia: vigencia, + Moneda: firstNonEmptyStr(d.Moneda, "MXN"), + TipoCambio: firstNonEmptyStr(d.TipoCambio, "NA"), + Proyecto: firstNonEmptyStr(d.Proyecto, "MKT Digital"), + EsquemaPago: firstNonEmptyStr(d.EsquemaPago, "Pago Unico/Mensual"), + Servicios: svcs, + EsDoble: d.EsDoble, + OpcionesMetadata: d.OpcionesMetadata, + PlanBucefaloNivel: pbNivel, + PlanBucefaloPrecio: pbPrecio, + ColorPrimario: firstNonEmptyStr(cfgMap["color_primario"], "#0400C4"), + ColorSecundario: firstNonEmptyStr(cfgMap["color_secundario"], "#0F172A"), + IncluirIVA: incluirIVA, + Observaciones: d.Observaciones, + }) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error generando Excel de borrador") + return + } + w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") + w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Cotizacion_%s.xlsx"`, domain.SanitizeFilename(firstNonEmptyStr(d.Numero, "BORRADOR")))) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(xlsxBytes) +} + +func resolveDraftBucefalo(d draftExportPayload) (*string, float64) { + if d.PlanBucefalo != nil { + if d.PlanBucefalo.Seleccionado != nil && !*d.PlanBucefalo.Seleccionado { + return nil, 0 + } + nv := d.PlanBucefalo.Nivel + pr := domain.BucefaloPrecio(nv) + if d.PlanBucefalo.Precio != nil { + pr = *d.PlanBucefalo.Precio + } + return &nv, pr + } + if d.PlanBucefaloNivel != nil && *d.PlanBucefaloNivel != "" { + pr := domain.BucefaloPrecio(*d.PlanBucefaloNivel) + if d.PlanBucefaloPrecio != nil { + pr = *d.PlanBucefaloPrecio + } + return d.PlanBucefaloNivel, pr + } + return nil, 0 +} + +// ── Propuesta Consultiva IA ────────────────────────────────────────────────── + +func (s *Server) handlePropuestaIAGet(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "propuesta_ia"}); !ok { + return + } + cotID := chi.URLParam(r, "id") + var id, estado, modelo string + var contenidoIA, contenidoEditado, traza, avisos []byte + var transcripcion, aprobadaPor *string + var aprobadaAt *time.Time + var createdAt, updatedAt time.Time + + err := s.Pool.QueryRow(r.Context(), ` + SELECT "id", "estado", "contenidoIA", "contenidoEditado", "transcripcion", "traza", "avisos", + "modelo", "aprobadaPor", "aprobadaAt", "createdAt", "updatedAt" + FROM "PropuestaIA" + WHERE "cotizacionId" = $1 + ORDER BY "createdAt" DESC + LIMIT 1 + `, cotID).Scan(&id, &estado, &contenidoIA, &contenidoEditado, &transcripcion, &traza, &avisos, + &modelo, &aprobadaPor, &aprobadaAt, &createdAt, &updatedAt) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + writeJSON(w, http.StatusOK, map[string]any{"propuesta": nil}) + return + } + writeError(w, http.StatusInternalServerError, "Error cargando propuesta IA") + return + } + + var cIA, cEd, tr, av any + _ = json.Unmarshal(contenidoIA, &cIA) + if len(contenidoEditado) > 0 { + _ = json.Unmarshal(contenidoEditado, &cEd) + } + if len(traza) > 0 { + _ = json.Unmarshal(traza, &tr) + } + _ = json.Unmarshal(avisos, &av) + if av == nil { + av = []any{} + } + + writeJSON(w, http.StatusOK, map[string]any{ + "propuesta": map[string]any{ + "id": id, "cotizacionId": cotID, "estado": estado, + "contenidoIA": cIA, "contenidoEditado": cEd, "transcripcion": transcripcion, + "traza": tr, "avisos": av, "modelo": modelo, + "aprobadaPor": aprobadaPor, "aprobadaAt": aprobadaAt, + "createdAt": createdAt, "updatedAt": updatedAt, + }, + }) +} + +func (s *Server) handlePropuestaIACreate(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "propuesta_ia"}); !ok { + return + } + cotID := chi.URLParam(r, "id") + var body struct { + Transcripcion string `json:"transcripcion"` + NotasAdicionales string `json:"notasAdicionales"` + } + _ = decodeJSON(r, &body) + + res, err := propuesta.GenerarPropuesta(r.Context(), s.Cfg, s.Pool, propuesta.GenerarInput{ + CotizacionID: cotID, + Transcripcion: body.Transcripcion, + NotasAdicionales: body.NotasAdicionales, + }) + if err != nil { + status := http.StatusInternalServerError + if strings.Contains(err.Error(), "doble") || strings.Contains(err.Error(), "partidas") || strings.Contains(err.Error(), "MINIMAX_API_KEY") { + status = http.StatusBadRequest + } + writeError(w, status, err.Error()) + return + } + + cJSON, _ := json.Marshal(res.Contenido) + tJSON, _ := json.Marshal(res.Traza) + aJSON, _ := json.Marshal(res.Avisos) + + id := db.NewID() + _, err = s.Pool.Exec(r.Context(), ` + INSERT INTO "PropuestaIA" ("id", "cotizacionId", "estado", "contenidoIA", "transcripcion", "traza", "avisos", "modelo", "createdAt", "updatedAt") + VALUES ($1, $2, 'borrador', $3, $4, $5, $6, $7, NOW(), NOW()) + `, id, cotID, cJSON, nullableTrim(body.Transcripcion), tJSON, aJSON, res.Modelo) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error guardando propuesta IA") + return + } + + writeJSON(w, http.StatusCreated, map[string]any{ + "propuesta": map[string]any{ + "id": id, "cotizacionId": cotID, "estado": "borrador", + "contenidoIA": res.Contenido, "contenidoEditado": nil, + "transcripcion": nullableTrim(body.Transcripcion), + "traza": res.Traza, "avisos": res.Avisos, "modelo": res.Modelo, + }, + }) +} + +func (s *Server) handlePropuestaIAPatch(w http.ResponseWriter, r *http.Request) { + actor, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "propuesta_ia"}) + if !ok { + return + } + cotID := chi.URLParam(r, "id") + var body struct { + ContenidoEditado map[string]any `json:"contenidoEditado"` + Estado string `json:"estado"` + } + if err := decodeJSON(r, &body); err != nil { + writeError(w, http.StatusBadRequest, "JSON invalido") + return + } + + var propID string + var transcripcion *string + var contenidoIA []byte + err := s.Pool.QueryRow(r.Context(), ` + SELECT "id", "transcripcion", "contenidoIA" FROM "PropuestaIA" + WHERE "cotizacionId" = $1 ORDER BY "createdAt" DESC LIMIT 1 + `, cotID).Scan(&propID, &transcripcion, &contenidoIA) + if err != nil { + writeError(w, http.StatusNotFound, "Propuesta IA no encontrada") + return + } + + contenido := body.ContenidoEditado + if contenido == nil { + _ = json.Unmarshal(contenidoIA, &contenido) + } + + full, _, _ := s.loadCotizacionFull(r.Context(), cotID, false) + econ, err := propuesta.CargarEconomiaCotizacion(r.Context(), s.Pool, cotID) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error cargando economia de cotizacion") + return + } + fuentesCliente := derefStr(transcripcion) + if full != nil && full.Observaciones != nil { + fuentesCliente += "\n" + *full.Observaciones + } + notasInternas := "" + if full != nil && full.ObservacionesInternas != nil { + notasInternas = *full.ObservacionesInternas + } + avisos := propuesta.ValidarPropuesta(contenido, econ, fuentesCliente, notasInternas) + + cEdJSON, _ := json.Marshal(contenido) + avJSON, _ := json.Marshal(avisos) + estado := "borrador" + var aprobadaPor *string + var aprobadaAt *time.Time + if body.Estado == "aprobada" { + if propuesta.HayBloqueantes(avisos) { + writeJSON(w, http.StatusConflict, map[string]any{"error": "Hay avisos bloqueantes pendientes por resolver", "avisos": avisos}) + return + } + estado = "aprobada" + ap := actor.Email + aprobadaPor = &ap + now := time.Now() + aprobadaAt = &now + } + + _, err = s.Pool.Exec(r.Context(), ` + UPDATE "PropuestaIA" + SET "contenidoEditado" = $1, "avisos" = $2, "estado" = $3, "aprobadaPor" = COALESCE($4, "aprobadaPor"), "aprobadaAt" = COALESCE($5, "aprobadaAt"), "updatedAt" = NOW() + WHERE "id" = $6 + `, cEdJSON, avJSON, estado, aprobadaPor, aprobadaAt, propID) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error actualizando propuesta IA") + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "ok": true, "id": propID, "estado": estado, "contenidoEditado": contenido, "avisos": avisos, + }) +} + +func (s *Server) handlePropuestaIAPDF(w http.ResponseWriter, r *http.Request) { + if _, ok := s.Auth.RequireActor(w, r, auth.RequireOptions{StaffOnly: true, RecursoTipo: "propuesta_ia"}); !ok { + return + } + cotID := chi.URLParam(r, "id") + anexo := r.URL.Query().Get("anexo") == "1" + + full, _, err := s.loadCotizacionFull(r.Context(), cotID, false) + if err != nil { + writeError(w, http.StatusNotFound, "Cotizacion no encontrada") + return + } + + var contenidoIA, contenidoEditado, avisosRaw []byte + err = s.Pool.QueryRow(r.Context(), ` + SELECT "contenidoIA", "contenidoEditado", "avisos" + FROM "PropuestaIA" WHERE "cotizacionId" = $1 ORDER BY "createdAt" DESC LIMIT 1 + `, cotID).Scan(&contenidoIA, &contenidoEditado, &avisosRaw) + if err != nil { + writeError(w, http.StatusNotFound, "No existe una propuesta IA generada para esta cotizacion") + return + } + + var avisos []propuesta.Aviso + _ = json.Unmarshal(avisosRaw, &avisos) + if !anexo && propuesta.HayBloqueantes(avisos) { + writeJSON(w, http.StatusConflict, map[string]any{"error": "Resuelve los avisos bloqueantes antes de exportar el PDF para el cliente", "avisos": avisos}) + return + } + + var contenido map[string]any + if len(contenidoEditado) > 0 { + _ = json.Unmarshal(contenidoEditado, &contenido) + } else { + _ = json.Unmarshal(contenidoIA, &contenido) + } + + econ, err := propuesta.CargarEconomiaCotizacion(r.Context(), s.Pool, cotID) + if err != nil { + writeError(w, http.StatusInternalServerError, "Error cargando economia") + return + } + econBytes, _ := json.Marshal(econ) + var econMap map[string]any + _ = json.Unmarshal(econBytes, &econMap) + + branding := s.getConfigBranding(r.Context()) + in := pdf.PropuestaPDFInput{ + CotizacionNumero: full.Numero, + ClienteNombre: full.ClienteNombre, + ClienteEmpresa: derefStr(full.ClienteEmpresa), + Proyecto: full.Proyecto, + Moneda: full.Moneda, + Fecha: full.Fecha, + Contenido: contenido, + Economia: econMap, + ColorPrimario: branding.ColorPrimario, + ColorSecundario: branding.ColorSecundario, + LogoBase64: branding.LogoBase64, + LogoMime: branding.LogoMime, + } + + var pdfBytes []byte + var filename string + if anexo { + pdfBytes, err = pdf.GenerarAnexoInternoPDF(in) + filename = fmt.Sprintf("AnexoInterno_%s.pdf", domain.SanitizeFilename(full.Numero)) + } else { + pdfBytes, err = pdf.GenerarPropuestaPDF(in) + filename = fmt.Sprintf("PropuestaConsultiva_%s.pdf", domain.SanitizeFilename(full.Numero)) + } + if err != nil { + writeError(w, http.StatusInternalServerError, "Error generando PDF de propuesta IA: "+err.Error()) + return + } + + w.Header().Set("Content-Type", "application/pdf") + w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename)) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(pdfBytes) +} diff --git a/internal/httpapi/httpapi_test.go b/internal/httpapi/httpapi_test.go new file mode 100644 index 0000000..0790143 --- /dev/null +++ b/internal/httpapi/httpapi_test.go @@ -0,0 +1,266 @@ +package httpapi + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "cotizador/internal/auth" + "cotizador/internal/config" +) + +func newTestServer(t *testing.T) (*Server, http.Handler) { + t.Helper() + cfg := &config.Config{ + Port: "3000", + AppURL: "https://cotizador.urieljareth.org", + JWTSecret: "test-secret-key-for-httpapi-tests-32b", + } + authSvc := auth.NewService(cfg.JWTSecret, false, nil) + srv := NewServer(cfg, nil, authSvc, nil, nil) + return srv, srv.Router() +} + +func makeCookie(t *testing.T, authSvc *auth.Service, sess auth.SessionPayload) *http.Cookie { + t.Helper() + tok, err := authSvc.SignSession(sess) + if err != nil { + t.Fatalf("SignSession: %v", err) + } + return &http.Cookie{Name: auth.SessionCookieName, Value: tok} +} + +func TestOpenAPIAndSPARouting(t *testing.T) { + _, router := newTestServer(t) + + // 1. OpenAPI 3.1 + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/openapi.json", nil) + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("expected 200 for /api/openapi.json, got %d", rec.Code) + } + var spec map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &spec); err != nil { + t.Fatalf("invalid openapi json: %v", err) + } + if spec["openapi"] != "3.1.0" { + t.Fatalf("expected openapi 3.1.0, got %v", spec["openapi"]) + } + if strings.Contains(rec.Body.String(), "cotizaciones:approve") { + t.Fatal("iron-clad rule violation: openapi mentions cotizaciones:approve") + } + + // 2. Unknown /api/* route returns 404 JSON, NOT SPA HTML + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/api/does-not-exist", nil) + router.ServeHTTP(rec, req) + if rec.Code != http.StatusNotFound { + t.Fatalf("expected 404 for unknown /api route, got %d", rec.Code) + } + if !strings.Contains(rec.Header().Get("Content-Type"), "application/json") { + t.Fatalf("expected JSON content-type for unknown /api route, got %q", rec.Header().Get("Content-Type")) + } + + // 3. SPA routes serve HTML + for _, p := range []string{"/", "/login", "/cotizaciones", "/cliente/pagos"} { + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, p, nil) + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("expected 200 for SPA path %s, got %d", p, rec.Code) + } + if !strings.Contains(strings.ToLower(rec.Body.String()), " %s %s: expected 403, got %d", tc.method, tc.path, rec.Code) + } + } + + // Staff (admin/asesor) cannot access /api/cliente/* + clientePaths := []struct{ method, path string }{ + {http.MethodGet, "/api/cliente/resumen"}, + {http.MethodGet, "/api/cliente/cotizaciones"}, + {http.MethodGet, "/api/cliente/pagos"}, + {http.MethodGet, "/api/cliente/push/config"}, + {http.MethodPost, "/api/cliente/push/suscribir"}, + {http.MethodDelete, "/api/cliente/push/suscribir"}, + } + for _, tc := range clientePaths { + for _, ck := range []*http.Cookie{adminCookie, asesorCookie} { + rec := httptest.NewRecorder() + req := httptest.NewRequest(tc.method, tc.path, nil) + req.AddCookie(ck) + router.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Errorf("staff -> %s %s: expected 403, got %d", tc.method, tc.path, rec.Code) + } + } + } + + // Asesor cannot access strictly admin-only routes (including aprobar!) + adminOnly := []struct{ method, path string }{ + {http.MethodPost, "/api/cotizaciones/q1/aprobar"}, + {http.MethodGet, "/api/agent-keys"}, + {http.MethodPost, "/api/agent-keys"}, + {http.MethodPost, "/api/agent-keys/k1/rotate"}, + {http.MethodPost, "/api/agent-keys/k1/revoke"}, + {http.MethodGet, "/api/audit-logs"}, + {http.MethodGet, "/api/webhooks"}, + {http.MethodPost, "/api/webhooks"}, + {http.MethodDelete, "/api/webhooks/w1"}, + {http.MethodGet, "/api/webhooks/deliveries"}, + } + for _, tc := range adminOnly { + rec := httptest.NewRecorder() + req := httptest.NewRequest(tc.method, tc.path, nil) + req.AddCookie(asesorCookie) + router.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Errorf("asesor -> %s %s: expected 403, got %d", tc.method, tc.path, rec.Code) + } + } + + // /api/auth/me works for both admin and cliente without DB + for _, tc := range []struct { + name string + ck *http.Cookie + role string + }{ + {"admin", adminCookie, "admin"}, + {"cliente", clienteCookie, "cliente"}, + } { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/auth/me", nil) + req.AddCookie(tc.ck) + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("/api/auth/me (%s): expected 200, got %d", tc.name, rec.Code) + } + var out map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &out) + u, _ := out["user"].(map[string]any) + if u["role"] != tc.role { + t.Fatalf("/api/auth/me (%s): expected role %s, got %v", tc.name, tc.role, u["role"]) + } + } + + // /api/auth/logout clears session cookie + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/auth/logout", nil) + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("/api/auth/logout: expected 200, got %d", rec.Code) + } + var cleared bool + for _, c := range rec.Result().Cookies() { + if c.Name == auth.SessionCookieName && c.MaxAge < 0 { + cleared = true + } + } + if !cleared { + t.Fatal("expected logout to clear cotizador-session cookie") + } +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go new file mode 100644 index 0000000..eeff23e --- /dev/null +++ b/internal/httpapi/server.go @@ -0,0 +1,343 @@ +package httpapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "regexp" + "strconv" + "strings" + "time" + + "cotizador/internal/auth" + "cotizador/internal/config" + "cotizador/internal/domain" + "cotizador/internal/notify" + "cotizador/internal/spa" + "cotizador/internal/webhooks" + + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + "github.com/jackc/pgx/v5/pgxpool" +) + +type Server struct { + Cfg *config.Config + Pool *pgxpool.Pool + Auth *auth.Service + Webhooks *webhooks.Dispatcher + Notify *notify.Service +} + +func NewServer(cfg *config.Config, pool *pgxpool.Pool, authSvc *auth.Service, wh *webhooks.Dispatcher, notif *notify.Service) *Server { + return &Server{ + Cfg: cfg, + Pool: pool, + Auth: authSvc, + Webhooks: wh, + Notify: notif, + } +} + +func (s *Server) Router() http.Handler { + r := chi.NewRouter() + r.Use(middleware.RequestID) + r.Use(middleware.RealIP) + r.Use(middleware.Recoverer) + + // API routes + r.Route("/api", func(r chi.Router) { + // Public + r.Get("/health", s.handleHealth) + r.Get("/openapi.json", s.handleOpenAPI) + r.Post("/auth/login", s.handleLogin) + r.Post("/auth/logout", s.handleLogout) + r.Get("/auth/me", s.handleMe) + r.Get("/aprobar/{token}", s.handleAprobarTokenGet) + r.Post("/aprobar/{token}", s.handleAprobarTokenPost) + + // SPA helpers (staff) + r.Get("/dashboard", s.handleDashboard) + r.Get("/asesores", s.handleAsesores) + + // Admin control plane + r.Get("/agent-keys", s.handleAgentKeysList) + r.Post("/agent-keys", s.handleAgentKeysCreate) + r.Post("/agent-keys/{id}/rotate", s.handleAgentKeysRotate) + r.Post("/agent-keys/{id}/revoke", s.handleAgentKeysRevoke) + r.Get("/audit-logs", s.handleAuditLogs) + r.Get("/webhooks", s.handleWebhooksList) + r.Post("/webhooks", s.handleWebhooksCreate) + r.Delete("/webhooks/{id}", s.handleWebhooksDelete) + r.Get("/webhooks/deliveries", s.handleWebhooksDeliveries) + + // Configuracion + r.Get("/configuracion", s.handleConfiguracionGet) + r.Put("/configuracion", s.handleConfiguracionPut) + + // Catalogo, Categorias, Paquetes + r.Get("/catalogo", s.handleCatalogoList) + r.Post("/catalogo", s.handleCatalogoCreate) + r.Get("/catalogo/{id}", s.handleCatalogoGet) + r.Patch("/catalogo/{id}", s.handleCatalogoPatch) + r.Put("/catalogo/{id}", s.handleCatalogoPatch) + r.Delete("/catalogo/{id}", s.handleCatalogoDelete) + + r.Get("/categorias", s.handleCategoriasList) + r.Post("/categorias", s.handleCategoriasCreate) + r.Put("/categorias/{id}", s.handleCategoriasUpdate) + r.Delete("/categorias/{id}", s.handleCategoriasDelete) + + r.Get("/paquetes", s.handlePaquetesList) + r.Post("/paquetes", s.handlePaquetesCreate) + r.Get("/paquetes/{id}", s.handlePaquetesGet) + r.Put("/paquetes/{id}", s.handlePaquetesUpdate) + r.Delete("/paquetes/{id}", s.handlePaquetesDelete) + r.Post("/paquetes/{id}/manage", s.handlePaquetesManage) + + // Clientes + r.Get("/clientes", s.handleClientesList) + r.Post("/clientes", s.handleClientesCreate) + r.Patch("/clientes/{id}", s.handleClientesUpdate) + r.Post("/clientes/{id}/acceso", s.handleClienteAccesoCreate) + r.Delete("/clientes/{id}/acceso", s.handleClienteAccesoDelete) + r.Post("/clientes/{id}/archivar", s.handleClienteArchivar) + + // Cotizaciones + r.Get("/cotizaciones", s.handleCotizacionesList) + r.Post("/cotizaciones", s.handleCotizacionesCreate) + r.Get("/cotizaciones/{id}", s.handleCotizacionesGet) + r.Put("/cotizaciones/{id}", s.handleCotizacionesUpdate) + r.Delete("/cotizaciones/{id}", s.handleCotizacionesDelete) + r.Post("/cotizaciones/{id}/solicitar-aprobacion", s.handleCotizacionSolicitarAprobacion) + r.Post("/cotizaciones/{id}/aprobar", s.handleCotizacionAprobar) + r.Post("/cotizaciones/{id}/enviar", s.handleCotizacionEnviar) + r.Patch("/cotizaciones/{id}/estado", s.handleCotizacionEstado) + r.Patch("/cotizaciones/{id}/precio", s.handleCotizacionPrecio) + + // Registro de horas + r.Get("/cotizaciones/{id}/horas", s.handleHorasList) + r.Post("/cotizaciones/{id}/horas", s.handleHorasCreate) + r.Put("/cotizaciones/{id}/horas/{registroId}", s.handleHorasUpdate) + r.Patch("/cotizaciones/{id}/horas/{registroId}", s.handleHorasEstadoPago) + r.Delete("/cotizaciones/{id}/horas/{registroId}", s.handleHorasDelete) + r.Post("/cotizaciones/{id}/nota-horas", s.handleNotaHorasPDF) + + // Cobros recurrentes & comprobantes + r.Get("/cobros/resumen", s.handleCobrosResumen) + r.Get("/cobros/programas", s.handleProgramasList) + r.Post("/cobros/programas", s.handleProgramasCreate) + r.Patch("/cobros/programas/{id}", s.handleProgramasUpdate) + r.Post("/cobros/generar", s.handleCobrosGenerar) + r.Get("/cobros/pagos", s.handlePagosList) + r.Post("/cobros/pagos/{id}/aprobar", s.handlePagoAprobar) + r.Post("/cobros/pagos/{id}/rechazar", s.handlePagoRechazar) + r.Post("/cobros/pagos/{id}/registrar", s.handlePagoRegistrar) + r.Post("/cobros/pagos/{id}/anular", s.handlePagoAnular) + r.Post("/cobros/pagos/{id}/reabrir", s.handlePagoReabrir) + r.Post("/cobros/recordatorios", s.handleCobrosRecordatorios) + r.Get("/comprobantes/{pagoId}", s.handleComprobanteGet) + + // Panel de cliente + r.Get("/cliente/resumen", s.handleClienteResumen) + r.Get("/cliente/cotizaciones", s.handleClienteCotizacionesList) + r.Get("/cliente/cotizaciones/{id}", s.handleClienteCotizacionGet) + r.Get("/cliente/pagos", s.handleClientePagosList) + r.Post("/cliente/pagos/{id}/comprobante", s.handleClienteComprobanteUpload) + r.Get("/cliente/push/config", s.handleClientePushConfig) + r.Post("/cliente/push/suscribir", s.handleClientePushSubscribe) + r.Delete("/cliente/push/suscribir", s.handleClientePushUnsubscribe) + + // Exports, Imports & Propuesta IA + r.Get("/export/pdf/{id}", s.handleExportPDFByID) + r.Post("/export/pdf", s.handleExportPDFDraft) + r.Get("/export/excel/{id}", s.handleExportExcelByID) + r.Post("/export/excel", s.handleExportExcelDraft) + r.Get("/export/catalogo", s.handleExportCatalogoCSV) + r.Get("/export/catalogo/plantilla", s.handleExportCatalogoPlantilla) + r.Post("/import/catalogo", s.handleImportCatalogoCSV) + + r.Get("/propuesta-ia/{id}", s.handlePropuestaIAGet) + r.Post("/propuesta-ia/{id}", s.handlePropuestaIACreate) + r.Patch("/propuesta-ia/{id}", s.handlePropuestaIAPatch) + r.Get("/propuesta-ia/{id}/pdf", s.handlePropuestaIAPDF) + + // Explicit JSON 404 for unknown /api/* routes + r.NotFound(func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusNotFound, map[string]any{"error": "Ruta API no encontrada"}) + }) + }) + + // Embedded Vite SPA for all non-API routes (including /sw.js, /favicon.ico, /login, /cliente/*, /aprobar/*) + r.NotFound(spa.Handler().ServeHTTP) + return r +} + +func writeJSON(w http.ResponseWriter, status int, payload any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(payload) +} + +func writeError(w http.ResponseWriter, status int, msg string) { + writeJSON(w, status, map[string]any{"error": msg}) +} + +type ValidationDetail struct { + Campo string `json:"campo"` + Mensaje string `json:"mensaje"` +} + +func writeValidationError(w http.ResponseWriter, detalles []ValidationDetail) { + writeJSON(w, http.StatusBadRequest, map[string]any{ + "error": "Datos invalidos", + "detalles": detalles, + }) +} + +func decodeJSON(r *http.Request, dst any) error { + dec := json.NewDecoder(r.Body) + return dec.Decode(dst) +} + +func parseIntQuery(r *http.Request, name string, def, minV, maxV int) int { + raw := strings.TrimSpace(r.URL.Query().Get(name)) + if raw == "" { + return def + } + v, err := strconv.Atoi(raw) + if err != nil { + return def + } + if v < minV { + return minV + } + if maxV > 0 && v > maxV { + return maxV + } + return v +} + +type BrandingConfig struct { + ColorPrimario string + ColorSecundario string + LogoBase64 string + LogoMime string +} + +func (s *Server) getAllConfigMap(ctx context.Context) map[string]string { + m := map[string]string{} + rows, err := s.Pool.Query(ctx, `SELECT "clave", "valor" FROM "Configuracion"`) + if err != nil { + return m + } + defer rows.Close() + for rows.Next() { + var k, v string + if rows.Scan(&k, &v) == nil { + m[k] = v + } + } + return m +} + +func (s *Server) getConfigBranding(ctx context.Context) BrandingConfig { + m := s.getAllConfigMap(ctx) + b := BrandingConfig{ + ColorPrimario: firstNonEmptyStr(m["color_primario"], "#0400C4"), + ColorSecundario: firstNonEmptyStr(m["color_secundario"], "#0F172A"), + } + if rawLogo := strings.TrimSpace(m["logo_base64"]); rawLogo != "" { + if strings.HasPrefix(rawLogo, "data:") { + // data:image/png;base64,XXXX + if idx := strings.Index(rawLogo, ","); idx > 0 { + meta := rawLogo[5:idx] + b.LogoMime = strings.Split(meta, ";")[0] + b.LogoBase64 = rawLogo[idx+1:] + } + } else if idx := strings.Index(rawLogo, ":"); idx > 0 && strings.Contains(rawLogo[:idx], "/") { + // mime:base64 + b.LogoMime = rawLogo[:idx] + b.LogoBase64 = rawLogo[idx+1:] + } else { + b.LogoMime = "image/png" + b.LogoBase64 = rawLogo + } + } + return b +} + +func (s *Server) getConfigBancaria(ctx context.Context) map[string]string { + m := s.getAllConfigMap(ctx) + keys := []string{ + "razon_social", "rfc", "domicilio_fiscal", + "banco_nacional", "cuenta_nacional", "clabe_interbancaria", "clabe_nacional", + "banco_internacional", "cuenta_internacional", "cuenta_internacional_swift", "swift", "routing_number", + "email_facturacion", "telefono_contacto", + } + out := map[string]string{} + for _, k := range keys { + if v, ok := m[k]; ok { + out[k] = v + } + } + return out +} + +var seqDigitsRe = regexp.MustCompile(`(\d{3})$`) + +func (s *Server) nextCotizacionSeq(ctx context.Context) int { + var latest string + err := s.Pool.QueryRow(ctx, `SELECT "numero" FROM "Cotizacion" ORDER BY "createdAt" DESC LIMIT 1`).Scan(&latest) + if err != nil { + return 1 + } + if m := seqDigitsRe.FindStringSubmatch(latest); len(m) == 2 { + if n, err := strconv.Atoi(m[1]); err == nil && n > 0 { + return n + 1 + } + } + return 1 +} + +func asesorInitials(name string) string { + parts := strings.Fields(strings.TrimSpace(name)) + if len(parts) == 0 { + return "UJ" + } + if len(parts) == 1 { + runes := []rune(strings.ToUpper(parts[0])) + if len(runes) >= 2 { + return string(runes[:2]) + } + return string(runes) + "X" + } + r1 := []rune(strings.ToUpper(parts[0]))[0] + r2 := []rune(strings.ToUpper(parts[1]))[0] + return string([]rune{r1, r2}) +} + +func (s *Server) siguienteNumeroCotizacion(ctx context.Context, asesorName string) string { + ini := asesorInitials(asesorName) + seq := s.nextCotizacionSeq(ctx) + now := time.Now() + for tries := 0; tries < 50; tries++ { + candidate := domain.GenerarNumeroCotizacion(ini, seq+tries, now) + var exists bool + _ = s.Pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM "Cotizacion" WHERE "numero" = $1)`, candidate).Scan(&exists) + if !exists { + return candidate + } + } + return fmt.Sprintf("UJ%02d%02d%s%03d", now.Year()%100, int(now.Month()), ini, seq+50) +} + +func firstNonEmptyStr(vals ...string) string { + for _, v := range vals { + if strings.TrimSpace(v) != "" { + return strings.TrimSpace(v) + } + } + return "" +} diff --git a/internal/idempotency/idempotency.go b/internal/idempotency/idempotency.go new file mode 100644 index 0000000..f40facb --- /dev/null +++ b/internal/idempotency/idempotency.go @@ -0,0 +1,108 @@ +package idempotency + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "time" + + "cotizador/internal/auth" + "cotizador/internal/db" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +const TTL = 24 * time.Hour + +type HandlerFunc func(rawBody []byte) (statusCode int, responseBody any) + +// Execute wraps a mutating endpoint with Idempotency-Key support (24h TTL, SHA-256 body hash). +func Execute(ctx context.Context, pool *pgxpool.Pool, w http.ResponseWriter, r *http.Request, actor *auth.Actor, fn HandlerFunc) { + rawBody, err := io.ReadAll(r.Body) + if err != nil { + writeJSON(w, http.StatusBadRequest, map[string]any{"error": "No se pudo leer el cuerpo de la solicitud"}) + return + } + r.Body = io.NopCloser(bytes.NewReader(rawBody)) + + idemHeader := strings.TrimSpace(r.Header.Get("Idempotency-Key")) + if idemHeader == "" { + status, body := fn(rawBody) + writeJSON(w, status, body) + return + } + + actorKey := "user:" + actor.UserID + if actor.IsAgent() { + actorKey = "agent:" + actor.KeyID + } + composedKey := fmt.Sprintf("%s:%s:%s:%s", actorKey, r.Method, r.URL.Path, idemHeader) + sum := sha256.Sum256(rawBody) + reqHash := hex.EncodeToString(sum[:]) + + var existingHash string + var existingStatus int + var existingBody json.RawMessage + var expiraAt time.Time + err = pool.QueryRow(ctx, ` + SELECT "requestHash", "statusCode", "responseBody", "expiraAt" + FROM "IdempotencyKey" + WHERE "key" = $1 + `, composedKey).Scan(&existingHash, &existingStatus, &existingBody, &expiraAt) + + if err == nil { + if time.Now().After(expiraAt) { + _, _ = pool.Exec(ctx, `DELETE FROM "IdempotencyKey" WHERE "key" = $1`, composedKey) + } else { + if existingHash != reqHash { + writeJSON(w, http.StatusConflict, map[string]any{ + "error": "Idempotency-Key ya fue usada con un cuerpo de solicitud distinto", + }) + return + } + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("X-Idempotency-Replayed", "true") + w.WriteHeader(existingStatus) + _, _ = w.Write(existingBody) + return + } + } else if !errors.Is(err, pgx.ErrNoRows) { + // Fall through gracefully on lookup error + } + + status, body := fn(rawBody) + bodyBytes, err := json.Marshal(body) + if err != nil { + bodyBytes = []byte(`{}`) + } + + if status < 500 { + _, _ = pool.Exec(ctx, ` + INSERT INTO "IdempotencyKey" ("id", "key", "method", "path", "requestHash", "statusCode", "responseBody", "expiraAt") + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT ("key") DO UPDATE SET + "requestHash" = EXCLUDED."requestHash", + "statusCode" = EXCLUDED."statusCode", + "responseBody" = EXCLUDED."responseBody", + "expiraAt" = EXCLUDED."expiraAt" + `, db.NewID(), composedKey, r.Method, r.URL.Path, reqHash, status, bodyBytes, time.Now().Add(TTL)) + } + + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _, _ = w.Write(bodyBytes) +} + +func writeJSON(w http.ResponseWriter, status int, payload any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(payload) +} diff --git a/internal/notify/notify.go b/internal/notify/notify.go new file mode 100644 index 0000000..d4dec62 --- /dev/null +++ b/internal/notify/notify.go @@ -0,0 +1,694 @@ +package notify + +import ( + "bytes" + "context" + "crypto/tls" + "encoding/base64" + "encoding/json" + "fmt" + "html" + "log" + "mime/quotedprintable" + "net" + "net/smtp" + "strings" + "time" + + "cotizador/internal/config" + "cotizador/internal/domain" + "cotizador/internal/webhooks" + + webpush "github.com/SherClockHolmes/webpush-go" + "github.com/jackc/pgx/v5/pgxpool" +) + +type Attachment struct { + Filename string + ContentType string + Content []byte +} + +type MailMessage struct { + To string + Subject string + Text string + HTML string + Attachments []Attachment +} + +type Service struct { + cfg *config.Config + pool *pgxpool.Pool + webhooks *webhooks.Dispatcher +} + +func NewService(cfg *config.Config, pool *pgxpool.Pool, wh *webhooks.Dispatcher) *Service { + return &Service{cfg: cfg, pool: pool, webhooks: wh} +} + +func (s *Service) SMTPConfigured() bool { + return s != nil && s.cfg != nil && s.cfg.SMTPHost != "" && s.cfg.SMTPFrom != "" +} + +func (s *Service) VAPIDConfigured() bool { + return s != nil && s.cfg != nil && s.cfg.VAPIDPublicKey != "" && s.cfg.VAPIDPrivateKey != "" +} + +func (s *Service) EnviarCorreo(msg MailMessage) bool { + if !s.SMTPConfigured() { + log.Printf("[email] SMTP no configurado; omitiendo correo a %s (%s)", msg.To, msg.Subject) + return false + } + to := strings.TrimSpace(msg.To) + if to == "" { + return false + } + + raw := buildMIMEMessage(s.cfg.SMTPFromName, s.cfg.SMTPFrom, to, msg) + addr := fmt.Sprintf("%s:%d", s.cfg.SMTPHost, s.cfg.SMTPPort) + + var err error + if s.cfg.SMTPPort == 465 { + err = sendSMTPImplicitTLS(addr, s.cfg.SMTPHost, s.cfg.SMTPUser, s.cfg.SMTPPass, s.cfg.SMTPFrom, to, raw) + } else { + err = sendSMTPStartTLS(addr, s.cfg.SMTPHost, s.cfg.SMTPUser, s.cfg.SMTPPass, s.cfg.SMTPFrom, to, raw) + } + if err != nil { + log.Printf("[email] error enviando correo a %s: %v", to, err) + return false + } + return true +} + +func sendSMTPImplicitTLS(addr, host, user, pass, from, to string, raw []byte) error { + dialer := &net.Dialer{Timeout: 10 * time.Second} + conn, err := tls.DialWithDialer(dialer, "tcp", addr, &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}) + if err != nil { + return err + } + client, err := smtp.NewClient(conn, host) + if err != nil { + _ = conn.Close() + return err + } + defer client.Close() + if user != "" { + if err := client.Auth(smtp.PlainAuth("", user, pass, host)); err != nil { + return err + } + } + if err := client.Mail(from); err != nil { + return err + } + if err := client.Rcpt(to); err != nil { + return err + } + w, err := client.Data() + if err != nil { + return err + } + if _, err := w.Write(raw); err != nil { + return err + } + if err := w.Close(); err != nil { + return err + } + return client.Quit() +} + +func sendSMTPStartTLS(addr, host, user, pass, from, to string, raw []byte) error { + conn, err := net.DialTimeout("tcp", addr, 10*time.Second) + if err != nil { + return err + } + client, err := smtp.NewClient(conn, host) + if err != nil { + _ = conn.Close() + return err + } + defer client.Close() + if ok, _ := client.Extension("STARTTLS"); ok { + if err := client.StartTLS(&tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}); err != nil { + return err + } + } + if user != "" { + if err := client.Auth(smtp.PlainAuth("", user, pass, host)); err != nil { + return err + } + } + if err := client.Mail(from); err != nil { + return err + } + if err := client.Rcpt(to); err != nil { + return err + } + w, err := client.Data() + if err != nil { + return err + } + if _, err := w.Write(raw); err != nil { + return err + } + if err := w.Close(); err != nil { + return err + } + return client.Quit() +} + +func buildMIMEMessage(fromName, fromAddr, to string, msg MailMessage) []byte { + var buf bytes.Buffer + fromHeader := fromAddr + if fromName != "" { + fromHeader = fmt.Sprintf("=?UTF-8?B?%s?= <%s>", base64.StdEncoding.EncodeToString([]byte(fromName)), fromAddr) + } + subjHeader := fmt.Sprintf("=?UTF-8?B?%s?=", base64.StdEncoding.EncodeToString([]byte(msg.Subject))) + + fmt.Fprintf(&buf, "From: %s\r\n", fromHeader) + fmt.Fprintf(&buf, "To: %s\r\n", to) + fmt.Fprintf(&buf, "Subject: %s\r\n", subjHeader) + fmt.Fprintf(&buf, "Date: %s\r\n", time.Now().Format(time.RFC1123Z)) + fmt.Fprintf(&buf, "MIME-Version: 1.0\r\n") + + mixedBoundary := fmt.Sprintf("ujc-mixed-%d", time.Now().UnixNano()) + altBoundary := fmt.Sprintf("ujc-alt-%d", time.Now().UnixNano()) + + if len(msg.Attachments) > 0 { + fmt.Fprintf(&buf, "Content-Type: multipart/mixed; boundary=%q\r\n\r\n", mixedBoundary) + fmt.Fprintf(&buf, "--%s\r\n", mixedBoundary) + } + + fmt.Fprintf(&buf, "Content-Type: multipart/alternative; boundary=%q\r\n\r\n", altBoundary) + + textBody := msg.Text + if textBody == "" { + textBody = "Consulta este mensaje en un cliente de correo compatible con HTML." + } + fmt.Fprintf(&buf, "--%s\r\n", altBoundary) + fmt.Fprintf(&buf, "Content-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n") + writeQP(&buf, textBody) + fmt.Fprintf(&buf, "\r\n") + + if msg.HTML != "" { + fmt.Fprintf(&buf, "--%s\r\n", altBoundary) + fmt.Fprintf(&buf, "Content-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n") + writeQP(&buf, msg.HTML) + fmt.Fprintf(&buf, "\r\n") + } + fmt.Fprintf(&buf, "--%s--\r\n", altBoundary) + + for _, att := range msg.Attachments { + fmt.Fprintf(&buf, "\r\n--%s\r\n", mixedBoundary) + ct := att.ContentType + if ct == "" { + ct = "application/octet-stream" + } + fmt.Fprintf(&buf, "Content-Type: %s; name=%q\r\n", ct, att.Filename) + fmt.Fprintf(&buf, "Content-Disposition: attachment; filename=%q\r\n", att.Filename) + fmt.Fprintf(&buf, "Content-Transfer-Encoding: base64\r\n\r\n") + enc := base64.StdEncoding.EncodeToString(att.Content) + for i := 0; i < len(enc); i += 76 { + end := i + 76 + if end > len(enc) { + end = len(enc) + } + buf.WriteString(enc[i:end]) + buf.WriteString("\r\n") + } + } + if len(msg.Attachments) > 0 { + fmt.Fprintf(&buf, "--%s--\r\n", mixedBoundary) + } + return buf.Bytes() +} + +func writeQP(buf *bytes.Buffer, s string) { + qw := quotedprintable.NewWriter(buf) + _, _ = qw.Write([]byte(s)) + _ = qw.Close() +} + +// EnviarPush sends a Web Push notification to all subscriptions of userID. Returns number delivered. +func (s *Service) EnviarPush(ctx context.Context, userID, titulo, cuerpo, urlPath string) int { + if !s.VAPIDConfigured() || s.pool == nil || userID == "" { + return 0 + } + rows, err := s.pool.Query(ctx, ` + SELECT "id", "endpoint", "p256dh", "auth" + FROM "SuscripcionPush" + WHERE "userId" = $1 + `, userID) + if err != nil { + return 0 + } + defer rows.Close() + + payload, _ := json.Marshal(map[string]string{ + "titulo": titulo, + "cuerpo": cuerpo, + "url": urlPath, + }) + + sent := 0 + var expiredIDs []string + for rows.Next() { + var id, endpoint, p256dh, authKey string + if err := rows.Scan(&id, &endpoint, &p256dh, &authKey); err != nil { + continue + } + sub := &webpush.Subscription{ + Endpoint: endpoint, + Keys: webpush.Keys{ + P256dh: p256dh, + Auth: authKey, + }, + } + resp, err := webpush.SendNotification(payload, sub, &webpush.Options{ + Subscriber: strings.TrimPrefix(s.cfg.VAPIDSubject, "mailto:"), + VAPIDPublicKey: s.cfg.VAPIDPublicKey, + VAPIDPrivateKey: s.cfg.VAPIDPrivateKey, + TTL: 86400, + }) + if err != nil { + log.Printf("[push] error enviando a %s: %v", id, err) + continue + } + _ = resp.Body.Close() + if resp.StatusCode == 404 || resp.StatusCode == 410 { + expiredIDs = append(expiredIDs, id) + } else if resp.StatusCode >= 200 && resp.StatusCode < 300 { + sent++ + } + } + + for _, id := range expiredIDs { + _, _ = s.pool.Exec(ctx, `DELETE FROM "SuscripcionPush" WHERE "id" = $1`, id) + } + return sent +} + +func (s *Service) GetAdminEmail(ctx context.Context) string { + if s.cfg != nil && s.cfg.AdminNotifyEmail != "" { + return s.cfg.AdminNotifyEmail + } + if s.pool == nil { + return "" + } + var email string + _ = s.pool.QueryRow(ctx, `SELECT "email" FROM "User" WHERE "role" = 'admin' ORDER BY "createdAt" ASC LIMIT 1`).Scan(&email) + return email +} + +func (s *Service) NotificarJarethBorrador(ctx context.Context, cotID, numero, clienteNombre, clienteEmpresa, proyecto, agenteNombre, approvalURL string, totalUnico, totalMensual float64) { + adminEmail := s.GetAdminEmail(ctx) + if adminEmail == "" { + log.Printf("[notify] sin correo de administrador para notificar borrador %s", numero) + return + } + portalURL := fmt.Sprintf("%s/cotizaciones/%s", s.cfg.AppURL, cotID) + empresaTxt := "" + if clienteEmpresa != "" { + empresaTxt = fmt.Sprintf(" (%s)", clienteEmpresa) + } + subj := fmt.Sprintf("Aprobacion requerida: Cotizacion %s — %s", numero, clienteNombre) + htmlBody := fmt.Sprintf(` +
+

Nueva cotizacion pendiente de aprobacion

+

El agente %s preparo el borrador %s.

+
    +
  • Cliente: %s%s
  • +
  • Proyecto: %s
  • +
  • Pago unico: %s
  • +
  • Pago mensual: %s
  • +
+

+ Revisar y aprobar cotizacion +

+

Tambien puedes revisarla en el panel: %s

+
+ `, html.EscapeString(agenteNombre), html.EscapeString(numero), html.EscapeString(clienteNombre), html.EscapeString(empresaTxt), html.EscapeString(proyecto), domain.FormatCurrency(totalUnico), domain.FormatCurrency(totalMensual), approvalURL, portalURL, portalURL) + + textBody := fmt.Sprintf("Nueva cotizacion %s creada por %s para %s%s.\nAprobar: %s\nPanel: %s", numero, agenteNombre, clienteNombre, empresaTxt, approvalURL, portalURL) + s.EnviarCorreo(MailMessage{To: adminEmail, Subject: subj, HTML: htmlBody, Text: textBody}) +} + +func (s *Service) NotificarJarethWhatsAppFueraVentana(ctx context.Context, numero, clienteNombre, telefono string) { + adminEmail := s.GetAdminEmail(ctx) + if adminEmail == "" { + return + } + subj := fmt.Sprintf("WhatsApp fuera de ventana 24h — Cotizacion %s", numero) + body := fmt.Sprintf("No se pudo enviar la cotizacion %s a %s (%s) por WhatsApp porque excedio la ventana de 24 horas y no hubo fallback de correo.", numero, clienteNombre, telefono) + s.EnviarCorreo(MailMessage{To: adminEmail, Subject: subj, Text: body, HTML: "

" + html.EscapeString(body) + "

"}) +} + +func (s *Service) EnviarCotizacionPorCorreo(to, clienteNombre, numero, proyecto string, pdfBytes []byte) bool { + subj := fmt.Sprintf("Cotizacion %s — Uriel Jareth Consulting", numero) + htmlBody := fmt.Sprintf(` +
+

Cotizacion %s

+

Hola %s,

+

Adjuntamos la propuesta economica correspondiente al proyecto %s.

+

Quedamos atentos a cualquier duda o comentario.

+

Uriel Jareth Consulting

+
+ `, html.EscapeString(numero), html.EscapeString(clienteNombre), html.EscapeString(proyecto)) + textBody := fmt.Sprintf("Hola %s,\n\nAdjuntamos la cotizacion %s para el proyecto %s.\n\nSaludos,\nUriel Jareth Consulting", clienteNombre, numero, proyecto) + return s.EnviarCorreo(MailMessage{ + To: to, + Subject: subj, + HTML: htmlBody, + Text: textBody, + Attachments: []Attachment{ + { + Filename: fmt.Sprintf("Cotizacion_%s.pdf", domain.SanitizeFilename(numero)), + ContentType: "application/pdf", + Content: pdfBytes, + }, + }, + }) +} + +func (s *Service) NotificarCobrosNuevos(ctx context.Context, pagoIDs []string) { + if s.pool == nil || len(pagoIDs) == 0 { + return + } + for _, pid := range pagoIDs { + var concepto, moneda, clienteNombre string + var email, userID *string + var monto float64 + var fecha time.Time + err := s.pool.QueryRow(ctx, ` + SELECT pr."concepto", pr."moneda", p."monto", p."fecha", + c."nombre", c."email", u."id" + FROM "PagoRecurrente" p + JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + JOIN "Cliente" c ON c."id" = pr."clienteId" + LEFT JOIN "User" u ON u."clienteId" = c."id" + WHERE p."id" = $1 + `, pid).Scan(&concepto, &moneda, &monto, &fecha, &clienteNombre, &email, &userID) + if err != nil { + continue + } + montoStr := domain.FormatMonto(monto, moneda) + fechaStr := domain.FormatFechaCobro(fecha) + urlPagos := fmt.Sprintf("%s/cliente/pagos", s.cfg.AppURL) + + if email != nil && strings.TrimSpace(*email) != "" { + s.EnviarCorreo(MailMessage{ + To: *email, + Subject: fmt.Sprintf("Nuevo cobro programado: %s (%s)", concepto, montoStr), + Text: fmt.Sprintf("Hola %s, tienes un cobro programado por %s (%s) con fecha %s. Sube tu comprobante en %s", clienteNombre, montoStr, concepto, fechaStr, urlPagos), + HTML: fmt.Sprintf(`
+

Nuevo cobro programado

+

Hola %s,

+

Se genero el cobro de %s por %s correspondiente al %s.

+

Ver y subir comprobante

+
`, html.EscapeString(clienteNombre), html.EscapeString(concepto), montoStr, fechaStr, urlPagos), + }) + } + if userID != nil && *userID != "" { + s.EnviarPush(ctx, *userID, "Nuevo cobro programado", fmt.Sprintf("%s — %s (%s)", concepto, montoStr, domain.FormatFechaCorta(fecha)), "/cliente/pagos") + } + } +} + +func (s *Service) NotificarVerificacion(ctx context.Context, pagoID string) { + if s.pool == nil { + return + } + var concepto, moneda, clienteNombre string + var email, userID *string + var monto float64 + var fecha time.Time + err := s.pool.QueryRow(ctx, ` + SELECT pr."concepto", pr."moneda", p."monto", p."fecha", + c."nombre", c."email", u."id" + FROM "PagoRecurrente" p + JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + JOIN "Cliente" c ON c."id" = pr."clienteId" + LEFT JOIN "User" u ON u."clienteId" = c."id" + WHERE p."id" = $1 + `, pagoID).Scan(&concepto, &moneda, &monto, &fecha, &clienteNombre, &email, &userID) + if err != nil { + return + } + montoStr := domain.FormatMonto(monto, moneda) + fechaStr := domain.FormatFechaCobro(fecha) + if email != nil && strings.TrimSpace(*email) != "" { + s.EnviarCorreo(MailMessage{ + To: *email, + Subject: fmt.Sprintf("Pago verificado: %s (%s)", concepto, montoStr), + Text: fmt.Sprintf("Hola %s, confirmamos tu pago de %s por %s (%s). Gracias.", clienteNombre, montoStr, concepto, fechaStr), + HTML: fmt.Sprintf(`

Hola %s,

Confirmamos que tu pago de %s por %s (%s) ha sido verificado. Gracias.

`, html.EscapeString(clienteNombre), montoStr, html.EscapeString(concepto), fechaStr), + }) + } + if userID != nil && *userID != "" { + s.EnviarPush(ctx, *userID, "Pago verificado", fmt.Sprintf("%s — %s confirmado", concepto, montoStr), "/cliente/pagos") + } +} + +func (s *Service) NotificarRechazo(ctx context.Context, pagoID, motivo string) { + if s.pool == nil { + return + } + var concepto, moneda, clienteNombre string + var email, userID *string + var monto float64 + var fecha time.Time + err := s.pool.QueryRow(ctx, ` + SELECT pr."concepto", pr."moneda", p."monto", p."fecha", + c."nombre", c."email", u."id" + FROM "PagoRecurrente" p + JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + JOIN "Cliente" c ON c."id" = pr."clienteId" + LEFT JOIN "User" u ON u."clienteId" = c."id" + WHERE p."id" = $1 + `, pagoID).Scan(&concepto, &moneda, &monto, &fecha, &clienteNombre, &email, &userID) + if err != nil { + return + } + montoStr := domain.FormatMonto(monto, moneda) + urlPagos := fmt.Sprintf("%s/cliente/pagos", s.cfg.AppURL) + if email != nil && strings.TrimSpace(*email) != "" { + s.EnviarCorreo(MailMessage{ + To: *email, + Subject: fmt.Sprintf("Comprobante rechazado: %s (%s)", concepto, montoStr), + Text: fmt.Sprintf("Hola %s, tu comprobante para %s (%s) fue rechazado. Motivo: %s. Puedes subir uno nuevo en %s", clienteNombre, concepto, montoStr, motivo, urlPagos), + HTML: fmt.Sprintf(`

Hola %s,

Tu comprobante para %s (%s) fue rechazado.

Motivo: %s

Subir nuevo comprobante

`, html.EscapeString(clienteNombre), html.EscapeString(concepto), montoStr, html.EscapeString(motivo), urlPagos), + }) + } + if userID != nil && *userID != "" { + s.EnviarPush(ctx, *userID, "Comprobante rechazado", fmt.Sprintf("%s: %s", concepto, motivo), "/cliente/pagos") + } +} + +type RecordatoriosResult struct { + ClientesNotificados int `json:"clientesNotificados"` + PagosRecordados int `json:"pagosRecordados"` + PagosVencidosEmit int `json:"pagosVencidosEmitidos"` + PagoIDsCubiertos []string `json:"-"` +} + +// EnviarRecordatoriosPendientes sends one account-statement reminder per client for overdue/due charges +// (estado in pendiente|rechazado, fecha <= hoy) and emits pago.vencido idempotently. +func (s *Service) EnviarRecordatoriosPendientes(ctx context.Context, clienteIDFilter string, forzar bool) (*RecordatoriosResult, error) { + if s.pool == nil { + return &RecordatoriosResult{}, nil + } + hoy := domain.HoyCalendario() + diasEspera := s.cfg.CobrosRecordatorioDias + if !forzar && diasEspera <= 0 { + return &RecordatoriosResult{}, nil + } + + args := []any{hoy} + whereCliente := "" + if clienteIDFilter != "" { + whereCliente = ` AND c."id" = $2` + args = append(args, clienteIDFilter) + } + + rows, err := s.pool.Query(ctx, ` + SELECT p."id", p."programaId", p."fecha", p."monto", p."estado", p."ultimoRecordatorioAt", + pr."concepto", pr."moneda", + c."id", c."nombre", COALESCE(c."empresa", ''), COALESCE(c."email", ''), COALESCE(c."telefono", ''), + COALESCE(u."id", '') + FROM "PagoRecurrente" p + JOIN "ProgramaPago" pr ON pr."id" = p."programaId" + JOIN "Cliente" c ON c."id" = pr."clienteId" + LEFT JOIN "User" u ON u."clienteId" = c."id" + WHERE p."estado" IN ('pendiente', 'rechazado') + AND p."fecha" <= $1`+whereCliente+` + ORDER BY c."nombre" ASC, p."fecha" ASC + `, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + type pagoRow struct { + ID string + ProgramaID string + Fecha time.Time + Monto float64 + Estado string + UltimoRecordatorioAt *time.Time + Concepto string + Moneda string + ClienteID string + ClienteNombre string + ClienteEmpresa string + ClienteEmail string + ClienteTelefono string + UserID string + } + + byClient := map[string][]pagoRow{} + var clientOrder []string + var vencidosItems []webhooks.PagoVencidoItem + + for rows.Next() { + var r pagoRow + if err := rows.Scan( + &r.ID, &r.ProgramaID, &r.Fecha, &r.Monto, &r.Estado, &r.UltimoRecordatorioAt, + &r.Concepto, &r.Moneda, + &r.ClienteID, &r.ClienteNombre, &r.ClienteEmpresa, &r.ClienteEmail, &r.ClienteTelefono, + &r.UserID, + ); err != nil { + continue + } + if _, ok := byClient[r.ClienteID]; !ok { + clientOrder = append(clientOrder, r.ClienteID) + } + byClient[r.ClienteID] = append(byClient[r.ClienteID], r) + + atraso := domain.DiasDeAtraso(r.Fecha, hoy) + if atraso > 0 { + vencidosItems = append(vencidosItems, webhooks.PagoVencidoItem{ + PagoID: r.ID, + ProgramaID: r.ProgramaID, + ClienteID: r.ClienteID, + ClienteNombre: r.ClienteNombre, + ClienteEmpresa: r.ClienteEmpresa, + ClienteEmail: r.ClienteEmail, + ClienteTelefono: r.ClienteTelefono, + Concepto: r.Concepto, + Monto: r.Monto, + Moneda: r.Moneda, + Fecha: r.Fecha.UTC().Format("2006-01-02"), + DiasAtraso: atraso, + }) + } + } + + // Best-effort idempotent webhook emission for overdue payments + res := &RecordatoriosResult{} + if s.webhooks != nil && len(vencidosItems) > 0 { + res.PagosVencidosEmit = s.webhooks.EmitirPagosVencidos(ctx, vencidosItems) + } + + // Load bank config for statement email + bancaria := map[string]string{} + cfgRows, err := s.pool.Query(ctx, `SELECT "clave", "valor" FROM "Configuracion"`) + if err == nil { + defer cfgRows.Close() + for cfgRows.Next() { + var k, v string + if cfgRows.Scan(&k, &v) == nil { + bancaria[k] = v + } + } + } + + cutoff := time.Now().Add(-time.Duration(diasEspera) * 24 * time.Hour) + for _, cid := range clientOrder { + pagos := byClient[cid] + if len(pagos) == 0 { + continue + } + if !forzar { + needsSend := false + for _, p := range pagos { + if p.UltimoRecordatorioAt == nil || p.UltimoRecordatorioAt.Before(cutoff) { + needsSend = true + break + } + } + if !needsSend { + continue + } + } + + first := pagos[0] + totales := map[string]float64{} + var rowsHTML strings.Builder + var rowsText strings.Builder + for _, p := range pagos { + totales[p.Moneda] = domain.Round2(totales[p.Moneda] + p.Monto) + fStr := domain.FormatFechaCorta(p.Fecha) + mStr := domain.FormatMonto(p.Monto, p.Moneda) + fmt.Fprintf(&rowsHTML, `%s%s%s`, + html.EscapeString(fStr), html.EscapeString(p.Concepto), mStr) + fmt.Fprintf(&rowsText, "- %s | %s | %s\n", fStr, p.Concepto, mStr) + } + + totalStr := domain.FormatTotales(totales) + urlPagos := fmt.Sprintf("%s/cliente/pagos", s.cfg.AppURL) + + bancoHTML := "" + if bancaria["banco_nacional"] != "" || bancaria["clabe_nacional"] != "" { + bancoHTML = fmt.Sprintf(`
+ Datos bancarios
+ Banco: %s
CLABE: %s
Cuenta: %s
Beneficiario: %s +
`, html.EscapeString(bancaria["banco_nacional"]), html.EscapeString(bancaria["clabe_nacional"]), html.EscapeString(bancaria["cuenta_nacional"]), html.EscapeString(bancaria["razon_social"])) + } + + delivered := false + if first.ClienteEmail != "" { + ok := s.EnviarCorreo(MailMessage{ + To: first.ClienteEmail, + Subject: fmt.Sprintf("Recordatorio de pagos pendientes (%s) — Uriel Jareth Consulting", totalStr), + Text: fmt.Sprintf("Hola %s,\n\nTienes pagos pendientes por %s:\n%s\nPuedes subir tus comprobantes en: %s", first.ClienteNombre, totalStr, rowsText.String(), urlPagos), + HTML: fmt.Sprintf(`
+

Estado de pagos pendientes

+

Hola %s,

+

Tienes los siguientes pagos pendientes por un total de %s:

+ + + %s +
FechaConceptoMonto
+ %s +

Subir comprobante

+
`, html.EscapeString(first.ClienteNombre), totalStr, rowsHTML.String(), bancoHTML, urlPagos), + }) + if ok { + delivered = true + } + } + + if first.UserID != "" { + if n := s.EnviarPush(ctx, first.UserID, "Pagos pendientes", fmt.Sprintf("Saldo pendiente: %s (%d cobro(s))", totalStr, len(pagos)), "/cliente/pagos"); n > 0 { + delivered = true + } + } + + if delivered { + res.ClientesNotificados++ + for _, p := range pagos { + _, _ = s.pool.Exec(ctx, ` + UPDATE "PagoRecurrente" + SET "ultimoRecordatorioAt" = NOW(), + "recordatoriosEnviados" = "recordatoriosEnviados" + 1, + "updatedAt" = NOW() + WHERE "id" = $1 + `, p.ID) + res.PagosRecordados++ + res.PagoIDsCubiertos = append(res.PagoIDsCubiertos, p.ID) + } + } + } + + return res, nil +} diff --git a/internal/pdf/cotizacion.go b/internal/pdf/cotizacion.go new file mode 100644 index 0000000..816e339 --- /dev/null +++ b/internal/pdf/cotizacion.go @@ -0,0 +1,582 @@ +package pdf + +import ( + "fmt" + "strings" + "time" + + "cotizador/internal/domain" +) + +type ServicioPDF struct { + Nombre string + Fase int + TipoPago string + Precio float64 + TiempoEntrega string + Entregables []string + EsPersonalizado bool + Horas *float64 + TarifaHora *float64 + ModeloCobro string + MontoMinimo *float64 + HorasIncluidas *float64 + Opcion *string +} + +type BonoPDF struct { + Numero int + Descripcion string +} + +// CotizacionPDFData holds client-facing quotation data for PDF generation. +// ObservacionesInternas is intentionally NOT declared here so internal notes +// can never leak into a client document. +type CotizacionPDFData struct { + Numero string + ClienteNombre string + ClienteEmpresa string + AsesorNombre string + Fecha time.Time + Vigencia time.Time + Moneda string + TipoCambio string + Proyecto string + EsquemaPago string + Servicios []ServicioPDF + EsDoble bool + OpcionesMetadata map[string]domain.MetaOpcion + PlanBucefaloNivel *string + PlanBucefaloPrecio float64 + IncluirBonos bool + Bonos []BonoPDF + IncluirIVA bool + Observaciones *string + ConfigBancaria map[string]string + ColorPrimario string + ColorSecundario string + LogoBase64 string + LogoMime string +} + +func servicioPDFToCalc(s ServicioPDF) domain.ServicioCalc { + return domain.ServicioCalc{ + Nombre: s.Nombre, + ModeloCobro: s.ModeloCobro, + EsPersonalizado: s.EsPersonalizado, + Horas: s.Horas, + TarifaHora: s.TarifaHora, + MontoMinimo: s.MontoMinimo, + HorasIncluidas: s.HorasIncluidas, + Opcion: s.Opcion, + TipoPago: s.TipoPago, + Precio: s.Precio, + Seleccionado: true, + } +} + +func serviciosPDFToCalc(list []ServicioPDF) []domain.ServicioCalc { + out := make([]domain.ServicioCalc, len(list)) + for i, s := range list { + out[i] = servicioPDFToCalc(s) + } + return out +} + +func GenerateCotizacionPDF(data CotizacionPDFData) ([]byte, error) { + primary := safeHex(data.ColorPrimario, defaultPrimary) + dark := safeHex(data.ColorSecundario, defaultDark) + + c := newCanvas(45, 55, 50, 50) + logo := registerLogo(c.doc, "cot_logo", data.LogoBase64, data.LogoMime) + + // Footer on every page. + c.doc.SetFooterFunc(func() { + c.hLine(c.L, c.L+c.W, c.ph-42, colorBorder, 0.5) + c.drawSingleLine("Uriel Jareth Consulting", c.L, c.ph-35, c.W, "", 6.5, colorMuted, "C") + c.drawSingleLine("urieljareth.com | contacto@urieljareth.com | (445) 182 9943", c.L, c.ph-26, c.W, "", 6.5, colorMuted, "C") + }) + + fmtMoney := func(n float64) string { + return formatMoney(n, data.Moneda) + } + + sectionTitle := func(title string, y float64) float64 { + y = c.need(20, y) + c.rectFill(c.L, y+1, 3, 9, primary) + c.drawSingleLine(title, c.L+10, y, c.W-10, "B", 9, dark, "L") + return y + 15 + } + + // ── PAGE 1: COVER ────────────────────────────── + c.doc.AddPage() + c.rectFill(0, 0, c.pw, c.ph, colorWhite) + + if logo.ok { + logo.drawByHeight(c.doc, c.L, 55, 65) + } else { + c.drawSingleLine("UJ", c.L, 55, 48, "B", 28, primary, "L") + c.drawSingleLine("Uriel Jareth Consulting", c.L+48, 70, c.W-48, "", 9, colorMuted, "L") + } + + barY := 130.0 + if logo.ok { + barY = 145.0 + } + c.rectFill(c.L, barY, c.W, 4, primary) + + c.drawSingleLine("Cotización", c.L, barY+24, c.W, "B", 36, dark, "L") + c.drawSingleLine(data.Numero, c.L, barY+68, c.W, "", 18, primary, "L") + + iy := barY + 110 + cL := c.L + cR := c.L + c.W*0.52 + colW := c.W * 0.46 + + type kv struct{ k, v string } + infoL := []kv{{"Cliente", data.ClienteNombre}} + if strings.TrimSpace(data.ClienteEmpresa) != "" { + infoL = append(infoL, kv{"Empresa", data.ClienteEmpresa}) + } + infoL = append(infoL, + kv{"Proyecto", data.Proyecto}, + kv{"Asesor", data.AsesorNombre}, + ) + infoR := []kv{ + {"Fecha", domain.FormatDateLongMX(data.Fecha)}, + {"Vigencia", domain.FormatDateLongMX(data.Vigencia)}, + {"Moneda", data.Moneda}, + {"Esquema", data.EsquemaPago}, + } + + maxRows := len(infoL) + if len(infoR) > maxRows { + maxRows = len(infoR) + } + for i := 0; i < maxRows; i++ { + hL, hR := 0.0, 0.0 + if i < len(infoL) { + c.drawSingleLine(infoL[i].k, cL, iy, colW, "", 9, colorMuted, "L") + hL = c.drawText(infoL[i].v, cL, iy+12, colW, "", 11, dark, "L") + } + if i < len(infoR) { + c.drawSingleLine(infoR[i].k, cR, iy, colW, "", 9, colorMuted, "L") + hR = c.drawText(infoR[i].v, cR, iy+12, colW, "", 11, dark, "L") + } + step := hL + if hR > step { + step = hR + } + if step < 18 { + step = 18 + } + iy += 14 + step + } + + // ── PAGE 2+: HOJA RESUMEN ────────────────────── + c.doc.AddPage() + y := c.mTop + + if logo.ok { + logo.drawRightAlignedByHeight(c.doc, c.L+c.W, c.mTop-5, 22) + } + + c.rectFill(c.L, y, 4, 16, primary) + c.drawSingleLine("Hoja Resumen", c.L+12, y, c.W-90, "B", 15, dark, "L") + y += 26 + + enAtencion := data.ClienteEmpresa + if strings.TrimSpace(enAtencion) == "" { + enAtencion = data.ClienteNombre + } + c.drawSingleLine("En atención a: "+enAtencion, c.L, y, c.W*0.44, "", 8, colorMuted, "L") + c.drawSingleLine("No. Cotización: "+data.Numero, c.L+c.W*0.45, y, c.W*0.55, "", 8, colorMuted, "L") + y += 11 + c.drawSingleLine("Asesor: "+data.AsesorNombre, c.L, y, c.W*0.44, "", 8, colorMuted, "L") + c.drawSingleLine(fmt.Sprintf("Fecha: %s | Moneda: %s", domain.FormatDateLongMX(data.Fecha), data.Moneda), c.L+c.W*0.45, y, c.W*0.55, "", 8, colorMuted, "L") + y += 16 + + colNombre := c.L + colTipo := c.L + c.W - 200 + colTiempo := c.L + c.W - 120 + colPrecio := c.L + c.W - 60 + nombreW := colTipo - colNombre - 16 + + drawTableHeader := func() { + y = c.need(20, y) + c.rowBg(y, 16, colorLightBG) + c.drawSingleLine("Servicio", colNombre+6, y+4, nombreW, "B", 7, dark, "L") + c.drawSingleLine("Tipo", colTipo+4, y+4, 72, "B", 7, dark, "L") + c.drawSingleLine("Entrega", colTiempo+4, y+4, 56, "B", 7, dark, "L") + c.drawSingleLine("Precio", colPrecio, y+4, 60, "B", 7, dark, "R") + y += 18 + } + + var unicos, mensuales []ServicioPDF + for _, s := range data.Servicios { + if s.TipoPago == "mensual" { + mensuales = append(mensuales, s) + } else { + unicos = append(unicos, s) + } + } + + drawSection := func(servicios []ServicioPDF, tipoLabel, tituloTotal string) { + if len(servicios) == 0 { + return + } + currentFase := -1 + for _, serv := range servicios { + if serv.Fase != currentFase { + currentFase = serv.Fase + y = c.need(20, y) + c.rectFill(c.L, y, c.W, 14, colorLightBG) + faseLbl := domain.FasesShort[serv.Fase] + if faseLbl == "" { + faseLbl = fmt.Sprintf("FASE %d", serv.Fase) + } + c.drawSingleLine(faseLbl, c.L+6, y+3, c.W-12, "B", 7, primary, "L") + y += 16 + } + + detalle := domain.DetalleModelo(servicioPDFToCalc(serv)) + hNombre := c.textHeight(serv.Nombre, nombreW, "", 8) + if hNombre < 11 { + hNombre = 11 + } + hTiempo := c.textHeight(serv.TiempoEntrega, 56, "", 7) + rowTopH := hNombre + if hTiempo > rowTopH { + rowTopH = hTiempo + } + hDetalle := 0.0 + if detalle != "" { + hDetalle = c.textHeight(detalle, nombreW-4, "I", 6.5) + 2 + } + colW := c.W * 0.44 + half := (len(serv.Entregables) + 1) / 2 + entH := 0.0 + for i := 0; i < half; i++ { + h1 := c.textHeight("• "+serv.Entregables[i], colW, "", 6.5) + h2 := 0.0 + if i+half < len(serv.Entregables) { + h2 = c.textHeight("• "+serv.Entregables[i+half], colW, "", 6.5) + } + if h2 > h1 { + h1 = h2 + } + entH += h1 + 1.5 + } + + totalServH := rowTopH + 2 + hDetalle + entH + 6 + y = c.need(totalServH, y) + + c.drawText(serv.Nombre, colNombre+6, y, nombreW, "", 8, dark, "L") + c.drawSingleLine(tipoLabel, colTipo+4, y, 72, "", 7, colorMuted, "L") + c.drawText(serv.TiempoEntrega, colTiempo+4, y, 56, "", 7, colorMuted, "L") + c.drawSingleLine(fmtMoney(serv.Precio), colPrecio, y, 60, "B", 8, dark, "R") + y += rowTopH + 2 + + if detalle != "" { + dh := c.drawText(detalle, colNombre+10, y, nombreW-4, "I", 6.5, colorMuted, "L") + y += dh + 2 + } + + if len(serv.Entregables) > 0 { + col1X := colNombre + 10 + col2X := colNombre + c.W*0.48 + for i := 0; i < half; i++ { + h1 := c.drawText("• "+serv.Entregables[i], col1X, y, colW, "", 6.5, colorMuted, "L") + h2 := 0.0 + if i+half < len(serv.Entregables) { + h2 = c.drawText("• "+serv.Entregables[i+half], col2X, y, colW, "", 6.5, colorMuted, "L") + } + if h2 > h1 { + h1 = h2 + } + y += h1 + 1.5 + } + } + + c.hLine(colNombre+6, c.L+c.W, y, colorSubtleSep, 0.2) + y += 4 + } + + y += 3 + total := 0.0 + for _, s := range servicios { + total += s.Precio + } + y = c.need(34, y) + c.rowBg(y, 18, "#f8fafc") + c.drawSingleLine(tituloTotal, colNombre+6, y+4, c.W-80, "B", 8.5, primary, "L") + c.drawSingleLine(fmtMoney(total), colPrecio-20, y+4, 80, "B", 8.5, primary, "R") + y += 22 + c.drawSingleLine("(Precios en Moneda Nacional, no incluyen IVA)", colNombre+6, y, c.W-12, "", 6.5, colorMuted, "L") + y += 12 + } + + drawOpcionHeader := func(op string) { + meta := data.OpcionesMetadata[op] + y = c.need(30, y) + y += 4 + c.rectFill(c.L, y, c.W, 18, primary) + title := "OPCIÓN " + op + if strings.TrimSpace(meta.Titulo) != "" { + title += ": " + meta.Titulo + } + c.drawSingleLine(title, c.L+8, y+3, c.W-16, "B", 10, colorWhite, "L") + y += 22 + if strings.TrimSpace(meta.Descripcion) != "" { + h := c.textHeight(meta.Descripcion, c.W-12, "", 7.5) + y = c.need(h+4, y) + c.drawText(meta.Descripcion, c.L+6, y, c.W-12, "", 7.5, dark, "L") + y += h + 4 + } + if strings.TrimSpace(meta.NoIncluye) != "" { + lbl := "No incluye: " + meta.NoIncluye + h := c.textHeight(lbl, c.W-12, "I", 7) + y = c.need(h+4, y) + c.drawText(lbl, c.L+6, y, c.W-12, "I", 7, colorMuted, "L") + y += h + 6 + } + } + + drawComparativa := func() { + calcs := serviciosPDFToCalc(data.Servicios) + t1 := domain.CalcularTotalesOpcion(calcs, "1") + t2 := domain.CalcularTotalesOpcion(calcs, "2") + + y = c.need(90, y) + y += 6 + c.rectFill(c.L, y+1, 3, 10, primary) + c.drawSingleLine("Comparativa de opciones", c.L+10, y, c.W-10, "B", 10, dark, "L") + y += 18 + + cLabel := c.L + cOp1 := c.L + c.W*0.45 + cOp2 := c.L + c.W*0.72 + wOp1 := c.W*0.27 - 4 + wOp2 := c.W*0.28 - 4 + + t1Tit := data.OpcionesMetadata["1"].Titulo + t2Tit := data.OpcionesMetadata["2"].Titulo + op1Lbl := "Opción 1" + if t1Tit != "" { + op1Lbl += " - " + t1Tit + } + op2Lbl := "Opción 2" + if t2Tit != "" { + op2Lbl += " - " + t2Tit + } + + c.rowBg(y, 16, colorLightBG) + c.drawSingleLine("Concepto", cLabel+6, y+4, c.W*0.43, "B", 7.5, dark, "L") + c.drawSingleLine(op1Lbl, cOp1, y+4, wOp1, "B", 7.5, dark, "L") + c.drawSingleLine(op2Lbl, cOp2, y+4, wOp2, "B", 7.5, dark, "L") + y += 18 + + ivaLbl := "" + if data.IncluirIVA { + ivaLbl = " (c/IVA)" + } + type compRow struct{ lab, v1, v2 string } + filas := []compRow{ + {"Total único" + ivaLbl, fmtMoney(domain.ConIVA(t1.TotalUnico, data.IncluirIVA)), fmtMoney(domain.ConIVA(t2.TotalUnico, data.IncluirIVA))}, + {"Total mensual" + ivaLbl, fmtMoney(domain.ConIVA(t1.TotalMensual, data.IncluirIVA)), fmtMoney(domain.ConIVA(t2.TotalMensual, data.IncluirIVA))}, + {"Horas estimadas", fmt.Sprintf("%g h", t1.Horas), fmt.Sprintf("%g h", t2.Horas)}, + } + for _, f := range filas { + y = c.need(14, y) + c.drawSingleLine(f.lab, cLabel+6, y, c.W*0.43, "", 8, dark, "L") + c.drawSingleLine(f.v1, cOp1, y, wOp1, "B", 8, dark, "L") + c.drawSingleLine(f.v2, cOp2, y, wOp2, "B", 8, dark, "L") + c.hLine(cLabel+6, c.L+c.W, y+12, colorSubtleSep, 0.2) + y += 14 + } + y += 8 + } + + filterByOp := func(list []ServicioPDF, op string) []ServicioPDF { + var out []ServicioPDF + for _, s := range list { + if s.Opcion != nil && (*s.Opcion == op || *s.Opcion == "ambas") { + out = append(out, s) + } + } + return out + } + + if data.EsDoble { + for _, op := range []string{"1", "2"} { + drawOpcionHeader(op) + drawTableHeader() + u := filterByOp(unicos, op) + me := filterByOp(mensuales, op) + if len(u) > 0 { + drawSection(u, "Único", fmt.Sprintf("Total Pago Único - Opción %s", op)) + } + if len(me) > 0 { + drawSection(me, "Mensual", fmt.Sprintf("Total Pago Mensual - Opción %s", op)) + } + } + drawComparativa() + } else { + drawTableHeader() + if len(unicos) > 0 { + drawSection(unicos, "Único", "Total Pago Único") + } + if len(mensuales) > 0 { + drawSection(mensuales, "Mensual", "Total Pago Mensual") + } + } + + if data.PlanBucefaloNivel != nil && strings.TrimSpace(*data.PlanBucefaloNivel) != "" { + y = c.need(20, y) + nivel := strings.TrimSpace(*data.PlanBucefaloNivel) + precio := data.PlanBucefaloPrecio + if precio <= 0 { + precio = domain.BucefaloPrecio(strings.ToLower(nivel)) + } + c.rowBg(y, 16, colorLightBG) + c.drawSingleLine("Plan Bucéfalo CRM - "+capitalize(nivel), colNombre+6, y+3, c.W-80, "B", 7.5, dark, "L") + c.drawSingleLine(fmtMoney(precio), colPrecio-20, y+3, 80, "B", 7.5, dark, "R") + y += 20 + } + + if data.IncluirBonos { + y = c.need(90, y) + y += 4 + c.rectFill(c.L, y+1, 3, 10, primary) + c.drawSingleLine("Bonos (Pago en una exhibición)", c.L+10, y, c.W-10, "B", 9, dark, "L") + y += 16 + + respaldo := []string{ + "Bono 1: 30 min mensuales en servicios Centinela (Sitio Web)", + "Bono 2: Workshop Estratégico de Buyer Persona", + "Bono 3: Workshop de Propuestas de Valor y Oferta Irresistible", + "Bono 4: 1 año de Membresía Premium", + "Bono 5: Un mes gratis de Bucéfalo CRM, Marketing y Ventas", + "Bono 6: Script de Ventas con más de 100 complementos", + } + var bonos []string + if len(data.Bonos) > 0 { + for _, b := range data.Bonos { + bonos = append(bonos, fmt.Sprintf("Bono %d: %s", b.Numero, b.Descripcion)) + } + } else { + bonos = respaldo + } + for _, b := range bonos { + txt := "• " + b + h := c.textHeight(txt, c.W-16, "", 7.5) + y = c.need(h+3, y) + c.drawText(txt, c.L+8, y, c.W-16, "", 7.5, dark, "L") + y += h + 3 + } + } + + // ── OBSERVACIONES (solo cliente) ─────────────── + if data.Observaciones != nil && strings.TrimSpace(*data.Observaciones) != "" { + y += 6 + y = sectionTitle("Observaciones", y) + raw := strings.ReplaceAll(*data.Observaciones, "\r\n", "\n") + for _, p := range strings.Split(raw, "\n") { + p = strings.TrimSpace(p) + if p == "" { + continue + } + lines := c.splitLines(p, c.W-4, "", 7.5) + lh := lineHeight(7.5) + for _, ln := range lines { + y = c.need(lh+2, y) + c.drawSingleLine(ln, c.L+2, y, c.W-4, "", 7.5, dark, "L") + y += lh + } + y += 4 + } + y += 4 + } + + // ── T&C PAGE ─────────────────────────────────── + c.doc.AddPage() + y = c.mTop + + if logo.ok { + logo.drawRightAlignedByHeight(c.doc, c.L+c.W, c.mTop-5, 22) + } + + c.rectFill(c.L, y, 4, 16, primary) + c.drawSingleLine("Términos y Condiciones", c.L+12, y, c.W-90, "B", 15, dark, "L") + y += 28 + + drawBullets := func(title string, items []string, yStart float64) float64 { + yy := sectionTitle(title, yStart) + for _, item := range items { + txt := "• " + item + h := c.textHeight(txt, c.W-4, "", 7.5) + yy = c.need(h+4, yy) + c.drawText(txt, c.L+2, yy, c.W-4, "", 7.5, dark, "L") + yy += h + 4 + } + return yy + 6 + } + + y = drawBullets("Condiciones", []string{ + "Esta cotización tiene una vigencia de 15 días hábiles.", + "Cualquier ajuste al proyecto después de la aprobación del contenido afectará la fecha de entrega y por consiguiente el costo.", + "El cliente deberá proporcionar la información solicitada por Uriel Jareth Consulting en tiempo y forma.", + "Si la falta de información provoca un excedente en los plazos de entrega del proyecto, las horas adicionales de servicio se cotizarán por separado.", + "Los pagos correspondientes a los servicios mensuales deberán realizarse en los primeros 5 días del mes.", + "Todo el material e información necesarios para la realización del sitio web deberán ser entregados en un plazo máximo de 40 días naturales a partir del arranque del proyecto.", + }, y) + + y = drawBullets("¿Qué no incluye el proyecto?", []string{ + "Generación de diseños, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado.", + "Redacción de entradas de Blog.", + "Integración de Servicios de terceros ajenos a los cotizados.", + "Servicio de Recuperación de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads.", + "Creación de Redes Sociales (En caso de requerir el servicio incluirá un costo adicional).", + }, y) + + y = drawBullets("Notas", []string{ + "El presente proyecto deberá tener un responsable oficial.", + "La Hora Centinela tiene un precio de $700.00 MXN.", + "Los archivos editables/fuente (AI, PSD) son propiedad intelectual de la agencia. Si requiere los archivos editables, estos pueden ser adquiridos abonando una tarifa de liberación (buy-out fee).", + "Si el proyecto se pausa por razones ajenas a Uriel Jareth Consulting, esto generará costo extra del 15% al 30% para retomar el proyecto.", + }, y) + + y += 6 + y = c.need(120, y) + y = sectionTitle("Datos Bancarios", y) + + bank := extractBankInfo(data.ConfigBancaria) + boxH := 48.0 + + c.rectFillStroke(c.L, y, c.W, boxH, colorLightBG, colorBorder, 0.5) + c.drawSingleLine("Transferencia Nacional", c.L+8, y+4, c.W-16, "B", 7, dark, "L") + if bank.CuentaNacional != "" { + c.drawSingleLine("Cuenta: "+bank.CuentaNacional, c.L+8, y+15, c.W*0.43, "", 6.5, dark, "L") + } + if bank.ClabeNacional != "" { + c.drawSingleLine("CLABE: "+bank.ClabeNacional, c.L+c.W*0.45, y+15, c.W*0.53, "", 6.5, dark, "L") + } + c.drawSingleLine("Razón Social: "+bank.RazonSocial, c.L+8, y+26, c.W*0.43, "", 6.5, dark, "L") + c.drawSingleLine("RFC: "+bank.RFC, c.L+c.W*0.45, y+26, c.W*0.53, "", 6.5, dark, "L") + if bank.BancoNacional != "" { + c.drawSingleLine("Banco: "+bank.BancoNacional, c.L+8, y+37, c.W*0.43, "", 6.5, dark, "L") + } + y += boxH + 6 + + y = c.need(boxH+6, y) + c.rectFillStroke(c.L, y, c.W, boxH, colorLightBG, colorBorder, 0.5) + c.drawSingleLine("Transferencia Internacional", c.L+8, y+4, c.W-16, "B", 7, dark, "L") + c.drawSingleLine("Beneficiario: "+bank.RazonSocial, c.L+8, y+15, c.W*0.43, "", 6.5, dark, "L") + if bank.ClabeInternacional != "" { + c.drawSingleLine("CLABE: "+bank.ClabeInternacional, c.L+c.W*0.45, y+15, c.W*0.53, "", 6.5, dark, "L") + } + c.drawSingleLine("Banco: BBVA México", c.L+8, y+26, c.W*0.43, "", 6.5, dark, "L") + c.drawSingleLine("SWIFT: "+bank.Swift, c.L+c.W*0.45, y+26, c.W*0.53, "", 6.5, dark, "L") + + return c.bytes() +} diff --git a/internal/pdf/helpers.go b/internal/pdf/helpers.go new file mode 100644 index 0000000..400a13e --- /dev/null +++ b/internal/pdf/helpers.go @@ -0,0 +1,429 @@ +package pdf + +import ( + "bytes" + "encoding/base64" + "fmt" + "image" + "image/jpeg" + "image/png" + "regexp" + "strconv" + "strings" + "unicode" + + "codeberg.org/go-pdf/fpdf" + "golang.org/x/image/font/gofont/gobold" + "golang.org/x/image/font/gofont/gobolditalic" + "golang.org/x/image/font/gofont/goitalic" + "golang.org/x/image/font/gofont/goregular" + "golang.org/x/image/webp" + + "cotizador/internal/domain" +) + +const ( + fontFamily = "Go" + + defaultPrimary = "#0400C4" + defaultDark = "#0F172A" + colorMuted = "#64748b" + colorBorder = "#cbd5e1" + colorLightBG = "#f1f5f9" + colorWhite = "#ffffff" + colorSubtleSep = "#e5e7eb" +) + +var ( + hexColorRe = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`) + swiftRe = regexp.MustCompile(`(?i)SWIFT[^:]*:\s*(\S+)`) + clabeRe = regexp.MustCompile(`(?i)CLABE[^:]*:\s*(\S+)`) +) + +func safeHex(v, fallback string) string { + v = strings.TrimSpace(v) + if hexColorRe.MatchString(v) { + return v + } + return fallback +} + +func parseHexRGB(hexStr, fallback string) (int, int, int) { + h := strings.TrimPrefix(safeHex(hexStr, fallback), "#") + r, _ := strconv.ParseInt(h[0:2], 16, 64) + g, _ := strconv.ParseInt(h[2:4], 16, 64) + b, _ := strconv.ParseInt(h[4:6], 16, 64) + return int(r), int(g), int(b) +} + +func capitalize(s string) string { + s = strings.TrimSpace(s) + if s == "" { + return "" + } + r := []rune(s) + r[0] = unicode.ToUpper(r[0]) + return string(r) +} + +func formatMoney(amount float64, moneda string) string { + if moneda == "" || strings.EqualFold(moneda, "MXN") { + return domain.FormatCurrency(amount) + } + return domain.FormatMonto(amount, moneda) +} + +type bankInfo struct { + RazonSocial string + RFC string + CuentaNacional string + ClabeNacional string + BancoNacional string + ClabeInternacional string + Swift string +} + +func extractBankInfo(cfg map[string]string) bankInfo { + if cfg == nil { + cfg = map[string]string{} + } + razon := strings.TrimSpace(cfg["razon_social"]) + if razon == "" { + razon = "URIEL JARETH ALVARADO ORTIZ" + } + rfc := strings.TrimSpace(cfg["rfc"]) + if rfc == "" { + rfc = "AAOU970201SU7" + } + cuentaNac := strings.TrimSpace(cfg["cuenta_nacional"]) + clabeNac := strings.TrimSpace(cfg["clabe_interbancaria"]) + if clabeNac == "" { + clabeNac = cuentaNac + } + bancoNac := "" + if cuentaNac != "" { + bancoNac = "BBVA" + } + swift := "BCMRMXMMPYM" + clabeInt := "" + if intl := cfg["cuenta_internacional_swift"]; intl != "" { + if m := swiftRe.FindStringSubmatch(intl); len(m) > 1 { + swift = m[1] + } + if m := clabeRe.FindStringSubmatch(intl); len(m) > 1 { + clabeInt = m[1] + } + } + return bankInfo{ + RazonSocial: razon, + RFC: rfc, + CuentaNacional: cuentaNac, + ClabeNacional: clabeNac, + BancoNacional: bancoNac, + ClabeInternacional: clabeInt, + Swift: swift, + } +} + +type logoAsset struct { + name string + w float64 + h float64 + ok bool +} + +// prepareLogoBytes decodes base64 and normalizes PNG/JPEG/WebP into a format fpdf safely accepts. +// WebP (and non-standard PNGs) are decoded and re-encoded as standard 8-bit PNG. +func prepareLogoBytes(b64, mime string) ([]byte, string, error) { + b64 = strings.TrimSpace(b64) + if b64 == "" { + return nil, "", fmt.Errorf("empty logo") + } + // Strip optional data URI prefix. + if idx := strings.Index(b64, ","); idx != -1 && strings.HasPrefix(b64[:idx], "data:") { + if mime == "" { + header := b64[len("data:"):idx] + if semi := strings.Index(header, ";"); semi != -1 { + mime = header[:semi] + } + } + b64 = b64[idx+1:] + } + raw, err := base64.StdEncoding.DecodeString(b64) + if err != nil { + raw, err = base64.RawStdEncoding.DecodeString(b64) + if err != nil { + return nil, "", err + } + } + if len(raw) < 8 { + return nil, "", fmt.Errorf("logo too short") + } + + m := strings.ToLower(strings.TrimSpace(mime)) + isWebP := m == "image/webp" || (len(raw) >= 12 && string(raw[0:4]) == "RIFF" && string(raw[8:12]) == "WEBP") + if isWebP { + img, err := webp.Decode(bytes.NewReader(raw)) + if err != nil { + return nil, "", err + } + var out bytes.Buffer + if err := png.Encode(&out, img); err != nil { + return nil, "", err + } + return out.Bytes(), "PNG", nil + } + + isJPEG := m == "image/jpeg" || m == "image/jpg" || (raw[0] == 0xFF && raw[1] == 0xD8) + if isJPEG { + if _, err := jpeg.DecodeConfig(bytes.NewReader(raw)); err != nil { + return nil, "", err + } + return raw, "JPG", nil + } + + isPNG := m == "image/png" || bytes.Equal(raw[0:8], []byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}) + if isPNG { + // Re-encode through image/png so interlaced or 16-bit PNGs always work with fpdf. + img, err := png.Decode(bytes.NewReader(raw)) + if err != nil { + return nil, "", err + } + var out bytes.Buffer + if err := png.Encode(&out, img); err != nil { + return nil, "", err + } + return out.Bytes(), "PNG", nil + } + + // Fallback: try generic image decode -> PNG. + img, _, err := image.Decode(bytes.NewReader(raw)) + if err != nil { + return nil, "", err + } + var out bytes.Buffer + if err := png.Encode(&out, img); err != nil { + return nil, "", err + } + return out.Bytes(), "PNG", nil +} + +func registerLogo(doc *fpdf.Fpdf, name, b64, mime string) logoAsset { + imgBytes, imgType, err := prepareLogoBytes(b64, mime) + if err != nil { + return logoAsset{} + } + opts := fpdf.ImageOptions{ImageType: imgType, ReadDpi: false} + info := doc.RegisterImageOptionsReader(name, opts, bytes.NewReader(imgBytes)) + if info == nil || !doc.Ok() { + doc.ClearError() + return logoAsset{} + } + return logoAsset{ + name: name, + w: info.Width(), + h: info.Height(), + ok: info.Width() > 0 && info.Height() > 0, + } +} + +func (l logoAsset) drawByHeight(doc *fpdf.Fpdf, x, y, targetH float64) { + if !l.ok { + return + } + doc.ImageOptions(l.name, x, y, 0, targetH, false, fpdf.ImageOptions{}, 0, "") +} + +func (l logoAsset) drawRightAlignedByHeight(doc *fpdf.Fpdf, rightX, y, targetH float64) { + if !l.ok { + return + } + w := targetH * (l.w / l.h) + if w > 90 { + w = 90 + targetH = w * (l.h / l.w) + } + doc.ImageOptions(l.name, rightX-w, y, w, targetH, false, fpdf.ImageOptions{}, 0, "") +} + +func (l logoAsset) drawFit(doc *fpdf.Fpdf, x, y, maxW, maxH float64) (float64, float64) { + if !l.ok { + return 0, 0 + } + scale := maxW / l.w + if sh := maxH / l.h; sh < scale { + scale = sh + } + w := l.w * scale + h := l.h * scale + doc.ImageOptions(l.name, x, y, w, h, false, fpdf.ImageOptions{}, 0, "") + return w, h +} + +type canvas struct { + doc *fpdf.Fpdf + pw float64 + ph float64 + mTop float64 + mBottom float64 + mLeft float64 + mRight float64 + W float64 + L float64 + maxY float64 +} + +func newCanvas(top, bottom, left, right float64) *canvas { + doc := fpdf.New("P", "pt", "Letter", "") + doc.AddUTF8FontFromBytes(fontFamily, "", goregular.TTF) + doc.AddUTF8FontFromBytes(fontFamily, "B", gobold.TTF) + doc.AddUTF8FontFromBytes(fontFamily, "I", goitalic.TTF) + doc.AddUTF8FontFromBytes(fontFamily, "BI", gobolditalic.TTF) + doc.SetMargins(left, top, right) + doc.SetAutoPageBreak(false, 0) + doc.SetCellMargin(0) + doc.SetFont(fontFamily, "", 10) + + pw, ph := doc.GetPageSize() + return &canvas{ + doc: doc, + pw: pw, + ph: ph, + mTop: top, + mBottom: bottom, + mLeft: left, + mRight: right, + W: pw - left - right, + L: left, + maxY: ph - bottom - 5, + } +} + +func (c *canvas) need(h, y float64) float64 { + if y+h > c.maxY { + c.doc.AddPage() + return c.mTop + } + return y +} + +func (c *canvas) setFont(style string, size float64) { + c.doc.SetFont(fontFamily, style, size) +} + +func (c *canvas) setTextColor(hex string) { + r, g, b := parseHexRGB(hex, defaultDark) + c.doc.SetTextColor(r, g, b) +} + +func (c *canvas) setFillColor(hex string) { + r, g, b := parseHexRGB(hex, colorWhite) + c.doc.SetFillColor(r, g, b) +} + +func (c *canvas) setDrawColor(hex string) { + r, g, b := parseHexRGB(hex, colorBorder) + c.doc.SetDrawColor(r, g, b) +} + +func lineHeight(size float64) float64 { + return size * 1.25 +} + +func (c *canvas) splitLines(txt string, width float64, style string, size float64) []string { + c.setFont(style, size) + if width <= 1 { + return []string{txt} + } + rawLines := strings.Split(strings.ReplaceAll(txt, "\r\n", "\n"), "\n") + var out []string + for _, rl := range rawLines { + if rl == "" { + out = append(out, "") + continue + } + parts := c.doc.SplitText(rl, width) + if len(parts) == 0 { + out = append(out, rl) + } else { + out = append(out, parts...) + } + } + if len(out) == 0 { + return []string{""} + } + return out +} + +func (c *canvas) textHeight(txt string, width float64, style string, size float64) float64 { + lines := c.splitLines(txt, width, style, size) + return float64(len(lines)) * lineHeight(size) +} + +// drawText writes multi-line wrapped text starting at (x, y) and returns total height drawn. +func (c *canvas) drawText(txt string, x, y, width float64, style string, size float64, color, align string) float64 { + if align == "" { + align = "L" + } + lines := c.splitLines(txt, width, style, size) + lh := lineHeight(size) + c.setFont(style, size) + c.setTextColor(color) + curY := y + for _, ln := range lines { + c.doc.SetXY(x, curY) + c.doc.CellFormat(width, lh, ln, "", 0, align, false, 0, "") + curY += lh + } + return float64(len(lines)) * lh +} + +// drawSingleLine writes text on one line without wrapping. +func (c *canvas) drawSingleLine(txt string, x, y, width float64, style string, size float64, color, align string) { + if align == "" { + align = "L" + } + c.setFont(style, size) + c.setTextColor(color) + c.doc.SetXY(x, y) + if width <= 0 { + width = c.doc.GetStringWidth(txt) + 2 + } + c.doc.CellFormat(width, lineHeight(size), txt, "", 0, align, false, 0, "") +} + +func (c *canvas) rectFill(x, y, w, h float64, fillHex string) { + c.setFillColor(fillHex) + c.doc.Rect(x, y, w, h, "F") +} + +func (c *canvas) rectFillStroke(x, y, w, h float64, fillHex, strokeHex string, lw float64) { + c.setFillColor(fillHex) + c.setDrawColor(strokeHex) + c.doc.SetLineWidth(lw) + c.doc.Rect(x, y, w, h, "DF") +} + +func (c *canvas) hLine(x1, x2, y float64, strokeHex string, lw float64) { + c.setDrawColor(strokeHex) + c.doc.SetLineWidth(lw) + c.doc.Line(x1, y, x2, y) +} + +func (c *canvas) circleFill(cx, cy, r float64, fillHex string) { + c.setFillColor(fillHex) + c.doc.Circle(cx, cy, r, "F") +} + +func (c *canvas) rowBg(y, h float64, bgHex string) { + c.rectFill(c.L, y, c.W, h, bgHex) + c.hLine(c.L, c.L+c.W, y+h, colorBorder, 0.3) +} + +func (c *canvas) bytes() ([]byte, error) { + var buf bytes.Buffer + if err := c.doc.Output(&buf); err != nil { + return nil, err + } + return buf.Bytes(), nil +} diff --git a/internal/pdf/nota_horas.go b/internal/pdf/nota_horas.go new file mode 100644 index 0000000..8884ead --- /dev/null +++ b/internal/pdf/nota_horas.go @@ -0,0 +1,394 @@ +package pdf + +import ( + "fmt" + "sort" + "strings" + "time" + + "cotizador/internal/domain" +) + +type RegistroHoraPDF struct { + Fecha time.Time + HoraInicio string + HoraFin string + Horas float64 + TarifaHora float64 + Descripcion string + EstadoPago string +} + +type NotaHorasPDFData struct { + Titulo string + Numero string + ClienteNombre string + ClienteEmpresa string + Proyecto string + AsesorNombre string + Moneda string + IncluirIVA bool + Modo string + MostrarEstado bool + MostrarBancarios bool + Registros []RegistroHoraPDF + ConfigBancaria map[string]string + ColorPrimario string + ColorSecundario string + LogoBase64 string + LogoMime string + FechaEmision time.Time +} + +type notaHorasGrupo struct { + Clave string + Etiqueta string + Count int + Horas float64 + Importe float64 +} + +func modoAgrupacionLabel(modo string) string { + switch modo { + case "dia": + return "Por día" + case "semana": + return "Por semana" + case "mes": + return "Por mes" + default: + return "Detalle" + } +} + +func etiquetaTotalNota(titulo string) string { + low := strings.ToLower(titulo) + switch { + case strings.Contains(low, "pagadas"): + return "Total pagado" + case strings.Contains(low, "por pagar"): + return "Total a pagar" + default: + return "Total" + } +} + +func GenerateNotaHorasPDF(data NotaHorasPDFData) ([]byte, error) { + primary := safeHex(data.ColorPrimario, defaultPrimary) + dark := safeHex(data.ColorSecundario, defaultDark) + muted := "#6b7280" + border := "#d1d5db" + headBG := "#f3f4f6" + + titulo := strings.TrimSpace(data.Titulo) + if titulo == "" { + titulo = "Nota de horas por pagar" + } + modo := strings.ToLower(strings.TrimSpace(data.Modo)) + if modo != "detalle" && modo != "dia" && modo != "semana" && modo != "mes" { + modo = "detalle" + } + modoLabel := modoAgrupacionLabel(modo) + + emitida := data.FechaEmision + if emitida.IsZero() { + emitida = time.Now() + } + + // Copy and sort records chronologically. + regs := make([]RegistroHoraPDF, len(data.Registros)) + copy(regs, data.Registros) + sort.Slice(regs, func(i, j int) bool { + if regs[i].Fecha.Equal(regs[j].Fecha) { + return regs[i].HoraInicio < regs[j].HoraInicio + } + return regs[i].Fecha.Before(regs[j].Fecha) + }) + + // Totals. + var totalHoras, subtotal float64 + for _, r := range regs { + totalHoras += r.Horas + subtotal += r.Horas * r.TarifaHora + } + totalHoras = domain.Round2(totalHoras) + subtotal = domain.Round2(subtotal) + iva := 0.0 + if data.IncluirIVA { + iva = domain.Round2(subtotal * domain.IVARate) + } + total := domain.Round2(subtotal + iva) + + // Periodo text. + periodoTexto := "Periodo: todos los registros" + if len(regs) > 0 { + minF := domain.FormatFechaRegistro(regs[0].Fecha) + maxF := domain.FormatFechaRegistro(regs[len(regs)-1].Fecha) + if minF == maxF { + periodoTexto = "Periodo: " + minF + } else { + periodoTexto = fmt.Sprintf("Periodo: %s al %s", minF, maxF) + } + } + + // Grouping if not detalle. + var grupos []notaHorasGrupo + if modo != "detalle" { + m := make(map[string]*notaHorasGrupo) + for _, r := range regs { + per := domain.PeriodoAgrupacionDe(r.Fecha, modo) + g, ok := m[per.Clave] + if !ok { + g = ¬aHorasGrupo{Clave: per.Clave, Etiqueta: per.Etiqueta} + m[per.Clave] = g + } + g.Count++ + g.Horas += r.Horas + g.Importe += r.Horas * r.TarifaHora + } + for _, g := range m { + g.Horas = domain.Round2(g.Horas) + g.Importe = domain.Round2(g.Importe) + grupos = append(grupos, *g) + } + sort.Slice(grupos, func(i, j int) bool { + return grupos[i].Clave < grupos[j].Clave + }) + } + + fmtMoney := func(n float64) string { + return formatMoney(n, data.Moneda) + } + + c := newCanvas(45, 55, 50, 50) + c.maxY = c.ph - c.mBottom + logo := registerLogo(c.doc, "nota_logo", data.LogoBase64, data.LogoMime) + + c.doc.AddPage() + y := c.mTop + + // ── ENCABEZADO ──────────────────────────────── + logoBottom := y + if logo.ok { + _, lh := logo.drawFit(c.doc, c.L, y, 46, 46) + logoBottom = y + lh + } + txtX := c.L + if logo.ok { + txtX = c.L + 58 + } + titleW := c.W - 170 + if logo.ok { + titleW = c.W - 58 - 115 + } + hTit := c.drawText(titulo, txtX, y+2, titleW, "B", 18, dark, "L") + sub := fmt.Sprintf("Cotización %s · %s", data.Numero, data.Proyecto) + hSub := c.drawText(sub, txtX, y+2+hTit+1, titleW, "", 9, muted, "L") + c.drawSingleLine("Emitida: "+domain.FormatFechaRegistro(emitida), c.L, y+2, c.W, "", 9, muted, "R") + + yTextEnd := y + 2 + hTit + 1 + hSub + 6 + y = y + 50 + if logoBottom+6 > y { + y = logoBottom + 6 + } + if yTextEnd > y { + y = yTextEnd + } + c.hLine(c.L, c.L+c.W, y, primary, 2.5) + y += 14 + + // ── META ────────────────────────────────────── + cliente := data.ClienteEmpresa + if strings.TrimSpace(cliente) == "" { + cliente = data.ClienteNombre + } + drawMetaLine := func(label, val string) { + c.setFont("B", 9.5) + lw := c.doc.GetStringWidth(label) + 2 + c.drawSingleLine(label, c.L, y, lw, "B", 9.5, dark, "L") + h := c.drawText(val, c.L+lw, y, c.W-lw, "", 9.5, dark, "L") + y += h + 2 + } + drawMetaLine("Cliente: ", cliente) + if strings.TrimSpace(data.ClienteEmpresa) != "" && strings.TrimSpace(data.ClienteNombre) != "" { + drawMetaLine("Contacto: ", data.ClienteNombre) + } + if strings.TrimSpace(data.AsesorNombre) != "" { + drawMetaLine("Asesor: ", data.AsesorNombre) + } + hPer := c.drawText(fmt.Sprintf("%s · Desglose %s", periodoTexto, strings.ToLower(modoLabel)), c.L, y, c.W, "", 8.5, muted, "L") + y += hPer + 12 + + // ── TABLA ───────────────────────────────────── + if modo == "detalle" { + wEstado := 0.0 + if data.MostrarEstado { + wEstado = 58.0 + } + cFecha := c.L + wFecha, wHorario, wHoras, wTarifa, wImporte := 62.0, 72.0, 42.0, 52.0, 58.0 + cHorario := cFecha + wFecha + cHoras := cHorario + wHorario + cTarifa := cHoras + wHoras + cImporte := cTarifa + wTarifa + cDesc := cImporte + wImporte + 6 + estadoPad := 0.0 + if wEstado > 0 { + estadoPad = 6.0 + } + wDesc := c.L + c.W - cDesc - wEstado - estadoPad + cEstado := c.L + c.W - wEstado + + drawHeader := func(yy float64) float64 { + c.rectFill(c.L, yy, c.W, 16, headBG) + c.drawSingleLine("FECHA", cFecha+4, yy+4, wFecha-4, "B", 7, dark, "L") + c.drawSingleLine("HORARIO", cHorario+4, yy+4, wHorario-4, "B", 7, dark, "L") + c.drawSingleLine("HORAS", cHoras, yy+4, wHoras-2, "B", 7, dark, "R") + c.drawSingleLine("TARIFA", cTarifa, yy+4, wTarifa-2, "B", 7, dark, "R") + c.drawSingleLine("IMPORTE", cImporte, yy+4, wImporte-2, "B", 7, dark, "R") + c.drawSingleLine("DESCRIPCIÓN", cDesc, yy+4, wDesc, "B", 7, dark, "L") + if wEstado > 0 { + c.drawSingleLine("ESTADO", cEstado, yy+4, wEstado, "B", 7, dark, "L") + } + return yy + 16 + } + + y = drawHeader(y) + for _, r := range regs { + descH := c.textHeight(r.Descripcion, wDesc, "", 8) + rowH := descH + 8 + if rowH < 16 { + rowH = 16 + } + if y+rowH > c.maxY { + y = drawHeader(c.need(rowH+16, y)) + } + c.drawSingleLine(domain.FormatFechaRegistro(r.Fecha), cFecha+4, y+4, wFecha-4, "", 8, dark, "L") + c.drawSingleLine(fmt.Sprintf("%s-%s", r.HoraInicio, r.HoraFin), cHorario+4, y+4, wHorario-4, "", 8, dark, "L") + c.drawSingleLine(fmt.Sprintf("%.2f", r.Horas), cHoras, y+4, wHoras-2, "", 8, dark, "R") + c.drawSingleLine(fmtMoney(r.TarifaHora), cTarifa, y+4, wTarifa-2, "", 8, dark, "R") + c.drawSingleLine(fmtMoney(r.Horas*r.TarifaHora), cImporte, y+4, wImporte-2, "", 8, dark, "R") + c.drawText(r.Descripcion, cDesc, y+4, wDesc, "", 8, dark, "L") + if wEstado > 0 { + est := "Por pagar" + if domain.EsPagada(r.EstadoPago) { + est = "Pagada" + } + c.drawSingleLine(est, cEstado, y+4, wEstado, "", 8, dark, "L") + } + c.hLine(c.L, c.L+c.W, y+rowH, border, 0.3) + y += rowH + } + } else { + wReg, wHor, wImp := 90.0, 90.0, 90.0 + cPer := c.L + wPer := c.W - wReg - wHor - wImp + cReg := cPer + wPer + cHor := cReg + wReg + cImp := cHor + wHor + + drawHeader := func(yy float64) float64 { + c.rectFill(c.L, yy, c.W, 16, headBG) + c.drawSingleLine(strings.ToUpper(modoLabel), cPer+4, yy+4, wPer-6, "B", 7, dark, "L") + c.drawSingleLine("REGISTROS", cReg, yy+4, wReg-2, "B", 7, dark, "R") + c.drawSingleLine("HORAS", cHor, yy+4, wHor-2, "B", 7, dark, "R") + c.drawSingleLine("IMPORTE", cImp, yy+4, wImp-2, "B", 7, dark, "R") + return yy + 16 + } + + y = drawHeader(y) + for _, g := range grupos { + rowH := 16.0 + if y+rowH > c.maxY { + y = drawHeader(c.need(rowH+16, y)) + } + c.drawSingleLine(g.Etiqueta, cPer+4, y+4, wPer-6, "", 8, dark, "L") + c.drawSingleLine(fmt.Sprintf("%d", g.Count), cReg, y+4, wReg-2, "", 8, dark, "R") + c.drawSingleLine(fmt.Sprintf("%.2f", g.Horas), cHor, y+4, wHor-2, "", 8, dark, "R") + c.drawSingleLine(fmtMoney(g.Importe), cImp, y+4, wImp-2, "", 8, dark, "R") + c.hLine(c.L, c.L+c.W, y+rowH, border, 0.3) + y += rowH + } + } + + // ── TOTALES ─────────────────────────────────── + y += 12 + totW := 240.0 + totX := c.L + c.W - totW + drawTotalLine := func(label, val string, bold, topLine bool) { + y = c.need(20, y) + if topLine { + c.hLine(totX, totX+totW, y, primary, 1.2) + y += 5 + } + style := "" + size := 9.0 + lblColor := muted + step := 15.0 + if bold { + style = "B" + size = 12.0 + lblColor = dark + step = 18.0 + } + c.drawSingleLine(label, totX, y, totW-95, style, size, lblColor, "L") + c.drawSingleLine(val, totX+totW-95, y, 95, style, size, dark, "R") + y += step + } + + drawTotalLine("Total de horas", fmt.Sprintf("%.2f h", totalHoras), false, false) + drawTotalLine("Subtotal", fmtMoney(subtotal), false, false) + if data.IncluirIVA { + drawTotalLine("IVA (16%)", fmtMoney(iva), false, false) + } + drawTotalLine(etiquetaTotalNota(titulo), fmtMoney(total), true, true) + + // ── DATOS PARA EL PAGO ──────────────────────── + if data.MostrarBancarios { + dp := extractBankInfo(data.ConfigBancaria) + boxH := 52.0 + y = c.need(boxH+34, y) + 16 + c.rectFill(c.L, y+1, 3, 10, primary) + c.drawSingleLine("Datos para el pago", c.L+10, y, c.W-10, "B", 10, dark, "L") + y += 16 + + c.rectFillStroke(c.L, y, c.W, boxH, headBG, border, 0.5) + c.drawSingleLine("Transferencia Nacional", c.L+8, y+5, c.W-16, "B", 8, dark, "L") + if dp.CuentaNacional != "" { + c.drawSingleLine("Cuenta: "+dp.CuentaNacional, c.L+8, y+18, c.W*0.48, "", 8.5, dark, "L") + } + if dp.ClabeNacional != "" { + c.drawSingleLine("CLABE: "+dp.ClabeNacional, c.L+c.W*0.5, y+18, c.W*0.48, "", 8.5, dark, "L") + } + c.drawSingleLine("Beneficiario: "+dp.RazonSocial, c.L+8, y+30, c.W*0.48, "", 8.5, dark, "L") + c.drawSingleLine("RFC: "+dp.RFC, c.L+c.W*0.5, y+30, c.W*0.48, "", 8.5, dark, "L") + if dp.BancoNacional != "" { + c.drawSingleLine("Banco: "+dp.BancoNacional, c.L+8, y+42, c.W*0.48, "", 8.5, dark, "L") + } + y += boxH + 8 + + if dp.ClabeInternacional != "" || dp.Swift != "" { + y = c.need(boxH, y) + c.rectFillStroke(c.L, y, c.W, boxH, headBG, border, 0.5) + c.drawSingleLine("Transferencia Internacional", c.L+8, y+5, c.W-16, "B", 8, dark, "L") + c.drawSingleLine("Beneficiario: "+dp.RazonSocial, c.L+8, y+18, c.W*0.48, "", 8.5, dark, "L") + if dp.ClabeInternacional != "" { + c.drawSingleLine("CLABE: "+dp.ClabeInternacional, c.L+c.W*0.5, y+18, c.W*0.48, "", 8.5, dark, "L") + } + c.drawSingleLine("Banco: BBVA México", c.L+8, y+30, c.W*0.48, "", 8.5, dark, "L") + if dp.Swift != "" { + c.drawSingleLine("SWIFT: "+dp.Swift, c.L+c.W*0.5, y+30, c.W*0.48, "", 8.5, dark, "L") + } + y += boxH + 8 + } + } + + // ── PIE ─────────────────────────────────────── + y = c.need(30, y) + 14 + c.drawText( + "Documento generado desde el Cotizador. Conteo de horas trabajadas para cobro del proyecto.", + c.L, y, c.W, "", 8, muted, "C", + ) + + return c.bytes() +} diff --git a/internal/pdf/pdf_test.go b/internal/pdf/pdf_test.go new file mode 100644 index 0000000..5d7f3d0 --- /dev/null +++ b/internal/pdf/pdf_test.go @@ -0,0 +1,454 @@ +package pdf + +import ( + "bytes" + "encoding/base64" + "image" + "image/color" + "image/jpeg" + "image/png" + "reflect" + "strings" + "testing" + "time" + + "github.com/HugoSmits86/nativewebp" + "golang.org/x/image/font/gofont/goregular" + "golang.org/x/image/font/sfnt" + + "cotizador/internal/domain" +) + +func f64(v float64) *float64 { return &v } +func str(v string) *string { return &v } + +func makeTestImage() image.Image { + img := image.NewNRGBA(image.Rect(0, 0, 32, 16)) + for y := 0; y < 16; y++ { + for x := 0; x < 32; x++ { + img.Set(x, y, color.NRGBA{R: 4, G: 0, B: 196, A: 255}) + } + } + return img +} + +func makePNGLogoB64(t *testing.T) string { + t.Helper() + var buf bytes.Buffer + if err := png.Encode(&buf, makeTestImage()); err != nil { + t.Fatalf("png encode: %v", err) + } + return base64.StdEncoding.EncodeToString(buf.Bytes()) +} + +func makeJPEGLogoB64(t *testing.T) string { + t.Helper() + var buf bytes.Buffer + if err := jpeg.Encode(&buf, makeTestImage(), &jpeg.Options{Quality: 85}); err != nil { + t.Fatalf("jpeg encode: %v", err) + } + return base64.StdEncoding.EncodeToString(buf.Bytes()) +} + +func makeWebPLogoB64(t *testing.T) string { + t.Helper() + var buf bytes.Buffer + if err := nativewebp.Encode(&buf, makeTestImage(), nil); err != nil { + t.Fatalf("webp encode: %v", err) + } + return base64.StdEncoding.EncodeToString(buf.Bytes()) +} + +func assertValidPDF(t *testing.T, b []byte, minPages int) { + t.Helper() + if len(b) < 500 { + t.Fatalf("PDF too small: %d bytes", len(b)) + } + if !bytes.HasPrefix(b, []byte("%PDF-")) { + t.Fatalf("missing %%PDF- header: %q", b[:min(20, len(b))]) + } + if !bytes.Contains(b, []byte("%%EOF")) { + t.Fatalf("missing %%%%EOF trailer") + } + pages := bytes.Count(b, []byte("/Type /Page\n")) + bytes.Count(b, []byte("/Type /Page ")) + bytes.Count(b, []byte("/Type /Page/")) + if pages < minPages { + t.Fatalf("expected at least %d pages, counted %d", minPages, pages) + } +} + +func TestGoFontGlyphCoverage(t *testing.T) { + f, err := sfnt.Parse(goregular.TTF) + if err != nil { + t.Fatalf("parse goregular: %v", err) + } + var buf sfnt.Buffer + const chars = "áéíóúüñÁÉÍÓÚÜÑ¿¡•·—×○$€%" + for _, r := range chars { + idx, err := f.GlyphIndex(&buf, r) + if err != nil || idx == 0 { + t.Errorf("goregular missing glyph for %q (U+%04X)", r, r) + } + } +} + +func TestCotizacionPDFDataHasNoObservacionesInternas(t *testing.T) { + rt := reflect.TypeOf(CotizacionPDFData{}) + for i := 0; i < rt.NumField(); i++ { + name := strings.ToLower(rt.Field(i).Name) + if strings.Contains(name, "interna") { + t.Fatalf("CotizacionPDFData must never declare internal observations field, found %q", rt.Field(i).Name) + } + } +} + +func TestGenerateCotizacionPDFSingleAndLogos(t *testing.T) { + fecha := time.Date(2026, 5, 10, 12, 0, 0, 0, time.UTC) + vigencia := domain.CalcularVigencia(fecha) + obs := "Primer párrafo con acentos: diseño, campaña y año.\n\n" + strings.Repeat("Observación extendida para probar el salto de línea automático en el PDF. ", 15) + + baseData := CotizacionPDFData{ + Numero: "UJ2605UR001", + ClienteNombre: "María José Peña", + ClienteEmpresa: "Industrias del Bajío S.A.", + AsesorNombre: "Uriel Jareth", + Fecha: fecha, + Vigencia: vigencia, + Moneda: "MXN", + TipoCambio: "N/A", + Proyecto: "Rediseño Web y Campaña de Adquisición", + EsquemaPago: "50% anticipo, 50% entrega", + Servicios: []ServicioPDF{ + { + Nombre: "Auditoría SEO y Técnica", + Fase: 0, + TipoPago: "unico", + Precio: 8500, + TiempoEntrega: "7 días", + Entregables: []string{"Reporte técnico", "Mapa de palabras clave", "Plan de acción"}, + ModeloCobro: "fijo", + }, + { + Nombre: "Desarrollo a la medida", + Fase: 1, + TipoPago: "unico", + Precio: 14000, + TiempoEntrega: "15 días", + Entregables: []string{"Arquitectura", "Implementación", "Pruebas QA"}, + ModeloCobro: "horas", + EsPersonalizado: true, + Horas: f64(20), + TarifaHora: f64(700), + }, + { + Nombre: "Soporte Mensual Retainer", + Fase: 2, + TipoPago: "mensual", + Precio: 7500, + TiempoEntrega: "Mensual", + Entregables: []string{"Monitoreo continuo", "Actualizaciones de seguridad"}, + ModeloCobro: "retainer", + MontoMinimo: f64(7500), + HorasIncluidas: f64(10), + TarifaHora: f64(700), + }, + { + Nombre: "Horas Centinela bajo demanda", + Fase: 3, + TipoPago: "mensual", + Precio: 0, + TiempoEntrega: "Según consumo", + ModeloCobro: "demanda", + TarifaHora: f64(700), + }, + }, + PlanBucefaloNivel: str("estandar"), + PlanBucefaloPrecio: 3500, + IncluirBonos: true, + Bonos: []BonoPDF{ + {Numero: 1, Descripcion: "Workshop estratégico de diseño"}, + {Numero: 2, Descripcion: "Un mes gratis de Bucéfalo CRM"}, + }, + IncluirIVA: true, + Observaciones: &obs, + ConfigBancaria: map[string]string{ + "razon_social": "URIEL JARETH ALVARADO ORTIZ", + "rfc": "AAOU970201SU7", + "cuenta_nacional": "0123456789", + "clabe_interbancaria": "012180001234567890", + "cuenta_internacional_swift": "CLABE: 012180001234567890 SWIFT: BCMRMXMMPYM", + }, + ColorPrimario: "#0400C4", + ColorSecundario: "#0F172A", + } + + cases := []struct { + name string + b64 string + mime string + }{ + {"no_logo", "", ""}, + {"png_logo", makePNGLogoB64(t), "image/png"}, + {"jpeg_logo", makeJPEGLogoB64(t), "image/jpeg"}, + {"webp_logo", makeWebPLogoB64(t), "image/webp"}, + {"data_uri_png", "data:image/png;base64," + makePNGLogoB64(t), ""}, + {"corrupt_logo_fallback", "not-valid-base64!!!", "image/png"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + d := baseData + d.LogoBase64 = tc.b64 + d.LogoMime = tc.mime + out, err := GenerateCotizacionPDF(d) + if err != nil { + t.Fatalf("GenerateCotizacionPDF(%s) error: %v", tc.name, err) + } + // Cover + Resumen + T&C = at least 3 pages + assertValidPDF(t, out, 3) + }) + } +} + +func TestGenerateCotizacionPDFDoblePropuesta(t *testing.T) { + fecha := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC) + d := CotizacionPDFData{ + Numero: "UJ2606UR002", + ClienteNombre: "Carlos Núñez", + ClienteEmpresa: "Núñez Logistics", + AsesorNombre: "Uriel Jareth", + Fecha: fecha, + Vigencia: domain.CalcularVigencia(fecha), + Moneda: "MXN", + Proyecto: "Transformación Digital", + EsquemaPago: "Mensual", + EsDoble: true, + IncluirIVA: true, + IncluirBonos: true, // exercises fallback bonos + OpcionesMetadata: map[string]domain.MetaOpcion{ + "1": {Titulo: "Esencial", Descripcion: "Arranque rápido con foco en captación.", NoIncluye: "Producción de video"}, + "2": {Titulo: "Crecimiento", Descripcion: "Estrategia integral con automatización.", NoIncluye: "Pauta publicitaria"}, + }, + Servicios: []ServicioPDF{ + {Nombre: "Auditoría inicial", Fase: 0, TipoPago: "unico", Precio: 5000, TiempoEntrega: "5 días", Opcion: str("ambas"), Horas: f64(6)}, + {Nombre: "Landing Page", Fase: 1, TipoPago: "unico", Precio: 12000, TiempoEntrega: "15 días", Opcion: str("1"), Horas: f64(15)}, + {Nombre: "Sitio Web Completo", Fase: 1, TipoPago: "unico", Precio: 28000, TiempoEntrega: "30 días", Opcion: str("2"), Horas: f64(35)}, + {Nombre: "Gestión Ads", Fase: 2, TipoPago: "mensual", Precio: 8000, TiempoEntrega: "Mensual", Opcion: str("ambas")}, + }, + ColorPrimario: "not-a-hex", + ColorSecundario: "", + } + + out, err := GenerateCotizacionPDF(d) + if err != nil { + t.Fatalf("GenerateCotizacionPDF doble error: %v", err) + } + assertValidPDF(t, out, 3) +} + +func TestGenerateNotaHorasPDFAllModes(t *testing.T) { + base := time.Date(2026, 5, 1, 12, 0, 0, 0, time.UTC) + var regs []RegistroHoraPDF + for i := 0; i < 35; i++ { + estado := "por_pagar" + if i%3 == 0 { + estado = "pagada" + } + regs = append(regs, RegistroHoraPDF{ + Fecha: base.AddDate(0, 0, i*2), + HoraInicio: "09:00", + HoraFin: "11:30", + Horas: 2.5, + TarifaHora: 700, + Descripcion: "Optimización de campaña y diseño de pruebas A/B con revisión de métricas", + EstadoPago: estado, + }) + } + + for _, modo := range []string{"detalle", "dia", "semana", "mes"} { + t.Run(modo, func(t *testing.T) { + out, err := GenerateNotaHorasPDF(NotaHorasPDFData{ + Titulo: "Nota de horas por pagar", + Numero: "UJ2605UR001", + ClienteNombre: "Ana Gómez", + ClienteEmpresa: "Gómez Tech", + Proyecto: "Soporte Continuo", + AsesorNombre: "Uriel Jareth", + Moneda: "MXN", + IncluirIVA: true, + Modo: modo, + MostrarEstado: modo == "detalle", + MostrarBancarios: true, + Registros: regs, + ConfigBancaria: map[string]string{ + "cuenta_nacional": "0123456789", + "clabe_interbancaria": "012180001234567890", + "cuenta_internacional_swift": "CLABE: 012180001234567890 SWIFT: BCMRMXMMPYM", + }, + LogoBase64: makeWebPLogoB64(t), + LogoMime: "image/webp", + FechaEmision: time.Date(2026, 7, 15, 12, 0, 0, 0, time.UTC), + }) + if err != nil { + t.Fatalf("GenerateNotaHorasPDF(%s) error: %v", modo, err) + } + minPages := 1 + if modo == "detalle" { + minPages = 2 + } + assertValidPDF(t, out, minPages) + }) + } +} + +func TestGenerarPropuestaYAnexoInternoPDF(t *testing.T) { + contenido := map[string]any{ + "hechos": map[string]any{ + "citas": []map[string]any{ + {"id": "C01", "textoLiteral": "Perdemos cotizaciones porque tardamos días en responder por WhatsApp.", "quienLoDijo": "el director comercial"}, + }, + "materialesPendientes": []map[string]any{ + {"texto": "Accesos a Google Ads y Meta Business", "bloqueaEntrega": true}, + }, + "decisionesPendientes": []map[string]any{ + {"texto": "Definir presupuesto mensual de pauta", "quienDecide": "Dirección General"}, + }, + "mencionesFueraDeAlcance": []string{"Producción de video corporativo"}, + "redFlags": []map[string]any{ + {"senal": "El cliente espera resultados en 48 horas", "severidad": "alta"}, + }, + }, + "diagnostico": map[string]any{ + "hallazgos": []map[string]any{ + {"id": "D01", "urgencia": "rojo", "titulo": "Fuga de leads", "descripcion": "No hay seguimiento estructurado en CRM.", "confianza": "confirmado"}, + {"id": "D02", "urgencia": "ambar", "titulo": "Sitio lento", "descripcion": "Tiempo de carga superior a 6 segundos.", "confianza": "estimado"}, + {"id": "D03", "urgencia": "verde", "titulo": "Buena reputación", "descripcion": "Reseñas de 4.9 estrellas en Google.", "confianza": "confirmado"}, + }, + "valorProblema": map[string]any{ + "dimensiones": []map[string]any{ + { + "tipo": "dinero", + "descripcion": "Leads perdidos por falta de seguimiento oportuno", + "montoAnualMXN": 480000.0, + "confianza": "estimado", + "factores": []map[string]any{ + {"nombre": "leads_perdidos_mes", "valor": 8.0, "confianza": "estimado"}, + {"nombre": "ticket_promedio", "valor": 5000.0, "confianza": "estimado"}, + }, + }, + }, + "notaMetodologia": "Cálculo conservador basado en promedio de los últimos 6 meses.", + }, + "resultados": []map[string]any{ + {"enunciado": "Responder a cada prospecto en menos de 5 minutos", "metrica": "Tiempo de primera respuesta", "periodoMedicion": "60 días"}, + }, + }, + "redaccion": map[string]any{ + "hero": map[string]any{ + "titulo": "Sistema de Captación y Seguimiento Comercial", + "subtitulo": "Propuesta diseñada para eliminar fugas de prospectos y multiplicar conversiones.", + }, + "citaDestacadaId": "C01", + "alcance": []map[string]any{ + {"refPartida": "P01", "descripcionResultado": "Diagnóstico completo para detectar cuellos de botella en captación."}, + }, + "beneficios": []map[string]any{ + {"etiqueta": "Cero leads perdidos", "texto": "Cada consulta entra automáticamente al embudo con recordatorios.", "hallazgoId": "D01"}, + }, + "exclusiones": []map[string]any{ + {"texto": "No incluye inversión en pauta publicitaria de Meta o Google.", "razon": "El cliente paga directo a la plataforma"}, + }, + "backlogEvolucion": []map[string]any{ + {"problema": "Integración con ERP contable", "momentoSugerido": "Trimestre 2"}, + }, + "notasInternas": []string{"NO_ENVIAR_SECRETO_ASESOR: negociar alcance antes de dar descuento"}, + }, + } + + economia := map[string]any{ + "partidas": []map[string]any{ + {"refPartida": "P01", "nombre": "Auditoría Comercial", "fase": 0, "tipoPago": "unico", "precio": 8000.0, "tiempoEntrega": "7 días", "entregables": []string{"Mapa de embudo"}}, + {"refPartida": "P02", "nombre": "Implementación CRM", "fase": 1, "tipoPago": "unico", "precio": 22000.0, "tiempoEntrega": "15 días", "entregables": []string{"Flujos", "Capacitación"}}, + }, + "planBucefalo": map[string]any{"nivel": "estandar", "precio": 3500.0}, + "totales": map[string]any{ + "subtotalUnico": 30000.0, + "subtotalMensual": 3500.0, + "ivaUnico": 4800.0, + "ivaMensual": 560.0, + "totalUnico": 34800.0, + "totalMensual": 4060.0, + "totalPrimerAnio": 83520.0, + "incluyeIva": true, + }, + "moneda": "MXN", + "asesor": "Uriel Jareth", + } + + in := PropuestaPDFInput{ + CotizacionNumero: "UJ2606UR010", + ClienteNombre: "Roberto Peña", + ClienteEmpresa: "Peña Industrial", + Proyecto: "CRM y Captación", + Moneda: "MXN", + Fecha: time.Date(2026, 6, 10, 12, 0, 0, 0, time.UTC), + Contenido: contenido, + Economia: economia, + ColorPrimario: "#0400C4", + ColorSecundario: "#0F172A", + LogoBase64: makePNGLogoB64(t), + LogoMime: "image/png", + } + + propPDF, err := GenerarPropuestaPDF(in) + if err != nil { + t.Fatalf("GenerarPropuestaPDF error: %v", err) + } + assertValidPDF(t, propPDF, 1) + + anexoPDF, err := GenerarAnexoInternoPDF(in) + if err != nil { + t.Fatalf("GenerarAnexoInternoPDF error: %v", err) + } + assertValidPDF(t, anexoPDF, 1) + + // Empty maps should also succeed safely. + emptyIn := PropuestaPDFInput{ + CotizacionNumero: "UJ2606UR011", + ClienteNombre: "Cliente Vacío", + Proyecto: "Proyecto Mínimo", + } + if out, err := GenerarPropuestaPDF(emptyIn); err != nil { + t.Fatalf("empty GenerarPropuestaPDF error: %v", err) + } else { + assertValidPDF(t, out, 1) + } + if out, err := GenerarAnexoInternoPDF(emptyIn); err != nil { + t.Fatalf("empty GenerarAnexoInternoPDF error: %v", err) + } else { + assertValidPDF(t, out, 1) + } +} + +func TestCalcularRatioPropuesta(t *testing.T) { + if r := calcularRatioPropuesta(10000, nil); r != nil { + t.Fatalf("expected nil for nil valorAnual") + } + if r := calcularRatioPropuesta(10000, f64(0)); r != nil { + t.Fatalf("expected nil for zero valorAnual") + } + cases := []struct { + total, valor float64 + want string + }{ + {5000, 100000, "subcotizado"}, + {20000, 100000, "en_rango"}, + {35000, 100000, "alto"}, + {50000, 100000, "objecion_probable"}, + } + for _, tc := range cases { + r := calcularRatioPropuesta(tc.total, f64(tc.valor)) + if r == nil || r.Lectura != tc.want { + t.Fatalf("calcularRatioPropuesta(%v,%v) = %+v, want %q", tc.total, tc.valor, r, tc.want) + } + } +} diff --git a/internal/pdf/propuesta.go b/internal/pdf/propuesta.go new file mode 100644 index 0000000..a50804b --- /dev/null +++ b/internal/pdf/propuesta.go @@ -0,0 +1,739 @@ +package pdf + +import ( + "encoding/json" + "fmt" + "math" + "strings" + "time" + + "cotizador/internal/domain" +) + +type PropuestaPDFInput struct { + CotizacionNumero string + ClienteNombre string + ClienteEmpresa string + Proyecto string + Moneda string + Fecha time.Time + Contenido map[string]any + Economia map[string]any + ColorPrimario string + ColorSecundario string + LogoBase64 string + LogoMime string +} + +// Internal typed shapes mirroring src/lib/propuesta/schemas.ts and economia.ts. +type propuestaContenido struct { + Hechos struct { + Citas []struct { + ID string `json:"id"` + TextoLiteral string `json:"textoLiteral"` + QuienLoDijo string `json:"quienLoDijo"` + } `json:"citas"` + MaterialesPendientes []struct { + Texto string `json:"texto"` + BloqueaEntrega bool `json:"bloqueaEntrega"` + } `json:"materialesPendientes"` + DecisionesPendientes []struct { + Texto string `json:"texto"` + QuienDecide string `json:"quienDecide"` + } `json:"decisionesPendientes"` + MencionesFueraDeAlcance []string `json:"mencionesFueraDeAlcance"` + RedFlags []struct { + Senal string `json:"senal"` + Severidad string `json:"severidad"` + } `json:"redFlags"` + } `json:"hechos"` + Diagnostico struct { + Hallazgos []struct { + ID string `json:"id"` + Urgencia string `json:"urgencia"` + Titulo string `json:"titulo"` + Descripcion string `json:"descripcion"` + Confianza string `json:"confianza"` + } `json:"hallazgos"` + ValorProblema struct { + Dimensiones []struct { + Tipo string `json:"tipo"` + Descripcion string `json:"descripcion"` + Factores []struct { + Nombre string `json:"nombre"` + Valor float64 `json:"valor"` + Confianza string `json:"confianza"` + } `json:"factores"` + MontoAnualMXN *float64 `json:"montoAnualMXN"` + Confianza string `json:"confianza"` + } `json:"dimensiones"` + NotaMetodologia string `json:"notaMetodologia"` + } `json:"valorProblema"` + Resultados []struct { + Enunciado string `json:"enunciado"` + Metrica string `json:"metrica"` + LineaBase *string `json:"lineaBase"` + PeriodoMedicion string `json:"periodoMedicion"` + } `json:"resultados"` + } `json:"diagnostico"` + Redaccion struct { + Hero struct { + Titulo string `json:"titulo"` + Subtitulo string `json:"subtitulo"` + } `json:"hero"` + CitaDestacadaID string `json:"citaDestacadaId"` + Alcance []struct { + RefPartida string `json:"refPartida"` + DescripcionResultado string `json:"descripcionResultado"` + } `json:"alcance"` + Beneficios []struct { + Etiqueta string `json:"etiqueta"` + Texto string `json:"texto"` + HallazgoID string `json:"hallazgoId"` + } `json:"beneficios"` + Exclusiones []struct { + Texto string `json:"texto"` + Razon string `json:"razon"` + } `json:"exclusiones"` + BacklogEvolucion []struct { + Problema string `json:"problema"` + MomentoSugerido string `json:"momentoSugerido"` + } `json:"backlogEvolucion"` + NotasInternas []string `json:"notasInternas"` + } `json:"redaccion"` +} + +type propuestaPartida struct { + RefPartida string `json:"refPartida"` + Nombre string `json:"nombre"` + Fase int `json:"fase"` + TipoPago string `json:"tipoPago"` + Precio float64 `json:"precio"` + TiempoEntrega string `json:"tiempoEntrega"` + ModeloCobro string `json:"modeloCobro"` + Entregables []string `json:"entregables"` +} + +type propuestaEconomia struct { + Partidas []propuestaPartida `json:"partidas"` + Totales struct { + SubtotalUnico float64 `json:"subtotalUnico"` + SubtotalMensual float64 `json:"subtotalMensual"` + IVAUnico float64 `json:"ivaUnico"` + IVAMensual float64 `json:"ivaMensual"` + TotalUnico float64 `json:"totalUnico"` + TotalMensual float64 `json:"totalMensual"` + TotalPrimerAnio float64 `json:"totalPrimerAnio"` + IncluyeIVA bool `json:"incluyeIva"` + } `json:"totales"` + Moneda string `json:"moneda"` + Asesor string `json:"asesor"` + PlanBucefalo *struct { + Nivel string `json:"nivel"` + Precio float64 `json:"precio"` + } `json:"planBucefalo"` +} + +func decodeMapInto[T any](src map[string]any) T { + var out T + if len(src) == 0 { + return out + } + b, err := json.Marshal(src) + if err != nil { + return out + } + _ = json.Unmarshal(b, &out) + return out +} + +var ( + colorSemaforo = map[string]string{ + "rojo": "#dc2626", + "ambar": "#d97706", + "azul": "#0400C4", + "verde": "#16a34a", + } + etiquetaSemaforo = map[string]string{ + "rojo": "Problema crítico", + "ambar": "Área de mejora", + "azul": "Oportunidad", + "verde": "Ventaja existente", + } + etiquetaConfianza = map[string]string{ + "confirmado": "Confirmado", + "estimado": "Estimado", + "por_validar": "Por validar", + } +) + +func detalleDePartida(p propuestaPartida) string { + var trozos []string + if len(p.Entregables) > 0 { + limit := len(p.Entregables) + if limit > 4 { + limit = 4 + } + trozos = append(trozos, strings.Join(p.Entregables[:limit], " · ")) + } + if strings.TrimSpace(p.TiempoEntrega) != "" { + trozos = append(trozos, "Entrega: "+p.TiempoEntrega) + } + if p.TipoPago == "mensual" { + trozos = append(trozos, "Servicio mensual") + } + return strings.Join(trozos, " | ") +} + +type ratioResult struct { + Ratio float64 + Lectura string +} + +func calcularRatioPropuesta(totalPrimerAnio float64, valorAnual *float64) *ratioResult { + if valorAnual == nil || *valorAnual <= 0 { + return nil + } + ratio := totalPrimerAnio / *valorAnual + lectura := "objecion_probable" + switch { + case ratio < 0.1: + lectura = "subcotizado" + case ratio <= 0.25: + lectura = "en_rango" + case ratio <= 0.4: + lectura = "alto" + } + return &ratioResult{ + Ratio: math.Round(ratio*1000) / 1000, + Lectura: lectura, + } +} + +func GenerarPropuestaPDF(in PropuestaPDFInput) ([]byte, error) { + primary := safeHex(in.ColorPrimario, defaultPrimary) + dark := safeHex(in.ColorSecundario, defaultDark) + muted := colorMuted + border := "#e2e8f0" + + prop := decodeMapInto[propuestaContenido](in.Contenido) + econ := decodeMapInto[propuestaEconomia](in.Economia) + + moneda := in.Moneda + if moneda == "" { + moneda = econ.Moneda + } + fmtMoney := func(n float64) string { + return formatMoney(n, moneda) + } + + fecha := in.Fecha + if fecha.IsZero() { + fecha = time.Now() + } + vigencia := domain.CalcularVigencia(fecha) + clienteDisplay := in.ClienteEmpresa + if strings.TrimSpace(clienteDisplay) == "" { + clienteDisplay = in.ClienteNombre + } + + c := newCanvas(50, 55, 50, 50) + c.doc.AliasNbPages("{nb}") + logo := registerLogo(c.doc, "prop_logo", in.LogoBase64, in.LogoMime) + + c.doc.SetFooterFunc(func() { + c.hLine(c.L, c.L+c.W, c.ph-42, border, 0.5) + leftTxt := fmt.Sprintf("%s · Propuesta consultiva · %s", in.CotizacionNumero, clienteDisplay) + c.drawSingleLine(leftTxt, c.L, c.ph-35, c.W-60, "", 7, muted, "L") + rightTxt := fmt.Sprintf("%d / {nb}", c.doc.PageNo()) + c.drawSingleLine(rightTxt, c.L, c.ph-35, c.W, "", 7, muted, "R") + }) + + c.doc.AddPage() + y := c.mTop + + titulo := func(t string) { + y = c.need(26, y) + c.rectFill(c.L, y+1, 3, 10, primary) + c.drawSingleLine(strings.ToUpper(t), c.L+10, y, c.W-10, "B", 10, dark, "L") + y += 20 + } + parrafo := func(t string, size float64, color string) { + raw := strings.ReplaceAll(t, "\r\n", "\n") + for _, p := range strings.Split(raw, "\n") { + p = strings.TrimSpace(p) + if p == "" { + continue + } + h := c.textHeight(p, c.W, "", size) + y = c.need(h+4, y) + c.drawText(p, c.L, y, c.W, "", size, color, "L") + y += h + 4 + } + } + + // ── HERO ── + if logo.ok { + logo.drawByHeight(c.doc, c.L, y, 26) + y += 34 + } + c.drawSingleLine("PROPUESTA CONSULTIVA", c.L, y, c.W, "B", 8.5, primary, "L") + y += 16 + + heroTit := strings.TrimSpace(prop.Redaccion.Hero.Titulo) + if heroTit == "" { + heroTit = in.Proyecto + } + if heroTit != "" { + hTit := c.drawText(heroTit, c.L, y, c.W, "B", 20, dark, "L") + y += hTit + 8 + } + if strings.TrimSpace(prop.Redaccion.Hero.Subtitulo) != "" { + parrafo(prop.Redaccion.Hero.Subtitulo, 10, muted) + y += 8 + } + + metaParts := []string{ + clienteDisplay, + in.CotizacionNumero, + domain.FormatDateShort(fecha), + "Vigencia " + domain.FormatDateShort(vigencia), + } + if strings.TrimSpace(econ.Asesor) != "" { + metaParts = append(metaParts, econ.Asesor) + } + meta := strings.Join(metaParts, " · ") + hMeta := c.drawText(meta, c.L, y, c.W, "", 8, muted, "L") + y += hMeta + 12 + c.hLine(c.L, c.L+c.W, y, border, 0.5) + y += 18 + + // ── DIAGNÓSTICO ── + if len(prop.Diagnostico.Hallazgos) > 0 || prop.Redaccion.CitaDestacadaID != "" { + titulo("Diagnóstico") + for _, cita := range prop.Hechos.Citas { + if cita.ID != "" && cita.ID == prop.Redaccion.CitaDestacadaID { + texto := fmt.Sprintf("\"%s\"", cita.TextoLiteral) + h := c.textHeight(texto, c.W-22, "I", 11) + y = c.need(h+22, y) + c.rectFill(c.L, y-3, 2.5, h+10, primary) + c.drawText(texto, c.L+12, y, c.W-22, "I", 11, dark, "L") + y += h + 4 + c.drawSingleLine("— "+cita.QuienLoDijo, c.L+12, y, c.W-22, "", 7.5, muted, "L") + y += 18 + break + } + } + for _, hal := range prop.Diagnostico.Hallazgos { + cuerpo := fmt.Sprintf("%s — %s", hal.Titulo, hal.Descripcion) + h := c.textHeight(cuerpo, c.W-24, "", 9) + y = c.need(h+16, y) + dotColor := colorSemaforo[hal.Urgencia] + if dotColor == "" { + dotColor = muted + } + c.circleFill(c.L+4.5, y+5, 3.2, dotColor) + c.drawText(cuerpo, c.L+16, y, c.W-24, "", 9, dark, "L") + y += h + 1 + subLbl := fmt.Sprintf("%s · %s", etiquetaSemaforo[hal.Urgencia], etiquetaConfianza[hal.Confianza]) + c.drawSingleLine(subLbl, c.L+16, y, c.W-24, "", 7, muted, "L") + y += 13 + } + y += 8 + } + + // ── VALOR DEL PROBLEMA ── + dims := prop.Diagnostico.ValorProblema.Dimensiones + if len(dims) > 0 { + titulo("Lo que cuesta no resolverlo") + for _, dim := range dims { + montoTxt := "sin cuantificar" + if dim.MontoAnualMXN != nil { + montoTxt = fmt.Sprintf("%s al año", fmtMoney(*dim.MontoAnualMXN)) + } + linea := fmt.Sprintf("%s — %s", dim.Descripcion, montoTxt) + h := c.textHeight(linea, c.W-14, "", 9) + y = c.need(h+14, y) + c.drawText(linea, c.L+6, y, c.W-14, "", 9, dark, "L") + y += h + 1 + c.drawSingleLine(etiquetaConfianza[dim.Confianza], c.L+6, y, c.W-14, "", 7, muted, "L") + y += 13 + } + if strings.TrimSpace(prop.Diagnostico.ValorProblema.NotaMetodologia) != "" { + y += 2 + parrafo(prop.Diagnostico.ValorProblema.NotaMetodologia, 8, muted) + } + y += 8 + } + + // ── RESULTADOS ── + if len(prop.Diagnostico.Resultados) > 0 { + titulo("Resultados a lograr") + for _, r := range prop.Diagnostico.Resultados { + t := fmt.Sprintf("• %s (%s, %s)", r.Enunciado, r.Metrica, r.PeriodoMedicion) + h := c.textHeight(t, c.W-8, "", 9) + y = c.need(h+6, y) + c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L") + y += h + 6 + } + y += 8 + } + + // ── ALCANCE ── + titulo("Alcance de la inversión") + descPorRef := make(map[string]string, len(prop.Redaccion.Alcance)) + for _, a := range prop.Redaccion.Alcance { + descPorRef[a.RefPartida] = a.DescripcionResultado + } + for _, p := range econ.Partidas { + descripcion := descPorRef[p.RefPartida] + respaldo := "" + if descripcion == "" { + respaldo = detalleDePartida(p) + } + hNombre := c.textHeight(p.Nombre, c.W*0.68, "B", 9.5) + subTxt := descripcion + if subTxt == "" { + subTxt = respaldo + } + hDesc := 0.0 + if subTxt != "" { + hDesc = c.textHeight(subTxt, c.W*0.68, "", 8) + } + y = c.need(hNombre+hDesc+14, y) + c.drawText(p.Nombre, c.L, y, c.W*0.68, "B", 9.5, dark, "L") + c.drawSingleLine(fmtMoney(p.Precio), c.L+c.W*0.7, y, c.W*0.3, "B", 9.5, primary, "R") + y += hNombre + 2 + if subTxt != "" { + c.drawText(subTxt, c.L, y, c.W*0.68, "", 8, muted, "L") + y += hDesc + 10 + } else { + y += 8 + } + } + + if econ.PlanBucefalo != nil && strings.TrimSpace(econ.PlanBucefalo.Nivel) != "" { + etiqueta := "CRM Bucéfalo — plan " + capitalize(econ.PlanBucefalo.Nivel) + hE := c.textHeight(etiqueta, c.W*0.68, "B", 9.5) + y = c.need(hE+22, y) + c.drawText(etiqueta, c.L, y, c.W*0.68, "B", 9.5, dark, "L") + c.drawSingleLine(fmtMoney(econ.PlanBucefalo.Precio)+" / mes", c.L+c.W*0.7, y, c.W*0.3, "B", 9.5, primary, "R") + y += hE + 2 + c.drawSingleLine("Servicio mensual", c.L, y, c.W*0.68, "", 8, muted, "L") + y += 20 + } + + y = c.need(58, y) + c.hLine(c.L, c.L+c.W, y, border, 0.5) + y += 10 + + // ── CAJA DE TOTALES ── + tot := econ.Totales + fila := func(etiqueta, valor string, fuerte bool) { + step := 15.0 + size := 9.0 + lblStyle := "" + lblColor := muted + valColor := dark + if fuerte { + step = 18.0 + size = 10.5 + lblStyle = "B" + lblColor = dark + valColor = primary + } + y = c.need(step, y) + c.drawSingleLine(etiqueta, c.L, y, c.W*0.6, lblStyle, size, lblColor, "L") + c.drawSingleLine(valor, c.L+c.W*0.6, y, c.W*0.4, "B", size, valColor, "R") + y += step + } + + if tot.SubtotalUnico > 0 { + fila("Subtotal pago único", fmtMoney(tot.SubtotalUnico), false) + if tot.IncluyeIVA { + fila("IVA 16%", fmtMoney(tot.IVAUnico), false) + fila("Total pago único", fmtMoney(tot.TotalUnico), true) + } else { + fila("Total pago único (sin IVA)", fmtMoney(tot.TotalUnico), true) + } + } + if tot.SubtotalMensual > 0 { + if tot.SubtotalUnico > 0 { + y += 4 + } + fila("Subtotal mensual", fmtMoney(tot.SubtotalMensual), false) + if tot.IncluyeIVA { + fila("IVA 16%", fmtMoney(tot.IVAMensual), false) + fila("Total mensual", fmtMoney(tot.TotalMensual), true) + } else { + fila("Total mensual (sin IVA)", fmtMoney(tot.TotalMensual), true) + } + } + + y = c.need(20, y) + notaIVA := "Los precios son en Moneda Nacional (MXN) y no incluyen IVA. Facturación CFDI." + if tot.IncluyeIVA { + notaIVA = "Los precios por partida son en Moneda Nacional (MXN) y no incluyen IVA; el IVA se desglosa arriba. Facturación CFDI." + } + hNota := c.drawText(notaIVA, c.L, y, c.W, "", 7.5, muted, "L") + y += hNota + 16 + + // ── BENEFICIOS ── + if len(prop.Redaccion.Beneficios) > 0 { + titulo("Por qué tiene sentido") + for _, b := range prop.Redaccion.Beneficios { + hEt := c.textHeight(b.Etiqueta, c.W*0.24, "B", 9) + hTx := c.textHeight(b.Texto, c.W*0.72, "", 8.5) + h := hEt + if hTx > h { + h = hTx + } + y = c.need(h+9, y) + c.drawText(b.Etiqueta, c.L, y, c.W*0.24, "B", 9, dark, "L") + c.drawText(b.Texto, c.L+c.W*0.27, y, c.W*0.72, "", 8.5, muted, "L") + y += h + 9 + } + y += 8 + } + + // ── EXCLUSIONES ── + if len(prop.Redaccion.Exclusiones) > 0 { + titulo("Qué no incluye esta propuesta") + for _, e := range prop.Redaccion.Exclusiones { + t2 := "× " + e.Texto + h := c.textHeight(t2, c.W-8, "", 8.5) + y = c.need(h+6, y) + c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, dark, "L") + y += h + 6 + } + y += 10 + } + + // ── PENDIENTES ── + mats := prop.Hechos.MaterialesPendientes + decs := prop.Hechos.DecisionesPendientes + if len(mats) > 0 || len(decs) > 0 { + titulo("Qué necesitamos de ustedes") + for _, mm := range mats { + suffix := "" + if mm.BloqueaEntrega { + suffix = " (el avance queda condicionado a esto)" + } + t2 := "○ " + mm.Texto + suffix + h := c.textHeight(t2, c.W-8, "", 8.5) + y = c.need(h+6, y) + c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, dark, "L") + y += h + 6 + } + for _, dd := range decs { + t2 := fmt.Sprintf("· %s (decide: %s)", dd.Texto, dd.QuienDecide) + h := c.textHeight(t2, c.W-8, "", 8.5) + y = c.need(h+6, y) + c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, muted, "L") + y += h + 6 + } + y += 10 + } + + // ── BACKLOG ── + if len(prop.Redaccion.BacklogEvolucion) > 0 { + titulo("Registrado para más adelante") + y = c.need(14, y) + c.drawSingleLine("No comprometido en esta propuesta.", c.L, y, c.W, "I", 7.5, muted, "L") + y += 14 + for _, b := range prop.Redaccion.BacklogEvolucion { + t2 := fmt.Sprintf("· %s (%s)", b.Problema, b.MomentoSugerido) + h := c.textHeight(t2, c.W-8, "", 8.5) + y = c.need(h+6, y) + c.drawText(t2, c.L+4, y, c.W-8, "", 8.5, dark, "L") + y += h + 6 + } + } + + return c.bytes() +} + +// GenerarAnexoInternoPDF renders the internal-only advisor annex as a separate document +// with an unmistakable red banner so it can never be confused with the client proposal. +func GenerarAnexoInternoPDF(in PropuestaPDFInput) ([]byte, error) { + prop := decodeMapInto[propuestaContenido](in.Contenido) + econ := decodeMapInto[propuestaEconomia](in.Economia) + + moneda := in.Moneda + if moneda == "" { + moneda = econ.Moneda + } + fmtMoney := func(n float64) string { + return formatMoney(n, moneda) + } + + dark := defaultDark + muted := colorMuted + redBanner := "#b91c1c" + + c := newCanvas(50, 55, 50, 50) + c.doc.AddPage() + + c.rectFill(0, 0, c.pw, 36, redBanner) + c.drawSingleLine("USO INTERNO — NO ENVIAR AL CLIENTE", c.L, 11, c.W, "B", 13, colorWhite, "L") + y := 56.0 + + clienteDisplay := in.ClienteEmpresa + if strings.TrimSpace(clienteDisplay) == "" { + clienteDisplay = in.ClienteNombre + } + metaParts := []string{in.CotizacionNumero, clienteDisplay} + if strings.TrimSpace(econ.Asesor) != "" { + metaParts = append(metaParts, econ.Asesor) + } + c.drawSingleLine(strings.Join(metaParts, " · "), c.L, y, c.W, "", 9, muted, "L") + y += 24 + + var valorAnualSum float64 + for _, dim := range prop.Diagnostico.ValorProblema.Dimensiones { + if dim.MontoAnualMXN != nil { + valorAnualSum += *dim.MontoAnualMXN + } + } + var valorAnual *float64 + if valorAnualSum > 0 { + v := valorAnualSum + valorAnual = &v + } + r := calcularRatioPropuesta(econ.Totales.TotalPrimerAnio, valorAnual) + + seccion := func(t string) { + y = c.need(24, y) + c.drawSingleLine(t, c.L, y, c.W, "B", 11, dark, "L") + y += 18 + } + linea := func(k, v string) { + y = c.need(15, y) + c.drawSingleLine(k, c.L, y, c.W*0.5, "", 9, muted, "L") + c.drawSingleLine(v, c.L+c.W*0.5, y, c.W*0.5, "B", 9, dark, "R") + y += 15 + } + + confirmados := 0 + for _, h := range prop.Diagnostico.Hallazgos { + if h.Confianza == "confirmado" { + confirmados++ + } + } + + valorAnualTxt := "sin cuantificar" + if valorAnual != nil { + valorAnualTxt = fmtMoney(*valorAnual) + } + ratioTxt := "no calculable" + if r != nil { + ratioTxt = fmt.Sprintf("%.1f%% — %s", r.Ratio*100, strings.ReplaceAll(r.Lectura, "_", " ")) + } + + seccion("Ponderación de la cotización") + linea("Inversión del primer año", fmtMoney(econ.Totales.TotalPrimerAnio)) + linea("Valor anual del problema", valorAnualTxt) + linea("Ratio precio / valor", ratioTxt) + linea("Hallazgos en el diagnóstico", fmt.Sprintf("%d", len(prop.Diagnostico.Hallazgos))) + linea("Cifras confirmadas", fmt.Sprintf("%d", confirmados)) + linea("Exclusiones definidas", fmt.Sprintf("%d", len(prop.Redaccion.Exclusiones))) + linea("Materiales pendientes", fmt.Sprintf("%d", len(prop.Hechos.MaterialesPendientes))) + linea("Decisiones pendientes", fmt.Sprintf("%d", len(prop.Hechos.DecisionesPendientes))) + linea("Red flags detectadas", fmt.Sprintf("%d", len(prop.Hechos.RedFlags))) + y += 6 + + if len(prop.Diagnostico.ValorProblema.Dimensiones) > 0 { + seccion("De dónde sale el valor anual") + sinConfirmar := false + for _, dim := range prop.Diagnostico.ValorProblema.Dimensiones { + montoTxt := "sin cifra" + if dim.MontoAnualMXN != nil { + montoTxt = fmtMoney(*dim.MontoAnualMXN) + } + y = c.need(14, y) + c.drawSingleLine(fmt.Sprintf("%s: %s", dim.Tipo, montoTxt), c.L, y, c.W, "B", 9, dark, "L") + y += 13 + hasConfirmed := false + if len(dim.Factores) > 0 { + partes := make([]string, 0, len(dim.Factores)) + for _, f := range dim.Factores { + if f.Confianza == "confirmado" { + hasConfirmed = true + } + partes = append(partes, fmt.Sprintf("%s = %g (%s)", f.Nombre, f.Valor, f.Confianza)) + } + desglose := strings.Join(partes, " x ") + h := c.textHeight(desglose, c.W-10, "", 8) + y = c.need(h+8, y) + c.drawText(desglose, c.L+6, y, c.W-10, "", 8, muted, "L") + y += h + 8 + } + if dim.MontoAnualMXN != nil && !hasConfirmed { + sinConfirmar = true + } + } + if sinConfirmar { + alerta := "Ojo: hay una cifra que descansa entera en factores estimados. Antes de fiarte del ratio, revisa que no falte un factor — la aritmética puede cuadrar y aun así estar inflada." + h := c.textHeight(alerta, c.W, "B", 8.5) + y = c.need(h+12, y) + c.drawText(alerta, c.L, y, c.W, "B", 8.5, redBanner, "L") + y += h + 14 + } + y += 4 + } + + if r != nil { + var nota string + switch r.Lectura { + case "subcotizado": + nota = "La inversión es menos del 10% de lo que el problema le cuesta al cliente cada año. Probablemente subcotizaste." + case "objecion_probable": + nota = "La inversión supera el 40% del valor anual del problema. Prepara la conversación de precio: se responde con alcance, no con descuento." + case "alto": + nota = "La inversión está en la banda alta. Justificable, pero conviene anclar bien el valor antes de dar el número." + default: + nota = "La inversión cae en el rango de referencia (15-25% del valor anual)." + } + h := c.textHeight(nota, c.W, "I", 8.5) + y = c.need(h+12, y) + c.drawText(nota, c.L, y, c.W, "I", 8.5, muted, "L") + y += h + 16 + } + + if len(prop.Hechos.RedFlags) > 0 { + seccion("Red flags") + for _, rf := range prop.Hechos.RedFlags { + t := fmt.Sprintf("· [%s] %s", rf.Severidad, rf.Senal) + h := c.textHeight(t, c.W-8, "", 9) + y = c.need(h+6, y) + c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L") + y += h + 6 + } + y += 10 + } + + if len(prop.Redaccion.NotasInternas) > 0 { + seccion("Notas para el asesor") + for _, n := range prop.Redaccion.NotasInternas { + t := "· " + n + h := c.textHeight(t, c.W-8, "", 9) + y = c.need(h+6, y) + c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L") + y += h + 6 + } + y += 10 + } + + if len(prop.Hechos.MencionesFueraDeAlcance) > 0 { + seccion("Se mencionó y quedó fuera") + for _, m := range prop.Hechos.MencionesFueraDeAlcance { + t := "· " + m + h := c.textHeight(t, c.W-8, "", 9) + y = c.need(h+6, y) + c.drawText(t, c.L+4, y, c.W-8, "", 9, dark, "L") + y += h + 6 + } + } + + return c.bytes() +} diff --git a/internal/propuesta/cliente_ia.go b/internal/propuesta/cliente_ia.go new file mode 100644 index 0000000..49d3e81 --- /dev/null +++ b/internal/propuesta/cliente_ia.go @@ -0,0 +1,476 @@ +package propuesta + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "regexp" + "strings" + "time" + + "cotizador/internal/config" +) + +const ( + DefaultMinimaxBaseURL = "https://api.minimax.io/anthropic" + DefaultMinimaxModel = "MiniMax-M3" + anthropicVersion = "2023-06-01" + maxTransitoriosDef = 3 +) + +// UsoTokens acumula el consumo de tokens reportado por el endpoint de mensajes. +type UsoTokens struct { + Entrada int `json:"entrada"` + Salida int `json:"salida"` + CacheLectura int `json:"cacheLectura"` + CacheEscritura int `json:"cacheEscritura"` +} + +// BloqueSystem representa un bloque del prompt de sistema con cache opcional. +type BloqueSystem struct { + Texto string + Cachear bool +} + +// Herramienta define la herramienta de salida estructurada para tool-calling. +type Herramienta struct { + Nombre string + Descripcion string + InputSchema map[string]any + Validar func(datos map[string]any) []string +} + +// OpcionesLlamada configura una invocacion con tool-calling y bucle de validacion. +type OpcionesLlamada struct { + System []BloqueSystem + MensajeUsuario string + Herramienta Herramienta + MaxIntentos int + MaxTokens int +} + +// ResultadoLlamada contiene la salida validada, el uso acumulado y los intentos. +type ResultadoLlamada struct { + Datos map[string]any + Uso UsoTokens + Intentos int +} + +// ClienteIA habla con el endpoint compatible con Anthropic Messages de MiniMax +// usando net/http puro (sin SDK externo). +type ClienteIA struct { + APIKey string + BaseURL string + Model string + HTTPClient *http.Client + Sleep func(ctx context.Context, d time.Duration) error +} + +// NuevoClienteIA construye el cliente de MiniMax leyendo MINIMAX_API_KEY, +// MINIMAX_BASE_URL y MINIMAX_MODEL (desde cfg si se pasa, o desde el entorno). +// Rechaza explicitamente una clave vacia y advierte cuando solo ANTHROPIC_API_KEY +// esta presente para evitar enviar credenciales al proveedor equivocado. +func NuevoClienteIA(cfg *config.Config) (*ClienteIA, error) { + var apiKey, baseURL, model string + if cfg != nil { + apiKey = strings.TrimSpace(cfg.MinimaxAPIKey) + baseURL = strings.TrimSpace(cfg.MinimaxBaseURL) + model = strings.TrimSpace(cfg.MinimaxModel) + } else { + apiKey = strings.TrimSpace(os.Getenv("MINIMAX_API_KEY")) + baseURL = strings.TrimSpace(os.Getenv("MINIMAX_BASE_URL")) + model = strings.TrimSpace(os.Getenv("MINIMAX_MODEL")) + } + + if apiKey == "" { + if strings.TrimSpace(os.Getenv("ANTHROPIC_API_KEY")) != "" { + return nil, errors.New( + "Falta MINIMAX_API_KEY (se detecto ANTHROPIC_API_KEY en el entorno, pero NO se usa para evitar mandar credenciales al proveedor equivocado). Define MINIMAX_API_KEY en .env.", + ) + } + return nil, errors.New( + "Falta MINIMAX_API_KEY. Definela en .env. No uses ANTHROPIC_API_KEY: la clave de MiniMax nunca debe enviarse a api.anthropic.com.", + ) + } + + if baseURL == "" { + baseURL = DefaultMinimaxBaseURL + } + baseURL = strings.TrimRight(baseURL, "/") + + if model == "" { + model = DefaultMinimaxModel + } + + return &ClienteIA{ + APIKey: apiKey, + BaseURL: baseURL, + Model: model, + HTTPClient: &http.Client{ + Timeout: 120 * time.Second, + }, + Sleep: sleepContext, + }, nil +} + +// NormalizarRespuesta corrige rarezas observadas en las respuestas de MiniMax +// antes de validar: a veces envuelve elementos de arrays en `{item: {...}}`. +// Solo desenvuelve cuando "item" es la UNICA clave del objeto. +func NormalizarRespuesta(v any) any { + switch val := v.(type) { + case []any: + out := make([]any, len(val)) + for i, elem := range val { + out[i] = NormalizarRespuesta(elem) + } + return out + case map[string]any: + if len(val) == 1 { + if inner, ok := val["item"]; ok { + return NormalizarRespuesta(inner) + } + } + out := make(map[string]any, len(val)) + for k, elem := range val { + out[k] = NormalizarRespuesta(elem) + } + return out + default: + return v + } +} + +type apiCacheControl struct { + Type string `json:"type"` +} + +type apiSystemBlock struct { + Type string `json:"type"` + Text string `json:"text"` + CacheControl *apiCacheControl `json:"cache_control,omitempty"` +} + +type apiTool struct { + Name string `json:"name"` + Description string `json:"description"` + InputSchema map[string]any `json:"input_schema"` +} + +type apiToolChoice struct { + Type string `json:"type"` + Name string `json:"name,omitempty"` +} + +type apiMessage struct { + Role string `json:"role"` + Content any `json:"content"` +} + +type apiRequest struct { + Model string `json:"model"` + MaxTokens int `json:"max_tokens"` + System []apiSystemBlock `json:"system,omitempty"` + Tools []apiTool `json:"tools,omitempty"` + ToolChoice *apiToolChoice `json:"tool_choice,omitempty"` + Messages []apiMessage `json:"messages"` +} + +type apiContentBlock struct { + Type string `json:"type"` + Text string `json:"text,omitempty"` + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Input any `json:"input,omitempty"` +} + +type apiUsage struct { + InputTokens int `json:"input_tokens"` + OutputTokens int `json:"output_tokens"` + CacheReadInputTokens int `json:"cache_read_input_tokens"` + CacheCreationInputTokens int `json:"cache_creation_input_tokens"` +} + +type apiResponse struct { + ID string `json:"id"` + Type string `json:"type"` + Role string `json:"role"` + Content []apiContentBlock `json:"content"` + StopReason string `json:"stop_reason"` + Usage apiUsage `json:"usage"` +} + +type apiHTTPError struct { + Status int + Body string +} + +func (e *apiHTTPError) Error() string { + return fmt.Sprintf("error HTTP %d del proveedor IA: %s", e.Status, e.Body) +} + +var ( + reTransitorio400 = regexp.MustCompile(`(?i)unexpected|internal|parse|unknown`) + reTransitorioRed = regexp.MustCompile(`(?i)ECONN|ETIMEDOUT|socket|network|connection reset|EOF|timeout`) +) + +func esTransitorio(err error) bool { + if err == nil { + return false + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return false + } + var httpErr *apiHTTPError + if errors.As(err, &httpErr) { + switch httpErr.Status { + case http.StatusRequestTimeout, http.StatusConflict, http.StatusTooManyRequests: + return true + } + if httpErr.Status >= 500 { + return true + } + if httpErr.Status == http.StatusBadRequest && reTransitorio400.MatchString(httpErr.Body) { + return true + } + return false + } + var netErr net.Error + if errors.As(err, &netErr) { + return true + } + return reTransitorioRed.MatchString(err.Error()) +} + +func sleepContext(ctx context.Context, d time.Duration) error { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil + } +} + +func (c *ClienteIA) crearMensaje(ctx context.Context, reqBody apiRequest) (*apiResponse, error) { + payload, err := json.Marshal(reqBody) + if err != nil { + return nil, fmt.Errorf("error serializando solicitud IA: %w", err) + } + + endpoint := strings.TrimRight(c.BaseURL, "/") + "/v1/messages" + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload)) + if err != nil { + return nil, fmt.Errorf("error creando solicitud HTTP: %w", err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("x-api-key", c.APIKey) + req.Header.Set("anthropic-version", anthropicVersion) + + httpClient := c.HTTPClient + if httpClient == nil { + httpClient = &http.Client{Timeout: 120 * time.Second} + } + + resp, err := httpClient.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + raw, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20)) + if err != nil { + return nil, err + } + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + bodyStr := strings.TrimSpace(string(raw)) + if len(bodyStr) > 1000 { + bodyStr = bodyStr[:1000] + } + return nil, &apiHTTPError{Status: resp.StatusCode, Body: bodyStr} + } + + var parsed apiResponse + if err := json.Unmarshal(raw, &parsed); err != nil { + return nil, fmt.Errorf("error decodificando respuesta IA: %w", err) + } + return &parsed, nil +} + +func (c *ClienteIA) crearMensajeConReintentos(ctx context.Context, reqBody apiRequest, maxTransitorios int) (*apiResponse, error) { + if maxTransitorios <= 0 { + maxTransitorios = maxTransitoriosDef + } + sleepFn := c.Sleep + if sleepFn == nil { + sleepFn = sleepContext + } + + var ultimo error + for i := 1; i <= maxTransitorios; i++ { + res, err := c.crearMensaje(ctx, reqBody) + if err == nil { + return res, nil + } + ultimo = err + if !esTransitorio(err) || i == maxTransitorios { + return nil, err + } + backoff := time.Duration(1<<(i-1)) * time.Second // 1s, 2s + if sleepErr := sleepFn(ctx, backoff); sleepErr != nil { + return nil, sleepErr + } + } + return nil, ultimo +} + +// LlamarConHerramienta invoca al modelo exigiendo una llamada a opts.Herramienta, +// normaliza rarezas de MiniMax, valida contra el contrato y reintenta devolviendo +// los errores exactos de validacion hasta opts.MaxIntentos. +func (c *ClienteIA) LlamarConHerramienta(ctx context.Context, opts OpcionesLlamada) (*ResultadoLlamada, error) { + maxIntentos := opts.MaxIntentos + if maxIntentos <= 0 { + maxIntentos = 3 + } + maxTokens := opts.MaxTokens + if maxTokens <= 0 { + maxTokens = 8000 + } + + systemBlocks := make([]apiSystemBlock, 0, len(opts.System)) + for _, b := range opts.System { + blk := apiSystemBlock{ + Type: "text", + Text: b.Texto, + } + if b.Cachear { + blk.CacheControl = &apiCacheControl{Type: "ephemeral"} + } + systemBlocks = append(systemBlocks, blk) + } + + tools := []apiTool{ + { + Name: opts.Herramienta.Nombre, + Description: opts.Herramienta.Descripcion, + InputSchema: opts.Herramienta.InputSchema, + }, + } + + toolChoice := &apiToolChoice{ + Type: "tool", + Name: opts.Herramienta.Nombre, + } + + mensajes := []apiMessage{ + {Role: "user", Content: opts.MensajeUsuario}, + } + + var uso UsoTokens + var ultimoError string + + for intento := 1; intento <= maxIntentos; intento++ { + res, err := c.crearMensajeConReintentos(ctx, apiRequest{ + Model: c.Model, + MaxTokens: maxTokens, + System: systemBlocks, + Tools: tools, + ToolChoice: toolChoice, + Messages: mensajes, + }, maxTransitoriosDef) + if err != nil { + return nil, err + } + + uso.Entrada += res.Usage.InputTokens + uso.Salida += res.Usage.OutputTokens + uso.CacheLectura += res.Usage.CacheReadInputTokens + uso.CacheEscritura += res.Usage.CacheCreationInputTokens + + var bloquesTool []apiContentBlock + var candidatos []apiContentBlock + for _, blk := range res.Content { + if blk.Type == "tool_use" { + bloquesTool = append(bloquesTool, blk) + if blk.Name == opts.Herramienta.Nombre { + candidatos = append(candidatos, blk) + } + } + } + + var primerFallo *apiContentBlock + for i := range candidatos { + cand := candidatos[i] + norm := NormalizarRespuesta(cand.Input) + datos, ok := norm.(map[string]any) + var errs []string + if !ok { + errs = []string{"La entrada de la herramienta debe ser un objeto JSON."} + } else if opts.Herramienta.Validar != nil { + errs = opts.Herramienta.Validar(datos) + } + if len(errs) == 0 { + return &ResultadoLlamada{ + Datos: datos, + Uso: uso, + Intentos: intento, + }, nil + } + if primerFallo == nil { + cp := cand + primerFallo = &cp + ultimoError = strings.Join(errs, "\n") + } + } + + if len(bloquesTool) > 0 { + if primerFallo == nil { + ultimoError = fmt.Sprintf("El modelo llamo a una herramienta inesperada. Usa %s.", opts.Herramienta.Nombre) + } + userBlocks := make([]any, 0, len(bloquesTool)+1) + for _, b := range bloquesTool { + content := fmt.Sprintf("Herramienta inesperada. Usa %s.", opts.Herramienta.Nombre) + if primerFallo != nil && b.ID == primerFallo.ID { + content = ultimoError + } + userBlocks = append(userBlocks, map[string]any{ + "type": "tool_result", + "tool_use_id": b.ID, + "is_error": true, + "content": content, + }) + } + userBlocks = append(userBlocks, map[string]any{ + "type": "text", + "text": fmt.Sprintf( + "La llamada no cumple el schema. Corrige EXACTAMENTE estos errores y vuelve a llamar a %s:\n\n%s\n\nRevisa que cada objeto este en el array que le corresponde y que no falte ningun campo obligatorio. No agregues campos que el schema no declara.", + opts.Herramienta.Nombre, + ultimoError, + ), + }) + mensajes = append(mensajes, + apiMessage{Role: "assistant", Content: res.Content}, + apiMessage{Role: "user", Content: userBlocks}, + ) + continue + } + + ultimoError = "El modelo respondio con prosa en vez de llamar a la herramienta." + mensajes = append(mensajes, + apiMessage{Role: "assistant", Content: res.Content}, + apiMessage{ + Role: "user", + Content: fmt.Sprintf("Debes responder llamando a la herramienta %s. No escribas prosa suelta.", opts.Herramienta.Nombre), + }, + ) + } + + return nil, fmt.Errorf("El paso %q agoto %d intentos.\nUltimo error:\n%s", opts.Herramienta.Nombre, maxIntentos, ultimoError) +} diff --git a/internal/propuesta/economia.go b/internal/propuesta/economia.go new file mode 100644 index 0000000..afa073e --- /dev/null +++ b/internal/propuesta/economia.go @@ -0,0 +1,224 @@ +package propuesta + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "math" + + "cotizador/internal/domain" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +// PartidaEconomia representa una linea cotizada canonica. +// Ref (P01, P02...) es lo unico que identifica la partida ante el modelo de IA; +// los precios e importes nunca viajan al prompt y solo los usa el renderizador +// o los calculos internos. +type PartidaEconomia struct { + Ref string `json:"refPartida"` + Nombre string `json:"nombre"` + Fase int `json:"fase"` + TipoPago string `json:"tipoPago"` + Precio float64 `json:"precio"` + TiempoEntrega string `json:"tiempoEntrega"` + Entregables []string `json:"entregables"` + ModeloCobro string `json:"modeloCobro"` + Horas *float64 `json:"horas"` + TarifaHora *float64 `json:"tarifaHora"` + MontoMinimo *float64 `json:"montoMinimo"` + HorasIncluidas *float64 `json:"horasIncluidas"` +} + +// RatioValor resume la lectura precio/valor del anexo interno. +type RatioValor struct { + Ratio float64 `json:"ratio"` + Etiqueta string `json:"etiqueta"` + Nota string `json:"nota"` +} + +// EconomiaCotizacion agrupa las partidas seleccionadas, el plan Bucefalo +// (si fue contratado) y los totales canonicos de la cotizacion. +type EconomiaCotizacion struct { + Partidas []PartidaEconomia `json:"partidas"` + PlanBucefalo *struct { + Nivel string `json:"nivel"` + Precio float64 `json:"precio"` + } `json:"planBucefalo"` + Totales domain.TotalesCotizacion `json:"totales"` + Moneda string `json:"moneda"` +} + +// CalcularRatio calcula el ratio precio/valor para el anexo interno comparando +// el desembolso total del primer ano contra el costo anual del problema del cliente. +// +// Cortes: +// - < 0.10: subcotizado +// - <= 0.25: en_rango +// - <= 0.40: alto +// - > 0.40: objecion_probable +func CalcularRatio(totalPrimerAnio, valorAnual float64) RatioValor { + if valorAnual <= 0 { + return RatioValor{ + Ratio: 0, + Etiqueta: "", + Nota: "Sin valor anual cuantificado del problema.", + } + } + + ratio := totalPrimerAnio / valorAnual + var etiqueta, nota string + switch { + case ratio < 0.10: + etiqueta = "subcotizado" + nota = "La inversion es menos del 10% de lo que el problema le cuesta al cliente cada ano. Probablemente subcotizaste." + case ratio <= 0.25: + etiqueta = "en_rango" + nota = "La inversion cae en el rango de referencia (15-25% del valor anual)." + case ratio <= 0.40: + etiqueta = "alto" + nota = "La inversion esta en la banda alta. Justificable, pero conviene anclar bien el valor antes de dar el numero." + default: + etiqueta = "objecion_probable" + nota = "La inversion supera el 40% del valor anual del problema. Prepara la conversacion de precio: se responde con alcance, no con descuento." + } + + return RatioValor{ + Ratio: math.Round(ratio*1000) / 1000, + Etiqueta: etiqueta, + Nota: nota, + } +} + +// CargarEconomiaCotizacion carga desde PostgreSQL las partidas seleccionadas, +// el plan Bucefalo (si aplica) y los totales canonicos de una cotizacion. +func CargarEconomiaCotizacion(ctx context.Context, pool *pgxpool.Pool, cotizacionID string) (*EconomiaCotizacion, error) { + if pool == nil { + return nil, errors.New("pool de base de datos no inicializado") + } + + var moneda string + var incluirIVA bool + err := pool.QueryRow(ctx, ` + SELECT "moneda", "incluirIva" + FROM "Cotizacion" + WHERE "id" = $1 + `, cotizacionID).Scan(&moneda, &incluirIVA) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, fmt.Errorf("Cotizacion %s no encontrada", cotizacionID) + } + return nil, fmt.Errorf("error consultando cotizacion %s: %w", cotizacionID, err) + } + + rows, err := pool.Query(ctx, ` + SELECT + COALESCE(NULLIF(cat."nombre", ''), NULLIF(sc."nombre", ''), 'Servicio') AS nombre, + sc."fase", + sc."tipoPago", + sc."precio", + sc."tiempoEntrega", + sc."entregables", + sc."modeloCobro", + sc."horas", + sc."tarifaHora", + sc."montoMinimo", + sc."horasIncluidas" + FROM "ServicioCotizado" sc + LEFT JOIN "ServicioCatalogo" cat ON cat."id" = sc."servicioCatalogoId" + WHERE sc."cotizacionId" = $1 AND sc."seleccionado" = true + ORDER BY sc."fase" ASC, sc."createdAt" ASC + `, cotizacionID) + if err != nil { + return nil, fmt.Errorf("error consultando servicios de cotizacion %s: %w", cotizacionID, err) + } + defer rows.Close() + + partidas := make([]PartidaEconomia, 0) + paraTotales := make([]domain.ServicioCalc, 0) + idx := 0 + + for rows.Next() { + var p PartidaEconomia + var entregablesRaw []byte + if err := rows.Scan( + &p.Nombre, + &p.Fase, + &p.TipoPago, + &p.Precio, + &p.TiempoEntrega, + &entregablesRaw, + &p.ModeloCobro, + &p.Horas, + &p.TarifaHora, + &p.MontoMinimo, + &p.HorasIncluidas, + ); err != nil { + return nil, fmt.Errorf("error leyendo servicio cotizado: %w", err) + } + idx++ + p.Ref = fmt.Sprintf("P%02d", idx) + p.Entregables = parseStringSliceJSON(entregablesRaw) + partidas = append(partidas, p) + paraTotales = append(paraTotales, domain.ServicioCalc{ + Nombre: p.Nombre, + ModeloCobro: p.ModeloCobro, + TipoPago: p.TipoPago, + Precio: p.Precio, + Seleccionado: true, + }) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("error iterando servicios cotizados: %w", err) + } + + var plan *struct { + Nivel string `json:"nivel"` + Precio float64 `json:"precio"` + } + var nivelPlan string + var precioPlan float64 + err = pool.QueryRow(ctx, ` + SELECT "nivel", "precio" + FROM "PlanBucefaloCotizacion" + WHERE "cotizacionId" = $1 AND "seleccionado" = true + LIMIT 1 + `, cotizacionID).Scan(&nivelPlan, &precioPlan) + if err == nil { + plan = &struct { + Nivel string `json:"nivel"` + Precio float64 `json:"precio"` + }{ + Nivel: nivelPlan, + Precio: precioPlan, + } + // El plan Bucefalo se cobra mensual y entra a los totales igual que en el PDF economico. + paraTotales = append(paraTotales, domain.ServicioCalc{ + TipoPago: "mensual", + Precio: precioPlan, + Seleccionado: true, + }) + } else if !errors.Is(err, pgx.ErrNoRows) { + return nil, fmt.Errorf("error consultando plan Bucefalo de %s: %w", cotizacionID, err) + } + + return &EconomiaCotizacion{ + Partidas: partidas, + PlanBucefalo: plan, + Totales: domain.CalcularTotalesCotizacion(paraTotales, incluirIVA), + Moneda: moneda, + }, nil +} + +func parseStringSliceJSON(raw []byte) []string { + if len(raw) == 0 { + return []string{} + } + var out []string + if err := json.Unmarshal(raw, &out); err != nil || out == nil { + return []string{} + } + return out +} diff --git a/internal/propuesta/pipeline.go b/internal/propuesta/pipeline.go new file mode 100644 index 0000000..b3ba476 --- /dev/null +++ b/internal/propuesta/pipeline.go @@ -0,0 +1,230 @@ +package propuesta + +import ( + "context" + "errors" + "fmt" + "strings" + + "cotizador/internal/config" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +// GenerarInput encapsula los datos de entrada para generar una propuesta consultiva. +type GenerarInput struct { + CotizacionID string + Transcripcion string + NotasAdicionales string +} + +// GenerarResult devuelve el contenido estructurado de la propuesta, la traza +// de consumo/intentos, los avisos de validacion y el modelo usado. +type GenerarResult struct { + Contenido map[string]any + Traza map[string]any + Avisos []Aviso + Modelo string +} + +type pasoTraza struct { + Paso string `json:"paso"` + Intentos int `json:"intentos"` + Uso UsoTokens `json:"uso"` +} + +// GenerarPropuesta ejecuta el pipeline consultivo de tres pasos (extraccion, +// diagnostico, redaccion) contra MiniMax y valida la salida contra las reglas +// de negocio y la economia canonica de la cotizacion. +func GenerarPropuesta(ctx context.Context, cfg *config.Config, pool *pgxpool.Pool, in GenerarInput) (*GenerarResult, error) { + if pool == nil { + return nil, errors.New("pool de base de datos no inicializado") + } + if strings.TrimSpace(in.CotizacionID) == "" { + return nil, errors.New("CotizacionID es obligatorio") + } + + var proyecto, observaciones, observacionesInternas, clienteNombre, clienteEmpresa string + var esDoble bool + err := pool.QueryRow(ctx, ` + SELECT + c."proyecto", + c."esDoble", + COALESCE(c."observaciones", ''), + COALESCE(c."observacionesInternas", ''), + cl."nombre", + COALESCE(cl."empresa", '') + FROM "Cotizacion" c + JOIN "Cliente" cl ON cl."id" = c."clienteId" + WHERE c."id" = $1 + `, in.CotizacionID).Scan( + &proyecto, + &esDoble, + &observaciones, + &observacionesInternas, + &clienteNombre, + &clienteEmpresa, + ) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, fmt.Errorf("Cotizacion %s no encontrada", in.CotizacionID) + } + return nil, fmt.Errorf("error cargando contexto de cotizacion %s: %w", in.CotizacionID, err) + } + + if esDoble { + return nil, errors.New( + "Esta cotizacion es de doble propuesta y el documento consultivo todavia no las soporta: sumaria las dos opciones como si fueran una sola. Genera la propuesta desde una cotizacion de opcion unica.", + ) + } + + rows, err := pool.Query(ctx, ` + SELECT "notas" + FROM "ServicioCotizado" + WHERE "cotizacionId" = $1 AND "notas" IS NOT NULL AND BTRIM("notas") <> '' + ORDER BY "fase" ASC, "createdAt" ASC + `, in.CotizacionID) + if err != nil { + return nil, fmt.Errorf("error consultando notas de partidas: %w", err) + } + var notasLista []string + for rows.Next() { + var n string + if err := rows.Scan(&n); err != nil { + rows.Close() + return nil, fmt.Errorf("error leyendo nota de partida: %w", err) + } + if trimmed := strings.TrimSpace(n); trimmed != "" { + notasLista = append(notasLista, trimmed) + } + } + if err := rows.Err(); err != nil { + rows.Close() + return nil, fmt.Errorf("error iterando notas de partidas: %w", err) + } + rows.Close() + + if extra := strings.TrimSpace(in.NotasAdicionales); extra != "" { + notasLista = append(notasLista, extra) + } + notasCombinadas := strings.Join(notasLista, "\n") + + economia, err := CargarEconomiaCotizacion(ctx, pool, in.CotizacionID) + if err != nil { + return nil, err + } + if len(economia.Partidas) == 0 { + return nil, errors.New("La cotizacion no tiene partidas seleccionadas. Agrega servicios antes de generar la propuesta.") + } + + cliente, err := NuevoClienteIA(cfg) + if err != nil { + return nil, err + } + + entrada := ContextoEntrada{ + Transcripcion: in.Transcripcion, + Notas: notasCombinadas, + Observaciones: observaciones, + Cliente: clienteNombre, + Empresa: clienteEmpresa, + Proyecto: proyecto, + } + + return ejecutarPipeline(ctx, cliente, entrada, economia, observacionesInternas) +} + +func ejecutarPipeline( + ctx context.Context, + cliente *ClienteIA, + entrada ContextoEntrada, + economia *EconomiaCotizacion, + notasInternas string, +) (*GenerarResult, error) { + system := []BloqueSystem{{Texto: SystemBase, Cachear: true}} + pasos := make([]pasoTraza, 0, 3) + var totalUso UsoTokens + acumular := func(u UsoTokens) { + totalUso.Entrada += u.Entrada + totalUso.Salida += u.Salida + totalUso.CacheLectura += u.CacheLectura + totalUso.CacheEscritura += u.CacheEscritura + } + + r1, err := cliente.LlamarConHerramienta(ctx, OpcionesLlamada{ + System: system, + MensajeUsuario: MensajePaso1(entrada), + Herramienta: Herramienta{ + Nombre: "registrar_hechos", + Descripcion: "Registra las citas literales, los hechos, los pendientes y las red flags extraidos del material de la reunion.", + InputSchema: SchemaHechos(), + Validar: ValidarHechos, + }, + MaxIntentos: 5, + MaxTokens: 8000, + }) + if err != nil { + return nil, err + } + pasos = append(pasos, pasoTraza{Paso: "extraccion", Intentos: r1.Intentos, Uso: r1.Uso}) + acumular(r1.Uso) + + r2, err := cliente.LlamarConHerramienta(ctx, OpcionesLlamada{ + System: system, + MensajeUsuario: MensajePaso2(entrada, r1.Datos, economia), + Herramienta: Herramienta{ + Nombre: "registrar_diagnostico", + Descripcion: "Registra los hallazgos con su semaforo de urgencia, el valor anual del problema y los resultados de negocio a lograr.", + InputSchema: SchemaDiagnostico(), + Validar: ValidarDiagnostico, + }, + MaxIntentos: 4, + MaxTokens: 8000, + }) + if err != nil { + return nil, err + } + pasos = append(pasos, pasoTraza{Paso: "diagnostico", Intentos: r2.Intentos, Uso: r2.Uso}) + acumular(r2.Uso) + + r3, err := cliente.LlamarConHerramienta(ctx, OpcionesLlamada{ + System: system, + MensajeUsuario: MensajePaso3(entrada, r1.Datos, r2.Datos, economia), + Herramienta: Herramienta{ + Nombre: "registrar_propuesta", + Descripcion: "Registra la redaccion final de la propuesta consultiva para el cliente.", + InputSchema: SchemaRedaccion(), + Validar: ValidarRedaccion, + }, + MaxIntentos: 4, + MaxTokens: 12000, + }) + if err != nil { + return nil, err + } + pasos = append(pasos, pasoTraza{Paso: "redaccion", Intentos: r3.Intentos, Uso: r3.Uso}) + acumular(r3.Uso) + + contenido := map[string]any{ + "hechos": r1.Datos, + "diagnostico": r2.Datos, + "redaccion": r3.Datos, + } + + fuentesCliente := strings.Join([]string{entrada.Transcripcion, entrada.Observaciones, entrada.Notas}, "\n") + avisos := ValidarPropuesta(contenido, economia, fuentesCliente, notasInternas) + + traza := map[string]any{ + "modelo": cliente.Model, + "pasos": pasos, + "totalUso": totalUso, + } + + return &GenerarResult{ + Contenido: contenido, + Traza: traza, + Avisos: avisos, + Modelo: cliente.Model, + }, nil +} diff --git a/internal/propuesta/prompts.go b/internal/propuesta/prompts.go new file mode 100644 index 0000000..b80b03b --- /dev/null +++ b/internal/propuesta/prompts.go @@ -0,0 +1,1043 @@ +package propuesta + +import ( + "encoding/json" + "fmt" + "regexp" + "strings" + "unicode/utf8" +) + +// SystemBase es la capa 1 del prompt: 100% estable entre cotizaciones y cacheable. +// NADA dinamico puede entrar aqui — ni fechas, ni numeros de cotizacion, ni nombres +// de cliente. Un solo byte que cambie invalida el cache de las pasadas siguientes. +const SystemBase = `# QUIEN ERES + +Consultor senior de digitalizacion de negocios para PyMEs mexicanas. Redactas la parte +narrativa de las propuestas de Uriel Jareth Consulting. No eres vendedor: eres +diagnosticador. Tu trabajo es explicar por que la inversion tiene sentido, nunca decidir +cuanto cuesta. + +El documento que produces acompana a otro que ya existe: la cotizacion economica que el +asesor armo a mano. Ese documento manda en todo lo que sea dinero. El tuyo manda en el +porque. + +# LOS PRINCIPIOS QUE NO SE NEGOCIAN + +P1. NO TOCAS LOS NUMEROS. No calculas, propones ni mencionas precios, totales, IVA ni + descuentos de Uriel Jareth Consulting. Ni siquiera los ves. Para referirte a una partida usa su + refPartida (P01, P02...). El sistema inyecta los importes despues de ti. + Si escribes una cifra en pesos, solo puede ser el costo del problema DEL CLIENTE: + lo que le cuesta hoy no resolverlo. Nunca un precio nuestro. + +P2. TODA AFIRMACION ES TRAZABLE. Cada cosa que digas sobre el cliente apunta a una cita + (C01...) o a un hecho (H01...). Si no tiene origen, no se escribe. No hay excepciones + y no importa lo razonable que suene. + +P3. ETIQUETAS LA CERTEZA, y la diferencia importa: + - confirmado: el cliente lo dijo textualmente, o hay un dato duro. + - estimado: lo derivaste con un calculo explicito que puedes mostrar. + - por_validar: es hipotesis tuya y nadie la ha confirmado. + Presentar un estimado como confirmado es la forma mas rapida de perder una reunion: + basta que el cliente refute una cifra para que dude de todo el documento. + +P4. LAS PALABRAS DEL CLIENTE SON SAGRADAS. Las citas van textuales, con sus muletillas si + hace falta. No las pulas ni les arregles la gramatica. + Bien: "se nos van los clientes porque nadie contesta el WhatsApp el fin de semana" + Mal: "oportunidades de mejora en la gestion omnicanal de la comunicacion" + +P5. VENDES RESULTADO, NO HERRAMIENTA. Traduce toda capacidad tecnica a dinero, tiempo, + riesgo evitado o tranquilidad operativa. + Mal: "Configuracion de Google Ads con estructura SKAG y scripts de puja." + Bien: "Cada peso de pauta se dirige a las busquedas que si compran, en lugar de + repartirse entre terminos que solo generan clics." + +P6. LO QUE NO INCLUYE VALE TANTO COMO LO QUE SI. Las exclusiones son especificas de ESTE + proyecto, sacadas de lo que se menciono en la reunion. + Mal: "No incluye servicios no mencionados." + Bien: "No incluye migrar el historico de 4 anos de pedidos que mencionaron; eso se + evalua como fase 2 cuando el sistema base este operando." + +P7. LA INCERTIDUMBRE SE DECLARA, NO SE RELLENA. Si falta un dato, va a pendientes con su + etiqueta. Jamas lo inventas. Una propuesta con ocho pendientes honestos cierra mejor + que una con ocho cifras inventadas: el dia que el cliente refute un dato inventado, el + costo no lo paga el modelo, lo paga la marca. + +P8. NO PROPONES SERVICIOS QUE EL ASESOR NO ELIGIO. Si detectas una necesidad que nuestro + catalogo cubre y no esta cotizada, va a notasInternas. Nunca al documento del cliente. + +# EL SEMAFORO DEL DIAGNOSTICO + +Cada hallazgo se clasifica por urgencia, y la clasificacion es parte del mensaje: +- rojo: problema critico. Le esta costando dinero hoy. +- ambar: area de mejora. Funciona, pero por debajo de lo que podria. +- azul: oportunidad. Algo que no esta haciendo y podria. +- verde: ventaja existente. Algo que el cliente YA hace bien. + +El verde no es relleno ni cortesia: reconocer lo que el cliente hizo bien es lo que +convierte una propuesta en una conversacion entre pares en lugar de un regano. Buscalo +de verdad. Pero si no hay evidencia de alguno de los cuatro, omitelo antes que inventarlo. + +# REGLAS DE CONTENIDO Y DE MARCA + +1. Espanol de Mexico. Tono cercano y profesional. Tutea al cliente. +2. Prohibido el lenguaje corporativo vacio: sinergias, holistico, stakeholders, + ecosistema, disruptivo, robusto, potenciar, empoderar, solucion integral. +3. El CRM se llama Bucefalo. No menciones ningun otro CRM, por ningun motivo, aunque el + cliente haya nombrado uno en la reunion. +4. Uriel Jareth Consulting ofrece UNICAMENTE servicios digitales. Si en la reunion pidieron marketing + tradicional, impresos o diseno para imprenta, va a exclusiones aclarando que no es un + servicio de Uriel Jareth Consulting. +5. Moneda MXN, IVA 16%, facturacion CFDI. Jamas montos en dolares ni en USD. +6. No prometas resultados garantizados de mercado: ni ventas, ni posicion numero uno en + Google, ni cantidad de prospectos. Prometes entregables, procesos y metricas de + seguimiento. La palabra "garantizado" no aparece sobre resultados de mercado. +7. No prometas soporte ilimitado ni mantenimiento gratuito indefinido. +8. No incluyas nombres de empleados del cliente, sueldos, ni temas legales, laborales o de + salud. Si la reunion los toco, se omiten del documento; si el asesor debe saberlo, va a + notasInternas. + +# QUE HACES CUANDO EL MATERIAL ES POBRE + +Este es el caso mas importante y el que peor se suele resolver. + +Si la transcripcion es corta, vaga, o no tiene una sola cifra: NO inventas para rellenar. +Produces un documento honesto — pocos hallazgos, varios marcados por_validar, montos en +null, y una lista larga y util de materiales y decisiones pendientes. + +Ese documento es un exito, no un fracaso. Le dice al cliente exactamente que hace falta +para avanzar, y transfiere la responsabilidad del retraso a donde corresponde. Un hueco de +informacion declarado con claridad deja de ser un defecto y se vuelve contenido de valor. + +Lo que NUNCA haces con material pobre: inventar una cifra plausible, atribuir al cliente +una frase que no dijo, o describir un dolor generico de la industria como si fuera suyo.` + +// ContextoEntrada concentra la informacion humana de la cotizacion para los prompts. +type ContextoEntrada struct { + Transcripcion string + Notas string + Observaciones string + Cliente string + Empresa string + Proyecto string +} + +// BloqueContexto construye la capa volatil del prompt para una cotizacion. +func BloqueContexto(e ContextoEntrada) string { + lineaCliente := "Cliente: " + e.Cliente + if strings.TrimSpace(e.Empresa) != "" { + lineaCliente += " (" + strings.TrimSpace(e.Empresa) + ")" + } + partes := []string{ + lineaCliente, + "Proyecto: " + e.Proyecto, + } + if obs := strings.TrimSpace(e.Observaciones); obs != "" { + partes = append(partes, "\n## Observaciones que el asesor escribio para el cliente\n"+obs) + } + if notas := strings.TrimSpace(e.Notas); notas != "" { + partes = append(partes, "\n## Notas por partida\n"+notas) + } + if tr := strings.TrimSpace(e.Transcripcion); tr != "" { + partes = append(partes, "\n## Transcripcion de la reunion\n"+tr) + } else { + partes = append(partes, "\n## Transcripcion de la reunion\n(No se entrego transcripcion. Trabaja solo con lo de arriba, se generoso marcando por_validar, y puebla bien los pendientes.)") + } + return strings.Join(partes, "\n") +} + +// MensajePaso1 arma el mensaje de usuario para la extraccion de hechos. +func MensajePaso1(e ContextoEntrada) string { + return BloqueContexto(e) + ` + +--- + +Extrae los hechos de este material y llama a registrar_hechos. + +Reglas de este paso: +- Las citas van TEXTUALES. Copialas del material, no las reescribas. Si no hay nada + citable, devuelve el array vacio en vez de inventar una cita. +- Numera las citas C01, C02... y los hechos H01, H02... +- Cada hecho apunta a las citas que lo sostienen. Un hecho sin ninguna cita solo puede + ser "por_validar". +- En quienLoDijo usa el ROL ("el socio", "quien atiende el WhatsApp"), no el nombre + propio, salvo que sea el interlocutor comercial. +- Si de alguna de estas listas no hay NADA que decir, devuelvela VACIA. Un array vacio + es la respuesta correcta; no metas "N/A", "ninguno" ni un guion para rellenar. +- En redFlags anota lo que deberia preocuparle al asesor: que pidan descuento antes de + entender el alcance, que no este presente quien decide, que no haya ninguna cifra del + problema, o un "hagan todo y luego vemos".` +} + +// MensajePaso2 arma el mensaje de usuario para el diagnostico. +// NUNCA incluye precios, totales ni IDs internos de base de datos (P1). +func MensajePaso2(e ContextoEntrada, hechos map[string]any, econ *EconomiaCotizacion) string { + var lineas []string + if econ != nil { + for _, p := range econ.Partidas { + lineas = append(lineas, fmt.Sprintf("- %s: %s (fase %d, pago %s)", p.Ref, p.Nombre, p.Fase, p.TipoPago)) + } + } + partidas := "(ninguna)" + if len(lineas) > 0 { + partidas = strings.Join(lineas, "\n") + } + + return fmt.Sprintf(`%s + +## Hechos extraidos en el paso anterior +%s + +## Partidas que el asesor ya eligio +%s + +(Las partidas van sin precio a proposito: tu no los necesitas y no debes mencionarlos.) + +--- + +Diagnostica y llama a registrar_diagnostico. + +Reglas de este paso: +- Reformula al problema de NEGOCIO. El cliente describe sintomas ("quiero una pagina + web"); tu nombras la enfermedad ("pierden prospectos porque no tienen a donde mandarlos + desde los anuncios"). +- Intenta cubrir el semaforo completo, incluido al menos un verde. Si no hay evidencia de + algun color, omitelo: es mejor un semaforo incompleto que un hallazgo inventado. +- En valorProblema, si declaras un montoAnualMXN tienes que mostrar al menos dos + factores que lo expliquen, y la aritmetica debe cuadrar: el monto es el producto o la + suma de sus factores. Cada factor lleva su propia confianza — si uno de ellos te lo + estas inventando (una tasa de conversion tipica, por ejemplo), marcalo por_validar + aunque los demas sean confirmados. Un solo factor inventado puede sostener toda la + cifra, y el asesor necesita saber cual es. +- Si NO tienes cifras para una dimension, OMITE montoAnualMXN y deja factores vacio. + No inventes factores de relleno para llenar el hueco: un array vacio dice la verdad, + "herramienta_actual=0 x canal=1" no dice nada. +- Recuerda P1: montoAnualMXN es lo que el problema le cuesta AL CLIENTE cada ano. No es + un precio de Uriel Jareth Consulting ni tiene relacion con lo que cotizamos. +- Los resultados a lograr son de negocio y medibles. "Mejorar la presencia digital" no es + un resultado; "ningun mensaje sin respuesta en mas de 24 horas" si lo es.`, + BloqueContexto(e), + marshalIndented(hechos), + partidas, + ) +} + +// MensajePaso3 arma el mensaje de usuario para la redaccion final. +// NUNCA incluye precios, totales ni IDs internos de base de datos (P1). +func MensajePaso3(_ ContextoEntrada, hechos map[string]any, diag map[string]any, econ *EconomiaCotizacion) string { + var lineas []string + if econ != nil { + for _, p := range econ.Partidas { + lineas = append(lineas, fmt.Sprintf("- %s: %s (fase %d, pago %s, entrega %s)", p.Ref, p.Nombre, p.Fase, p.TipoPago, p.TiempoEntrega)) + } + } + partidas := "(ninguna)" + if len(lineas) > 0 { + partidas = strings.Join(lineas, "\n") + } + + return fmt.Sprintf(`## Hechos +%s + +## Diagnostico +%s + +## Partidas a describir +%s + +--- + +Redacta la propuesta y llama a registrar_propuesta. + +Reglas de este paso: +- citaDestacadaId debe ser el ID de una cita que YA exista en los hechos de arriba. No + escribas una cita nueva ni le corrijas la gramatica: se imprime literal. +- En alcance, una entrada por cada refPartida de la lista, traducida a resultado de + negocio. No menciones importes ni plazos de pago: el sistema los inyecta. +- Cada beneficio apunta al hallazgoId que resuelve. Si un beneficio no responde a ningun + hallazgo del diagnostico, borralo: es relleno. +- Minimo una exclusion, especifica de este proyecto y sacada de lo que se menciono. +- El backlog es lo que quedo fuera y merece registrarse. Va con la etiqueta de que NO + esta comprometido en esta propuesta. +- notasInternas es lo unico que el cliente no vera. Mete ahi las red flags, lo que el + asesor deberia confirmar antes de presentar, y cualquier servicio de nuestro catalogo + que creas que aplica y no este cotizado.`, + marshalIndented(hechos), + marshalIndented(diag), + partidas, + ) +} + +func marshalIndented(v any) string { + b, err := json.MarshalIndent(v, "", " ") + if err != nil { + return "{}" + } + return string(b) +} + +// ───────────────────── JSON Schemas de las herramientas ───────────────────── +// +// REGLA ESTRUCTURAL (P1): ningun schema declara propiedades de dinero de +// Uriel Jareth Consulting (precio, total, subtotal, iva, montoMinimo, +// tarifaHora, descuento). `montoAnualMXN` si existe y representa el costo +// anual del problema DEL CLIENTE. + +// SchemaHechos devuelve el JSON Schema (sin $schema) de `registrar_hechos`. +func SchemaHechos() map[string]any { + return map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{ + "citas", + "hechos", + "materialesPendientes", + "decisionesPendientes", + "mencionesFueraDeAlcance", + "redFlags", + }, + "properties": map[string]any{ + "citas": map[string]any{ + "type": "array", + "maxItems": 30, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"id", "textoLiteral", "quienLoDijo"}, + "properties": map[string]any{ + "id": map[string]any{ + "type": "string", + "pattern": `^C\d{2}$`, + "description": "El id de cita debe ser C01, C02...", + }, + "textoLiteral": map[string]any{ + "type": "string", + "minLength": 10, + "description": "Cita TEXTUAL del cliente, palabra por palabra. Nunca parafraseada ni corregida.", + }, + "quienLoDijo": map[string]any{ + "type": "string", + "description": "Rol del interlocutor comercial ('el socio', 'quien atiende el WhatsApp'). No nombres de empleados.", + }, + }, + }, + }, + "hechos": map[string]any{ + "type": "array", + "maxItems": 40, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"id", "enunciado", "confianza", "citas"}, + "properties": map[string]any{ + "id": map[string]any{ + "type": "string", + "pattern": `^H\d{2}$`, + "description": "El id de hecho debe ser H01, H02...", + }, + "enunciado": map[string]any{ + "type": "string", + "minLength": 10, + }, + "confianza": map[string]any{ + "type": "string", + "enum": []string{"confirmado", "estimado", "por_validar"}, + }, + "citas": map[string]any{ + "type": "array", + "description": "IDs de las citas que sostienen este hecho.", + "items": map[string]any{ + "type": "string", + "pattern": `^C\d{2}$`, + }, + }, + }, + }, + }, + "materialesPendientes": map[string]any{ + "type": "array", + "maxItems": 15, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"texto", "bloqueaEntrega"}, + "properties": map[string]any{ + "texto": map[string]any{"type": "string", "minLength": 3}, + "bloqueaEntrega": map[string]any{"type": "boolean"}, + }, + }, + }, + "decisionesPendientes": map[string]any{ + "type": "array", + "maxItems": 15, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"texto", "quienDecide"}, + "properties": map[string]any{ + "texto": map[string]any{"type": "string", "minLength": 3}, + "quienDecide": map[string]any{"type": "string"}, + }, + }, + }, + "mencionesFueraDeAlcance": map[string]any{ + "type": "array", + "maxItems": 15, + "items": map[string]any{"type": "string", "minLength": 3}, + }, + "redFlags": map[string]any{ + "type": "array", + "maxItems": 10, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"senal", "severidad"}, + "properties": map[string]any{ + "senal": map[string]any{"type": "string", "minLength": 3}, + "severidad": map[string]any{"type": "string", "enum": []string{"baja", "media", "alta"}}, + }, + }, + }, + }, + } +} + +// SchemaDiagnostico devuelve el JSON Schema (sin $schema) de `registrar_diagnostico`. +func SchemaDiagnostico() map[string]any { + return map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"hallazgos", "valorProblema", "resultados"}, + "properties": map[string]any{ + "hallazgos": map[string]any{ + "type": "array", + "minItems": 1, + "maxItems": 12, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"id", "urgencia", "titulo", "descripcion", "confianza", "citas", "hechos"}, + "properties": map[string]any{ + "id": map[string]any{ + "type": "string", + "pattern": `^D\d{2}$`, + "description": "El id de hallazgo debe ser D01, D02...", + }, + "urgencia": map[string]any{ + "type": "string", + "enum": []string{"rojo", "ambar", "azul", "verde"}, + "description": "rojo=problema critico, ambar=area de mejora, azul=oportunidad, verde=ventaja que el cliente YA tiene", + }, + "titulo": map[string]any{ + "type": "string", + "minLength": 3, + "maxLength": 140, + }, + "descripcion": map[string]any{ + "type": "string", + "minLength": 20, + }, + "confianza": map[string]any{ + "type": "string", + "enum": []string{"confirmado", "estimado", "por_validar"}, + }, + "citas": map[string]any{ + "type": "array", + "items": map[string]any{"type": "string", "pattern": `^C\d{2}$`}, + }, + "hechos": map[string]any{ + "type": "array", + "items": map[string]any{"type": "string", "pattern": `^H\d{2}$`}, + }, + }, + }, + }, + "valorProblema": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"dimensiones", "notaMetodologia"}, + "properties": map[string]any{ + "dimensiones": map[string]any{ + "type": "array", + "maxItems": 4, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"tipo", "descripcion", "factores", "confianza", "hechos"}, + "properties": map[string]any{ + "tipo": map[string]any{ + "type": "string", + "enum": []string{"dinero", "tiempo", "oportunidad", "error"}, + }, + "descripcion": map[string]any{ + "type": "string", + "minLength": 10, + }, + "factores": map[string]any{ + "type": "array", + "maxItems": 6, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"nombre", "valor", "confianza"}, + "properties": map[string]any{ + "nombre": map[string]any{"type": "string"}, + "valor": map[string]any{"type": "number"}, + "confianza": map[string]any{ + "type": "string", + "enum": []string{"confirmado", "estimado", "por_validar"}, + }, + }, + }, + }, + "montoAnualMXN": map[string]any{ + "type": []string{"number", "null"}, + "description": "Costo ANUAL del problema DEL CLIENTE. No es un precio de Uriel Jareth Consulting. Omitelo si no hay cifras.", + }, + "confianza": map[string]any{ + "type": "string", + "enum": []string{"confirmado", "estimado", "por_validar"}, + }, + "hechos": map[string]any{ + "type": "array", + "items": map[string]any{"type": "string", "pattern": `^H\d{2}$`}, + }, + }, + }, + }, + "notaMetodologia": map[string]any{ + "type": "string", + "description": "Como se llego a las cifras, en una o dos frases.", + }, + }, + }, + "resultados": map[string]any{ + "type": "array", + "maxItems": 5, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"enunciado", "metrica", "lineaBase", "periodoMedicion"}, + "properties": map[string]any{ + "enunciado": map[string]any{"type": "string", "minLength": 15}, + "metrica": map[string]any{"type": "string"}, + "lineaBase": map[string]any{"type": []string{"string", "null"}}, + "periodoMedicion": map[string]any{"type": "string"}, + }, + }, + }, + }, + } +} + +// SchemaRedaccion devuelve el JSON Schema (sin $schema) de `registrar_propuesta`. +func SchemaRedaccion() map[string]any { + return map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{ + "hero", + "citaDestacadaId", + "alcance", + "beneficios", + "exclusiones", + "backlogEvolucion", + "notasInternas", + }, + "properties": map[string]any{ + "hero": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"titulo", "subtitulo"}, + "properties": map[string]any{ + "titulo": map[string]any{"type": "string", "minLength": 5, "maxLength": 90}, + "subtitulo": map[string]any{"type": "string", "minLength": 20, "maxLength": 400}, + }, + }, + "citaDestacadaId": map[string]any{ + "type": "string", + "pattern": `^C\d{2}$`, + "description": "ID de una cita YA extraida en el paso 1. Se imprime literal; no la reescribas.", + }, + "alcance": map[string]any{ + "type": "array", + "maxItems": 120, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"refPartida", "descripcionResultado"}, + "properties": map[string]any{ + "refPartida": map[string]any{ + "type": "string", + "pattern": `^P\d{2}$`, + "description": "Debe ser P01, P02...", + }, + "descripcionResultado": map[string]any{ + "type": "string", + "minLength": 20, + "description": "La partida traducida a resultado de negocio. Sin jerga tecnica y SIN mencionar importes.", + }, + }, + }, + }, + "beneficios": map[string]any{ + "type": "array", + "maxItems": 8, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"etiqueta", "texto", "hallazgoId"}, + "properties": map[string]any{ + "etiqueta": map[string]any{"type": "string", "minLength": 3, "maxLength": 70}, + "texto": map[string]any{"type": "string", "minLength": 20}, + "hallazgoId": map[string]any{ + "type": "string", + "pattern": `^D\d{2}$`, + "description": "El hallazgo que este beneficio resuelve. Si no responde a ninguno, no lo incluyas.", + }, + }, + }, + }, + "exclusiones": map[string]any{ + "type": "array", + "minItems": 1, + "maxItems": 10, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"texto", "razon"}, + "properties": map[string]any{ + "texto": map[string]any{ + "type": "string", + "minLength": 15, + "description": "Especifica de ESTE proyecto, nunca generica.", + }, + "razon": map[string]any{"type": "string", "minLength": 5}, + }, + }, + }, + "backlogEvolucion": map[string]any{ + "type": "array", + "maxItems": 8, + "items": map[string]any{ + "type": "object", + "additionalProperties": false, + "required": []string{"problema", "momentoSugerido"}, + "properties": map[string]any{ + "problema": map[string]any{"type": "string", "minLength": 10}, + "momentoSugerido": map[string]any{"type": "string"}, + }, + }, + }, + "notasInternas": map[string]any{ + "type": "array", + "maxItems": 10, + "description": "SOLO para el asesor. Nunca se imprime en el documento del cliente.", + "items": map[string]any{"type": "string", "minLength": 5}, + }, + }, + } +} + +// ───────────────────── Validadores de contrato por paso ───────────────────── + +var ( + reRefPartida = regexp.MustCompile(`^P\d{2}$`) + reIDCita = regexp.MustCompile(`^C\d{2}$`) + reIDHecho = regexp.MustCompile(`^H\d{2}$`) + reIDHallazgo = regexp.MustCompile(`^D\d{2}$`) +) + +func esEnumValido(v string, permitidos ...string) bool { + for _, p := range permitidos { + if v == p { + return true + } + } + return false +} + +func checkStrictKeys(m map[string]any, prefix string, allowed map[string]bool, errs *[]string) { + for k := range m { + if !allowed[k] { + *errs = append(*errs, fmt.Sprintf("%s: propiedad no declarada %q", prefix, k)) + } + } +} + +func reqString(m map[string]any, key, path string, minLen, maxLen int, pattern *regexp.Regexp, errs *[]string) string { + raw, ok := m[key] + if !ok || raw == nil { + *errs = append(*errs, fmt.Sprintf("%s: campo obligatorio faltante", path)) + return "" + } + s, ok := raw.(string) + if !ok { + *errs = append(*errs, fmt.Sprintf("%s: debe ser texto", path)) + return "" + } + n := utf8.RuneCountInString(s) + if minLen > 0 && n < minLen { + *errs = append(*errs, fmt.Sprintf("%s: longitud minima %d (tiene %d)", path, minLen, n)) + } + if maxLen > 0 && n > maxLen { + *errs = append(*errs, fmt.Sprintf("%s: longitud maxima %d (tiene %d)", path, maxLen, n)) + } + if pattern != nil && !pattern.MatchString(s) { + *errs = append(*errs, fmt.Sprintf("%s: formato invalido %q (esperado %s)", path, s, pattern.String())) + } + return s +} + +func reqArray(m map[string]any, key, path string, minItems, maxItems int, errs *[]string) []any { + raw, ok := m[key] + if !ok || raw == nil { + *errs = append(*errs, fmt.Sprintf("%s: arreglo obligatorio faltante", path)) + return nil + } + arr, ok := raw.([]any) + if !ok { + *errs = append(*errs, fmt.Sprintf("%s: debe ser un arreglo", path)) + return nil + } + if minItems > 0 && len(arr) < minItems { + *errs = append(*errs, fmt.Sprintf("%s: requiere al menos %d elemento(s)", path, minItems)) + } + if maxItems > 0 && len(arr) > maxItems { + *errs = append(*errs, fmt.Sprintf("%s: maximo %d elementos (tiene %d)", path, maxItems, len(arr))) + } + return arr +} + +func asNumber(v any) (float64, bool) { + switch x := v.(type) { + case float64: + return x, true + case float32: + return float64(x), true + case int: + return float64(x), true + case int64: + return float64(x), true + case json.Number: + f, err := x.Float64() + return f, err == nil + default: + return 0, false + } +} + +// ValidarHechos valida el resultado del paso 1 (`registrar_hechos`). +func ValidarHechos(m map[string]any) []string { + var errs []string + checkStrictKeys(m, "hechos", map[string]bool{ + "citas": true, "hechos": true, "materialesPendientes": true, + "decisionesPendientes": true, "mencionesFueraDeAlcance": true, "redFlags": true, + }, &errs) + + if citas := reqArray(m, "citas", "citas", 0, 30, &errs); citas != nil { + for i, item := range citas { + p := fmt.Sprintf("citas[%d]", i) + obj, ok := item.(map[string]any) + if !ok { + errs = append(errs, p+": debe ser un objeto") + continue + } + reqString(obj, "id", p+".id", 1, 0, reIDCita, &errs) + reqString(obj, "textoLiteral", p+".textoLiteral", 10, 0, nil, &errs) + reqString(obj, "quienLoDijo", p+".quienLoDijo", 0, 0, nil, &errs) + } + } + + if hechos := reqArray(m, "hechos", "hechos", 0, 40, &errs); hechos != nil { + for i, item := range hechos { + p := fmt.Sprintf("hechos[%d]", i) + obj, ok := item.(map[string]any) + if !ok { + errs = append(errs, p+": debe ser un objeto") + continue + } + reqString(obj, "id", p+".id", 1, 0, reIDHecho, &errs) + reqString(obj, "enunciado", p+".enunciado", 10, 0, nil, &errs) + conf := reqString(obj, "confianza", p+".confianza", 1, 0, nil, &errs) + if conf != "" && !esEnumValido(conf, "confirmado", "estimado", "por_validar") { + errs = append(errs, p+".confianza: valor invalido "+conf) + } + if refs := reqArray(obj, "citas", p+".citas", 0, 0, &errs); refs != nil { + for j, r := range refs { + s, ok := r.(string) + if !ok || !reIDCita.MatchString(s) { + errs = append(errs, fmt.Sprintf("%s.citas[%d]: debe coincidir con ^C\\d{2}$", p, j)) + } + } + } + } + } + + if mats := reqArray(m, "materialesPendientes", "materialesPendientes", 0, 15, &errs); mats != nil { + for i, item := range mats { + p := fmt.Sprintf("materialesPendientes[%d]", i) + obj, ok := item.(map[string]any) + if !ok { + errs = append(errs, p+": debe ser un objeto") + continue + } + reqString(obj, "texto", p+".texto", 3, 0, nil, &errs) + if _, ok := obj["bloqueaEntrega"].(bool); !ok { + errs = append(errs, p+".bloqueaEntrega: debe ser booleano") + } + } + } + + if decs := reqArray(m, "decisionesPendientes", "decisionesPendientes", 0, 15, &errs); decs != nil { + for i, item := range decs { + p := fmt.Sprintf("decisionesPendientes[%d]", i) + obj, ok := item.(map[string]any) + if !ok { + errs = append(errs, p+": debe ser un objeto") + continue + } + reqString(obj, "texto", p+".texto", 3, 0, nil, &errs) + reqString(obj, "quienDecide", p+".quienDecide", 0, 0, nil, &errs) + } + } + + if mencs := reqArray(m, "mencionesFueraDeAlcance", "mencionesFueraDeAlcance", 0, 15, &errs); mencs != nil { + for i, item := range mencs { + s, ok := item.(string) + if !ok || utf8.RuneCountInString(s) < 3 { + errs = append(errs, fmt.Sprintf("mencionesFueraDeAlcance[%d]: debe ser texto de al menos 3 caracteres", i)) + } + } + } + + if flags := reqArray(m, "redFlags", "redFlags", 0, 10, &errs); flags != nil { + for i, item := range flags { + p := fmt.Sprintf("redFlags[%d]", i) + obj, ok := item.(map[string]any) + if !ok { + errs = append(errs, p+": debe ser un objeto") + continue + } + reqString(obj, "senal", p+".senal", 3, 0, nil, &errs) + sev := reqString(obj, "severidad", p+".severidad", 1, 0, nil, &errs) + if sev != "" && !esEnumValido(sev, "baja", "media", "alta") { + errs = append(errs, p+".severidad: valor invalido "+sev) + } + } + } + + return errs +} + +// ValidarDiagnostico valida el resultado del paso 2 (`registrar_diagnostico`). +// Tolera la omision de `montoAnualMXN` (rellenando nil) igual que Zod `.default(null)`. +func ValidarDiagnostico(m map[string]any) []string { + var errs []string + checkStrictKeys(m, "diagnostico", map[string]bool{ + "hallazgos": true, "valorProblema": true, "resultados": true, + }, &errs) + + if hs := reqArray(m, "hallazgos", "hallazgos", 1, 12, &errs); hs != nil { + for i, item := range hs { + p := fmt.Sprintf("hallazgos[%d]", i) + obj, ok := item.(map[string]any) + if !ok { + errs = append(errs, p+": debe ser un objeto") + continue + } + reqString(obj, "id", p+".id", 1, 0, reIDHallazgo, &errs) + urg := reqString(obj, "urgencia", p+".urgencia", 1, 0, nil, &errs) + if urg != "" && !esEnumValido(urg, "rojo", "ambar", "azul", "verde") { + errs = append(errs, p+".urgencia: valor invalido "+urg) + } + reqString(obj, "titulo", p+".titulo", 3, 140, nil, &errs) + reqString(obj, "descripcion", p+".descripcion", 20, 0, nil, &errs) + conf := reqString(obj, "confianza", p+".confianza", 1, 0, nil, &errs) + if conf != "" && !esEnumValido(conf, "confirmado", "estimado", "por_validar") { + errs = append(errs, p+".confianza: valor invalido "+conf) + } + if refs := reqArray(obj, "citas", p+".citas", 0, 0, &errs); refs != nil { + for j, r := range refs { + if s, ok := r.(string); !ok || !reIDCita.MatchString(s) { + errs = append(errs, fmt.Sprintf("%s.citas[%d]: debe coincidir con ^C\\d{2}$", p, j)) + } + } + } + if refs := reqArray(obj, "hechos", p+".hechos", 0, 0, &errs); refs != nil { + for j, r := range refs { + if s, ok := r.(string); !ok || !reIDHecho.MatchString(s) { + errs = append(errs, fmt.Sprintf("%s.hechos[%d]: debe coincidir con ^H\\d{2}$", p, j)) + } + } + } + } + } + + vpRaw, ok := m["valorProblema"] + if !ok || vpRaw == nil { + errs = append(errs, "valorProblema: campo obligatorio faltante") + } else if vp, ok := vpRaw.(map[string]any); !ok { + errs = append(errs, "valorProblema: debe ser un objeto") + } else { + reqString(vp, "notaMetodologia", "valorProblema.notaMetodologia", 0, 0, nil, &errs) + if dims := reqArray(vp, "dimensiones", "valorProblema.dimensiones", 0, 4, &errs); dims != nil { + for i, item := range dims { + p := fmt.Sprintf("valorProblema.dimensiones[%d]", i) + obj, ok := item.(map[string]any) + if !ok { + errs = append(errs, p+": debe ser un objeto") + continue + } + tipo := reqString(obj, "tipo", p+".tipo", 1, 0, nil, &errs) + if tipo != "" && !esEnumValido(tipo, "dinero", "tiempo", "oportunidad", "error") { + errs = append(errs, p+".tipo: valor invalido "+tipo) + } + reqString(obj, "descripcion", p+".descripcion", 10, 0, nil, &errs) + conf := reqString(obj, "confianza", p+".confianza", 1, 0, nil, &errs) + if conf != "" && !esEnumValido(conf, "confirmado", "estimado", "por_validar") { + errs = append(errs, p+".confianza: valor invalido "+conf) + } + if refs := reqArray(obj, "hechos", p+".hechos", 0, 0, &errs); refs != nil { + for j, r := range refs { + if s, ok := r.(string); !ok || !reIDHecho.MatchString(s) { + errs = append(errs, fmt.Sprintf("%s.hechos[%d]: debe coincidir con ^H\\d{2}$", p, j)) + } + } + } + factores := reqArray(obj, "factores", p+".factores", 0, 6, &errs) + for j, f := range factores { + fp := fmt.Sprintf("%s.factores[%d]", p, j) + fobj, ok := f.(map[string]any) + if !ok { + errs = append(errs, fp+": debe ser un objeto") + continue + } + reqString(fobj, "nombre", fp+".nombre", 0, 0, nil, &errs) + if _, ok := asNumber(fobj["valor"]); !ok { + errs = append(errs, fp+".valor: debe ser numerico") + } + fconf := reqString(fobj, "confianza", fp+".confianza", 1, 0, nil, &errs) + if fconf != "" && !esEnumValido(fconf, "confirmado", "estimado", "por_validar") { + errs = append(errs, fp+".confianza: valor invalido "+fconf) + } + } + + rawMonto, present := obj["montoAnualMXN"] + if !present || rawMonto == nil { + obj["montoAnualMXN"] = nil + } else if _, ok := asNumber(rawMonto); !ok { + errs = append(errs, p+".montoAnualMXN: debe ser numerico o null") + } else if len(factores) < 2 { + errs = append(errs, p+".factores: Si declaras montoAnualMXN, muestra al menos 2 factores que lo expliquen.") + } + } + } + } + + if res := reqArray(m, "resultados", "resultados", 0, 5, &errs); res != nil { + for i, item := range res { + p := fmt.Sprintf("resultados[%d]", i) + obj, ok := item.(map[string]any) + if !ok { + errs = append(errs, p+": debe ser un objeto") + continue + } + reqString(obj, "enunciado", p+".enunciado", 15, 0, nil, &errs) + reqString(obj, "metrica", p+".metrica", 0, 0, nil, &errs) + reqString(obj, "periodoMedicion", p+".periodoMedicion", 0, 0, nil, &errs) + if rawLB, exists := obj["lineaBase"]; !exists || rawLB == nil { + obj["lineaBase"] = nil + } else if _, ok := rawLB.(string); !ok { + errs = append(errs, p+".lineaBase: debe ser texto o null") + } + } + } + + return errs +} + +// ValidarRedaccion valida el resultado del paso 3 (`registrar_propuesta`). +func ValidarRedaccion(m map[string]any) []string { + var errs []string + checkStrictKeys(m, "redaccion", map[string]bool{ + "hero": true, "citaDestacadaId": true, "alcance": true, + "beneficios": true, "exclusiones": true, "backlogEvolucion": true, "notasInternas": true, + }, &errs) + + heroRaw, ok := m["hero"] + if !ok || heroRaw == nil { + errs = append(errs, "hero: campo obligatorio faltante") + } else if hero, ok := heroRaw.(map[string]any); !ok { + errs = append(errs, "hero: debe ser un objeto") + } else { + reqString(hero, "titulo", "hero.titulo", 5, 90, nil, &errs) + reqString(hero, "subtitulo", "hero.subtitulo", 20, 400, nil, &errs) + } + + reqString(m, "citaDestacadaId", "citaDestacadaId", 1, 0, reIDCita, &errs) + + if alcance := reqArray(m, "alcance", "alcance", 0, 120, &errs); alcance != nil { + for i, item := range alcance { + p := fmt.Sprintf("alcance[%d]", i) + obj, ok := item.(map[string]any) + if !ok { + errs = append(errs, p+": debe ser un objeto") + continue + } + reqString(obj, "refPartida", p+".refPartida", 1, 0, reRefPartida, &errs) + reqString(obj, "descripcionResultado", p+".descripcionResultado", 20, 0, nil, &errs) + } + } + + if bens := reqArray(m, "beneficios", "beneficios", 0, 8, &errs); bens != nil { + for i, item := range bens { + p := fmt.Sprintf("beneficios[%d]", i) + obj, ok := item.(map[string]any) + if !ok { + errs = append(errs, p+": debe ser un objeto") + continue + } + reqString(obj, "etiqueta", p+".etiqueta", 3, 70, nil, &errs) + reqString(obj, "texto", p+".texto", 20, 0, nil, &errs) + reqString(obj, "hallazgoId", p+".hallazgoId", 1, 0, reIDHallazgo, &errs) + } + } + + if excls := reqArray(m, "exclusiones", "exclusiones", 1, 10, &errs); excls != nil { + for i, item := range excls { + p := fmt.Sprintf("exclusiones[%d]", i) + obj, ok := item.(map[string]any) + if !ok { + errs = append(errs, p+": debe ser un objeto") + continue + } + reqString(obj, "texto", p+".texto", 15, 0, nil, &errs) + reqString(obj, "razon", p+".razon", 5, 0, nil, &errs) + } + } + + if back := reqArray(m, "backlogEvolucion", "backlogEvolucion", 0, 8, &errs); back != nil { + for i, item := range back { + p := fmt.Sprintf("backlogEvolucion[%d]", i) + obj, ok := item.(map[string]any) + if !ok { + errs = append(errs, p+": debe ser un objeto") + continue + } + reqString(obj, "problema", p+".problema", 10, 0, nil, &errs) + reqString(obj, "momentoSugerido", p+".momentoSugerido", 0, 0, nil, &errs) + } + } + + if notas := reqArray(m, "notasInternas", "notasInternas", 0, 10, &errs); notas != nil { + for i, item := range notas { + s, ok := item.(string) + if !ok || utf8.RuneCountInString(s) < 5 { + errs = append(errs, fmt.Sprintf("notasInternas[%d]: debe ser texto de al menos 5 caracteres", i)) + } + } + } + + return errs +} diff --git a/internal/propuesta/propuesta_test.go b/internal/propuesta/propuesta_test.go new file mode 100644 index 0000000..5ef78ac --- /dev/null +++ b/internal/propuesta/propuesta_test.go @@ -0,0 +1,876 @@ +package propuesta + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "regexp" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "cotizador/internal/config" + "cotizador/internal/domain" +) + +// ─────────────────────────── economia.go ─────────────────────────── + +func TestCalcularRatio(t *testing.T) { + // Sin valor anual / cero / negativo -> sin etiqueta ni division entre cero + for _, val := range []float64{0, -5, -1000} { + r := CalcularRatio(100000, val) + if r.Ratio != 0 || r.Etiqueta != "" { + t.Fatalf("valorAnual=%v: esperado Ratio=0 Etiqueta=\"\", obtuve %+v", val, r) + } + if r.Nota == "" { + t.Fatalf("valorAnual=%v: esperaba Nota explicativa", val) + } + } + + casos := []struct { + nombre string + total float64 + valor float64 + etiqueta string + ratio float64 + }{ + {"5% subcotizado", 50000, 1000000, "subcotizado", 0.05}, + {"corte exacto 10% en_rango", 100000, 1000000, "en_rango", 0.1}, + {"20% en_rango", 200000, 1000000, "en_rango", 0.2}, + {"corte exacto 25% en_rango", 250000, 1000000, "en_rango", 0.25}, + {"35% alto", 350000, 1000000, "alto", 0.35}, + {"corte exacto 40% alto", 400000, 1000000, "alto", 0.4}, + {"60% objecion_probable", 600000, 1000000, "objecion_probable", 0.6}, + {"redondeo a 3 decimales", 123456, 1000000, "en_rango", 0.123}, + } + + for _, tc := range casos { + t.Run(tc.nombre, func(t *testing.T) { + got := CalcularRatio(tc.total, tc.valor) + if got.Etiqueta != tc.etiqueta { + t.Fatalf("etiqueta: esperado %q, obtuve %q (ratio=%v)", tc.etiqueta, got.Etiqueta, got.Ratio) + } + if got.Ratio != tc.ratio { + t.Fatalf("ratio: esperado %v, obtuve %v", tc.ratio, got.Ratio) + } + if got.Nota == "" { + t.Fatalf("se esperaba Nota no vacia para %q", tc.etiqueta) + } + }) + } +} + +// ─────────────────────────── cliente_ia.go ─────────────────────────── + +func TestNuevoClienteIA(t *testing.T) { + t.Run("rechaza clave faltante nombrando MINIMAX_API_KEY y ANTHROPIC_API_KEY", func(t *testing.T) { + t.Setenv("MINIMAX_API_KEY", "") + t.Setenv("ANTHROPIC_API_KEY", "") + _, err := NuevoClienteIA(&config.Config{}) + if err == nil { + t.Fatal("esperaba error sin MINIMAX_API_KEY") + } + if !strings.Contains(err.Error(), "MINIMAX_API_KEY") || !strings.Contains(err.Error(), "ANTHROPIC_API_KEY") { + t.Fatalf("mensaje debe mencionar MINIMAX_API_KEY y ANTHROPIC_API_KEY: %q", err.Error()) + } + }) + + t.Run("advierte explicitamente si solo ANTHROPIC_API_KEY esta definida", func(t *testing.T) { + t.Setenv("MINIMAX_API_KEY", "") + t.Setenv("ANTHROPIC_API_KEY", "sk-ant-solo-prueba") + _, err := NuevoClienteIA(&config.Config{}) + if err == nil { + t.Fatal("esperaba error cuando solo ANTHROPIC_API_KEY esta definida") + } + if !strings.Contains(err.Error(), "ANTHROPIC_API_KEY") || !strings.Contains(err.Error(), "MINIMAX_API_KEY") { + t.Fatalf("error debe advertir sobre ANTHROPIC_API_KEY: %q", err.Error()) + } + }) + + t.Run("defaults e ignorar ANTHROPIC_BASE_URL", func(t *testing.T) { + t.Setenv("ANTHROPIC_BASE_URL", "https://api.anthropic.com") + c, err := NuevoClienteIA(&config.Config{MinimaxAPIKey: "clave-prueba"}) + if err != nil { + t.Fatalf("error inesperado: %v", err) + } + if !strings.Contains(c.BaseURL, "api.minimax.io") { + t.Fatalf("BaseURL esperado de MiniMax, obtuve %q", c.BaseURL) + } + if strings.Contains(c.BaseURL, "api.anthropic.com") { + t.Fatalf("ANTHROPIC_BASE_URL no debe secuestrar BaseURL: %q", c.BaseURL) + } + if c.Model != "MiniMax-M3" { + t.Fatalf("Model por defecto esperado MiniMax-M3, obtuve %q", c.Model) + } + }) + + t.Run("respeta MINIMAX_BASE_URL y MINIMAX_MODEL", func(t *testing.T) { + c, err := NuevoClienteIA(&config.Config{ + MinimaxAPIKey: "clave-prueba", + MinimaxBaseURL: "https://ejemplo.local/anthropic/", + MinimaxModel: "MiniMax-M2", + }) + if err != nil { + t.Fatalf("error inesperado: %v", err) + } + if c.BaseURL != "https://ejemplo.local/anthropic" { + t.Fatalf("BaseURL inesperado: %q", c.BaseURL) + } + if c.Model != "MiniMax-M2" { + t.Fatalf("Model inesperado: %q", c.Model) + } + }) +} + +func TestNormalizarRespuesta(t *testing.T) { + casos := []struct { + nombre string + in any + want any + }{ + { + "desenvuelve {item: X} cuando item es la unica clave", + map[string]any{"item": map[string]any{"a": 1}}, + map[string]any{"a": 1}, + }, + { + "desenvuelve dentro de arrays", + []any{map[string]any{"item": map[string]any{"a": 1}}, map[string]any{"item": map[string]any{"a": 2}}}, + []any{map[string]any{"a": 1}, map[string]any{"a": 2}}, + }, + { + "desenvuelve en profundidad", + map[string]any{"lista": []any{map[string]any{"item": map[string]any{"x": []any{map[string]any{"item": 5}}}}}}, + map[string]any{"lista": []any{map[string]any{"x": []any{5}}}}, + }, + { + "NO toca un objeto con item junto a otras claves", + map[string]any{"item": 1, "otro": 2}, + map[string]any{"item": 1, "otro": 2}, + }, + { + "deja intactos valores simples", + "texto", + "texto", + }, + { + "deja intacto nil", + nil, + nil, + }, + { + "no altera un objeto normal", + map[string]any{"a": 1, "b": []any{1, 2}}, + map[string]any{"a": 1, "b": []any{1, 2}}, + }, + { + "caso real: alcance envuelto", + map[string]any{"alcance": []any{map[string]any{"item": map[string]any{"refPartida": "P01", "descripcionResultado": "x"}}}}, + map[string]any{"alcance": []any{map[string]any{"refPartida": "P01", "descripcionResultado": "x"}}}, + }, + } + + for _, tc := range casos { + t.Run(tc.nombre, func(t *testing.T) { + got := NormalizarRespuesta(tc.in) + if !reflect.DeepEqual(got, tc.want) { + t.Fatalf("esperado %#v, obtuve %#v", tc.want, got) + } + }) + } +} + +func TestClienteIAToolCallingRetryYFeedback(t *testing.T) { + var calls int32 + var sawToolChoice, sawCacheControl, sawToolResultError bool + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := atomic.AddInt32(&calls, 1) + if r.URL.Path != "/v1/messages" { + t.Errorf("path inesperado: %s", r.URL.Path) + } + if r.Header.Get("x-api-key") != "test-key" { + t.Errorf("x-api-key faltante o invalido: %q", r.Header.Get("x-api-key")) + } + + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Fatalf("body JSON invalido: %v", err) + } + if tc, ok := body["tool_choice"].(map[string]any); ok && tc["type"] == "tool" && tc["name"] == "registrar_hechos" { + sawToolChoice = true + } + if sys, ok := body["system"].([]any); ok && len(sys) > 0 { + if s0, ok := sys[0].(map[string]any); ok { + if cc, ok := s0["cache_control"].(map[string]any); ok && cc["type"] == "ephemeral" { + sawCacheControl = true + } + } + } + + // Llamada 1: fallo transitorio 429 + if n == 1 { + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"error":"rate_limit"}`)) + return + } + // Llamada 2: devuelve tool_use invalido (cita muy corta -> dispara feedback loop) + if n == 2 { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": "msg_1", + "type": "message", + "role": "assistant", + "content": []any{ + map[string]any{ + "type": "tool_use", + "id": "tu_1", + "name": "registrar_hechos", + "input": map[string]any{ + "citas": []any{map[string]any{"id": "C01", "textoLiteral": "corta", "quienLoDijo": "socio"}}, + "hechos": []any{}, "materialesPendientes": []any{}, + "decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{}, + }, + }, + }, + "usage": map[string]any{"input_tokens": 100, "output_tokens": 50, "cache_creation_input_tokens": 80}, + }) + return + } + + // Llamada 3: verificar que llego tool_result con is_error=true y responder valido envuelto en {item:...} + if msgs, ok := body["messages"].([]any); ok && len(msgs) >= 3 { + if last, ok := msgs[len(msgs)-1].(map[string]any); ok { + if blocks, ok := last["content"].([]any); ok { + for _, b := range blocks { + if bm, ok := b.(map[string]any); ok && bm["type"] == "tool_result" && bm["is_error"] == true { + sawToolResultError = true + } + } + } + } + } + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": "msg_2", + "type": "message", + "role": "assistant", + "content": []any{ + map[string]any{ + "type": "tool_use", + "id": "tu_2", + "name": "registrar_hechos", + "input": map[string]any{ + "citas": []any{map[string]any{"item": map[string]any{ + "id": "C01", + "textoLiteral": "no llevamos control de quien contesta el whatsapp el fin de semana", + "quienLoDijo": "el socio", + }}}, + "hechos": []any{}, "materialesPendientes": []any{}, + "decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{}, + }, + }, + }, + "usage": map[string]any{"input_tokens": 120, "output_tokens": 60, "cache_read_input_tokens": 80}, + }) + })) + defer srv.Close() + + cliente := &ClienteIA{ + APIKey: "test-key", + BaseURL: srv.URL, + Model: "MiniMax-M3", + HTTPClient: srv.Client(), + Sleep: func(context.Context, time.Duration) error { return nil }, + } + + res, err := cliente.LlamarConHerramienta(context.Background(), OpcionesLlamada{ + System: []BloqueSystem{{Texto: SystemBase, Cachear: true}}, + MensajeUsuario: "extrae hechos", + Herramienta: Herramienta{ + Nombre: "registrar_hechos", + Descripcion: "test", + InputSchema: SchemaHechos(), + Validar: ValidarHechos, + }, + MaxIntentos: 3, + MaxTokens: 1000, + }) + if err != nil { + t.Fatalf("error inesperado: %v", err) + } + if !sawToolChoice { + t.Fatal("esperaba tool_choice: {type: tool, name: registrar_hechos}") + } + if !sawCacheControl { + t.Fatal("esperaba cache_control: {type: ephemeral}") + } + if !sawToolResultError { + t.Fatal("esperaba feedback loop con tool_result is_error=true") + } + if res.Intentos != 2 { + t.Fatalf("esperaba 2 intentos de validacion (mas 1 reintento HTTP 429), obtuve %d", res.Intentos) + } + if res.Uso.Entrada != 220 || res.Uso.Salida != 110 || res.Uso.CacheEscritura != 80 || res.Uso.CacheLectura != 80 { + t.Fatalf("acumulacion de uso incorrecta: %+v", res.Uso) + } +} + +// ─────────────────────────── prompts.go & schemas ─────────────────────────── + +func TestSystemBaseCacheInvariants(t *testing.T) { + anioActual := strconv.Itoa(time.Now().Year()) + if strings.Contains(SystemBase, anioActual) { + t.Fatalf("SystemBase no debe contener el anio actual (%s)", anioActual) + } + if regexp.MustCompile(`\d{4}-\d{2}-\d{2}`).MatchString(SystemBase) { + t.Fatal("SystemBase no debe contener fechas ISO") + } + if regexp.MustCompile(`UJ\d{4}`).MatchString(SystemBase) { + t.Fatal("SystemBase no debe contener folios de cotizacion") + } + if len(SystemBase) <= 2500 { + t.Fatalf("SystemBase debe superar el minimo cacheable (>2500 chars), tiene %d", len(SystemBase)) + } + + for _, p := range []string{"P1.", "P2.", "P3.", "P4.", "P5.", "P6.", "P7.", "P8."} { + if !strings.Contains(SystemBase, p) { + t.Fatalf("SystemBase debe declarar principio %s", p) + } + } + for _, s := range []string{ + "rojo:", "ambar:", "azul:", "verde:", "entre pares", + "Bucefalo", "ningun otro CRM", "USD", "garantizado", + "sinergias", "UNICAMENTE servicios digitales", + "nombres de empleados", "MATERIAL ES POBRE", "contenido de valor", + } { + if !strings.Contains(SystemBase, s) { + t.Fatalf("SystemBase debe contener %q", s) + } + } +} + +func TestBloqueContextoYMensajesSinPrecios(t *testing.T) { + sinNada := BloqueContexto(ContextoEntrada{Cliente: "Ana", Proyecto: "P"}) + if !strings.Contains(sinNada, "No se entrego transcripcion") { + t.Fatal("sin transcripcion debe declararlo explicitamente") + } + if strings.Contains(sinNada, "()") { + t.Fatal("sin empresa no debe imprimir parentesis vacios") + } + + conTodo := BloqueContexto(ContextoEntrada{ + Transcripcion: "TRANS", Notas: "NOTAS", Observaciones: "OBS", + Cliente: "Ana", Empresa: "ACME", Proyecto: "P", + }) + for _, needle := range []string{"TRANS", "NOTAS", "OBS", "(ACME)"} { + if !strings.Contains(conTodo, needle) { + t.Fatalf("BloqueContexto debe incluir %q", needle) + } + } + + econ := &EconomiaCotizacion{ + Partidas: []PartidaEconomia{ + {Ref: "P01", Nombre: "Sitio web", Fase: 1, TipoPago: "unico", Precio: 12345, TiempoEntrega: "2 semanas", ModeloCobro: "fijo"}, + }, + Totales: domain.TotalesCotizacion{ + SubtotalUnico: 12345, IVAUnico: 1975.2, TotalUnico: 14320.2, TotalPrimerAnio: 14320.2, IncluyeIVA: true, + }, + Moneda: "MXN", + } + ctx := ContextoEntrada{Transcripcion: "t", Cliente: "Ana", Empresa: "ACME", Proyecto: "P"} + hechos := map[string]any{"citas": []any{}, "hechos": []any{}} + diag := map[string]any{"hallazgos": []any{}, "valorProblema": map[string]any{"dimensiones": []any{}, "notaMetodologia": ""}} + + m1 := MensajePaso1(ctx) + m2 := MensajePaso2(ctx, hechos, econ) + m3 := MensajePaso3(ctx, hechos, diag, econ) + + if !strings.Contains(m1, "registrar_hechos") || !strings.Contains(m1, "TEXTUALES") { + t.Fatal("MensajePaso1 debe pedir registrar_hechos y citas TEXTUALES") + } + if !strings.Contains(m2, "registrar_diagnostico") { + t.Fatal("MensajePaso2 debe pedir registrar_diagnostico") + } + if !strings.Contains(m3, "registrar_propuesta") { + t.Fatal("MensajePaso3 debe pedir registrar_propuesta") + } + + for nombre, msg := range map[string]string{"paso 2": m2, "paso 3": m3} { + if strings.Contains(msg, "12345") || strings.Contains(msg, "14320") { + t.Fatalf("%s NO puede filtrar precios o totales", nombre) + } + if !strings.Contains(msg, "P01") { + t.Fatalf("%s SI debe incluir refPartida P01", nombre) + } + } +} + +func TestToolSchemasZeroUJCPriceKeys(t *testing.T) { + schemas := []map[string]any{SchemaHechos(), SchemaDiagnostico(), SchemaRedaccion()} + rawBytes, err := json.Marshal(schemas) + if err != nil { + t.Fatalf("error serializando schemas: %v", err) + } + todos := string(rawBytes) + + prohibidos := []string{"precio", "total", "subtotal", "iva", "montoMinimo", "tarifaHora", "descuento"} + for _, p := range prohibidos { + if strings.Contains(todos, `"`+p+`"`) { + t.Fatalf("ningun tool schema puede declarar propiedad de dinero UJC %q", p) + } + } + if !strings.Contains(todos, `"montoAnualMXN"`) { + t.Fatal("SchemaDiagnostico debe incluir montoAnualMXN (costo del problema del cliente)") + } + if strings.Contains(todos, `"$schema"`) { + t.Fatal("los tool schemas no deben llevar $schema") + } + if strings.Contains(todos, `"calculo"`) { + t.Fatal("la dimension de valorProblema debe ser plana, sin objeto calculo") + } + if !strings.Contains(todos, `"additionalProperties"`) || !strings.Contains(todos, `"description"`) { + t.Fatal("los tool schemas deben conservar additionalProperties y description") + } +} + +func TestValidadoresSchemaPasos(t *testing.T) { + // Hechos vacios validos (material pobre) + if errs := ValidarHechos(map[string]any{ + "citas": []any{}, "hechos": []any{}, "materialesPendientes": []any{}, + "decisionesPendientes": []any{}, "mencionesFueraDeAlcance": []any{}, "redFlags": []any{}, + }); len(errs) != 0 { + t.Fatalf("hechos vacios deben ser validos: %v", errs) + } + + // Diagnostico: omitir montoAnualMXN se tolera y rellena nil; con monto y <2 factores se rechaza + dimSinMonto := map[string]any{ + "tipo": "tiempo", "descripcion": "Horas perdidas en atencion", + "factores": []any{}, "confianza": "por_validar", "hechos": []any{}, + } + diag := map[string]any{ + "hallazgos": []any{map[string]any{ + "id": "D01", "urgencia": "rojo", "titulo": "Titulo valido", + "descripcion": strings.Repeat("x", 25), "confianza": "confirmado", + "citas": []any{}, "hechos": []any{}, + }}, + "valorProblema": map[string]any{ + "dimensiones": []any{dimSinMonto}, + "notaMetodologia": "sin cifras", + }, + "resultados": []any{}, + } + if errs := ValidarDiagnostico(diag); len(errs) != 0 { + t.Fatalf("diagnostico omitiendo montoAnualMXN debe validar: %v", errs) + } + if val, exists := dimSinMonto["montoAnualMXN"]; !exists || val != nil { + t.Fatalf("omitir montoAnualMXN debe rellenar nil, obtuve exists=%v val=%v", exists, val) + } + + // Con montoAnualMXN y solo 1 factor -> error + dimUnFactor := map[string]any{ + "tipo": "tiempo", "descripcion": "Horas perdidas en atencion", + "factores": []any{map[string]any{"nombre": "a", "valor": 1.0, "confianza": "estimado"}}, + "montoAnualMXN": 1.0, "confianza": "estimado", "hechos": []any{}, + } + diag["valorProblema"].(map[string]any)["dimensiones"] = []any{dimUnFactor} + if errs := ValidarDiagnostico(diag); len(errs) == 0 { + t.Fatal("esperaba rechazo al declarar montoAnualMXN con menos de 2 factores") + } + + // Redaccion estricta rechaza propiedad desconocida `precioTotal` + red := map[string]any{ + "hero": map[string]any{"titulo": "Titulo valido", "subtitulo": strings.Repeat("x", 25)}, + "citaDestacadaId": "C01", + "alcance": []any{map[string]any{"refPartida": "P01", "descripcionResultado": strings.Repeat("x", 25)}}, + "beneficios": []any{}, + "exclusiones": []any{map[string]any{"texto": strings.Repeat("x", 20), "razon": "porque si"}}, + "backlogEvolucion": []any{}, + "notasInternas": []any{}, + "precioTotal": 99999, + } + if errs := ValidarRedaccion(red); len(errs) == 0 { + t.Fatal("ValidarRedaccion debe rechazar propiedades desconocidas") + } +} + +// ─────────────────────────── validacion.go ─────────────────────────── + +const citaPrueba = "no llevamos control de quien contesta el whatsapp el fin de semana" + +func econPrueba() *EconomiaCotizacion { + return &EconomiaCotizacion{ + Partidas: []PartidaEconomia{ + {Ref: "P01", Nombre: "Sitio web", Fase: 1, TipoPago: "unico", Precio: 12000, TiempoEntrega: "2 semanas", ModeloCobro: "fijo"}, + }, + Totales: domain.TotalesCotizacion{ + SubtotalUnico: 12000, IVAUnico: 1920, TotalUnico: 13920, TotalPrimerAnio: 13920, IncluyeIVA: true, + }, + Moneda: "MXN", + } +} + +func propuestaBase() map[string]any { + return map[string]any{ + "hechos": map[string]any{ + "citas": []any{ + map[string]any{"id": "C01", "textoLiteral": citaPrueba, "quienLoDijo": "el socio"}, + }, + "hechos": []any{ + map[string]any{"id": "H01", "enunciado": "No hay control de la atencion", "confianza": "confirmado", "citas": []any{"C01"}}, + }, + "materialesPendientes": []any{map[string]any{"texto": "Accesos al dominio", "bloqueaEntrega": true}}, + "decisionesPendientes": []any{map[string]any{"texto": "Definir responsable de atencion", "quienDecide": "el socio"}}, + "mencionesFueraDeAlcance": []any{}, + "redFlags": []any{}, + }, + "diagnostico": map[string]any{ + "hallazgos": []any{ + map[string]any{ + "id": "D01", "urgencia": "rojo", "titulo": "Prospectos sin seguimiento", + "descripcion": "Los mensajes del fin de semana se pierden.", + "confianza": "confirmado", "citas": []any{"C01"}, "hechos": []any{"H01"}, + }, + }, + "valorProblema": map[string]any{ + "dimensiones": []any{ + map[string]any{ + "tipo": "tiempo", "descripcion": "Horas perdidas de atencion", + "factores": []any{ + map[string]any{"nombre": "horas por semana", "valor": 8.0, "confianza": "confirmado"}, + map[string]any{"nombre": "semanas", "valor": 52.0, "confianza": "confirmado"}, + map[string]any{"nombre": "costo por hora", "valor": 400.0, "confianza": "estimado"}, + }, + "montoAnualMXN": 166400.0, "confianza": "estimado", "hechos": []any{"H01"}, + }, + }, + "notaMetodologia": "Ocho horas por semana a costo cargado.", + }, + "resultados": []any{ + map[string]any{ + "enunciado": "Ningun mensaje sin respuesta en mas de 24 horas", + "metrica": "tiempo de respuesta", "lineaBase": nil, "periodoMedicion": "mensual", + }, + }, + }, + "redaccion": map[string]any{ + "hero": map[string]any{ + "titulo": "Propuesta de digitalizacion", + "subtitulo": "Ordenar la atencion para dejar de perder prospectos.", + }, + "citaDestacadaId": "C01", + "alcance": []any{ + map[string]any{"refPartida": "P01", "descripcionResultado": "Un lugar a donde mandar a los prospectos que llegan de los anuncios."}, + }, + "beneficios": []any{ + map[string]any{"etiqueta": "Respuesta", "texto": "Cada mensaje queda registrado y con responsable.", "hallazgoId": "D01"}, + }, + "exclusiones": []any{ + map[string]any{"texto": "No incluye migrar el historico de pedidos de los ultimos 4 anos.", "razon": "Se evalua en fase 2."}, + }, + "backlogEvolucion": []any{}, + "notasInternas": []any{"El socio es quien decide."}, + }, + } +} + +func tieneRegla(avisos []Aviso, regla string) bool { + for _, a := range avisos { + if a.Regla == regla { + return true + } + } + return false +} + +func severidadRegla(avisos []Aviso, regla string) string { + for _, a := range avisos { + if a.Regla == regla { + return a.Severidad + } + } + return "" +} + +func TestNormalizarTexto(t *testing.T) { + if got := NormalizarTexto("¿Cómo estás, Juan?"); got != "como estas juan" { + t.Fatalf("esperado %q, obtuve %q", "como estas juan", got) + } + if got := NormalizarTexto(" a b "); got != "a b" { + t.Fatalf("esperado %q, obtuve %q", "a b", got) + } +} + +func TestValidarPropuestaTodasLasReglas(t *testing.T) { + econ := econPrueba() + fuentes := "El socio dijo: " + citaPrueba + ". Nada mas." + + t.Run("propuesta limpia sin bloqueantes", func(t *testing.T) { + avisos := ValidarPropuesta(propuestaBase(), econ, fuentes, "") + if HayBloqueantes(avisos) { + t.Fatalf("propuesta limpia no debe producir bloqueantes: %+v", avisos) + } + if len(avisos) != 0 { + t.Fatalf("propuesta limpia no debe producir avisos: %+v", avisos) + } + }) + + t.Run("R0 fuga de notas internas 7-gramas", func(t *testing.T) { + interno := "el socio pidio descuento antes de entender el alcance del proyecto completo" + + // Fuga en hero + p := propuestaBase() + p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "Contexto del proyecto: " + interno + "." + av := ValidarPropuesta(p, econ, fuentes, interno) + if !tieneRegla(av, "R0") || severidadRegla(av, "R0") != "bloqueante" { + t.Fatalf("R0 debe bloquear fuga en hero: %+v", av) + } + + // Fuga en hallazgo + p = propuestaBase() + p["diagnostico"].(map[string]any)["hallazgos"].([]any)[0].(map[string]any)["descripcion"] = "Observado: " + interno + "." + av = ValidarPropuesta(p, econ, fuentes, interno) + if !tieneRegla(av, "R0") { + t.Fatalf("R0 debe revisar todos los campos visibles (hallazgo): %+v", av) + } + + // Sin fuga -> ok + if tieneRegla(ValidarPropuesta(propuestaBase(), econ, fuentes, interno), "R0") { + t.Fatal("R0 no debe disparar si no hay fuga") + } + + // En notasInternas del propio resultado -> NO se imprime, NO dispara R0 + p = propuestaBase() + p["redaccion"].(map[string]any)["notasInternas"] = []any{interno} + if tieneRegla(ValidarPropuesta(p, econ, fuentes, interno), "R0") { + t.Fatal("R0 no debe quejarse de notasInternas (no se imprimen)") + } + }) + + t.Run("R2 y R2b referencias de partidas", func(t *testing.T) { + p := propuestaBase() + p["redaccion"].(map[string]any)["alcance"].([]any)[0].(map[string]any)["refPartida"] = "P99" + av := ValidarPropuesta(p, econ, fuentes, "") + if !tieneRegla(av, "R2") || severidadRegla(av, "R2") != "bloqueante" { + t.Fatalf("R2 debe bloquear partida inventada P99: %+v", av) + } + + p = propuestaBase() + p["redaccion"].(map[string]any)["alcance"] = []any{} + av = ValidarPropuesta(p, econ, fuentes, "") + if !tieneRegla(av, "R2b") || severidadRegla(av, "R2b") != "advertencia" { + t.Fatalf("R2b debe advertir partida cotizada no descrita: %+v", av) + } + }) + + t.Run("R3 cita destacada existe y es literal", func(t *testing.T) { + p := propuestaBase() + p["redaccion"].(map[string]any)["citaDestacadaId"] = "C09" + av := ValidarPropuesta(p, econ, fuentes, "") + if !tieneRegla(av, "R3") || severidadRegla(av, "R3") != "bloqueante" { + t.Fatalf("R3 debe bloquear cita inexistente: %+v", av) + } + + p = propuestaBase() + p["hechos"].(map[string]any)["citas"].([]any)[0].(map[string]any)["textoLiteral"] = "esto nunca lo dijo nadie en la reunion" + av = ValidarPropuesta(p, econ, fuentes, "") + if !tieneRegla(av, "R3") { + t.Fatalf("R3 debe bloquear cita no literal: %+v", av) + } + + // Tolera acentos, mayusculas y puntuacion + p = propuestaBase() + p["hechos"].(map[string]any)["citas"].([]any)[0].(map[string]any)["textoLiteral"] = "NO LLEVAMOS CONTROL, de quién contesta... el WhatsApp el fin de semana!" + if tieneRegla(ValidarPropuesta(p, econ, fuentes, ""), "R3") { + t.Fatal("R3 debe tolerar acentos, mayusculas y puntuacion") + } + }) + + t.Run("R4 confirmado sin evidencia", func(t *testing.T) { + p := propuestaBase() + h0 := p["diagnostico"].(map[string]any)["hallazgos"].([]any)[0].(map[string]any) + h0["citas"] = []any{} + h0["hechos"] = []any{} + av := ValidarPropuesta(p, econ, fuentes, "") + if !tieneRegla(av, "R4") || severidadRegla(av, "R4") != "advertencia" { + t.Fatalf("R4 debe advertir hallazgo confirmado sin citas ni hechos: %+v", av) + } + }) + + t.Run("R5 aritmetica dentro de 2% y R5b sin factores confirmados", func(t *testing.T) { + // No cuadra -> R5 bloqueante + p := propuestaBase() + dim := p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any) + dim["montoAnualMXN"] = 999999.0 + av := ValidarPropuesta(p, econ, fuentes, "") + if !tieneRegla(av, "R5") || severidadRegla(av, "R5") != "bloqueante" { + t.Fatalf("R5 debe bloquear aritmetica inconsistente: %+v", av) + } + + // Cuadra por suma dentro de 2% -> sin R5 + p = propuestaBase() + dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any) + dim["factores"] = []any{ + map[string]any{"nombre": "a", "valor": 10000.0, "confianza": "confirmado"}, + map[string]any{"nombre": "b", "valor": 5000.0, "confianza": "estimado"}, + } + dim["montoAnualMXN"] = 15100.0 // diferencia < 1% + if tieneRegla(ValidarPropuesta(p, econ, fuentes, ""), "R5") { + t.Fatal("R5 debe aceptar suma dentro del margen de 2%") + } + + // Sin cifra (nil) -> sin R5 ni R5b + p = propuestaBase() + dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any) + dim["montoAnualMXN"] = nil + dim["factores"] = []any{} + av = ValidarPropuesta(p, econ, fuentes, "") + if tieneRegla(av, "R5") || tieneRegla(av, "R5b") { + t.Fatalf("sin montoAnualMXN no debe disparar R5 ni R5b: %+v", av) + } + + // Solo estimados -> R5b advertencia + p = propuestaBase() + dim = p["diagnostico"].(map[string]any)["valorProblema"].(map[string]any)["dimensiones"].([]any)[0].(map[string]any) + for _, f := range dim["factores"].([]any) { + f.(map[string]any)["confianza"] = "estimado" + } + av = ValidarPropuesta(p, econ, fuentes, "") + if !tieneRegla(av, "R5b") || severidadRegla(av, "R5b") != "advertencia" { + t.Fatalf("R5b debe advertir cuando ningun factor es confirmado: %+v", av) + } + }) + + t.Run("R6 hallazgoId colgante", func(t *testing.T) { + p := propuestaBase() + p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["hallazgoId"] = "D99" + av := ValidarPropuesta(p, econ, fuentes, "") + if !tieneRegla(av, "R6") || severidadRegla(av, "R6") != "advertencia" { + t.Fatalf("R6 debe advertir beneficio colgante: %+v", av) + } + }) + + t.Run("MARCA MONEDA GARANTIA PII", func(t *testing.T) { + // MARCA + p := propuestaBase() + p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["texto"] = "Lo integramos con HubSpot sin problema alguno." + av := ValidarPropuesta(p, econ, fuentes, "") + if !tieneRegla(av, "MARCA") || severidadRegla(av, "MARCA") != "bloqueante" { + t.Fatalf("MARCA debe bloquear otro CRM: %+v", av) + } + + // MONEDA + p = propuestaBase() + p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "Una inversion de 1,800 USD al mes para tu negocio." + av = ValidarPropuesta(p, econ, fuentes, "") + if !tieneRegla(av, "MONEDA") || severidadRegla(av, "MONEDA") != "bloqueante" { + t.Fatalf("MONEDA debe bloquear USD: %+v", av) + } + + // GARANTIA + p = propuestaBase() + p["redaccion"].(map[string]any)["beneficios"].([]any)[0].(map[string]any)["texto"] = "Te garantizamos la posicion numero uno en Google." + av = ValidarPropuesta(p, econ, fuentes, "") + if !tieneRegla(av, "GARANTIA") || severidadRegla(av, "GARANTIA") != "bloqueante" { + t.Fatalf("GARANTIA debe bloquear promesa garantizada: %+v", av) + } + + // PII (advertencia, no bloqueante) + p = propuestaBase() + p["redaccion"].(map[string]any)["hero"].(map[string]any)["subtitulo"] = "El sueldo de quien atiende sale muy caro hoy en dia." + av = ValidarPropuesta(p, econ, fuentes, "") + if !tieneRegla(av, "PII") || severidadRegla(av, "PII") != "advertencia" || HayBloqueantes(av) { + t.Fatalf("PII debe ser advertencia no bloqueante: %+v", av) + } + }) +} + +// ─────────────────────────── pipeline.go ─────────────────────────── + +func TestEjecutarPipelineTresPasos(t *testing.T) { + base := propuestaBase() + var step int32 + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := atomic.AddInt32(&step, 1) + var toolName string + var payload any + switch n { + case 1: + toolName = "registrar_hechos" + payload = base["hechos"] + case 2: + toolName = "registrar_diagnostico" + payload = base["diagnostico"] + case 3: + toolName = "registrar_propuesta" + payload = base["redaccion"] + default: + t.Fatalf("llamada inesperada #%d", n) + } + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": "msg_" + strconv.Itoa(int(n)), + "type": "message", + "role": "assistant", + "content": []any{ + map[string]any{ + "type": "tool_use", + "id": "tu_" + strconv.Itoa(int(n)), + "name": toolName, + "input": payload, + }, + }, + "usage": map[string]any{ + "input_tokens": 100 * int(n), + "output_tokens": 50 * int(n), + "cache_read_input_tokens": 40, + "cache_creation_input_tokens": 10, + }, + }) + })) + defer srv.Close() + + cliente := &ClienteIA{ + APIKey: "test-key", + BaseURL: srv.URL, + Model: "MiniMax-M3", + HTTPClient: srv.Client(), + Sleep: func(context.Context, time.Duration) error { return nil }, + } + + res, err := ejecutarPipeline( + context.Background(), + cliente, + ContextoEntrada{ + Transcripcion: "El socio dijo: " + citaPrueba + ".", + Cliente: "Juan Perez", + Empresa: "ACME", + Proyecto: "MKT Digital", + }, + econPrueba(), + "nota confidencial que no debe aparecer en la propuesta final jamas", + ) + if err != nil { + t.Fatalf("error en pipeline: %v", err) + } + if res.Modelo != "MiniMax-M3" { + t.Fatalf("Modelo esperado MiniMax-M3, obtuve %q", res.Modelo) + } + if HayBloqueantes(res.Avisos) { + t.Fatalf("no esperaba bloqueantes en pipeline limpio: %+v", res.Avisos) + } + if res.Contenido["hechos"] == nil || res.Contenido["diagnostico"] == nil || res.Contenido["redaccion"] == nil { + t.Fatalf("Contenido incompleto: %+v", res.Contenido) + } + totalUso, ok := res.Traza["totalUso"].(UsoTokens) + if !ok || totalUso.Entrada != 600 || totalUso.Salida != 300 || totalUso.CacheLectura != 120 || totalUso.CacheEscritura != 30 { + t.Fatalf("Traza totalUso incorrecta: %#v", res.Traza["totalUso"]) + } +} diff --git a/internal/propuesta/validacion.go b/internal/propuesta/validacion.go new file mode 100644 index 0000000..27d4333 --- /dev/null +++ b/internal/propuesta/validacion.go @@ -0,0 +1,476 @@ +package propuesta + +import ( + "fmt" + "math" + "regexp" + "strings" + "unicode" + + "golang.org/x/text/unicode/norm" +) + +// Aviso describe un hallazgo de validacion post-generacion. +// Severidad: "bloqueante" | "advertencia". +type Aviso struct { + Regla string `json:"regla"` + Severidad string `json:"severidad"` + Mensaje string `json:"mensaje"` + Campo string `json:"campo,omitempty"` +} + +// NormalizarTexto quita acentos, pasa a minusculas, elimina puntuacion y +// colapsa espacios. Laxa a proposito para sobrevivir al ruido de transcripcion. +func NormalizarTexto(s string) string { + decomposed := norm.NFD.String(s) + var b strings.Builder + b.Grow(len(decomposed)) + for _, r := range decomposed { + if unicode.Is(unicode.Mn, r) { + continue + } + r = unicode.ToLower(r) + if unicode.IsLetter(r) || unicode.IsNumber(r) { + b.WriteRune(r) + } else { + b.WriteByte(' ') + } + } + return strings.Join(strings.Fields(b.String()), " ") +} + +var ( + reOtroCRM = regexp.MustCompile(`(?i)\b(hubspot|salesforce|pipedrive|zoho|go\s*high\s*level|gohighlevel|clientify|kommo|monday\s*crm)\b`) + rePromesaGarantia = regexp.MustCompile(`(?i)\bgarantiza(mos|do|da|r|remos)?\b|\baseguramos\s+(ventas|resultados|posici)`) + reMontoUSD = regexp.MustCompile(`(?i)\b(usd|d[oóÓ]lares|dlls?)\b|\$\s*[\d,.]+\s*(usd|dls)\b`) + reTemaSensible = regexp.MustCompile(`(?i)\b(sueldo|salario|n[oóÓ]mina|despido|demanda laboral|incapacidad|embarazo|enfermedad)\b`) +) + +type campoVisible struct { + campo string + texto string +} + +func getMap(m map[string]any, key string) map[string]any { + if m == nil { + return nil + } + if sub, ok := m[key].(map[string]any); ok { + return sub + } + return nil +} + +func getSlice(m map[string]any, key string) []any { + if m == nil { + return nil + } + if arr, ok := m[key].([]any); ok { + return arr + } + return nil +} + +func getString(m map[string]any, key string) string { + if m == nil { + return "" + } + if s, ok := m[key].(string); ok { + return s + } + return "" +} + +// textoVisible recopila TODOS los campos de texto que terminan impresos en el +// documento del cliente (excluyendo notasInternas, redFlags y razon de exclusiones). +func textoVisible(contenido map[string]any) []campoVisible { + hechos := getMap(contenido, "hechos") + diag := getMap(contenido, "diagnostico") + red := getMap(contenido, "redaccion") + hero := getMap(red, "hero") + vp := getMap(diag, "valorProblema") + + out := []campoVisible{ + {campo: "hero.titulo", texto: getString(hero, "titulo")}, + {campo: "hero.subtitulo", texto: getString(hero, "subtitulo")}, + {campo: "valorProblema.notaMetodologia", texto: getString(vp, "notaMetodologia")}, + } + + citaDestID := getString(red, "citaDestacadaId") + for _, raw := range getSlice(hechos, "citas") { + c, ok := raw.(map[string]any) + if !ok { + continue + } + id := getString(c, "id") + if id != "" && id == citaDestID { + out = append(out, + campoVisible{campo: fmt.Sprintf("citas.%s.textoLiteral", id), texto: getString(c, "textoLiteral")}, + campoVisible{campo: fmt.Sprintf("citas.%s.quienLoDijo", id), texto: getString(c, "quienLoDijo")}, + ) + break + } + } + + for i, raw := range getSlice(diag, "hallazgos") { + h, ok := raw.(map[string]any) + if !ok { + continue + } + out = append(out, + campoVisible{campo: fmt.Sprintf("hallazgos[%d].titulo", i), texto: getString(h, "titulo")}, + campoVisible{campo: fmt.Sprintf("hallazgos[%d].descripcion", i), texto: getString(h, "descripcion")}, + ) + } + + for i, raw := range getSlice(vp, "dimensiones") { + d, ok := raw.(map[string]any) + if !ok { + continue + } + out = append(out, campoVisible{ + campo: fmt.Sprintf("valorProblema.dimensiones[%d]", i), + texto: getString(d, "descripcion"), + }) + } + + for i, raw := range getSlice(diag, "resultados") { + r, ok := raw.(map[string]any) + if !ok { + continue + } + out = append(out, + campoVisible{campo: fmt.Sprintf("resultados[%d].enunciado", i), texto: getString(r, "enunciado")}, + campoVisible{campo: fmt.Sprintf("resultados[%d].metrica", i), texto: getString(r, "metrica")}, + campoVisible{campo: fmt.Sprintf("resultados[%d].periodoMedicion", i), texto: getString(r, "periodoMedicion")}, + ) + } + + for i, raw := range getSlice(red, "alcance") { + a, ok := raw.(map[string]any) + if !ok { + continue + } + out = append(out, campoVisible{ + campo: fmt.Sprintf("alcance[%d]", i), + texto: getString(a, "descripcionResultado"), + }) + } + + for i, raw := range getSlice(red, "beneficios") { + b, ok := raw.(map[string]any) + if !ok { + continue + } + out = append(out, campoVisible{ + campo: fmt.Sprintf("beneficios[%d]", i), + texto: getString(b, "etiqueta") + " " + getString(b, "texto"), + }) + } + + for i, raw := range getSlice(red, "exclusiones") { + e, ok := raw.(map[string]any) + if !ok { + continue + } + out = append(out, campoVisible{ + campo: fmt.Sprintf("exclusiones[%d]", i), + texto: getString(e, "texto"), + }) + } + + for i, raw := range getSlice(red, "backlogEvolucion") { + b, ok := raw.(map[string]any) + if !ok { + continue + } + out = append(out, + campoVisible{campo: fmt.Sprintf("backlog[%d].problema", i), texto: getString(b, "problema")}, + campoVisible{campo: fmt.Sprintf("backlog[%d].momentoSugerido", i), texto: getString(b, "momentoSugerido")}, + ) + } + + for i, raw := range getSlice(hechos, "materialesPendientes") { + m, ok := raw.(map[string]any) + if !ok { + continue + } + out = append(out, campoVisible{ + campo: fmt.Sprintf("materiales[%d]", i), + texto: getString(m, "texto"), + }) + } + + for i, raw := range getSlice(hechos, "decisionesPendientes") { + d, ok := raw.(map[string]any) + if !ok { + continue + } + out = append(out, + campoVisible{campo: fmt.Sprintf("decisiones[%d].texto", i), texto: getString(d, "texto")}, + campoVisible{campo: fmt.Sprintf("decisiones[%d].quienDecide", i), texto: getString(d, "quienDecide")}, + ) + } + + return out +} + +func ngramas(texto string, n int) map[string]struct{} { + palabras := strings.Fields(NormalizarTexto(texto)) + out := make(map[string]struct{}) + if n <= 0 || len(palabras) < n { + return out + } + for i := 0; i+n <= len(palabras); i++ { + out[strings.Join(palabras[i:i+n], " ")] = struct{}{} + } + return out +} + +func truncar(s string, max int) string { + r := []rune(s) + if len(r) <= max { + return s + } + return string(r[:max]) +} + +// ValidarPropuesta ejecuta las reglas deterministicas post-generacion: +// R0, R2, R2b, R3, R4, R5, R5b, R6, MARCA, MONEDA, GARANTIA y PII. +func ValidarPropuesta(contenido map[string]any, economia *EconomiaCotizacion, fuentesCliente string, notasInternas string) []Aviso { + avisos := make([]Aviso, 0) + visible := textoVisible(contenido) + + hechos := getMap(contenido, "hechos") + diag := getMap(contenido, "diagnostico") + red := getMap(contenido, "redaccion") + vp := getMap(diag, "valorProblema") + + // ── R0 (bloqueante): fuga de notas internas del asesor (7-gramas) ── + if strings.TrimSpace(notasInternas) != "" { + internos := ngramas(notasInternas, 7) + if len(internos) > 0 { + for _, v := range visible { + palabras := strings.Fields(NormalizarTexto(v.texto)) + for i := 0; i+7 <= len(palabras); i++ { + g := strings.Join(palabras[i:i+7], " ") + if _, leaked := internos[g]; leaked { + avisos = append(avisos, Aviso{ + Regla: "R0", + Severidad: "bloqueante", + Campo: v.campo, + Mensaje: fmt.Sprintf("Texto de las notas internas aparece en el documento del cliente: %q", g), + }) + break + } + } + } + } + } + + // ── R2 (bloqueante) / R2b (advertencia): correspondencia de partidas ── + refsReales := make(map[string]bool) + if economia != nil { + for _, p := range economia.Partidas { + refsReales[p.Ref] = true + } + } + refsUsadas := make(map[string]bool) + for _, raw := range getSlice(red, "alcance") { + a, ok := raw.(map[string]any) + if !ok { + continue + } + ref := getString(a, "refPartida") + refsUsadas[ref] = true + if !refsReales[ref] { + avisos = append(avisos, Aviso{ + Regla: "R2", + Severidad: "bloqueante", + Campo: "alcance " + ref, + Mensaje: fmt.Sprintf("La partida %s no existe en la cotizacion.", ref), + }) + } + } + if economia != nil { + for _, real := range economia.Partidas { + if !refsUsadas[real.Ref] { + avisos = append(avisos, Aviso{ + Regla: "R2b", + Severidad: "advertencia", + Campo: real.Ref, + Mensaje: fmt.Sprintf("La partida %q (%s) esta cotizada pero no aparece descrita.", real.Nombre, real.Ref), + }) + } + } + } + + // ── R3 (bloqueante): cita destacada existe y aparece literal en fuentesCliente ── + citaID := getString(red, "citaDestacadaId") + var citaEncontrada map[string]any + for _, raw := range getSlice(hechos, "citas") { + c, ok := raw.(map[string]any) + if ok && getString(c, "id") == citaID && citaID != "" { + citaEncontrada = c + break + } + } + if citaEncontrada == nil { + avisos = append(avisos, Aviso{ + Regla: "R3", + Severidad: "bloqueante", + Campo: "citaDestacadaId", + Mensaje: fmt.Sprintf("citaDestacadaId %s no corresponde a ninguna cita extraida.", citaID), + }) + } else if strings.TrimSpace(fuentesCliente) != "" { + textoLiteral := getString(citaEncontrada, "textoLiteral") + if !strings.Contains(NormalizarTexto(fuentesCliente), NormalizarTexto(textoLiteral)) { + avisos = append(avisos, Aviso{ + Regla: "R3", + Severidad: "bloqueante", + Campo: citaID, + Mensaje: fmt.Sprintf("La cita destacada no aparece literal en las fuentes: \"%s...\"", truncar(textoLiteral, 70)), + }) + } + } + + // ── R4 (advertencia): hallazgo confirmado sin citas ni hechos ── + idsHallazgo := make(map[string]bool) + for i, raw := range getSlice(diag, "hallazgos") { + h, ok := raw.(map[string]any) + if !ok { + continue + } + if id := getString(h, "id"); id != "" { + idsHallazgo[id] = true + } + if getString(h, "confianza") == "confirmado" && len(getSlice(h, "citas"))+len(getSlice(h, "hechos")) == 0 { + avisos = append(avisos, Aviso{ + Regla: "R4", + Severidad: "advertencia", + Campo: fmt.Sprintf("hallazgos[%d]", i), + Mensaje: fmt.Sprintf("%q se declara confirmado sin citas ni hechos. Deberia ser por_validar.", getString(h, "titulo")), + }) + } + } + + // ── R5 (bloqueante) y R5b (advertencia): aritmetica y evidencia del valor anual ── + for i, raw := range getSlice(vp, "dimensiones") { + d, ok := raw.(map[string]any) + if !ok { + continue + } + rawMonto, exists := d["montoAnualMXN"] + if !exists || rawMonto == nil { + continue + } + m, ok := asNumber(rawMonto) + if !ok { + continue + } + + factores := getSlice(d, "factores") + producto := 1.0 + suma := 0.0 + confirmados := 0 + for _, fRaw := range factores { + f, ok := fRaw.(map[string]any) + if !ok { + continue + } + val, _ := asNumber(f["valor"]) + producto *= val + suma += val + if getString(f, "confianza") == "confirmado" { + confirmados++ + } + } + + base := math.Max(math.Abs(m), 1.0) + cuadra := math.Abs(producto-m)/base < 0.02 || math.Abs(suma-m)/base < 0.02 + if !cuadra { + avisos = append(avisos, Aviso{ + Regla: "R5", + Severidad: "bloqueante", + Campo: fmt.Sprintf("valorProblema.dimensiones[%d]", i), + Mensaje: fmt.Sprintf("montoAnualMXN %v no cuadra con sus factores (producto %v, suma %v).", m, producto, suma), + }) + } + if confirmados == 0 { + avisos = append(avisos, Aviso{ + Regla: "R5b", + Severidad: "advertencia", + Campo: fmt.Sprintf("valorProblema.dimensiones[%d]", i), + Mensaje: fmt.Sprintf( + "La cifra de %v no tiene ni un factor confirmado: descansa entera en estimaciones. Revisa el desglose antes de fiarte del ratio precio/valor.", + m, + ), + }) + } + } + + // ── R6 (advertencia): referencias colgantes de hallazgoId en beneficios ── + for i, raw := range getSlice(red, "beneficios") { + b, ok := raw.(map[string]any) + if !ok { + continue + } + hid := getString(b, "hallazgoId") + if !idsHallazgo[hid] { + avisos = append(avisos, Aviso{ + Regla: "R6", + Severidad: "advertencia", + Campo: fmt.Sprintf("beneficios[%d]", i), + Mensaje: fmt.Sprintf("El beneficio apunta al hallazgo %s, que no existe.", hid), + }) + } + } + + // ── Filtros de contenido sobre lo visible al cliente ── + for _, v := range visible { + if reOtroCRM.MatchString(v.texto) { + avisos = append(avisos, Aviso{ + Regla: "MARCA", + Severidad: "bloqueante", + Campo: v.campo, + Mensaje: "Menciona un CRM que no es Bucefalo.", + }) + } + if reMontoUSD.MatchString(v.texto) { + avisos = append(avisos, Aviso{ + Regla: "MONEDA", + Severidad: "bloqueante", + Campo: v.campo, + Mensaje: "Contiene un monto o referencia en USD.", + }) + } + if rePromesaGarantia.MatchString(v.texto) { + avisos = append(avisos, Aviso{ + Regla: "GARANTIA", + Severidad: "bloqueante", + Campo: v.campo, + Mensaje: "Promete un resultado garantizado.", + }) + } + if reTemaSensible.MatchString(v.texto) { + avisos = append(avisos, Aviso{ + Regla: "PII", + Severidad: "advertencia", + Campo: v.campo, + Mensaje: "Menciona un tema laboral, salarial o de salud. Revisalo antes de enviar.", + }) + } + } + + return avisos +} + +// HayBloqueantes devuelve true si algun aviso tiene severidad "bloqueante". +func HayBloqueantes(avisos []Aviso) bool { + for _, a := range avisos { + if a.Severidad == "bloqueante" { + return true + } + } + return false +} diff --git a/internal/scheduler/scheduler.go b/internal/scheduler/scheduler.go new file mode 100644 index 0000000..16fd56a --- /dev/null +++ b/internal/scheduler/scheduler.go @@ -0,0 +1,143 @@ +package scheduler + +import ( + "context" + "log" + "slices" + "time" + + "cotizador/internal/db" + "cotizador/internal/domain" + "cotizador/internal/notify" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// GenerarCobros idempotently creates missing PagoRecurrente rows up to `hasta` (defaults to today MX). +// Returns the IDs of newly inserted PagoRecurrente rows. +func GenerarCobros(ctx context.Context, pool *pgxpool.Pool, programaID string, hasta *time.Time) ([]string, error) { + limite := domain.HoyCalendario() + if hasta != nil { + y, m, d := domain.ACalendario(*hasta) + limite = time.Date(y, m, d, 0, 0, 0, 0, time.UTC) + } + + query := ` + SELECT "id", "monto", "frecuencia", "diaSemana", "diaMes", "fechaInicio", "fechaFin" + FROM "ProgramaPago" + WHERE "activo" = true + ` + var args []any + if programaID != "" { + query += ` AND "id" = $1` + args = append(args, programaID) + } + + rows, err := pool.Query(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + + type prog struct { + ID string + Monto float64 + Frecuencia string + DiaSemana *int + DiaMes *int + FechaInicio time.Time + FechaFin *time.Time + } + var programas []prog + for rows.Next() { + var p prog + if err := rows.Scan(&p.ID, &p.Monto, &p.Frecuencia, &p.DiaSemana, &p.DiaMes, &p.FechaInicio, &p.FechaFin); err != nil { + continue + } + programas = append(programas, p) + } + + var creados []string + for _, p := range programas { + fechas := domain.FechasPeriodo(domain.ProgramaCalendario{ + Frecuencia: p.Frecuencia, + DiaSemana: p.DiaSemana, + DiaMes: p.DiaMes, + FechaInicio: p.FechaInicio, + FechaFin: p.FechaFin, + }, limite) + for _, f := range fechas { + newID := db.NewID() + var insertedID string + err := pool.QueryRow(ctx, ` + INSERT INTO "PagoRecurrente" ("id", "programaId", "fecha", "monto", "estado", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, 'pendiente', NOW(), NOW()) + ON CONFLICT ("programaId", "fecha") DO NOTHING + RETURNING "id" + `, newID, p.ID, f, p.Monto).Scan(&insertedID) + if err == nil && insertedID != "" { + creados = append(creados, insertedID) + } + } + } + return creados, nil +} + +// Start runs the recurring charges & reminder scheduler (20s initial delay, every 60 minutes). +func Start(ctx context.Context, pool *pgxpool.Pool, notifier *notify.Service) { + runOnce := func() { + cctx, cancel := context.WithTimeout(ctx, 2*time.Minute) + defer cancel() + + nuevos, err := GenerarCobros(cctx, pool, "", nil) + if err != nil { + log.Printf("[scheduler] error generando cobros: %v", err) + return + } + + var cubiertos []string + if domain.HoraMexico(time.Now()) >= domain.HoraRecordatorios { + res, err := notifier.EnviarRecordatoriosPendientes(cctx, "", false) + if err != nil { + log.Printf("[scheduler] error enviando recordatorios: %v", err) + } else if res != nil { + cubiertos = res.PagoIDsCubiertos + if res.ClientesNotificados > 0 || res.PagosVencidosEmit > 0 { + log.Printf("[scheduler] recordatorios=%d clientes (%d pagos), pago.vencido=%d", res.ClientesNotificados, res.PagosRecordados, res.PagosVencidosEmit) + } + } + } + + // Notify newly created charges not already covered by a reminder in this same tick + var porAvisar []string + for _, id := range nuevos { + if !slices.Contains(cubiertos, id) { + porAvisar = append(porAvisar, id) + } + } + if len(porAvisar) > 0 { + notifier.NotificarCobrosNuevos(cctx, porAvisar) + log.Printf("[scheduler] %d cobro(s) nuevo(s) generados y notificados", len(porAvisar)) + } + } + + go func() { + select { + case <-ctx.Done(): + return + case <-time.After(20 * time.Second): + } + runOnce() + + ticker := time.NewTicker(60 * time.Minute) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + runOnce() + } + } + }() +} diff --git a/internal/seed/data.go b/internal/seed/data.go new file mode 100644 index 0000000..9d85692 --- /dev/null +++ b/internal/seed/data.go @@ -0,0 +1,1883 @@ +package seed + +import ( + "fmt" + "regexp" + "strings" +) + +type CategoriaSeed struct { + Nombre string + Descripcion string + Color string + Orden int +} + +type ServicioSeed struct { + Nombre string + Descripcion string + Fase int + TipoPago string + PrecioBase float64 + TiempoEntrega string + Categoria string + Variante string + Nivel string + Orden int + SoloAdmin bool + EntregablesDefault []string +} + +type ServRef struct { + Nombre string + Nivel string +} + +type FasePaqueteSeed struct { + Orden int + Nombre string + Servicios []ServRef +} + +type PaqueteSeed struct { + ID string + Nombre string + Descripcion string + Fases []FasePaqueteSeed +} + +type BonoSeed struct { + Numero int + Titulo string + Descripcion string +} + +type FinanciamientoSeed struct { + Meses int + Tasa float64 + Comision float64 + MontoMinimo float64 + IVA float64 +} + +type ConfigSeed struct { + Clave string + Valor string +} + +var whitespaceRe = regexp.MustCompile(`\s+`) +var bucefaloSeedRe = regexp.MustCompile(`(?i)buc[eé]falo`) + +// ServicioID reproduces prisma/seed.ts: +// servicio.nombre.toLowerCase().replace(/\s+/g, "-").substring(0, 30) + "-" + servicio.orden +func ServicioID(nombre string, orden int) string { + slug := whitespaceRe.ReplaceAllString(strings.ToLower(nombre), "-") + runes := []rune(slug) + if len(runes) > 30 { + slug = string(runes[:30]) + } + return fmt.Sprintf("%s-%d", slug, orden) +} + +// IsSoloAdmin returns true for Bucefalo CRM items and any item explicitly marked soloAdmin. +func IsSoloAdmin(id, nombre string, explicit bool) bool { + if explicit { + return true + } + if id == "configuracion-y-puesta-en-marc-12" || id == "plan-mensual-crm-bucefalo-18" { + return true + } + return bucefaloSeedRe.MatchString(nombre) +} + +func DefaultCategorias() []CategoriaSeed { + return []CategoriaSeed{ + {Nombre: "SEO", Descripcion: "Optimizacion para motores de busqueda", Color: "#10b981", Orden: 1}, + {Nombre: "Marketing", Descripcion: "Estrategia y marketing digital", Color: "#6366f1", Orden: 2}, + {Nombre: "Paid Media", Descripcion: "Publicidad pagada en plataformas digitales", Color: "#f59e0b", Orden: 3}, + {Nombre: "Desarrollo Web", Descripcion: "Diseno y desarrollo de sitios web y ecommerce", Color: "#3b82f6", Orden: 4}, + {Nombre: "Automatizaciones", Descripcion: "Automatizacion de procesos y flujos de trabajo", Color: "#8b5cf6", Orden: 5}, + {Nombre: "CRM", Descripcion: "Gestion de relaciones con clientes", Color: "#ec4899", Orden: 6}, + {Nombre: "Desarrollo Personalizado", Descripcion: "Soluciones a medida y desarrollo custom", Color: "#14b8a6", Orden: 7}, + } +} + +func DefaultCatAlias() map[string]string { + return map[string]string{ + "auditoria": "Marketing", + "estrategia": "Marketing", + "diseno": "Desarrollo Web", + "sitio_web": "Desarrollo Web", + "ecommerce": "Desarrollo Web", + "ads": "Paid Media", + "redes": "Marketing", + "seo": "SEO", + "contenido": "Marketing", + "crm": "CRM", + "acompanamiento": "Marketing", + "otros": "Desarrollo Personalizado", + } +} + +func DefaultServicios() []ServicioSeed { + return []ServicioSeed{ + { + Nombre: "Auditoria en Redes Sociales", + Descripcion: "Auditoria completa de presencia en redes sociales", + Fase: 0, + TipoPago: "unico", + PrecioBase: 2990, + TiempoEntrega: "4 - 10 dias", + Categoria: "auditoria", + Orden: 1, + EntregablesDefault: []string{ + "Revision de presencia en redes sociales", + "Analisis de contenido publicado", + "Evaluacion de engagement", + "Documento de Evaluacion Total de Auditoria", + "Junta de Resultados", + }, + }, + { + Nombre: "Auditoria en Sitio Web", + Descripcion: "Auditoria tecnica y de rendimiento de sitio web", + Fase: 0, + TipoPago: "unico", + PrecioBase: 2990, + TiempoEntrega: "4 - 10 dias", + Categoria: "auditoria", + Orden: 2, + EntregablesDefault: []string{ + "Seguridad de dominio (vulnerabilidades)", + "Velocidad de sitio web (core web vital)", + "Diseno responsivo", + "Performance del sitio", + "Revison de SEO On Page y Off Page", + "Chequeo de listado del sitio en listas negras", + "Chequeo de Malware y Codigo Malicioso", + "Revision de Firewall en el Sitio", + "Recomendaciones SEO", + "Revision de Google Search Console", + "Revision de pixeles de Google y FB Ads", + "Documento de Evaluacion Total de Auditoria", + "Junta de Resultados", + }, + }, + { + Nombre: "Auditoria en Ecommerce", + Descripcion: "Auditoria completa de tienda en linea", + Fase: 0, + TipoPago: "unico", + PrecioBase: 2990, + TiempoEntrega: "4 - 10 dias", + Categoria: "auditoria", + Orden: 3, + EntregablesDefault: []string{ + "Revision de Seguridad de dominio", + "Revision de Certificado SSL", + "Revision de Metodos de Pago", + "Revision de Metodos de Envio", + "Revision de Velocidad de Sitio Web", + "Revision de Categorizacion de Productos", + "Revision de Filtrado de Productos", + "Revision de Carritos Abandonados", + "Revision de Correos Transaccionales", + "Revision de Pasos de Checkout", + "Documento de Evaluacion Total de Auditoria", + "Junta de Resultados", + }, + }, + { + Nombre: "Auditoria de cuentas Google Ads y Meta Ads", + Descripcion: "Auditoria de cuentas publicitarias", + Fase: 0, + TipoPago: "unico", + PrecioBase: 2990, + TiempoEntrega: "4 - 10 dias", + Categoria: "auditoria", + Orden: 4, + EntregablesDefault: []string{ + "Revision de Configuracion General de Google Ads", + "Revision de Configuracion de Facebook/Instagram Ads", + "Revision de la Segmentacion de Publicos Personalizados", + "Revision de Configuracion de Campanas", + "Revision de Configuracion de Grupo de Anuncios", + "Revision de Conversiones y Eventos Personalizados", + "Revision de Integracion e Implementacion de Pixeles", + "Revision de Estrategia de Presupuesto", + "Revision de Anuncios Graficos", + "Revision de Extensiones en los Anuncios", + "Documento de Evaluacion Total de Auditoria", + "Junta de Resultados", + }, + }, + { + Nombre: "Estudio Digital de Mercado", + Descripcion: "Estudio completo de mercado digital", + Fase: 1, + TipoPago: "unico", + PrecioBase: 4900, + TiempoEntrega: "4 - 10 dias", + Categoria: "estrategia", + Orden: 5, + EntregablesDefault: []string{ + "Estudio de Competencia Organica", + "Estudio de Competencia Pagada", + "Estudio de Demanda", + "Estudio de Tendencia", + "Estudio de Segmentacion de Mercado", + "Junta de Analisis de Resultados y Conclusiones", + }, + }, + { + Nombre: "Diseno de Identidad Corporativa", + Descripcion: "Creacion de identidad corporativa completa", + Fase: 1, + TipoPago: "unico", + PrecioBase: 11900, + TiempoEntrega: "7 - 15 dias", + Categoria: "diseno", + Orden: 6, + EntregablesDefault: []string{ + "Creacion de Logotipo y Favicon", + "Manual de Identidad Corporativa (colores, tipografias, usos)", + "Plantillas para Redes Sociales (posts, historias, carruseles)", + "Plantilla para portada de Redes Sociales", + "Entrega de archivos editables", + "Entrega de Mockups", + "Aplicativos Digitales (firma electronica, diapositivas, wallpaper)", + "Aplicativos Fisicos (tarjetas, hojas membretadas)", + "Presentacion de Propuestas", + "Tres juntas de revision", + }, + }, + { + Nombre: "Diseno de Sitio Web (WordPress)", + Descripcion: "Diseno y desarrollo de sitio web en WordPress", + Fase: 1, + TipoPago: "unico", + PrecioBase: 35000, + TiempoEntrega: "4 - 8 semanas", + Categoria: "sitio_web", + Variante: "wordpress", + Orden: 7, + EntregablesDefault: []string{ + "Desarrollo y Estructuracion Jerarquica de Sitio Web", + "Creacion de Paginas Basicas (TyC, PyP, Gracias, 404)", + "Optimizacion Avanzada SEO en cada Pagina", + "Sitio adaptado a ordenadores, tabletas y celulares (responsive)", + "Configuracion Avanzada de Velocidad de Carga", + "Diseno y Optimizacion de elementos graficos", + "Integracion y Configuracion de Contacto por WhatsApp y Llamada", + "Configuracion de Plugins de Seguridad", + "Capacitacion Basica de Sitio", + "Poliza de mantenimiento", + "Respaldo de seguridad semanal", + "Creacion y Optimizacion de Blog optimizado para SEO", + "Integracion de Formulario", + "Documento Estadisticas de Sitio Web (mensual)", + "Indexacion en Motores de Busqueda", + "Configuracion de Google Analytics 4, Tag Manager, Google Ads, Pixel y Capi de Facebook", + "Configuracion de Google Search Console", + "Revision de TyC, Politicas y Privacidad", + "Creacion de Textos Comerciales", + "Soporte de Primer y Segundo Nivel", + "Dominio, Certificado SSL, Hosting Incluido (5GB) - 1 Ano", + "Incluye tres revisiones del Proyecto", + }, + }, + { + Nombre: "Diseno de Ecommerce (WooCommerce)", + Descripcion: "Tienda en linea con WooCommerce", + Fase: 1, + TipoPago: "unico", + PrecioBase: 19900, + TiempoEntrega: "4 - 8 semanas", + Categoria: "ecommerce", + Variante: "woocommerce", + Orden: 8, + EntregablesDefault: []string{ + "Desarrollo y Estructuracion de Ecommerce", + "Creacion de Paginas Basicas (TyC, PyP, Gracias, 404)", + "Optimizacion Avanzada SEO en cada Pagina de Productos y Categorias", + "Diseno Responsivo (UI / UX)", + "Configuracion Avanzada de Velocidad de Carga", + "Diseno y Optimizacion de elementos graficos para cada Pagina", + "Integracion y Configuracion de Contacto por WhatsApp y Llamada", + "Integracion de Formulario", + "Integracion de Plugins de Seguridad", + "Capacitacion Basica de Sitio", + "Integracion de Metodos de Pago", + "Integracion de Metodos de Envio", + "Configuracion Jerarquica de Categoria por Nivel", + "Configuracion de Enlazado de Categorias", + "Configuracion de Carritos Abandonados", + "Documento Estadisticas de Sitio Web (mensual)", + "Indexacion en Motores de Busqueda", + "Configuracion de Google Analytics 4, Tag Manager, Google Ads, Pixel y Capi de Facebook para Ecommerce", + "Configuracion de Google Search Console", + "Incluye tres revisiones del Proyecto", + "Dominio, Certificado SSL, Hosting Incluido (5GB) - 1 Ano", + "Creacion de Textos Comerciales", + "Desarrollo y Estructuracion de Blog", + }, + }, + { + Nombre: "Diseno Tienda en Linea (Shopify)", + Descripcion: "Tienda en linea con Shopify", + Fase: 1, + TipoPago: "unico", + PrecioBase: 21900, + TiempoEntrega: "4 - 8 semanas", + Categoria: "ecommerce", + Variante: "shopify", + Orden: 9, + EntregablesDefault: []string{ + "Desarrollo y Estructuracion de Ecommerce", + "Configuracion de Paginas Basicas (TyC, AyP, Contacto, Nosotros, 404)", + "Configuracion de Paginas de Ecommerce (Mi cuenta, Inicio de sesion, Politicas)", + "Configuracion y Personalizacion de Template", + "Optimizacion SEO en cada Pagina de Productos y Categorias", + "Diseno Responsivo (UI / UX)", + "Configuracion de Velocidad de Carga en Sitio Web", + "Diseno y Optimizacion de elementos graficos para cada Pagina", + "Integracion y Configuracion de App de Contacto por WhatsApp", + "Integracion de Apps para Metodos de Pago", + "Integracion de Apps para Metodos de Envio", + "Configuracion y Estructura de Menu Principal", + "Soporte de Primer y Segundo Nivel", + "Creacion de Categorias de Tienda", + "Configuracion de Correos Base para Ecommerce", + "Configuracion de Carritos Abandonados", + "Indexacion en Motores de Busqueda", + "Configuracion de Google Search Console", + "Implementacion de Google Analytics 4", + "Capi y Pixel de Facebook", + "Creacion de Textos Comerciales", + "Capacitacion Basica de Tienda", + "Incluye tres revisiones del Proyecto", + "Dominio", + }, + }, + { + Nombre: "Creacion y Optimizacion de Redes Sociales", + Descripcion: "Creacion y brandeo de perfiles en redes sociales", + Fase: 1, + TipoPago: "unico", + PrecioBase: 2500, + TiempoEntrega: "4 - 10 dias", + Categoria: "redes", + Orden: 10, + EntregablesDefault: []string{ + "Creacion de Redes Sociales (Facebook, Instagram)", + "Brandeo de las Redes y Optimizacion", + }, + }, + { + Nombre: "Creacion y Optimizacion de la Ficha de Google My Business", + Descripcion: "Configuracion y optimizacion de perfil de Google", + Fase: 1, + TipoPago: "unico", + PrecioBase: 2000, + TiempoEntrega: "4 - 10 dias", + Categoria: "seo", + Orden: 11, + EntregablesDefault: []string{ + "Creacion y Configuracion de Perfil de Negocio de Google", + "Optimizacion de Perfil de Negocio de Google", + "Generacion de Mapas Fractales", + "Plantillas para Publicaciones en Perfil de Negocio", + "Reporte de resultados", + }, + }, + { + Nombre: "Configuracion y Puesta en Marcha del CRM Bucefalo", + Descripcion: "Configuracion inicial de cuenta CRM Bucefalo", + Fase: 1, + TipoPago: "unico", + PrecioBase: 3900, + TiempoEntrega: "4 - 10 dias", + Categoria: "crm", + Orden: 12, + SoloAdmin: true, + EntregablesDefault: []string{ + "Configuracion de cuenta CRM Bucefalo", + "Curso de Capacitacion", + "Configuracion de Automatizaciones", + "Configuracion de Pipeline de Oportunidades", + "Configuracion de Campos Personalizados", + "Integracion de Calendario", + "Configuracion de Reportes", + }, + }, + { + Nombre: "Configuracion, Optimizacion y Puesta en Marcha de Google Ads y Meta Ads", + Descripcion: "Setup completo de ambas plataformas publicitarias", + Fase: 1, + TipoPago: "unico", + PrecioBase: 4000, + TiempoEntrega: "4 - 10 dias", + Categoria: "ads", + Orden: 13, + EntregablesDefault: []string{ + "Configuracion y estructura de las Campanas de Google Ads", + "Configuracion de Conversiones", + "Configuracion de la Segmentacion de Publicos Personalizados", + "Configuracion de listas de terminos de busqueda negativos", + "Configuracion de listas de terminos busqueda", + "Configuracion de Anuncios publicitarios", + "Configuracion de Extensiones en los anuncios", + "Configuracion de Cuenta Facebook Ads e Instagram Ads", + "Configuracion de Pixeles de Conversion", + "Configuracion de Anuncios Publicitarios para Meta", + "Configuracion de Conversiones Personalizadas", + }, + }, + { + Nombre: "Tablero de Inspiracion", + Descripcion: "Estrategia creativa para campanas publicitarias", + Fase: 2, + TipoPago: "unico", + PrecioBase: 2900, + TiempoEntrega: "6 - 10 dias", + Categoria: "estrategia", + Orden: 14, + EntregablesDefault: []string{ + "Estrategia Creativa", + "Segmentacion de Mercado", + "Complexogramo", + "Analisis de Competencia", + "Analisis de los mejores Anuncios Locales, Nacionales e Internacionales", + }, + }, + { + Nombre: "Configuracion y Optimizacion Google Ads", + Descripcion: "Configuracion y optimizacion mensual de Google Ads", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 4900, + TiempoEntrega: "4 - 10 dias", + Categoria: "ads", + Orden: 15, + EntregablesDefault: []string{ + "Revision de la Segmentacion de Publicos Personalizados", + "Revision de Listas de Terminos de Busqueda Negativos", + "Revision de Listas de Terminos Busqueda", + "Revision de Anuncios Publicitarios", + "Revision de Anuncios Graficos", + "Una Sesion de Acompanamiento para Google", + }, + }, + { + Nombre: "Manejo y Optimizacion de Meta Ads", + Descripcion: "Manejo y optimizacion mensual de Meta Ads", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 1500, + TiempoEntrega: "4 - 10 dias", + Categoria: "ads", + Orden: 16, + EntregablesDefault: []string{ + "Revision de la Configuracion de Conversiones", + "Revision de la Segmentacion de Publicos Personalizados", + "Revision de Conversiones Personalizadas", + "Revision de Anuncios Publicitarios", + "Una Sesion de Acompanamiento para la Creacion de Portafolio Comercial / Facebook", + }, + }, + { + Nombre: "Manejo Basico de Redes Sociales", + Descripcion: "Manejo mensual basico de redes sociales", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 3000, + TiempoEntrega: "4 - 10 dias", + Categoria: "redes", + Orden: 17, + EntregablesDefault: []string{ + "Realizacion de Parrilla, Diseno y Programacion", + "3 - 5 Post Mensuales", + }, + }, + { + Nombre: "Plan Mensual CRM Bucefalo", + Descripcion: "Suscripcion mensual al CRM Bucefalo", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 3900, + TiempoEntrega: "Mensual", + Categoria: "crm", + Orden: 18, + SoloAdmin: true, + EntregablesDefault: []string{ + "Uso completo del CRM segun plan contratado", + "Soporte tecnico", + "Actualizaciones del sistema", + }, + }, + { + Nombre: "Desarrollo de Plan de Contenido", + Descripcion: "Plan estrategico de contenido", + Fase: 3, + TipoPago: "unico", + PrecioBase: 2900, + TiempoEntrega: "6 - 10 dias", + Categoria: "contenido", + Orden: 19, + EntregablesDefault: []string{ + "Analisis situacional de la marca", + "Objetivos de la marca", + "Analisis de Audiencia y Competencia", + "Estrategias de Contenido", + "Propuesta de Contenido", + "Plan de Acciones", + "Canales de Distribucion", + "Medicion y Metricas", + }, + }, + { + Nombre: "Generacion de Contenido", + Descripcion: "Generacion mensual de contenido para redes", + Fase: 3, + TipoPago: "mensual", + PrecioBase: 8000, + TiempoEntrega: "Mensual", + Categoria: "contenido", + Orden: 20, + EntregablesDefault: []string{ + "Manejo de Parrilla Mensual (Facebook, Instagram, Pinterest, YouTube, Tik Tok)", + "Publicaciones Estaticas para Redes Sociales", + "Post para Blog", + "Video YouTube largo, Generacion de Reels, Shorts", + "Escucha Social (analisis de opiniones de clientes)", + "Junta de Reporte mensual", + }, + }, + { + Nombre: "Posicionamiento SEO", + Descripcion: "Posicionamiento SEO mensual", + Fase: 3, + TipoPago: "mensual", + PrecioBase: 2900, + TiempoEntrega: "4 - 10 dias", + Categoria: "seo", + Orden: 21, + EntregablesDefault: []string{ + "Posicionamiento de KW (3 palabras clave)", + "Traqueo de las Palabras Clave", + "Creacion de Enlaces Externos al Sitio", + "Citaciones para el Sitio", + "Reporte de resultados (mensual)", + }, + }, + { + Nombre: "Estrategia SEO Completa", + Descripcion: "Estrategia SEO completa con contenido y backlinks", + Fase: 3, + TipoPago: "mensual", + PrecioBase: 2900, + TiempoEntrega: "Mensual", + Categoria: "seo", + Orden: 22, + EntregablesDefault: []string{ + "Busqueda y definicion de KW a atacar", + "Definicion de tematica y KW por Mes (calendario semestral)", + "Monitoreo de posiciones en SERPS de KW", + "Busqueda de backlinks de la competencia", + "Gestion con medios y webs para el correcto enlazado", + "Indexacion a Backlinks y monitoreo", + "Generacion de contenido SEO para Post del blog o Landing", + "Generacion de Imagenes y video para ilustracion", + "Generacion de Url (post o Landing) para posicionamiento", + "Optimizacion SEO de todas las Url nuevas", + "Enlazado Interno de todo el sitio web", + "Optimizacion de usabilidad del sitio", + "Optimizacion de Copy", + "Optimizacion de EEAT", + "Optimizacion de enlazado interno", + "Optimizacion de prominencia Semantica", + "Reporte mensual", + }, + }, + { + Nombre: "Plan de Acompanamiento Integral", + Descripcion: "Servicio integral de acompanamiento estrategico y operativo durante un periodo minimo obligatorio de 9 meses (3 meses operando Uriel Jareth Consulting, 3 operando en conjunto y 3 meses operando en acompanamiento)", + Fase: 0, + TipoPago: "mensual", + PrecioBase: 9000, + TiempoEntrega: "Minimo 9 meses", + Categoria: "acompanamiento", + Orden: 23, + EntregablesDefault: []string{ + "Manejo de Google Ads (Performance Max, Demand Gen, IA Max for Search)", + "Implementacion con first-party data y third-party data", + "Reportes mensuales con analisis de resultados Google Ads", + "Manejo de Meta Ads (Advantage+, campanas por objetivo, remarketing dinamico)", + "Segmentacion y automatizacion con IA", + "Reportes mensuales con analisis de resultados Meta Ads", + }, + }, + { + Nombre: "Logo e Identidad", + Descripcion: "Diseno de identidad de marca y logotipo", + Fase: 1, + TipoPago: "unico", + PrecioBase: 6903, + TiempoEntrega: "7 - 15 dias", + Categoria: "diseno", + Nivel: "Emprendedor", + Orden: 101, + EntregablesDefault: []string{ + "Investigacion de Tendencias, Mercado, Competencia y Demanda", + "Creacion y Propuesta del Naming: 2", + "Propuesta del Logotipo: 2", + "Creacion Logotipo", + "Diseno de Aplicativos Fisicos: 2", + "Diseno de Aplicativos Digitales: 4", + "Manual de Identidad", + "Atencion y asesoria al cliente", + "Revisiones", + }, + }, + { + Nombre: "Logo e Identidad", + Descripcion: "Diseno de identidad de marca y logotipo", + Fase: 1, + TipoPago: "unico", + PrecioBase: 12093, + TiempoEntrega: "7 - 15 dias", + Categoria: "diseno", + Nivel: "PYME", + Orden: 102, + EntregablesDefault: []string{ + "Investigacion de Tendencias, Mercado, Competencia y Demanda", + "Creacion y Propuesta del Naming: 3", + "Propuesta del Logotipo: 3", + "Creacion Logotipo", + "Aplicativos Fisicos: 4", + "Aplicativos Digitales: 4", + "Manual de Identidad", + "Atencion y asesoria al cliente", + "Revisiones", + "Kit Basico para Redes Sociales (1 portada, 1 foto de perfil, 1 template RSS)", + }, + }, + { + Nombre: "Logo e Identidad", + Descripcion: "Diseno de identidad de marca y logotipo", + Fase: 1, + TipoPago: "unico", + PrecioBase: 17283, + TiempoEntrega: "7 - 15 dias", + Categoria: "diseno", + Nivel: "Empresario", + Orden: 103, + EntregablesDefault: []string{ + "Investigacion de Tendencias, Mercado, Competencia y Demanda", + "Creacion y Propuesta del Naming: 4", + "Propuesta del Logotipo: 4", + "Creacion Logotipo", + "Aplicativos Fisicos: 6", + "Aplicativos Digitales: 4", + "Manual de Identidad", + "Atencion y asesoria al cliente", + "Revisiones", + "Kit Basico para Redes Sociales (1 portada, 1 foto de perfil, 4 templates RSS)", + }, + }, + { + Nombre: "Logo e Identidad", + Descripcion: "Diseno de identidad de marca y logotipo", + Fase: 1, + TipoPago: "unico", + PrecioBase: 42368, + TiempoEntrega: "10 - 20 dias", + Categoria: "diseno", + Nivel: "Corporativo", + Orden: 104, + EntregablesDefault: []string{ + "Investigacion de Tendencias, Mercado, Competencia y Demanda", + "Creacion y Propuesta del Naming: 5", + "Propuesta del Logotipo: 5", + "Creacion Logotipo", + "Aplicativos Fisicos: 10", + "Aplicativos Digitales: 4", + "Manual de Identidad", + "Atencion y asesoria al cliente", + "Revisiones", + "Kit Basico para Redes Sociales (3 portadas, 1 foto de perfil, 6 templates RSS)", + "Iconografia", + "Registro del IMPI (10 anos)", + }, + }, + { + Nombre: "Pagina Web", + Descripcion: "Creacion, configuracion y optimizacion de sitio web", + Fase: 1, + TipoPago: "unico", + PrecioBase: 7768, + TiempoEntrega: "15 - 30 dias", + Categoria: "sitio_web", + Nivel: "Emprendedor", + Orden: 111, + EntregablesDefault: []string{ + "Propuesta de Diseno: 2", + "Creacion, Configuracion y Optimizacion de Sitio Web", + "Configuracion de Chat en Sitio Web", + "Optimizacion Basico SEO", + "Optimizacion basica de Velocidad de Carga", + "Estadisticas de Sitio Web (mensual)", + "Cambios de Informacion al Mes (No Acumulable): 1", + "Capacitacion basica para Manejo de Sitio Web", + "Reuniones de Trabajo", + "Alta en Buscadores", + "Cuentas de E-mail con Dominio", + "Paginas base (Gracias/Politicas/Terminos/Contacto/Nosotros/404)", + "Diseno Responsivo", + "Integracion de Formulario", + "Espacio 12 GB", + "Certificado Seguridad SSL (1 ano)", + "Integracion de Hosting (1 ano)", + "Asesoria y Adquisicion de Dominio (1 ano)", + }, + }, + { + Nombre: "Pagina Web", + Descripcion: "Creacion, configuracion y optimizacion de sitio web", + Fase: 1, + TipoPago: "unico", + PrecioBase: 13996, + TiempoEntrega: "15 - 30 dias", + Categoria: "sitio_web", + Nivel: "PYME", + Orden: 112, + EntregablesDefault: []string{ + "Propuesta de Diseno: 4", + "Creacion, Configuracion y Optimizacion de Sitio Web", + "Configuracion de Chat en Sitio Web", + "Optimizacion Basico SEO", + "Optimizacion basica de Velocidad de Carga", + "Estadisticas de Sitio Web (mensual)", + "Cambios de Informacion al Mes (No Acumulable): 2", + "Capacitacion basica para Manejo de Sitio Web", + "Reuniones de Trabajo", + "Alta en Buscadores", + "Cuentas de E-mail con Dominio", + "Paginas base (Gracias/Politicas/Terminos/Contacto/Nosotros/404)", + "Diseno Responsivo", + "Integracion de Formulario", + "Espacio 12 GB", + "Certificado Seguridad SSL (1 ano)", + "Integracion de Hosting (1 ano)", + "Asesoria y Adquisicion de Dominio (1 ano)", + }, + }, + { + Nombre: "Pagina Web", + Descripcion: "Creacion, configuracion y optimizacion de sitio web", + Fase: 1, + TipoPago: "unico", + PrecioBase: 21781, + TiempoEntrega: "20 - 35 dias", + Categoria: "sitio_web", + Nivel: "Empresario", + Orden: 113, + EntregablesDefault: []string{ + "Propuesta de Diseno: 6", + "Creacion, Configuracion y Optimizacion de Sitio Web", + "Configuracion de Chat en Sitio Web", + "Optimizacion Basico SEO", + "Optimizacion basica de Velocidad de Carga", + "Estadisticas de Sitio Web (mensual)", + "Cambios de Informacion al Mes (No Acumulable): 3", + "Investigacion Tendencias, Mercado, Competencia y Demanda", + "Capacitacion basica para Manejo de Sitio Web", + "Reuniones de Trabajo", + "Alta en Buscadores", + "Cuentas de E-mail con Dominio", + "Paginas base (Gracias/Politicas/Terminos/Contacto/Nosotros/404)", + "Diseno Responsivo", + "Integracion de Formulario", + "Espacio 12 GB", + "Integracion Base de Datos para Correo", + "Certificado Seguridad SSL (1 ano)", + "Integracion de Hosting (1 ano)", + "Asesoria y Adquisicion de Dominio (1 ano)", + }, + }, + { + Nombre: "Pagina Web", + Descripcion: "Creacion, configuracion y optimizacion de sitio web", + Fase: 1, + TipoPago: "unico", + PrecioBase: 39254, + TiempoEntrega: "25 - 45 dias", + Categoria: "sitio_web", + Nivel: "Corporativo", + Orden: 114, + EntregablesDefault: []string{ + "Propuesta de Diseno: 8", + "Creacion, Configuracion y Optimizacion de Sitio Web", + "Configuracion de Chat en Sitio Web", + "Optimizacion Avanzado SEO", + "Optimizacion Avanzado de Velocidad de Carga", + "Optimizacion SEO Local", + "Estadisticas de Sitio Web (mensual)", + "Cambios de Informacion al Mes (No Acumulable): 5", + "Investigacion Tendencias, Mercado, Competencia y Demanda", + "Escritura Comercial", + "Capacitacion basica para Manejo de Sitio Web", + "Reuniones de Trabajo", + "Alta en Buscadores", + "Cuentas de E-mail con Dominio", + "Paginas base (incluye Bolsa de Trabajo)", + "Diseno Responsivo", + "Integracion de Formulario", + "Espacio 12 GB", + "Integracion Base de Datos para Correo", + "Certificado Seguridad SSL (1 ano)", + "Integracion de Hosting (1 ano)", + "Asesoria y Adquisicion de Dominio (1 ano)", + "Integracion CRM", + }, + }, + { + Nombre: "Tienda en Linea", + Descripcion: "Desarrollo de tienda en linea (Magento, Shopify, WordPress)", + Fase: 1, + TipoPago: "unico", + PrecioBase: 17283, + TiempoEntrega: "20 - 40 dias", + Categoria: "ecommerce", + Nivel: "Emprendedor", + Orden: 121, + EntregablesDefault: []string{ + "Configuracion en Tienda en Linea (Magento, Shopify, WordPress)", + "Eleccion de plantilla y Estructura de diseno (UX, UI)", + "Desarrollo y Estructura de tienda Optimizada para SEO", + "Creacion y Configuracion de Categorias", + "Diseno y Configuracion de Blog", + "Carga de Productos: 100", + "Capacitacion", + "Atencion y asesoria al cliente", + "Certificado Seguridad SSL (1 ano)", + "Integracion de Hosting (1 ano)", + "Asesoria y Adquisicion de Dominio (1 ano)", + "Integracion de metodos de pago", + "Integracion de metodos de envio", + "Integracion de Chat", + "Integracion y Configuracion de Google Analytics", + "Integracion y Configuracion de Search Console", + }, + }, + { + Nombre: "Tienda en Linea", + Descripcion: "Desarrollo de tienda en linea (Magento, Shopify, WordPress)", + Fase: 1, + TipoPago: "unico", + PrecioBase: 26106, + TiempoEntrega: "25 - 45 dias", + Categoria: "ecommerce", + Nivel: "PYME", + Orden: 122, + EntregablesDefault: []string{ + "Configuracion en Tienda en Linea (Magento, Shopify, WordPress)", + "Eleccion de plantilla y Estructura de diseno (UX, UI)", + "Desarrollo y Estructura de tienda Optimizada para SEO", + "Creacion y Configuracion de Categorias", + "Diseno y Configuracion de Blog", + "Carga de Productos: 250", + "Configuracion de productos seleccionados y recomendados (upsell, cross selling)", + "Capacitacion", + "Atencion y asesoria al cliente", + "Certificado Seguridad SSL (1 ano)", + "Integracion de Hosting (1 ano)", + "Asesoria y Adquisicion de Dominio (1 ano)", + "Integracion de metodos de pago", + "Integracion de metodos de envio", + "Integracion de Chat", + "Integracion y Configuracion de Google Analytics", + "Integracion y Configuracion de Search Console", + "Estrategias para recuperacion de carritos abandonados", + }, + }, + { + Nombre: "Tienda en Linea", + Descripcion: "Desarrollo de tienda en linea (Magento, Shopify, WordPress)", + Fase: 1, + TipoPago: "unico", + PrecioBase: 26106, + TiempoEntrega: "30 - 50 dias", + Categoria: "ecommerce", + Nivel: "Empresario", + Orden: 123, + EntregablesDefault: []string{ + "Configuracion en Tienda en Linea (Magento, Shopify, WordPress)", + "Eleccion de plantilla y Estructura de diseno (UX, UI)", + "Desarrollo y Estructura de tienda Optimizada para SEO", + "Creacion y Configuracion de Categorias", + "Diseno y Configuracion de Blog", + "Carga de Productos: 500", + "Configuracion de productos seleccionados y recomendados (upsell, cross selling)", + "Desarrollo de Contenido SEO", + "Asesoramiento para estrategias de promociones y descuentos", + "Capacitacion", + "Atencion y asesoria al cliente", + "Certificado Seguridad SSL (1 ano)", + "Integracion de Hosting (1 ano)", + "Asesoria y Adquisicion de Dominio (1 ano)", + "Integracion de metodos de pago", + "Integracion de metodos de envio", + "Integracion de Chat", + "Integracion y Configuracion de Google Analytics", + "Integracion y Configuracion de Search Console", + "Estrategias para recuperacion de carritos abandonados", + }, + }, + { + Nombre: "E-commerce", + Descripcion: "Tienda en linea completa: plataforma, hosting, dominio y puesta en marcha", + Fase: 1, + TipoPago: "unico", + PrecioBase: 17283, + TiempoEntrega: "20 - 40 dias", + Categoria: "ecommerce", + Variante: "Hemeroteca", + Nivel: "Emprendedor", + Orden: 131, + EntregablesDefault: []string{ + "Asesoria y Eleccion de Plataforma", + "Hosting, Eleccion y Asesoria de Dominio", + "Certificado SSL", + "Asesoria y Eleccion de Plantilla Base", + "Configuracion en Tienda en Linea", + "Integracion Metodos de Pago", + "Integracion Metodos de Envio", + "Integracion de Chat: 1", + "Configuracion Paginas Transaccionales", + "Integracion Google Analytics", + "Integracion Search Console", + "Estructura Tienda en Linea Optimizada", + "Creacion y Configuracion de Categorias", + "Diseno y Configuracion de Blog", + "Carga de Productos: 100", + "Diseno y Personalizacion de Tienda", + "Capacitacion y Puesta en Marcha", + "Soporte por Correo Electronico (24 hrs)", + "Juntas de Retroalimentacion cada Mes", + }, + }, + { + Nombre: "E-commerce", + Descripcion: "Tienda en linea completa: plataforma, hosting, dominio y puesta en marcha", + Fase: 1, + TipoPago: "unico", + PrecioBase: 26106, + TiempoEntrega: "25 - 45 dias", + Categoria: "ecommerce", + Variante: "Hemeroteca", + Nivel: "PYME", + Orden: 132, + EntregablesDefault: []string{ + "Asesoria y Eleccion de Plataforma", + "Hosting, Eleccion y Asesoria de Dominio", + "Certificado SSL", + "Asesoria y Eleccion de Plantilla Base", + "Configuracion en Tienda en Linea", + "Integracion Metodos de Pago", + "Integracion Metodos de Envio", + "Integracion de Chat: 2", + "Configuracion Paginas Transaccionales", + "Integracion Google Analytics", + "Integracion Search Console", + "Estructura Tienda en Linea Optimizada", + "Creacion y Configuracion de Categorias", + "Diseno y Configuracion de Blog", + "Carga de Productos: 250", + "Diseno y Personalizacion de Tienda", + "Capacitacion y Puesta en Marcha", + "Soporte por Correo Electronico (12 hrs)", + "Juntas de Retroalimentacion cada Mes", + }, + }, + { + Nombre: "E-commerce", + Descripcion: "Tienda en linea completa: plataforma, hosting, dominio y puesta en marcha", + Fase: 1, + TipoPago: "unico", + PrecioBase: 34756, + TiempoEntrega: "30 - 50 dias", + Categoria: "ecommerce", + Variante: "Hemeroteca", + Nivel: "Empresario", + Orden: 133, + EntregablesDefault: []string{ + "Asesoria y Eleccion de Plataforma", + "Hosting, Eleccion y Asesoria de Dominio", + "Certificado SSL", + "Asesoria y Eleccion de Plantilla Base", + "Configuracion en Tienda en Linea", + "Integracion Metodos de Pago", + "Integracion Metodos de Envio", + "Integracion de Chat: 3", + "Configuracion Paginas Transaccionales", + "Integracion Google Analytics", + "Integracion Search Console", + "Estructura Tienda en Linea Optimizada", + "Creacion y Configuracion de Categorias", + "Diseno y Configuracion de Blog", + "Carga de Productos: 500", + "Diseno y Personalizacion de Tienda", + "Capacitacion y Puesta en Marcha", + "Soporte por Correo Electronico (8 hrs)", + "Juntas de Retroalimentacion cada Mes", + "Diseno Responsivo UX", + "Configuracion de Carritos Abandonados", + "Up-Selling, Cross-Selling", + }, + }, + { + Nombre: "E-commerce", + Descripcion: "Tienda en linea completa: plataforma, hosting, dominio y puesta en marcha", + Fase: 1, + TipoPago: "unico", + PrecioBase: 43579, + TiempoEntrega: "35 - 60 dias", + Categoria: "ecommerce", + Variante: "Hemeroteca", + Nivel: "Corporativo", + Orden: 134, + EntregablesDefault: []string{ + "Asesoria y Eleccion de Plataforma", + "Hosting, Eleccion y Asesoria de Dominio", + "Certificado SSL", + "Asesoria y Eleccion de Plantilla Base", + "Configuracion en Tienda en Linea", + "Integracion Metodos de Pago", + "Integracion Metodos de Envio", + "Integracion de Chat: 4", + "Configuracion Paginas Transaccionales", + "Integracion Google Analytics", + "Integracion Search Console", + "Estructura Tienda en Linea Optimizada", + "Creacion y Configuracion de Categorias", + "Diseno y Configuracion de Blog", + "Carga de Productos: ilimitados", + "Diseno y Personalizacion de Tienda", + "Capacitacion y Puesta en Marcha", + "Soporte por Correo Electronico (inmediata)", + "Juntas de Retroalimentacion cada Mes", + "Diseno Responsivo UX", + "Configuracion de Carritos Abandonados", + "Up-Selling, Cross-Selling", + "Desarrollo Contenido SEO", + "Asesoramiento Promociones y Descuentos", + "Configuracion Programas de Lealtad", + }, + }, + { + Nombre: "Menu Digital", + Descripcion: "Menu digital con QR personalizado", + Fase: 1, + TipoPago: "unico", + PrecioBase: 1713, + TiempoEntrega: "7 - 15 dias", + Categoria: "sitio_web", + Nivel: "Emprendedor", + Orden: 141, + EntregablesDefault: []string{ + "Diseno de Menu Digital", + "QR Personalizado / Dinamico", + "Diseno de Pegatinas", + "Un Idioma (Espanol)", + "Lecturas Ilimitadas", + "Alojamiento de Menu y QR", + "Soporte por Ticket", + "Juntas de Retroalimentacion Cada Mes", + }, + }, + { + Nombre: "Menu Digital", + Descripcion: "Menu digital con QR personalizado", + Fase: 1, + TipoPago: "unico", + PrecioBase: 3443, + TiempoEntrega: "7 - 15 dias", + Categoria: "sitio_web", + Nivel: "PYME", + Orden: 142, + EntregablesDefault: []string{ + "Diseno de Menu Digital", + "QR Personalizado / Dinamico", + "Diseno de Pegatinas", + "Un Idioma (Espanol)", + "Lecturas Ilimitadas", + "Alojamiento de Menu y QR", + "Soporte por Ticket", + "Juntas de Retroalimentacion Cada Mes", + "Integracion de Redes Sociales", + "Hasta 100 Productos", + "Actualizaciones por Ano: 10", + "Boton de WhatsApp", + "Promocion Mensual", + "Captacion de Base de Datos", + "E-mail Marketing Automation", + "Templates a Elegir: 5", + }, + }, + { + Nombre: "Menu Digital", + Descripcion: "Menu digital con QR personalizado", + Fase: 1, + TipoPago: "unico", + PrecioBase: 5173, + TiempoEntrega: "10 - 20 dias", + Categoria: "sitio_web", + Nivel: "Empresario", + Orden: 143, + EntregablesDefault: []string{ + "Diseno de Menu Digital", + "QR Personalizado / Dinamico", + "Diseno de Pegatinas", + "Un Idioma (Espanol)", + "Lecturas Ilimitadas", + "Alojamiento de Menu y QR", + "Soporte por Ticket", + "Juntas de Retroalimentacion Cada Mes", + "Integracion de Redes Sociales", + "Hasta 100 Productos", + "Actualizaciones por Ano: 10", + "Boton de WhatsApp", + "Promocion Mensual", + "Captacion de Base de Datos", + "E-mail Marketing Automation", + "Templates a Elegir: 5", + "Pagina Web (Menu Digital)", + "Pago en Linea", + "Personalizacion de Productos", + "Guia de Nutricion por Producto", + "Multiples Addons", + "Notificacion de Nueva Orden", + "Mensajes de Horarios de Atencion", + "Multiples Menus o Secciones", + "100% Responsivo", + "Etiquetas Personalizables", + }, + }, + { + Nombre: "Google Ads", + Descripcion: "Creacion, configuracion y optimizacion de campanas Google Ads", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 2578, + TiempoEntrega: "Servicio mensual", + Categoria: "ads", + Nivel: "Emprendedor", + Orden: 201, + EntregablesDefault: []string{ + "Creacion y Configuracion de cuenta Google Ads", + "Investigacion y Optimizacion de palabras clave positivas y negativas", + "Creacion de Campanas Publicitarias: 1 a 3", + "Optimizacion de presupuesto de Campanas diaria", + "Integracion con Google Analytics", + "Integracion de etiqueta de pixeles de conversion", + "Reporte de Resultado mensual y junta de retroalimentacion", + "Atencion y asesoria al cliente", + }, + }, + { + Nombre: "Google Ads", + Descripcion: "Creacion, configuracion y optimizacion de campanas Google Ads", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 5173, + TiempoEntrega: "Servicio mensual", + Categoria: "ads", + Nivel: "PYME", + Orden: 202, + EntregablesDefault: []string{ + "Creacion y Configuracion de cuenta Google Ads", + "Investigacion y Optimizacion de palabras clave positivas y negativas", + "Creacion de Campanas Publicitarias: 1 a 6", + "Optimizacion de presupuesto de Campanas diaria", + "Configuracion de Anuncios de Remarketing", + "Integracion con Google Analytics", + "Integracion de etiqueta de pixeles de conversion", + "Reporte de Resultado mensual y junta de retroalimentacion", + "Atencion y asesoria al cliente", + }, + }, + { + Nombre: "Google Ads", + Descripcion: "Creacion, configuracion y optimizacion de campanas Google Ads", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 10363, + TiempoEntrega: "Servicio mensual", + Categoria: "ads", + Nivel: "Empresario", + Orden: 203, + EntregablesDefault: []string{ + "Creacion y Configuracion de cuenta Google Ads", + "Investigacion y Optimizacion de palabras clave positivas y negativas", + "Creacion de Campanas Publicitarias: 10", + "Optimizacion de presupuesto de Campanas diaria", + "Configuracion de Anuncios de Remarketing", + "Configuracion de Anuncios para Red Display", + "Automatizacion de envio de Ficha de Prospectos", + "Integracion con Google Analytics", + "Integracion de etiqueta de pixeles de conversion", + "Integracion de Herramientas de automatizacion", + "Reporte de Resultado mensual y junta de retroalimentacion", + "Atencion y asesoria al cliente", + }, + }, + { + Nombre: "Google Ads", + Descripcion: "Creacion, configuracion y optimizacion de campanas Google Ads", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 17456, + TiempoEntrega: "Servicio mensual", + Categoria: "ads", + Nivel: "Corporativo", + Orden: 204, + EntregablesDefault: []string{ + "Creacion y Configuracion de cuenta Google Ads", + "Investigacion y Optimizacion de palabras clave positivas y negativas", + "Creacion de Campanas Publicitarias: 15", + "Optimizacion de presupuesto de Campanas diaria", + "Configuracion de Anuncios de Remarketing", + "Configuracion de Anuncios para Red Display", + "Configuracion de Google Merchant Center", + "Configuracion y Optimizacion del Fit de productos", + "Configuracion de Campanas para Shopping", + "Configuracion de cuenta BING", + "Configuracion de Campanas BING", + "Automatizacion de envio de Ficha de Prospectos", + "Integracion con Google Analytics", + "Integracion de etiqueta de pixeles de conversion", + "Integracion de Herramientas de automatizacion", + "Reporte de Resultado mensual y junta de retroalimentacion", + "Atencion y asesoria al cliente", + }, + }, + { + Nombre: "Facebook & Instagram Ads", + Descripcion: "Creacion y optimizacion de campanas en Meta (Facebook e Instagram)", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 2578, + TiempoEntrega: "Servicio mensual", + Categoria: "ads", + Nivel: "Emprendedor", + Orden: 211, + EntregablesDefault: []string{ + "Investigacion, Segmentacion y Optimizacion del Publico Objetivo", + "Creacion y Configuracion del Administrador de Anuncios", + "Creacion de Artes para Anuncios Publicitarios", + "Creacion y Configuracion de Campanas Publicitarias: 1 a 3", + "Configuracion de lista de Remarketing", + "Optimizacion de presupuesto diario y campanas publicitarias", + "Instalacion de Pixeles en Pag. Web", + "Reporte de Resultado mensual y junta de retroalimentacion", + "Atencion y asesoria al cliente", + }, + }, + { + Nombre: "Facebook & Instagram Ads", + Descripcion: "Creacion y optimizacion de campanas en Meta (Facebook e Instagram)", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 5173, + TiempoEntrega: "Servicio mensual", + Categoria: "ads", + Nivel: "PYME", + Orden: 212, + EntregablesDefault: []string{ + "Investigacion, Segmentacion y Optimizacion del Publico Objetivo", + "Creacion y Configuracion del Administrador de Anuncios", + "Creacion de Artes para Anuncios Publicitarios", + "Creacion y Configuracion de Campanas Publicitarias: 1 a 6", + "Configuracion de lista de Remarketing", + "Optimizacion de presupuesto diario y campanas publicitarias", + "Instalacion de Pixeles en Pag. Web", + "Reporte de Resultado mensual y junta de retroalimentacion", + "Atencion y asesoria al cliente", + }, + }, + { + Nombre: "Facebook & Instagram Ads", + Descripcion: "Creacion y optimizacion de campanas en Meta (Facebook e Instagram)", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 6903, + TiempoEntrega: "Servicio mensual", + Categoria: "ads", + Nivel: "Empresario", + Orden: 213, + EntregablesDefault: []string{ + "Investigacion, Segmentacion y Optimizacion del Publico Objetivo", + "Creacion y Configuracion del Administrador de Anuncios", + "Creacion de Artes para Anuncios Publicitarios", + "Creacion y Configuracion de Campanas Publicitarias: 1 a 8", + "Configuracion de lista de Remarketing", + "Optimizacion de presupuesto diario y campanas publicitarias", + "Instalacion de Pixeles en Pag. Web", + "Integracion de herramientas de automatizacion", + "Reporte de Resultado mensual y junta de retroalimentacion", + "Atencion y asesoria al cliente", + }, + }, + { + Nombre: "Facebook & Instagram Ads", + Descripcion: "Creacion y optimizacion de campanas en Meta (Facebook e Instagram)", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 13131, + TiempoEntrega: "Servicio mensual", + Categoria: "ads", + Nivel: "Corporativo", + Orden: 214, + EntregablesDefault: []string{ + "Investigacion, Segmentacion y Optimizacion del Publico Objetivo", + "Creacion y Configuracion del Administrador de Anuncios", + "Creacion de Artes para Anuncios Publicitarios", + "Creacion y Configuracion de Campanas Publicitarias: 1 a 15", + "Creacion de Anuncios para Shopping", + "Configuracion de lista de Remarketing", + "Configuracion de catalogo de Productos de Facebook", + "Optimizacion de presupuesto diario y campanas publicitarias", + "Instalacion de Pixeles en Pag. Web", + "Integracion de herramientas de automatizacion", + "Reporte de Resultado mensual y junta de retroalimentacion", + "Atencion y asesoria al cliente", + }, + }, + { + Nombre: "Manejo de Redes Sociales", + Descripcion: "Gestion y contenido de redes sociales", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 6903, + TiempoEntrega: "Servicio mensual", + Categoria: "redes", + Nivel: "Emprendedor", + Orden: 221, + EntregablesDefault: []string{ + "Creacion, Configuracion y/o Optimizacion de pagina de Facebook", + "Medicion de conversiones", + "Estrategia de contenido Publicitario", + "Creacion de embudo de conversion", + "Desarrollo de Cover", + "Creacion de artes y copys para Post", + "Posteos de Publicacion al mes: 10", + "Asesoria al cliente por correo electronico (24 hrs)", + "Informes periodicos", + "Integracion de Google Analytics", + }, + }, + { + Nombre: "Manejo de Redes Sociales", + Descripcion: "Gestion y contenido de redes sociales", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 12093, + TiempoEntrega: "Servicio mensual", + Categoria: "redes", + Nivel: "PYME", + Orden: 222, + EntregablesDefault: []string{ + "Creacion, Configuracion y/o Optimizacion de pagina de Facebook", + "Medicion de conversiones", + "Estrategia de contenido Publicitario", + "Creacion de embudo de conversion", + "Desarrollo de Cover", + "Creacion de artes y copys para Post", + "Posteos de Publicacion al mes: 15", + "Asesoria al cliente por correo electronico (24 hrs)", + "Informes periodicos", + "Integracion de Google Analytics", + "Integracion Search Console", + "Desarrollo Tienda en Linea Optimizada", + "Video", + }, + }, + { + Nombre: "Manejo de Redes Sociales", + Descripcion: "Gestion y contenido de redes sociales", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 17456, + TiempoEntrega: "Servicio mensual", + Categoria: "redes", + Nivel: "Empresario", + Orden: 223, + EntregablesDefault: []string{ + "Creacion, Configuracion y/o Optimizacion de pagina de Facebook", + "Medicion de conversiones", + "Estrategia de contenido Publicitario", + "Creacion de embudo de conversion", + "Desarrollo de Cover", + "Creacion de artes y copys para Post", + "Posteos de Publicacion al mes: 15", + "Asesoria al cliente por correo electronico (24 hrs)", + "Informes periodicos", + "Integracion de Google Analytics", + "Integracion Search Console", + "Desarrollo Tienda en Linea Optimizada", + "Video", + "Gifs", + "Dinamicas", + }, + }, + { + Nombre: "Manejo de Redes Sociales", + Descripcion: "Gestion y contenido de redes sociales", + Fase: 2, + TipoPago: "mensual", + PrecioBase: 42195, + TiempoEntrega: "Servicio mensual", + Categoria: "redes", + Nivel: "Corporativo", + Orden: 224, + EntregablesDefault: []string{ + "Creacion, Configuracion y/o Optimizacion de pagina de Facebook", + "Medicion de conversiones", + "Estrategia de contenido Publicitario", + "Creacion de embudo de conversion", + "Desarrollo de Cover", + "Creacion de artes y copys para Post", + "Posteos de Publicacion al mes: 15", + "Asesoria al cliente por correo electronico (24 hrs)", + "Informes periodicos", + "Integracion de Google Analytics", + "Integracion Search Console", + "Desarrollo Tienda en Linea Optimizada", + "Video", + "Gifs", + "Dinamicas", + "Concursos", + "Manejo Inmediato de Crisis", + }, + }, + { + Nombre: "Posicionamiento SEO", + Descripcion: "Estrategia y posicionamiento SEO mensual", + Fase: 3, + TipoPago: "mensual", + PrecioBase: 3443, + TiempoEntrega: "Servicio mensual", + Categoria: "seo", + Nivel: "Emprendedor", + Orden: 301, + EntregablesDefault: []string{ + "No. KeyWords: 5", + "Estudio y definicion de Palabras Clave", + "Analisis de la competencia", + "Optimizacion tecnica de la estructura del Sitio a nivel SEO", + "Optimizacion de la velocidad de carga en Sitio", + "Creacion y Optimizacion del Sitemap.xml", + "Reporte mensual de trafico y posicion Web", + "Integracion y Configuracion de Google Search Console", + "Integracion y Configuracion de Google Analytics", + "Plan para desarrollo de contenido Estrategico para SEO", + "Estrategia y Generacion de BackLinks", + "Alta de Buscadores", + "Generacion de trafico social a tu Sitio Web", + "Sindicacion en Redes Sociales Externas", + "Atencion y asesoria al cliente", + }, + }, + { + Nombre: "Posicionamiento SEO", + Descripcion: "Estrategia y posicionamiento SEO mensual", + Fase: 3, + TipoPago: "mensual", + PrecioBase: 5173, + TiempoEntrega: "Servicio mensual", + Categoria: "seo", + Nivel: "PYME", + Orden: 302, + EntregablesDefault: []string{ + "No. KeyWords: 10", + "Estudio y definicion de Palabras Clave", + "Analisis de la competencia", + "Optimizacion tecnica de la estructura del Sitio a nivel SEO", + "Optimizacion de la velocidad de carga en Sitio", + "Optimizacion de SEO local (Google My Business)", + "Creacion y Optimizacion del Sitemap.xml", + "Reporte mensual de trafico y posicion Web", + "Integracion y Configuracion de Google Search Console", + "Integracion y Configuracion de Google Analytics", + "Plan para desarrollo de contenido Estrategico para SEO", + "Estrategia y Generacion de BackLinks", + "Alta de Buscadores", + "Generacion de trafico social a tu Sitio Web", + "Sindicacion en Redes Sociales Externas", + "Atencion y asesoria al cliente", + }, + }, + { + Nombre: "Posicionamiento SEO", + Descripcion: "Estrategia y posicionamiento SEO mensual", + Fase: 3, + TipoPago: "mensual", + PrecioBase: 6903, + TiempoEntrega: "Servicio mensual", + Categoria: "seo", + Nivel: "Empresario", + Orden: 303, + EntregablesDefault: []string{ + "No. KeyWords: 15", + "Estudio y definicion de Palabras Clave", + "Analisis de la competencia", + "Optimizacion tecnica de la estructura del Sitio a nivel SEO", + "Optimizacion de la velocidad de carga en Sitio", + "Optimizacion de SEO local (Google My Business)", + "Creacion y Optimizacion del Sitemap.xml", + "Reporte mensual de trafico y posicion Web", + "Integracion y Configuracion de Google Search Console: 15", + "Integracion y Configuracion de Google Analytics", + "Plan para desarrollo de contenido Estrategico para SEO", + "Estrategia y Generacion de BackLinks", + "Alta de Buscadores", + "Generacion de trafico social a tu Sitio Web", + "Sindicacion en Redes Sociales Externas", + "Desarrollo de contenido para Sitios Externos", + "Atencion y asesoria al cliente", + }, + }, + { + Nombre: "Posicionamiento SEO", + Descripcion: "Estrategia y posicionamiento SEO mensual", + Fase: 3, + TipoPago: "mensual", + PrecioBase: 8633, + TiempoEntrega: "Servicio mensual", + Categoria: "seo", + Nivel: "Corporativo", + Orden: 304, + EntregablesDefault: []string{ + "No. KeyWords: 20", + "Estudio y definicion de Palabras Clave", + "Analisis de la competencia", + "Optimizacion tecnica de la estructura del Sitio a nivel SEO", + "Optimizacion de la velocidad de carga en Sitio", + "Optimizacion de SEO local (Google My Business)", + "Creacion y Optimizacion del Sitemap.xml", + "Reporte mensual de trafico y posicion Web", + "Integracion y Configuracion de Google Search Console: 15", + "Integracion y Configuracion de Google Analytics", + "Plan para desarrollo de contenido Estrategico para SEO", + "Estrategia y Generacion de BackLinks", + "Alta de Buscadores", + "Generacion de trafico social a tu Sitio Web", + "Sindicacion en Redes Sociales Externas", + "Desarrollo de contenido para Sitios Externos", + "Atencion y asesoria al cliente", + }, + }, + { + Nombre: "Estrategia Empresarial en Ecommerce", + Descripcion: "Auditoria y estrategia integral para ecommerce (SEO, tecnica y seguridad Shopify, estudios de mercado/competencia y embudos de venta)", + Fase: 0, + TipoPago: "unico", + PrecioBase: 12900, + TiempoEntrega: "10 - 20 dias", + Categoria: "estrategia", + Orden: 100, + EntregablesDefault: []string{ + "Auditoria completa de situacion actual del SEO del Sitio", + "Auditoria Tecnica de Shopify", + "Auditoria en Seguridad de Shopify", + "Estudio de canales de comunicacion y captacion", + "Estudio de Segmentos de Mercado para Landing Pages de prospeccion", + "Estudio de Keyword Research para Categorizacion Jerarquica de Ecommerce", + "Estudio de Keyword Research para creacion de Landing Page para prospeccion", + "Estudio de competencia organica", + "Estudio de competencia pagada", + "Estudio de tendencias", + "Adicional: Embudo de ventas para Ecommerce", + "Adicional: Embudo de ventas para captacion", + }, + }, + } +} + +func DefaultFasesGeneral() []FasePaqueteSeed { + return []FasePaqueteSeed{ + {Orden: 0, Nombre: "Auditoria / Acompanamiento"}, + {Orden: 1, Nombre: "Setup e Infraestructura"}, + {Orden: 2, Nombre: "Publicidad y Manejo"}, + {Orden: 3, Nombre: "Contenido y SEO"}, + } +} + +func DefaultPaquetesPyme() []PaqueteSeed { + return []PaqueteSeed{ + { + ID: "paquete-arranque", + Nombre: "Arranque Esencial", + Descripcion: "Inicio - cualquier giro. Minimo viable para una PyME que arranca: presencia profesional en redes y Google, y primeros clientes.", + Fases: []FasePaqueteSeed{ + { + Orden: 0, + Nombre: "Auditoria / Acompanamiento", + Servicios: []ServRef{ + {Nombre: "Auditoria en Redes Sociales"}, + }, + }, + { + Orden: 1, + Nombre: "Setup e Infraestructura", + Servicios: []ServRef{ + {Nombre: "Creacion y Optimizacion de Redes Sociales"}, + {Nombre: "Creacion y Optimizacion de la Ficha de Google My Business"}, + }, + }, + { + Orden: 2, + Nombre: "Publicidad y Manejo", + Servicios: []ServRef{ + {Nombre: "Manejo Basico de Redes Sociales"}, + }, + }, + }, + }, + { + ID: "paquete-marca", + Nombre: "Marca + Presencia", + Descripcion: "Inicio - marca nueva o personal. Imagen profesional (identidad), redes y primeras campanas de alcance antes de invertir en pauta fuerte.", + Fases: []FasePaqueteSeed{ + { + Orden: 0, + Nombre: "Auditoria / Acompanamiento", + Servicios: []ServRef{ + {Nombre: "Auditoria en Redes Sociales"}, + }, + }, + { + Orden: 1, + Nombre: "Setup e Infraestructura", + Servicios: []ServRef{ + {Nombre: "Logo e Identidad", Nivel: "Emprendedor"}, + {Nombre: "Creacion y Optimizacion de Redes Sociales"}, + {Nombre: "Creacion y Optimizacion de la Ficha de Google My Business"}, + }, + }, + { + Orden: 2, + Nombre: "Publicidad y Manejo", + Servicios: []ServRef{ + {Nombre: "Manejo Basico de Redes Sociales"}, + {Nombre: "Manejo y Optimizacion de Meta Ads"}, + }, + }, + { + Orden: 3, + Nombre: "Contenido y SEO", + Servicios: []ServRef{ + {Nombre: "Desarrollo de Plan de Contenido"}, + }, + }, + }, + }, + { + ID: "paquete-local", + Nombre: "Negocio Local en Crecimiento", + Descripcion: "Crecimiento - giro local (restaurante, consultorio, tienda fisica, servicios). Visibilidad local y captacion por WhatsApp/llamada: web, ficha de Google, redes, Meta Ads y SEO local.", + Fases: []FasePaqueteSeed{ + { + Orden: 0, + Nombre: "Auditoria / Acompanamiento", + Servicios: []ServRef{ + {Nombre: "Auditoria en Sitio Web"}, + }, + }, + { + Orden: 1, + Nombre: "Setup e Infraestructura", + Servicios: []ServRef{ + {Nombre: "Pagina Web", Nivel: "Emprendedor"}, + {Nombre: "Creacion y Optimizacion de la Ficha de Google My Business"}, + {Nombre: "Creacion y Optimizacion de Redes Sociales"}, + }, + }, + { + Orden: 2, + Nombre: "Publicidad y Manejo", + Servicios: []ServRef{ + {Nombre: "Manejo Basico de Redes Sociales"}, + {Nombre: "Manejo y Optimizacion de Meta Ads"}, + }, + }, + { + Orden: 3, + Nombre: "Contenido y SEO", + Servicios: []ServRef{ + {Nombre: "Posicionamiento SEO"}, + }, + }, + }, + }, + { + ID: "paquete-leads-b2b", + Nombre: "Servicios / B2B: Generacion de Leads", + Descripcion: "Crecimiento - servicios profesionales / B2B. Motor de prospeccion: sitio web solido, CRM Bucefalo, campanas de Google Ads, contenido y SEO.", + Fases: []FasePaqueteSeed{ + { + Orden: 0, + Nombre: "Auditoria / Acompanamiento", + Servicios: []ServRef{ + {Nombre: "Auditoria en Sitio Web"}, + {Nombre: "Estudio Digital de Mercado"}, + }, + }, + { + Orden: 1, + Nombre: "Setup e Infraestructura", + Servicios: []ServRef{ + {Nombre: "Diseno de Sitio Web (WordPress)"}, + {Nombre: "Configuracion y Puesta en Marcha del CRM Bucefalo"}, + {Nombre: "Configuracion, Optimizacion y Puesta en Marcha de Google Ads y Meta Ads"}, + }, + }, + { + Orden: 2, + Nombre: "Publicidad y Manejo", + Servicios: []ServRef{ + {Nombre: "Configuracion y Optimizacion Google Ads"}, + {Nombre: "Plan Mensual CRM Bucefalo"}, + }, + }, + { + Orden: 3, + Nombre: "Contenido y SEO", + Servicios: []ServRef{ + {Nombre: "Desarrollo de Plan de Contenido"}, + {Nombre: "Posicionamiento SEO"}, + }, + }, + }, + }, + { + ID: "paquete-ecommerce", + Nombre: "Ecommerce Lanzamiento", + Descripcion: "Inicio / Crecimiento - ecommerce. Vender en linea desde cero con buen setup de medicion y pauta: tienda WooCommerce, CRM y campanas de Google y Meta.", + Fases: []FasePaqueteSeed{ + { + Orden: 0, + Nombre: "Auditoria / Acompanamiento", + Servicios: []ServRef{ + {Nombre: "Auditoria en Ecommerce"}, + }, + }, + { + Orden: 1, + Nombre: "Setup e Infraestructura", + Servicios: []ServRef{ + {Nombre: "Diseno de Ecommerce (WooCommerce)"}, + {Nombre: "Configuracion, Optimizacion y Puesta en Marcha de Google Ads y Meta Ads"}, + {Nombre: "Configuracion y Puesta en Marcha del CRM Bucefalo"}, + }, + }, + { + Orden: 2, + Nombre: "Publicidad y Manejo", + Servicios: []ServRef{ + {Nombre: "Manejo y Optimizacion de Meta Ads"}, + {Nombre: "Configuracion y Optimizacion Google Ads"}, + }, + }, + }, + }, + { + ID: "paquete-360", + Nombre: "Escalamiento 360 Integral", + Descripcion: "Escalamiento - negocio consolidado, cualquier giro. Paquete tope: ads en niveles altos, redes profesionales, contenido, SEO completo y acompanamiento estrategico. El asesor recorta segun presupuesto.", + Fases: []FasePaqueteSeed{ + { + Orden: 0, + Nombre: "Auditoria / Acompanamiento", + Servicios: []ServRef{ + {Nombre: "Auditoria en Sitio Web"}, + {Nombre: "Auditoria de cuentas Google Ads y Meta Ads"}, + {Nombre: "Estudio Digital de Mercado"}, + {Nombre: "Plan de Acompanamiento Integral"}, + }, + }, + { + Orden: 1, + Nombre: "Setup e Infraestructura", + Servicios: []ServRef{ + {Nombre: "Diseno de Identidad Corporativa"}, + {Nombre: "Diseno de Sitio Web (WordPress)"}, + {Nombre: "Configuracion y Puesta en Marcha del CRM Bucefalo"}, + {Nombre: "Configuracion, Optimizacion y Puesta en Marcha de Google Ads y Meta Ads"}, + }, + }, + { + Orden: 2, + Nombre: "Publicidad y Manejo", + Servicios: []ServRef{ + {Nombre: "Google Ads", Nivel: "Empresario"}, + {Nombre: "Facebook & Instagram Ads", Nivel: "Empresario"}, + {Nombre: "Manejo de Redes Sociales", Nivel: "PYME"}, + {Nombre: "Plan Mensual CRM Bucefalo"}, + }, + }, + { + Orden: 3, + Nombre: "Contenido y SEO", + Servicios: []ServRef{ + {Nombre: "Desarrollo de Plan de Contenido"}, + {Nombre: "Generacion de Contenido"}, + {Nombre: "Estrategia SEO Completa"}, + }, + }, + }, + }, + } +} + +func DefaultBonos() []BonoSeed { + return []BonoSeed{ + {Numero: 1, Titulo: "Servicio Centinela Web", Descripcion: "30 minutos mensuales en servicios Centinela (Sitio Web)"}, + {Numero: 2, Titulo: "Workshop Buyer Persona", Descripcion: "Workshop Estrategico de Buyer Persona"}, + {Numero: 3, Titulo: "Workshop Propuesta de Valor", Descripcion: "Workshop de Propuestas de Valor y Oferta Irresistible"}, + {Numero: 4, Titulo: "Membresia Premium", Descripcion: "1 ano de Membresia Premium"}, + {Numero: 5, Titulo: "Mes Gratis Bucefalo", Descripcion: "Un mes gratis de Bucefalo CRM, Marketing y Ventas"}, + {Numero: 6, Titulo: "Script de Ventas", Descripcion: "Script de Ventas con mas de 100 complementos"}, + } +} + +func DefaultFinanciamientoPlanes() []FinanciamientoSeed { + return []FinanciamientoSeed{ + {Meses: 3, Tasa: 0.077, Comision: 2.5, MontoMinimo: 300, IVA: 0.16}, + {Meses: 6, Tasa: 0.107, Comision: 2.5, MontoMinimo: 600, IVA: 0.16}, + {Meses: 9, Tasa: 0.137, Comision: 2.5, MontoMinimo: 900, IVA: 0.16}, + {Meses: 12, Tasa: 0.167, Comision: 2.5, MontoMinimo: 1200, IVA: 0.16}, + } +} + +func DefaultConfigs() []ConfigSeed { + return []ConfigSeed{ + {Clave: "razon_social", Valor: "URIEL JARETH ALVARADO ORTIZ"}, + {Clave: "rfc", Valor: "AAOU970201SU7"}, + {Clave: "domicilio_fiscal", Valor: ""}, + {Clave: "cuenta_nacional", Valor: "012227015788120440"}, + {Clave: "clabe_interbancaria", Valor: "012227015788120440"}, + {Clave: "cuenta_internacional", Valor: "Beneficiario: URIEL JARETH ALVARADO ORTIZ\nCLABE: 012227015788120440\nBanco: BBVA"}, + {Clave: "cuenta_internacional_swift", Valor: "Beneficiario: URIEL JARETH ALVARADO ORTIZ\nCodigo SWIFT / BIC: BCMRMXMMPYM\nCLABE: 012227015788120440\nBanco: BBVA Mexico"}, + {Clave: "hora_centinela", Valor: "700"}, + {Clave: "anualidad_hosting", Valor: "5000"}, + {Clave: "iva", Valor: "0.16"}, + {Clave: "terminos_condiciones", Valor: "- Esta cotizacion tiene una vigencia de 15 dias habiles.\n- Cualquier ajuste al proyecto despues de la aprobacion del contenido afectara la fecha de entrega y por consiguiente el costo.\n- El cliente debera proporcionar la informacion solicitada por Uriel Jareth Consulting en tiempo y forma.\n- Si la falta de informacion provoca un excedente en los plazos de entrega del proyecto, las horas adicionales de servicio se cotizaran por separado.\n- Los pagos correspondientes a los servicios mensuales deberan realizarse en los primeros 5 dias del mes.\n- Todo el material e informacion necesarios para la realizacion del sitio web deberan ser entregados en un plazo maximo de 40 dias naturales a partir del arranque del proyecto."}, + {Clave: "no_incluye", Valor: "- Generacion de disenos, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado. (Estos servicios son Extras, pueden ser realizados por Uriel Jareth Consulting y se cotizan como adicionales mediante cotizacion).\n- Redaccion de entradas de Blog.\n- Integracion de Servicios de terceros ajenos a los cotizados.\n- Servicio de Recuperacion de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads (En Caso de Requerir el Servicio se Aplicara uso de Hora Centinela).\n- Creacion de Redes Sociales (En Caso de Requerir el Servicio Incluira un Costo Adicional)."}, + {Clave: "notas_adicionales", Valor: "- El presente proyecto debera tener un responsable oficial, a quien se le compartiran los avances y con quien se mantendra la comunicacion.\n- La Hora Centinela tiene un precio de $700.00 MXN.\n- Nuestros servicios incluyen la entrega de archivos finales listos para su uso (JPG, PNG, PDF, etc.). Los archivos editables/fuente (AI, PSD) son propiedad intelectual de la agencia y no estan incluidos, salvo en proyectos de Branding/Logotipos.\n- SI EL PROYECTO SE PAUSA POR RAZONES AJENAS A URIEL JARETH CONSULTING O FALTA DE CONTINUIDAD, ESTO GENERARA COSTO EXTRA PARA RETOMAR EL PROYECTO (SE CONSIDERARA UN COSTO QUE PUEDE IR DEL 15% AL 30% CON BASE A LA COTIZACION INICIAL)."}, + {Clave: "color_primario", Valor: "#0400C4"}, + {Clave: "color_secundario", Valor: "#0F172A"}, + {Clave: "logo_base64", Valor: ""}, + } +} diff --git a/internal/seed/provision.go b/internal/seed/provision.go new file mode 100644 index 0000000..99f54f3 --- /dev/null +++ b/internal/seed/provision.go @@ -0,0 +1,376 @@ +package seed + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "strconv" + "strings" + "time" + + "cotizador/internal/auth" + "cotizador/internal/db" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +// AgentKeyPreset defines a named agent API key preset. +type AgentKeyPreset struct { + Nombre string + Scopes []string + RateLimitPerMin int +} + +// DefaultAgentPresets returns the 5 standard agent API key presets matching scripts/provision-agent-keys.ts. +func DefaultAgentPresets() []AgentKeyPreset { + return []AgentKeyPreset{ + { + Nombre: "sales-agent", + Scopes: []string{ + "catalogo:leer", + "clientes:leer", + "clientes:escribir", + "cotizaciones:leer", + "cotizaciones:borrador", + "cotizaciones:enviar", + }, + RateLimitPerMin: 60, + }, + { + Nombre: "jefe-operaciones", + Scopes: []string{ + "catalogo:leer", + "clientes:leer", + "cotizaciones:leer", + "cobros:leer", + }, + RateLimitPerMin: 120, + }, + { + Nombre: "cobranza", + Scopes: []string{ + "clientes:leer", + "cobros:leer", + }, + RateLimitPerMin: 60, + }, + { + Nombre: "entrega", + Scopes: []string{ + "clientes:leer", + "cotizaciones:leer_aceptadas", + }, + RateLimitPerMin: 60, + }, + { + Nombre: "n8n-ecosystem", + Scopes: []string{ + "catalogo:leer", + "clientes:leer", + "cotizaciones:leer", + "cotizaciones:enviar", + "cobros:leer", + }, + RateLimitPerMin: 180, + }, + } +} + +type provisionOpts struct { + List bool + Preset bool + Rotate bool + Nombre string + Scopes []string + RateLimitPerMin int + HasRateLimit bool +} + +func parseProvisionArgs(args []string) (provisionOpts, error) { + opts := provisionOpts{RateLimitPerMin: 60} + for i := 0; i < len(args); i++ { + tok := args[i] + if !strings.HasPrefix(tok, "--") { + continue + } + key := tok[2:] + var val string + hasEq := false + if eq := strings.IndexByte(key, '='); eq >= 0 { + val = key[eq+1:] + key = key[:eq] + hasEq = true + } + + nextVal := func() string { + if hasEq { + return val + } + if i+1 < len(args) && !strings.HasPrefix(args[i+1], "--") { + i++ + return args[i] + } + return "" + } + + switch key { + case "list": + opts.List = true + case "preset": + opts.Preset = true + case "rotate": + opts.Rotate = true + case "nombre": + opts.Nombre = strings.TrimSpace(nextVal()) + case "scopes": + raw := nextVal() + for _, part := range strings.Split(raw, ",") { + s := strings.TrimSpace(part) + if s != "" { + opts.Scopes = append(opts.Scopes, s) + } + } + case "rate-limit": + raw := strings.TrimSpace(nextVal()) + if raw != "" { + n, err := strconv.Atoi(raw) + if err == nil && n > 0 { + opts.RateLimitPerMin = n + opts.HasRateLimit = true + } + } + } + } + + if !opts.List && !opts.Preset && opts.Nombre == "" { + return opts, errors.New("Uso: provision-keys --list | --preset [--rotate] | --nombre --scopes [--rate-limit 60] [--rotate]") + } + + if !opts.List && !opts.Preset { + for _, sc := range opts.Scopes { + if !auth.IsValidScope(sc) { + return opts, fmt.Errorf("Scope invalido: %q. Validos: %s", sc, strings.Join(auth.AgentScopes, ", ")) + } + } + } + return opts, nil +} + +func dedupeStrings(in []string) []string { + seen := make(map[string]struct{}, len(in)) + out := make([]string, 0, len(in)) + for _, s := range in { + if _, ok := seen[s]; ok { + continue + } + seen[s] = struct{}{} + out = append(out, s) + } + return out +} + +type listedKey struct { + ID string `json:"id"` + Nombre string `json:"nombre"` + Prefijo string `json:"prefijo"` + Scopes []string `json:"scopes"` + RateLimitPerMin int `json:"rateLimitPerMin"` + Activo bool `json:"activo"` + RevokedAt *time.Time `json:"revokedAt"` + LastUsedAt *time.Time `json:"lastUsedAt"` + CreatedAt time.Time `json:"createdAt"` +} + +type provisionResult struct { + Nombre string `json:"nombre"` + Action string `json:"action"` + ID string `json:"id"` + Prefijo string `json:"prefijo"` + Scopes []string `json:"scopes"` + RateLimitPerMin int `json:"rateLimitPerMin"` + Activo *bool `json:"activo,omitempty"` + RawKey string `json:"rawKey,omitempty"` +} + +// RunProvisionKeys ports scripts/provision-agent-keys.ts to Go. +func RunProvisionKeys(ctx context.Context, pool *pgxpool.Pool, args []string) error { + return runProvisionKeysWithWriter(ctx, pool, args, os.Stdout) +} + +func runProvisionKeysWithWriter(ctx context.Context, pool *pgxpool.Pool, args []string, out io.Writer) error { + opts, err := parseProvisionArgs(args) + if err != nil { + return err + } + + if opts.List { + rows, err := pool.Query(ctx, ` + SELECT "id", "nombre", "prefijo", "scopes", "rateLimitPerMin", "activo", "revokedAt", "lastUsedAt", "createdAt" + FROM "AgentApiKey" + ORDER BY "createdAt" ASC + `) + if err != nil { + return fmt.Errorf("list agent keys: %w", err) + } + defer rows.Close() + + keys := make([]listedKey, 0) + for rows.Next() { + var k listedKey + if err := rows.Scan(&k.ID, &k.Nombre, &k.Prefijo, &k.Scopes, &k.RateLimitPerMin, &k.Activo, &k.RevokedAt, &k.LastUsedAt, &k.CreatedAt); err != nil { + return fmt.Errorf("scan agent key: %w", err) + } + if k.Scopes == nil { + k.Scopes = []string{} + } + keys = append(keys, k) + } + if err := rows.Err(); err != nil { + return err + } + + return writeIndentedJSON(out, map[string]any{ + "ok": true, + "keys": keys, + }) + } + + var targets []AgentKeyPreset + if opts.Preset { + targets = DefaultAgentPresets() + } else { + targets = []AgentKeyPreset{ + { + Nombre: opts.Nombre, + Scopes: opts.Scopes, + RateLimitPerMin: opts.RateLimitPerMin, + }, + } + } + + results := make([]provisionResult, 0, len(targets)) + for _, target := range targets { + var existingID, existingNombre, existingPrefijo string + var existingScopes []string + var existingRateLimit int + var existingActivo bool + + err := pool.QueryRow(ctx, ` + SELECT "id", "nombre", "prefijo", "scopes", "rateLimitPerMin", "activo" + FROM "AgentApiKey" + WHERE "nombre" = $1 + `, target.Nombre).Scan(&existingID, &existingNombre, &existingPrefijo, &existingScopes, &existingRateLimit, &existingActivo) + + exists := true + if errors.Is(err, pgx.ErrNoRows) { + exists = false + } else if err != nil { + return fmt.Errorf("lookup agent key %s: %w", target.Nombre, err) + } + + if exists && !opts.Rotate { + activo := existingActivo + if existingScopes == nil { + existingScopes = []string{} + } + results = append(results, provisionResult{ + Nombre: existingNombre, + Action: "exists", + ID: existingID, + Prefijo: existingPrefijo, + Scopes: existingScopes, + RateLimitPerMin: existingRateLimit, + Activo: &activo, + }) + continue + } + + var scopesFinal []string + if len(target.Scopes) > 0 { + scopesFinal = dedupeStrings(target.Scopes) + } else if exists { + scopesFinal = existingScopes + } + if len(scopesFinal) == 0 { + return fmt.Errorf("Debes indicar --scopes al crear la clave %q", target.Nombre) + } + + rawKey, prefijo, keyHash := auth.GenerateAPIKey() + + if exists { + rateLimit := target.RateLimitPerMin + if !opts.Preset && !opts.HasRateLimit && existingRateLimit > 0 { + rateLimit = existingRateLimit + } + if rateLimit <= 0 { + rateLimit = existingRateLimit + } + if rateLimit <= 0 { + rateLimit = 60 + } + _, err := pool.Exec(ctx, ` + UPDATE "AgentApiKey" + SET "prefijo" = $1, + "keyHash" = $2, + "scopes" = $3, + "rateLimitPerMin" = $4, + "activo" = true, + "revokedAt" = NULL, + "updatedAt" = NOW() + WHERE "id" = $5 + `, prefijo, keyHash, scopesFinal, rateLimit, existingID) + if err != nil { + return fmt.Errorf("rotate agent key %s: %w", target.Nombre, err) + } + results = append(results, provisionResult{ + Nombre: existingNombre, + Action: "rotated", + ID: existingID, + Prefijo: prefijo, + Scopes: scopesFinal, + RateLimitPerMin: rateLimit, + RawKey: rawKey, + }) + } else { + newID := db.NewID() + rateLimit := target.RateLimitPerMin + if rateLimit <= 0 { + rateLimit = 60 + } + _, err := pool.Exec(ctx, ` + INSERT INTO "AgentApiKey" ("id", "nombre", "prefijo", "keyHash", "scopes", "rateLimitPerMin", "activo", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, $5, $6, true, NOW(), NOW()) + `, newID, target.Nombre, prefijo, keyHash, scopesFinal, rateLimit) + if err != nil { + return fmt.Errorf("create agent key %s: %w", target.Nombre, err) + } + results = append(results, provisionResult{ + Nombre: target.Nombre, + Action: "created", + ID: newID, + Prefijo: prefijo, + Scopes: scopesFinal, + RateLimitPerMin: rateLimit, + RawKey: rawKey, + }) + } + } + + return writeIndentedJSON(out, map[string]any{ + "ok": true, + "results": results, + }) +} + +func writeIndentedJSON(w io.Writer, v any) error { + b, err := json.MarshalIndent(v, "", " ") + if err != nil { + return err + } + _, err = fmt.Fprintln(w, string(b)) + return err +} diff --git a/internal/seed/seed.go b/internal/seed/seed.go new file mode 100644 index 0000000..f34e9aa --- /dev/null +++ b/internal/seed/seed.go @@ -0,0 +1,348 @@ +package seed + +import ( + "context" + "encoding/json" + "fmt" + "log" + "strings" + + "cotizador/internal/auth" + "cotizador/internal/config" + "cotizador/internal/db" + + "github.com/jackc/pgx/v5/pgxpool" +) + +type servicioRow struct { + ID string + Nombre string + Fase int + Nivel *string +} + +// Run executes the idempotent database seed matching prisma/seed.ts. +func Run(ctx context.Context, pool *pgxpool.Pool, cfg *config.Config) error { + if cfg == nil { + cfg = &config.Config{} + } + + log.Println("Seeding database...") + + // ── USERS ── + adminEmail := strings.TrimSpace(cfg.SeedAdminEmail) + if adminEmail == "" { + adminEmail = "admin@urieljareth.com" + } + adminName := strings.TrimSpace(cfg.SeedAdminName) + if adminName == "" { + adminName = "Administrador" + } + adminPassword := cfg.SeedAdminPassword + if adminPassword == "" { + log.Printf(` AVISO: SEED_ADMIN_PASSWORD no definida. Si el usuario %s no existe, se creara con password "admin123" — cambiala de inmediato.`, adminEmail) + } + rawAdminPass := adminPassword + if rawAdminPass == "" { + rawAdminPass = "admin123" + } + adminHash, err := auth.HashPassword(rawAdminPass) + if err != nil { + return fmt.Errorf("hash password admin: %w", err) + } + + if adminPassword != "" { + _, err = pool.Exec(ctx, ` + INSERT INTO "User" ("id", "email", "password", "name", "role", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, 'admin', NOW(), NOW()) + ON CONFLICT ("email") DO UPDATE SET + "password" = EXCLUDED."password", + "updatedAt" = NOW() + `, db.NewID(), adminEmail, adminHash, adminName) + } else { + _, err = pool.Exec(ctx, ` + INSERT INTO "User" ("id", "email", "password", "name", "role", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, 'admin', NOW(), NOW()) + ON CONFLICT ("email") DO NOTHING + `, db.NewID(), adminEmail, adminHash, adminName) + } + if err != nil { + return fmt.Errorf("upsert admin user: %w", err) + } + + asesorEmail := strings.TrimSpace(cfg.SeedAsesorEmail) + if asesorEmail != "" { + asesorName := strings.TrimSpace(cfg.SeedAsesorName) + if asesorName == "" { + asesorName = "Asesor" + } + asesorPassword := cfg.SeedAsesorPass + rawAsesorPass := asesorPassword + if rawAsesorPass == "" { + rawAsesorPass = "asesor123" + } + asesorHash, err := auth.HashPassword(rawAsesorPass) + if err != nil { + return fmt.Errorf("hash password asesor: %w", err) + } + if asesorPassword != "" { + _, err = pool.Exec(ctx, ` + INSERT INTO "User" ("id", "email", "password", "name", "role", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, 'asesor', NOW(), NOW()) + ON CONFLICT ("email") DO UPDATE SET + "password" = EXCLUDED."password", + "updatedAt" = NOW() + `, db.NewID(), asesorEmail, asesorHash, asesorName) + } else { + _, err = pool.Exec(ctx, ` + INSERT INTO "User" ("id", "email", "password", "name", "role", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, 'asesor', NOW(), NOW()) + ON CONFLICT ("email") DO NOTHING + `, db.NewID(), asesorEmail, asesorHash, asesorName) + } + if err != nil { + return fmt.Errorf("upsert asesor user: %w", err) + } + } + + // ── CATEGORIAS (must be created BEFORE servicios for FK) ── + categorias := DefaultCategorias() + catMap := make(map[string]string, len(categorias)) + for _, cat := range categorias { + var catID string + err := pool.QueryRow(ctx, ` + INSERT INTO "Categoria" ("id", "nombre", "descripcion", "color", "activo", "orden", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, true, $5, NOW(), NOW()) + ON CONFLICT ("nombre") DO UPDATE SET + "color" = EXCLUDED."color", + "orden" = EXCLUDED."orden", + "updatedAt" = NOW() + RETURNING "id" + `, db.NewID(), cat.Nombre, cat.Descripcion, cat.Color, cat.Orden).Scan(&catID) + if err != nil { + return fmt.Errorf("upsert categoria %s: %w", cat.Nombre, err) + } + catMap[cat.Nombre] = catID + } + + // ── SERVICIOS CATALOGO ── + catAlias := DefaultCatAlias() + servicios := DefaultServicios() + for _, s := range servicios { + catNombre, ok := catAlias[s.Categoria] + if !ok { + catNombre = "Desarrollo Personalizado" + } + var catID *string + if id, exists := catMap[catNombre]; exists { + idCopy := id + catID = &idCopy + } + var variante *string + if s.Variante != "" { + v := s.Variante + variante = &v + } + var nivel *string + if s.Nivel != "" { + n := s.Nivel + nivel = &n + } + entregablesJSON, err := json.Marshal(s.EntregablesDefault) + if err != nil { + return fmt.Errorf("marshal entregables %s: %w", s.Nombre, err) + } + servicioID := ServicioID(s.Nombre, s.Orden) + soloAdmin := IsSoloAdmin(servicioID, s.Nombre, s.SoloAdmin) + + _, err = pool.Exec(ctx, ` + INSERT INTO "ServicioCatalogo" ( + "id", "nombre", "descripcion", "fase", "tipoPago", "precioBase", + "tiempoEntrega", "entregablesDefault", "categoriaId", "variante", + "nivel", "activo", "soloAdmin", "orden", "createdAt", "updatedAt" + ) VALUES ( + $1, $2, $3, $4, $5, $6, + $7, $8::jsonb, $9, $10, + $11, true, $12, $13, NOW(), NOW() + ) + ON CONFLICT ("id") DO UPDATE SET + "soloAdmin" = CASE WHEN EXCLUDED."soloAdmin" THEN true ELSE "ServicioCatalogo"."soloAdmin" END + `, + servicioID, s.Nombre, s.Descripcion, s.Fase, s.TipoPago, s.PrecioBase, + s.TiempoEntrega, string(entregablesJSON), catID, variante, + nivel, soloAdmin, s.Orden, + ) + if err != nil { + return fmt.Errorf("upsert servicio %s: %w", servicioID, err) + } + } + + // Load all services currently in DB for package mapping (mirrors prisma.servicioCatalogo.findMany()). + rows, err := pool.Query(ctx, `SELECT "id", "nombre", "fase", "nivel" FROM "ServicioCatalogo"`) + if err != nil { + return fmt.Errorf("query servicios: %w", err) + } + var allServicios []servicioRow + for rows.Next() { + var r servicioRow + if err := rows.Scan(&r.ID, &r.Nombre, &r.Fase, &r.Nivel); err != nil { + rows.Close() + return fmt.Errorf("scan servicio: %w", err) + } + allServicios = append(allServicios, r) + } + rows.Close() + if err := rows.Err(); err != nil { + return fmt.Errorf("iterate servicios: %w", err) + } + + // ── PAQUETE GENERAL ── + _, err = pool.Exec(ctx, ` + INSERT INTO "Paquete" ("id", "nombre", "descripcion", "activo", "createdAt", "updatedAt") + VALUES ('paquete-general', 'General', 'Paquete completo de servicios de marketing digital', true, NOW(), NOW()) + ON CONFLICT ("id") DO NOTHING + `) + if err != nil { + return fmt.Errorf("upsert paquete-general: %w", err) + } + + fasesGeneral := DefaultFasesGeneral() + faseMap := make(map[int]string, len(fasesGeneral)) + for _, fg := range fasesGeneral { + faseID := fmt.Sprintf("fase-general-%d", fg.Orden) + _, err := pool.Exec(ctx, ` + INSERT INTO "FasePaquete" ("id", "paqueteId", "nombre", "orden", "createdAt", "updatedAt") + VALUES ($1, 'paquete-general', $2, $3, NOW(), NOW()) + ON CONFLICT ("id") DO UPDATE SET + "nombre" = EXCLUDED."nombre", + "orden" = EXCLUDED."orden", + "updatedAt" = NOW() + `, faseID, fg.Nombre, fg.Orden) + if err != nil { + return fmt.Errorf("upsert fase %s: %w", faseID, err) + } + faseMap[fg.Orden] = faseID + } + + for _, s := range allServicios { + fasePaqueteID, ok := faseMap[s.Fase] + if !ok { + continue + } + _, err := pool.Exec(ctx, ` + INSERT INTO "ServicioPaquete" ("id", "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt") + VALUES ($1, $2, $3, NOW(), NOW()) + ON CONFLICT ("servicioCatalogoId", "fasePaqueteId") DO NOTHING + `, db.NewID(), s.ID, fasePaqueteID) + if err != nil { + return fmt.Errorf("upsert servicioPaquete general (%s -> %s): %w", s.ID, fasePaqueteID, err) + } + } + + // ── PAQUETES RECOMENDADOS PYME ── + for _, pq := range DefaultPaquetesPyme() { + _, err := pool.Exec(ctx, ` + INSERT INTO "Paquete" ("id", "nombre", "descripcion", "activo", "createdAt", "updatedAt") + VALUES ($1, $2, $3, true, NOW(), NOW()) + ON CONFLICT ("id") DO UPDATE SET + "nombre" = EXCLUDED."nombre", + "descripcion" = EXCLUDED."descripcion", + "activo" = true, + "updatedAt" = NOW() + `, pq.ID, pq.Nombre, pq.Descripcion) + if err != nil { + return fmt.Errorf("upsert paquete %s: %w", pq.ID, err) + } + + for _, fase := range pq.Fases { + faseID := fmt.Sprintf("fase-%s-%d", pq.ID, fase.Orden) + _, err := pool.Exec(ctx, ` + INSERT INTO "FasePaquete" ("id", "paqueteId", "nombre", "orden", "createdAt", "updatedAt") + VALUES ($1, $2, $3, $4, NOW(), NOW()) + ON CONFLICT ("id") DO UPDATE SET + "nombre" = EXCLUDED."nombre", + "orden" = EXCLUDED."orden", + "updatedAt" = NOW() + `, faseID, pq.ID, fase.Nombre, fase.Orden) + if err != nil { + return fmt.Errorf("upsert fase %s: %w", faseID, err) + } + + for _, ref := range fase.Servicios { + servicioCatalogoID, err := findServicioID(allServicios, ref.Nombre, ref.Nivel) + if err != nil { + return err + } + _, err = pool.Exec(ctx, ` + INSERT INTO "ServicioPaquete" ("id", "servicioCatalogoId", "fasePaqueteId", "createdAt", "updatedAt") + VALUES ($1, $2, $3, NOW(), NOW()) + ON CONFLICT ("servicioCatalogoId", "fasePaqueteId") DO NOTHING + `, db.NewID(), servicioCatalogoID, faseID) + if err != nil { + return fmt.Errorf("upsert servicioPaquete (%s -> %s): %w", servicioCatalogoID, faseID, err) + } + } + } + } + + // ── BONOS (only insert when table is empty) ── + var bonoCount int + if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM "Bono"`).Scan(&bonoCount); err != nil { + return fmt.Errorf("count bonos: %w", err) + } + if bonoCount == 0 { + for _, bono := range DefaultBonos() { + _, err := pool.Exec(ctx, ` + INSERT INTO "Bono" ("id", "numero", "titulo", "descripcion", "activo") + VALUES ($1, $2, $3, $4, true) + `, db.NewID(), bono.Numero, bono.Titulo, bono.Descripcion) + if err != nil { + return fmt.Errorf("insert bono %d: %w", bono.Numero, err) + } + } + } + + // ── FINANCIAMIENTO PLANES ── + for _, plan := range DefaultFinanciamientoPlanes() { + _, err := pool.Exec(ctx, ` + INSERT INTO "FinanciamientoPlan" ("id", "meses", "tasa", "comision", "montoMinimo", "iva") + VALUES ($1, $2, $3, $4, $5, $6) + ON CONFLICT ("meses") DO NOTHING + `, db.NewID(), plan.Meses, plan.Tasa, plan.Comision, plan.MontoMinimo, plan.IVA) + if err != nil { + return fmt.Errorf("upsert financiamiento %d meses: %w", plan.Meses, err) + } + } + + // ── CONFIGURACION (ON CONFLICT DO NOTHING to preserve production branding/bank settings) ── + for _, c := range DefaultConfigs() { + _, err := pool.Exec(ctx, ` + INSERT INTO "Configuracion" ("id", "clave", "valor", "updatedAt") + VALUES ($1, $2, $3, NOW()) + ON CONFLICT ("clave") DO NOTHING + `, db.NewID(), c.Clave, c.Valor) + if err != nil { + return fmt.Errorf("upsert configuracion %s: %w", c.Clave, err) + } + } + + log.Println("Seed completed successfully!") + return nil +} + +func findServicioID(all []servicioRow, nombre, nivel string) (string, error) { + var matches []string + for _, s := range all { + sNivel := "" + if s.Nivel != nil { + sNivel = *s.Nivel + } + if s.Nombre == nombre && sNivel == nivel { + matches = append(matches, s.ID) + } + } + if len(matches) != 1 { + return "", fmt.Errorf("Paquete PyME: '%s' (nivel=%q) resolvio %d servicios", nombre, nivel, len(matches)) + } + return matches[0], nil +} diff --git a/internal/seed/seed_test.go b/internal/seed/seed_test.go new file mode 100644 index 0000000..5ec3b8c --- /dev/null +++ b/internal/seed/seed_test.go @@ -0,0 +1,218 @@ +package seed + +import ( + "strings" + "testing" + + "cotizador/internal/auth" +) + +func TestSeedDataCounts(t *testing.T) { + categorias := DefaultCategorias() + if len(categorias) != 7 { + t.Fatalf("expected 7 categorias, got %d", len(categorias)) + } + + servicios := DefaultServicios() + if len(servicios) != 58 { + t.Fatalf("expected 58 servicios (exact count in prisma/seed.ts), got %d", len(servicios)) + } + + // 1 paquete-general + 6 paquetes PyME = 7 paquetes total + paquetesPyme := DefaultPaquetesPyme() + if len(paquetesPyme) != 6 { + t.Fatalf("expected 6 paquetes PyME (7 total with paquete-general), got %d", len(paquetesPyme)) + } + if len(DefaultFasesGeneral()) != 4 { + t.Fatalf("expected 4 fases in paquete-general, got %d", len(DefaultFasesGeneral())) + } + + bonos := DefaultBonos() + if len(bonos) != 6 { + t.Fatalf("expected 6 bonos, got %d", len(bonos)) + } + + planes := DefaultFinanciamientoPlanes() + if len(planes) != 4 { + t.Fatalf("expected 4 financiamiento planes, got %d", len(planes)) + } + expectedMeses := []int{3, 6, 9, 12} + for i, m := range expectedMeses { + if planes[i].Meses != m { + t.Errorf("plan[%d].Meses = %d, want %d", i, planes[i].Meses, m) + } + } + + configs := DefaultConfigs() + if len(configs) != 16 { + t.Fatalf("expected 16 config keys, got %d", len(configs)) + } +} + +func TestServicioIDsAndSoloAdmin(t *testing.T) { + servicios := DefaultServicios() + seen := make(map[string]bool, len(servicios)) + soloAdminIDs := make(map[string]bool) + + for _, s := range servicios { + id := ServicioID(s.Nombre, s.Orden) + if seen[id] { + t.Fatalf("duplicate servicio ID: %s", id) + } + seen[id] = true + + if IsSoloAdmin(id, s.Nombre, s.SoloAdmin) { + soloAdminIDs[id] = true + } + } + + // Verify exact known slug IDs from prisma/seed.ts + for _, want := range []string{ + "auditoria-en-sitio-web-2", + "configuracion-y-puesta-en-marc-12", + "plan-mensual-crm-bucefalo-18", + "logo-e-identidad-101", + "estrategia-empresarial-en-ecom-100", + } { + if !seen[want] { + t.Errorf("expected slug ID %q not found in DefaultServicios", want) + } + } + + // Verify soloAdmin flags on Bucefalo CRM items + if len(soloAdminIDs) != 2 { + t.Fatalf("expected exactly 2 soloAdmin servicios, got %d: %v", len(soloAdminIDs), soloAdminIDs) + } + if !soloAdminIDs["configuracion-y-puesta-en-marc-12"] { + t.Errorf("expected configuracion-y-puesta-en-marc-12 to be soloAdmin") + } + if !soloAdminIDs["plan-mensual-crm-bucefalo-18"] { + t.Errorf("expected plan-mensual-crm-bucefalo-18 to be soloAdmin") + } + + // Accented/case-insensitive Bucefalo detection + if !IsSoloAdmin("otro-1", "Servicio Bucéfalo Extra", false) { + t.Errorf("expected accented Bucéfalo name to trigger soloAdmin") + } + if IsSoloAdmin("auditoria-en-sitio-web-2", "Auditoria en Sitio Web", false) { + t.Errorf("expected normal service NOT to trigger soloAdmin") + } +} + +func TestCategoriasAndPaqueteReferences(t *testing.T) { + catSet := make(map[string]bool) + for _, c := range DefaultCategorias() { + catSet[c.Nombre] = true + } + + catAlias := DefaultCatAlias() + var rows []servicioRow + for _, s := range DefaultServicios() { + catNombre, ok := catAlias[s.Categoria] + if !ok { + t.Errorf("servicio %q has unknown categoria alias %q", s.Nombre, s.Categoria) + } + if !catSet[catNombre] { + t.Errorf("catAlias %q -> %q not found in DefaultCategorias", s.Categoria, catNombre) + } + var nivelPtr *string + if s.Nivel != "" { + n := s.Nivel + nivelPtr = &n + } + rows = append(rows, servicioRow{ + ID: ServicioID(s.Nombre, s.Orden), + Nombre: s.Nombre, + Fase: s.Fase, + Nivel: nivelPtr, + }) + } + + // Every service referenced in all 6 PyME packages must resolve uniquely + for _, pq := range DefaultPaquetesPyme() { + if !strings.HasPrefix(pq.ID, "paquete-") { + t.Errorf("unexpected paquete ID %q", pq.ID) + } + for _, f := range pq.Fases { + for _, ref := range f.Servicios { + id, err := findServicioID(rows, ref.Nombre, ref.Nivel) + if err != nil { + t.Errorf("paquete %s fase %d: %v", pq.ID, f.Orden, err) + } + if id == "" { + t.Errorf("paquete %s fase %d: empty id for %s", pq.ID, f.Orden, ref.Nombre) + } + } + } + } +} + +func TestConfigKeysUnique(t *testing.T) { + seen := make(map[string]bool) + for _, c := range DefaultConfigs() { + if seen[c.Clave] { + t.Fatalf("duplicate config clave: %s", c.Clave) + } + seen[c.Clave] = true + } + for _, required := range []string{"razon_social", "rfc", "clabe_interbancaria", "color_primario", "color_secundario", "logo_base64", "iva"} { + if !seen[required] { + t.Errorf("missing required config key %q", required) + } + } +} + +func TestProvisionArgsAndPresets(t *testing.T) { + // Presets sanity + presets := DefaultAgentPresets() + if len(presets) != 5 { + t.Fatalf("expected 5 agent presets, got %d", len(presets)) + } + for _, p := range presets { + for _, sc := range p.Scopes { + if !auth.IsValidScope(sc) { + t.Errorf("preset %s has invalid scope %q", p.Nombre, sc) + } + if strings.Contains(sc, "aprobar") { + t.Errorf("preset %s must NEVER contain an approval scope: %q", p.Nombre, sc) + } + } + } + + // --list + opts, err := parseProvisionArgs([]string{"--list"}) + if err != nil || !opts.List { + t.Fatalf("expected --list to parse cleanly, got opts=%+v err=%v", opts, err) + } + + // --preset --rotate + opts, err = parseProvisionArgs([]string{"--preset", "--rotate"}) + if err != nil || !opts.Preset || !opts.Rotate { + t.Fatalf("expected --preset --rotate to parse cleanly, got opts=%+v err=%v", opts, err) + } + + // --nombre with valid scopes and rate limit + opts, err = parseProvisionArgs([]string{ + "--nombre", "custom-agent", + "--scopes", "catalogo:leer,clientes:leer", + "--rate-limit", "90", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if opts.Nombre != "custom-agent" || len(opts.Scopes) != 2 || opts.RateLimitPerMin != 90 || !opts.HasRateLimit { + t.Fatalf("unexpected parsed opts: %+v", opts) + } + + // invalid scope rejected + _, err = parseProvisionArgs([]string{"--nombre", "bad", "--scopes", "cotizaciones:aprobar"}) + if err == nil { + t.Fatalf("expected error for invalid approval scope") + } + + // missing action rejected + _, err = parseProvisionArgs([]string{}) + if err == nil { + t.Fatalf("expected usage error when no flags given") + } +} diff --git a/internal/spa/dist/index.html b/internal/spa/dist/index.html new file mode 100644 index 0000000..04e8e38 --- /dev/null +++ b/internal/spa/dist/index.html @@ -0,0 +1 @@ +Cotizador — Uriel Jareth Consulting
diff --git a/internal/spa/spa.go b/internal/spa/spa.go new file mode 100644 index 0000000..7837632 --- /dev/null +++ b/internal/spa/spa.go @@ -0,0 +1,55 @@ +package spa + +import ( + "embed" + "io/fs" + "net/http" + "path" + "strings" +) + +//go:embed all:dist +var distFS embed.FS + +// Handler serves the embedded Vite React SPA with client-side routing fallback, +// immutable caching for /assets/*, and no-cache for index.html and /sw.js. +func Handler() http.Handler { + sub, err := fs.Sub(distFS, "dist") + if err != nil { + panic(err) + } + fileServer := http.FileServer(http.FS(sub)) + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + p := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/") + if p == "" { + p = "index.html" + } + + // Try exact static file first + if f, err := sub.Open(p); err == nil { + stat, statErr := f.Stat() + _ = f.Close() + if statErr == nil && !stat.IsDir() { + if strings.HasPrefix(p, "assets/") { + w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") + } else if p == "sw.js" || p == "index.html" { + w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") + } + fileServer.ServeHTTP(w, r) + return + } + } + + // SPA fallback to index.html for client routes + indexBytes, err := fs.ReadFile(sub, "index.html") + if err != nil { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(indexBytes) + }) +} diff --git a/internal/webhooks/webhooks.go b/internal/webhooks/webhooks.go new file mode 100644 index 0000000..2cdc904 --- /dev/null +++ b/internal/webhooks/webhooks.go @@ -0,0 +1,349 @@ +package webhooks + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "slices" + "strconv" + "strings" + "time" + + "cotizador/internal/config" + "cotizador/internal/db" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" +) + +var EventosOficiales = []string{ + "cotizacion.creada", + "cotizacion.aprobada", + "cotizacion.enviada", + "cotizacion.aceptada", + "cotizacion.rechazada", + "cotizacion.vencida", + "pago.registrado", + "pago.vencido", +} + +func EsEventoValido(evento string) bool { + return evento == "*" || slices.Contains(EventosOficiales, evento) +} + +// FirmarPayload returns "sha256=<64-hex>" HMAC-SHA256 signature. +func FirmarPayload(rawPayload []byte, secret string) string { + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write(rawPayload) + return "sha256=" + hex.EncodeToString(mac.Sum(nil)) +} + +// VerificarFirma performs constant-time HMAC-SHA256 verification. +func VerificarFirma(rawPayload []byte, signatureHeader, secret string) bool { + if secret == "" || !strings.HasPrefix(signatureHeader, "sha256=") { + return false + } + expected := FirmarPayload(rawPayload, secret) + return hmac.Equal([]byte(expected), []byte(signatureHeader)) +} + +type Dispatcher struct { + pool *pgxpool.Pool + cfg *config.Config + client *http.Client +} + +func NewDispatcher(pool *pgxpool.Pool, cfg *config.Config) *Dispatcher { + return &Dispatcher{ + pool: pool, + cfg: cfg, + client: &http.Client{Timeout: 8 * time.Second}, + } +} + +type target struct { + EndpointID *string + URL string + Secret string +} + +func (d *Dispatcher) Emitir(ctx context.Context, evento string, data map[string]any) { + if d == nil || d.pool == nil { + return + } + + var targets []target + seenURL := map[string]bool{} + + rows, err := d.pool.Query(ctx, ` + SELECT "id", "url", "secret", "eventos" + FROM "WebhookEndpoint" + WHERE "activo" = true + `) + if err == nil { + defer rows.Close() + for rows.Next() { + var id, urlStr, secret string + var eventos []string + if err := rows.Scan(&id, &urlStr, &secret, &eventos); err != nil { + continue + } + if slices.Contains(eventos, "*") || slices.Contains(eventos, evento) { + eid := id + targets = append(targets, target{EndpointID: &eid, URL: urlStr, Secret: secret}) + seenURL[urlStr] = true + } + } + } + + if d.cfg != nil && d.cfg.WebhookN8NURL != "" && !seenURL[d.cfg.WebhookN8NURL] { + targets = append(targets, target{ + EndpointID: nil, + URL: d.cfg.WebhookN8NURL, + Secret: d.cfg.WebhookN8NSecret, + }) + } + + if len(targets) == 0 { + return + } + + envelope := map[string]any{ + "event": evento, + "timestamp": time.Now().UTC().Format(time.RFC3339), + "data": data, + } + rawPayload, err := json.Marshal(envelope) + if err != nil { + return + } + + for _, t := range targets { + d.deliverWithRetry(ctx, t, evento, rawPayload) + } +} + +func (d *Dispatcher) deliverWithRetry(ctx context.Context, t target, evento string, rawPayload []byte) { + deliveryID := uuid.NewString() + ts := strconv.FormatInt(time.Now().Unix(), 10) + sig := "" + if t.Secret != "" { + sig = FirmarPayload(rawPayload, t.Secret) + } + + var statusCode *int + var lastErr string + exito := false + intentos := 0 + + for attempt := 1; attempt <= 3; attempt++ { + intentos = attempt + req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.URL, bytes.NewReader(rawPayload)) + if err != nil { + lastErr = err.Error() + break + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Cotizador-Event", evento) + req.Header.Set("X-Cotizador-Timestamp", ts) + req.Header.Set("X-Cotizador-Delivery-Id", deliveryID) + if sig != "" { + req.Header.Set("X-Cotizador-Signature", sig) + } + + resp, err := d.client.Do(req) + if err != nil { + lastErr = err.Error() + } else { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) + _ = resp.Body.Close() + sc := resp.StatusCode + statusCode = &sc + if sc >= 200 && sc < 300 { + exito = true + lastErr = "" + break + } + lastErr = fmt.Sprintf("HTTP %d", sc) + if sc < 500 { + break + } + } + + if attempt < 3 { + time.Sleep(time.Duration(attempt) * 500 * time.Millisecond) + } + } + + var errPtr *string + if lastErr != "" { + errPtr = &lastErr + } + _, err := d.pool.Exec(ctx, ` + INSERT INTO "WebhookDelivery" ("id", "endpointId", "url", "evento", "payload", "statusCode", "exito", "intentos", "error") + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + `, db.NewID(), t.EndpointID, t.URL, evento, rawPayload, statusCode, exito, intentos, errPtr) + if err != nil { + log.Printf("[webhooks] error guardando WebhookDelivery (%s -> %s): %v", evento, t.URL, err) + } +} + +type WhatsAppSendResult struct { + OK bool + Outside24h bool + StatusCode int + ErrorMessage string + ResponsePayload map[string]any +} + +// InvocarEnvioWhatsAppN8n sends cotizacion.enviar_whatsapp to WEBHOOK_WHATSAPP_SEND_URL (15s timeout, no retries). +func (d *Dispatcher) InvocarEnvioWhatsAppN8n(ctx context.Context, payload map[string]any) WhatsAppSendResult { + if d == nil || d.cfg == nil || d.cfg.WebhookWhatsAppSendURL == "" { + return WhatsAppSendResult{ + OK: false, + ErrorMessage: "WEBHOOK_WHATSAPP_SEND_URL no esta configurado", + } + } + + raw, err := json.Marshal(payload) + if err != nil { + return WhatsAppSendResult{OK: false, ErrorMessage: err.Error()} + } + + client := &http.Client{Timeout: 15 * time.Second} + req, err := http.NewRequestWithContext(ctx, http.MethodPost, d.cfg.WebhookWhatsAppSendURL, bytes.NewReader(raw)) + if err != nil { + return WhatsAppSendResult{OK: false, ErrorMessage: err.Error()} + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Cotizador-Event", "cotizacion.enviar_whatsapp") + req.Header.Set("X-Cotizador-Timestamp", strconv.FormatInt(time.Now().Unix(), 10)) + req.Header.Set("X-Cotizador-Delivery-Id", uuid.NewString()) + if d.cfg.WebhookN8NSecret != "" { + req.Header.Set("X-Cotizador-Signature", FirmarPayload(raw, d.cfg.WebhookN8NSecret)) + } + + resp, err := client.Do(req) + if err != nil { + return WhatsAppSendResult{OK: false, ErrorMessage: err.Error()} + } + defer resp.Body.Close() + bodyBytes, _ := io.ReadAll(io.LimitReader(resp.Body, 64*1024)) + + var parsed map[string]any + _ = json.Unmarshal(bodyBytes, &parsed) + + outside := false + if parsed != nil { + if v, ok := parsed["outside_24h_window"].(bool); ok && v { + outside = true + } + if code, ok := parsed["code"].(string); ok && code == "outside_24h_window" { + outside = true + } + if errStr, ok := parsed["error"].(string); ok && strings.Contains(strings.ToLower(errStr), "outside_24h") { + outside = true + } + } + + if resp.StatusCode >= 200 && resp.StatusCode < 300 && !outside { + return WhatsAppSendResult{ + OK: true, + StatusCode: resp.StatusCode, + ResponsePayload: parsed, + } + } + + errMsg := fmt.Sprintf("HTTP %d", resp.StatusCode) + if parsed != nil { + if m, ok := parsed["error"].(string); ok && m != "" { + errMsg = m + } else if m, ok := parsed["message"].(string); ok && m != "" { + errMsg = m + } + } + return WhatsAppSendResult{ + OK: false, + Outside24h: outside, + StatusCode: resp.StatusCode, + ErrorMessage: errMsg, + ResponsePayload: parsed, + } +} + +type PagoVencidoItem struct { + PagoID string + ProgramaID string + ClienteID string + ClienteNombre string + ClienteEmpresa string + ClienteEmail string + ClienteTelefono string + Concepto string + Monto float64 + Moneda string + Fecha string + DiasAtraso int +} + +// PagoVencidoStore abstracts atomic claim for testability. +type PagoVencidoStore interface { + ClaimVencido(ctx context.Context, pagoID string) (bool, error) +} + +type pgPagoVencidoStore struct { + pool *pgxpool.Pool +} + +func (s pgPagoVencidoStore) ClaimVencido(ctx context.Context, pagoID string) (bool, error) { + tag, err := s.pool.Exec(ctx, ` + UPDATE "PagoRecurrente" + SET "vencidoNotificadoAt" = NOW(), "updatedAt" = NOW() + WHERE "id" = $1 AND "vencidoNotificadoAt" IS NULL + `, pagoID) + if err != nil { + return false, err + } + return tag.RowsAffected() == 1, nil +} + +// EmitirPagosVencidosIdempotente atomically stamps vencidoNotificadoAt and emits pago.vencido once per charge. +func EmitirPagosVencidosIdempotente(ctx context.Context, store PagoVencidoStore, items []PagoVencidoItem, emit func(ctx context.Context, evento string, data map[string]any)) int { + emitted := 0 + for _, it := range items { + claimed, err := store.ClaimVencido(ctx, it.PagoID) + if err != nil || !claimed { + continue + } + emit(ctx, "pago.vencido", map[string]any{ + "pagoId": it.PagoID, + "programaId": it.ProgramaID, + "clienteId": it.ClienteID, + "clienteNombre": it.ClienteNombre, + "clienteEmpresa": it.ClienteEmpresa, + "clienteEmail": it.ClienteEmail, + "clienteTelefono": it.ClienteTelefono, + "concepto": it.Concepto, + "monto": it.Monto, + "moneda": it.Moneda, + "fecha": it.Fecha, + "diasAtraso": it.DiasAtraso, + }) + emitted++ + } + return emitted +} + +func (d *Dispatcher) EmitirPagosVencidos(ctx context.Context, items []PagoVencidoItem) int { + if d == nil || d.pool == nil { + return 0 + } + return EmitirPagosVencidosIdempotente(ctx, pgPagoVencidoStore{pool: d.pool}, items, d.Emitir) +} diff --git a/internal/webhooks/webhooks_test.go b/internal/webhooks/webhooks_test.go new file mode 100644 index 0000000..c4634b9 --- /dev/null +++ b/internal/webhooks/webhooks_test.go @@ -0,0 +1,74 @@ +package webhooks + +import ( + "context" + "strings" + "sync" + "testing" +) + +func TestHMACSigningAndEvents(t *testing.T) { + if len(EventosOficiales) != 8 { + t.Fatalf("expected 8 official events, got %d", len(EventosOficiales)) + } + payload := []byte(`{"event":"cotizacion.aprobada","data":{"id":"c1"}}`) + secret := "whsec_test_123" + sig := FirmarPayload(payload, secret) + if !strings.HasPrefix(sig, "sha256=") || len(sig) != 7+64 { + t.Fatalf("invalid signature format: %s", sig) + } + if !VerificarFirma(payload, sig, secret) { + t.Fatal("valid signature rejected") + } + if VerificarFirma([]byte(`{"tampered":true}`), sig, secret) { + t.Fatal("tampered payload accepted") + } + if VerificarFirma(payload, sig, "wrong-secret") { + t.Fatal("wrong secret accepted") + } + if VerificarFirma(payload, "invalid", secret) { + t.Fatal("malformed header accepted") + } +} + +type memClaimStore struct { + mu sync.Mutex + claimed map[string]bool +} + +func (m *memClaimStore) ClaimVencido(_ context.Context, pagoID string) (bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.claimed[pagoID] { + return false, nil + } + m.claimed[pagoID] = true + return true, nil +} + +func TestPagoVencidoIdempotencyConcurrency(t *testing.T) { + store := &memClaimStore{claimed: map[string]bool{}} + items := []PagoVencidoItem{{PagoID: "p1", ClienteID: "c1", Monto: 750, Moneda: "MXN", DiasAtraso: 3}} + + var mu sync.Mutex + totalEmitted := 0 + emit := func(_ context.Context, _ string, _ map[string]any) { + mu.Lock() + totalEmitted++ + mu.Unlock() + } + + var wg sync.WaitGroup + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() + EmitirPagosVencidosIdempotente(context.Background(), store, items, emit) + }() + } + wg.Wait() + + if totalEmitted != 1 { + t.Fatalf("expected exactly 1 emission under concurrency, got %d", totalEmitted) + } +} diff --git a/next.config.ts b/next.config.ts deleted file mode 100644 index bda8d0e..0000000 --- a/next.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextConfig } from "next"; - -const nextConfig: NextConfig = { - // sharp/nodemailer/web-push traen binarios o crypto nativo: empaquetarlos - // rompe el build de produccion. - serverExternalPackages: ["pdfkit", "sharp", "nodemailer", "web-push"], - poweredByHeader: false, -}; - -export default nextConfig; diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index a2f835d..0000000 --- a/package-lock.json +++ /dev/null @@ -1,10362 +0,0 @@ -{ - "name": "cotizador-uj", - "version": "0.1.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "cotizador-uj", - "version": "0.1.0", - "dependencies": { - "@anthropic-ai/sdk": "^0.115.0", - "@prisma/adapter-pg": "^7.8.0", - "@prisma/client": "^7.8.0", - "bcryptjs": "^3.0.3", - "clsx": "^2.1.1", - "dotenv": "^17.4.2", - "exceljs": "^4.4.0", - "jose": "^6.2.3", - "lucide-react": "^1.11.0", - "next": "16.2.4", - "nodemailer": "^10.1.7", - "pdfkit": "^0.18.0", - "pg": "^8.20.0", - "prisma": "^7.8.0", - "react": "19.2.4", - "react-dom": "19.2.4", - "sharp": "^0.35.5", - "web-push": "^3.6.7", - "zod": "^4.3.6", - "zustand": "^5.0.12" - }, - "devDependencies": { - "@tailwindcss/postcss": "^4", - "@types/bcryptjs": "^2.4.6", - "@types/node": "^20", - "@types/nodemailer": "^8.0.2", - "@types/pdfkit": "^0.17.6", - "@types/react": "^19", - "@types/react-dom": "^19", - "@types/web-push": "^3.6.4", - "eslint": "^9", - "eslint-config-next": "16.2.4", - "tailwindcss": "^4", - "tsx": "^4.21.0", - "typescript": "^5" - } - }, - "node_modules/@alloc/quick-lru": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", - "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@anthropic-ai/sdk": { - "version": "0.115.0", - "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.115.0.tgz", - "integrity": "sha512-BJrFIVyjNuU8lfDyIJTvlRYzgQg+zEl78BxE7fq8esULsGz9IRQvGtW5spq3tydmtjQb/GFdooKGdGsetpx+lQ==", - "license": "MIT", - "dependencies": { - "json-schema-to-ts": "^3.1.1", - "standardwebhooks": "^1.0.0" - }, - "bin": { - "anthropic-ai-sdk": "bin/cli" - }, - "peerDependencies": { - "zod": "^3.25.0 || ^4.0.0" - }, - "peerDependenciesMeta": { - "zod": { - "optional": true - } - } - }, - "node_modules/@babel/code-frame": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", - "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-validator-identifier": "^7.28.5", - "js-tokens": "^4.0.0", - "picocolors": "^1.1.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/compat-data": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz", - "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/core": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", - "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.0", - "@babel/generator": "^7.29.0", - "@babel/helper-compilation-targets": "^7.28.6", - "@babel/helper-module-transforms": "^7.28.6", - "@babel/helpers": "^7.28.6", - "@babel/parser": "^7.29.0", - "@babel/template": "^7.28.6", - "@babel/traverse": "^7.29.0", - "@babel/types": "^7.29.0", - "@jridgewell/remapping": "^2.3.5", - "convert-source-map": "^2.0.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.3", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" - } - }, - "node_modules/@babel/generator": { - "version": "7.29.1", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", - "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.29.0", - "@babel/types": "^7.29.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "jsesc": "^3.0.2" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-compilation-targets": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz", - "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/compat-data": "^7.28.6", - "@babel/helper-validator-option": "^7.27.1", - "browserslist": "^4.24.0", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-globals": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", - "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-imports": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz", - "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/traverse": "^7.28.6", - "@babel/types": "^7.28.6" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-transforms": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz", - "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-imports": "^7.28.6", - "@babel/helper-validator-identifier": "^7.28.5", - "@babel/traverse": "^7.28.6" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", - "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", - "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-option": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz", - "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helpers": { - "version": "7.29.2", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz", - "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/template": "^7.28.6", - "@babel/types": "^7.29.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/parser": { - "version": "7.29.2", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz", - "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.29.0" - }, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/runtime": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz", - "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==", - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/template": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", - "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.28.6", - "@babel/parser": "^7.28.6", - "@babel/types": "^7.28.6" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz", - "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.0", - "@babel/generator": "^7.29.0", - "@babel/helper-globals": "^7.28.0", - "@babel/parser": "^7.29.0", - "@babel/template": "^7.28.6", - "@babel/types": "^7.29.0", - "debug": "^4.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/types": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", - "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.27.1", - "@babel/helper-validator-identifier": "^7.28.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@electric-sql/pglite": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.4.1.tgz", - "integrity": "sha512-mZ9NzzUSYPOCnxHH1oAHPRzoMFJHY472raDKwXl/+6oPbpdJ7g8LsCN4FSaIIfkiCKHhb3iF/Zqo3NYxaIhU7Q==", - "license": "Apache-2.0" - }, - "node_modules/@electric-sql/pglite-socket": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/@electric-sql/pglite-socket/-/pglite-socket-0.1.1.tgz", - "integrity": "sha512-p2hoXw3Z3LQHwTeikdZNsFBOvXGqKY2hk51BBw+8NKND8eoH+8LFOtW9Z8CQKmTJ2qqGYu82ipqiyFZOTTXNfw==", - "license": "Apache-2.0", - "bin": { - "pglite-server": "dist/scripts/server.js" - }, - "peerDependencies": { - "@electric-sql/pglite": "0.4.1" - } - }, - "node_modules/@electric-sql/pglite-tools": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/@electric-sql/pglite-tools/-/pglite-tools-0.3.1.tgz", - "integrity": "sha512-C+T3oivmy9bpQvSxVqXA1UDY8cB9Eb9vZHL9zxWwEUfDixbXv4G3r2LjoTdR33LD8aomR3O9ZXEO3XEwr/cUCA==", - "license": "Apache-2.0", - "peerDependencies": { - "@electric-sql/pglite": "0.4.1" - } - }, - "node_modules/@emnapi/core": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", - "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.1", - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/runtime": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", - "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/wasi-threads": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", - "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz", - "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz", - "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz", - "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz", - "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz", - "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz", - "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz", - "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz", - "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz", - "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz", - "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz", - "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz", - "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz", - "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz", - "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz", - "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz", - "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz", - "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz", - "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz", - "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz", - "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz", - "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openharmony-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz", - "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz", - "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz", - "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz", - "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz", - "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@eslint-community/eslint-utils": { - "version": "4.9.1", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", - "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" - } - }, - "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", - "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@eslint-community/regexpp": { - "version": "4.12.2", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", - "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.0.0 || ^14.0.0 || >=16.0.0" - } - }, - "node_modules/@eslint/config-array": { - "version": "0.21.2", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz", - "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/object-schema": "^2.1.7", - "debug": "^4.3.1", - "minimatch": "^3.1.5" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/config-helpers": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", - "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/core": "^0.17.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/core": { - "version": "0.17.0", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", - "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@types/json-schema": "^7.0.15" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/eslintrc": { - "version": "3.3.5", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz", - "integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==", - "dev": true, - "license": "MIT", - "dependencies": { - "ajv": "^6.14.0", - "debug": "^4.3.2", - "espree": "^10.0.1", - "globals": "^14.0.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.1.1", - "minimatch": "^3.1.5", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@eslint/js": { - "version": "9.39.4", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.4.tgz", - "integrity": "sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://eslint.org/donate" - } - }, - "node_modules/@eslint/object-schema": { - "version": "2.1.7", - "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", - "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/plugin-kit": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", - "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/core": "^0.17.0", - "levn": "^0.4.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@fast-csv/format": { - "version": "4.3.5", - "resolved": "https://registry.npmjs.org/@fast-csv/format/-/format-4.3.5.tgz", - "integrity": "sha512-8iRn6QF3I8Ak78lNAa+Gdl5MJJBM5vRHivFtMRUWINdevNo00K7OXxS2PshawLKTejVwieIlPmK5YlLu6w4u8A==", - "license": "MIT", - "dependencies": { - "@types/node": "^14.0.1", - "lodash.escaperegexp": "^4.1.2", - "lodash.isboolean": "^3.0.3", - "lodash.isequal": "^4.5.0", - "lodash.isfunction": "^3.0.9", - "lodash.isnil": "^4.0.0" - } - }, - "node_modules/@fast-csv/format/node_modules/@types/node": { - "version": "14.18.63", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz", - "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==", - "license": "MIT" - }, - "node_modules/@fast-csv/parse": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/@fast-csv/parse/-/parse-4.3.6.tgz", - "integrity": "sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA==", - "license": "MIT", - "dependencies": { - "@types/node": "^14.0.1", - "lodash.escaperegexp": "^4.1.2", - "lodash.groupby": "^4.6.0", - "lodash.isfunction": "^3.0.9", - "lodash.isnil": "^4.0.0", - "lodash.isundefined": "^3.0.1", - "lodash.uniq": "^4.5.0" - } - }, - "node_modules/@fast-csv/parse/node_modules/@types/node": { - "version": "14.18.63", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz", - "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==", - "license": "MIT" - }, - "node_modules/@hono/node-server": { - "version": "1.19.11", - "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.11.tgz", - "integrity": "sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g==", - "license": "MIT", - "engines": { - "node": ">=18.14.1" - }, - "peerDependencies": { - "hono": "^4" - } - }, - "node_modules/@humanfs/core": { - "version": "0.19.2", - "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", - "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@humanfs/types": "^0.15.0" - }, - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanfs/node": { - "version": "0.16.8", - "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", - "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@humanfs/core": "^0.19.2", - "@humanfs/types": "^0.15.0", - "@humanwhocodes/retry": "^0.4.0" - }, - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanfs/types": { - "version": "0.15.0", - "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", - "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanwhocodes/module-importer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", - "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12.22" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@humanwhocodes/retry": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", - "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18.18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@img/colour": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", - "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/@img/sharp-darwin-arm64": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", - "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", - "cpu": [ - "arm64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-darwin-arm64": "1.3.4" - } - }, - "node_modules/@img/sharp-darwin-x64": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", - "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-darwin-x64": "1.3.4" - } - }, - "node_modules/@img/sharp-freebsd-wasm32": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", - "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", - "license": "Apache-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "dependencies": { - "@img/sharp-wasm32": "0.35.5" - }, - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-darwin-arm64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", - "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", - "cpu": [ - "arm64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "darwin" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-darwin-x64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", - "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", - "cpu": [ - "x64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "darwin" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-arm": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", - "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", - "cpu": [ - "arm" - ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-arm64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", - "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", - "cpu": [ - "arm64" - ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-ppc64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", - "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", - "cpu": [ - "ppc64" - ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-riscv64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", - "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", - "cpu": [ - "riscv64" - ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-s390x": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", - "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", - "cpu": [ - "s390x" - ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-x64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", - "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", - "cpu": [ - "x64" - ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linuxmusl-arm64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", - "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", - "cpu": [ - "arm64" - ], - "libc": [ - "musl" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linuxmusl-x64": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", - "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", - "cpu": [ - "x64" - ], - "libc": [ - "musl" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-linux-arm": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", - "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", - "cpu": [ - "arm" - ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-arm": "1.3.4" - } - }, - "node_modules/@img/sharp-linux-arm64": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", - "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", - "cpu": [ - "arm64" - ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-arm64": "1.3.4" - } - }, - "node_modules/@img/sharp-linux-ppc64": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", - "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", - "cpu": [ - "ppc64" - ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-ppc64": "1.3.4" - } - }, - "node_modules/@img/sharp-linux-riscv64": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", - "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", - "cpu": [ - "riscv64" - ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-riscv64": "1.3.4" - } - }, - "node_modules/@img/sharp-linux-s390x": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", - "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", - "cpu": [ - "s390x" - ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-s390x": "1.3.4" - } - }, - "node_modules/@img/sharp-linux-x64": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", - "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", - "cpu": [ - "x64" - ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.3.4" - } - }, - "node_modules/@img/sharp-linuxmusl-arm64": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", - "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", - "cpu": [ - "arm64" - ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" - } - }, - "node_modules/@img/sharp-linuxmusl-x64": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", - "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", - "cpu": [ - "x64" - ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-x64": "1.3.4" - } - }, - "node_modules/@img/sharp-wasm32": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", - "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", - "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", - "optional": true, - "dependencies": { - "@emnapi/runtime": "^1.11.3" - }, - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-webcontainers-wasm32": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", - "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", - "cpu": [ - "wasm32" - ], - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "@img/sharp-wasm32": "0.35.5" - }, - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-win32-arm64": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", - "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", - "cpu": [ - "arm64" - ], - "license": "Apache-2.0 AND LGPL-3.0-or-later", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-win32-ia32": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", - "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", - "cpu": [ - "ia32" - ], - "license": "Apache-2.0 AND LGPL-3.0-or-later", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-win32-x64": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", - "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0 AND LGPL-3.0-or-later", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", - "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/remapping": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", - "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@kurkle/color": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz", - "integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==", - "license": "MIT" - }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "0.2.12", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz", - "integrity": "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "^1.4.3", - "@emnapi/runtime": "^1.4.3", - "@tybys/wasm-util": "^0.10.0" - } - }, - "node_modules/@next/env": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/@next/env/-/env-16.2.4.tgz", - "integrity": "sha512-dKkkOzOSwFYe5RX6y26fZgkSpVAlIOJKQHIiydQcrWH6y/97+RceSOAdjZ14Qa3zLduVUy0TXcn+EiM6t4rPgw==", - "license": "MIT" - }, - "node_modules/@next/eslint-plugin-next": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.2.4.tgz", - "integrity": "sha512-tOX826JJ96gYK/go18sPUgMq9FK1tqxBFfUCEufJb5XIkWFFmpgU7mahJANKGkHs7F41ir3tReJ3Lv5La0RvhA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-glob": "3.3.1" - } - }, - "node_modules/@next/swc-darwin-arm64": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.2.4.tgz", - "integrity": "sha512-OXTFFox5EKN1Ym08vfrz+OXxmCcEjT4SFMbNRsWZE99dMqt2Kcusl5MqPXcW232RYkMLQTy0hqgAMEsfEd/l2A==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-darwin-x64": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.2.4.tgz", - "integrity": "sha512-XhpVnUfmYWvD3YrXu55XdcAkQtOnvaI6wtQa8fuF5fGoKoxIUZ0kWPtcOfqJEWngFF/lOS9l3+O9CcownhiQxQ==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-linux-arm64-gnu": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.2.4.tgz", - "integrity": "sha512-Mx/tjlNA3G8kg14QvuGAJ4xBwPk1tUHq56JxZ8CXnZwz1Etz714soCEzGQQzVMz4bEnGPowzkV6Xrp6wAkEWOQ==", - "cpu": [ - "arm64" - ], - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-linux-arm64-musl": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.2.4.tgz", - "integrity": "sha512-iVMMp14514u7Nup2umQS03nT/bN9HurK8ufylC3FZNykrwjtx7V1A7+4kvhbDSCeonTVqV3Txnv0Lu+m2oDXNg==", - "cpu": [ - "arm64" - ], - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-linux-x64-gnu": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.2.4.tgz", - "integrity": "sha512-EZOvm1aQWgnI/N/xcWOlnS3RQBk0VtVav5Zo7n4p0A7UKyTDx047k8opDbXgBpHl4CulRqRfbw3QrX2w5UOXMQ==", - "cpu": [ - "x64" - ], - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-linux-x64-musl": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.2.4.tgz", - "integrity": "sha512-h9FxsngCm9cTBf71AR4fGznDEDx1hS7+kSEiIRjq5kO1oXWm07DxVGZjCvk0SGx7TSjlUqhI8oOyz7NfwAdPoA==", - "cpu": [ - "x64" - ], - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-win32-arm64-msvc": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.2.4.tgz", - "integrity": "sha512-3NdJV5OXMSOeJYijX+bjaLge3mJBlh4ybydbT4GFoB/2hAojWHtMhl3CYlYoMrjPuodp0nzFVi4Tj2+WaMg+Ow==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-win32-x64-msvc": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.2.4.tgz", - "integrity": "sha512-kMVGgsqhO5YTYODD9IPGGhA6iprWidQckK3LmPeW08PIFENRmgfb4MjXHO+p//d+ts2rpjvK5gXWzXSMrPl9cw==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@noble/ciphers": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz", - "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nolyfill/is-core-module": { - "version": "1.0.39", - "resolved": "https://registry.npmjs.org/@nolyfill/is-core-module/-/is-core-module-1.0.39.tgz", - "integrity": "sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.4.0" - } - }, - "node_modules/@prisma/adapter-pg": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/@prisma/adapter-pg/-/adapter-pg-7.8.0.tgz", - "integrity": "sha512-ygb3UkerK3v8MDpXVgCISdRNDozpxh6+JVJgiIGbSr5KBgz10LLf5ejUskPGoXlsIjxsOu6nuy1JVQr2EKGSlg==", - "license": "Apache-2.0", - "dependencies": { - "@prisma/driver-adapter-utils": "7.8.0", - "@types/pg": "^8.16.0", - "pg": "^8.16.3", - "postgres-array": "3.0.4" - } - }, - "node_modules/@prisma/client": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/@prisma/client/-/client-7.8.0.tgz", - "integrity": "sha512-HFp3Dawv/3sU3JtlPha90IB+48lS7zHiH4LKZPjmcE8YH5P9DOXGPvo8dqOtO7MqLDd1p2hOWMcFlRT1DMblHw==", - "license": "Apache-2.0", - "dependencies": { - "@prisma/client-runtime-utils": "7.8.0" - }, - "engines": { - "node": "^20.19 || ^22.12 || >=24.0" - }, - "peerDependencies": { - "prisma": "*", - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "prisma": { - "optional": true - }, - "typescript": { - "optional": true - } - } - }, - "node_modules/@prisma/client-runtime-utils": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/@prisma/client-runtime-utils/-/client-runtime-utils-7.8.0.tgz", - "integrity": "sha512-5NQZztQ0oY/ADFkmd9gPuweH5A1/CCY8YQPorLLO0Mu6a87mY5gsnDkzmFmIHs9NFaLnZojzgddFVN4RpKYrdw==", - "license": "Apache-2.0" - }, - "node_modules/@prisma/config": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/@prisma/config/-/config-7.8.0.tgz", - "integrity": "sha512-HFESzd9rx2ZQxlK+TL7tu1HPvCqrHiL6LCxYykI2c34mvaUuIVVl3lYuicJD/MNnzgPnyeBEMlK4WTomJCV5jw==", - "license": "Apache-2.0", - "dependencies": { - "c12": "3.3.4", - "deepmerge-ts": "7.1.5", - "effect": "3.20.0", - "empathic": "2.0.0" - } - }, - "node_modules/@prisma/debug": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-7.8.0.tgz", - "integrity": "sha512-p+QZReysDUqXC+mk17q9a+Y/qzh4c2KYliDK30buYUyfrGeTGSyfmc0AIrJRhZJrLHhRiJa9Au/J72h3C+szvA==", - "license": "Apache-2.0" - }, - "node_modules/@prisma/dev": { - "version": "0.24.3", - "resolved": "https://registry.npmjs.org/@prisma/dev/-/dev-0.24.3.tgz", - "integrity": "sha512-ffHlQuKXZiaDt9Go0OnCTdJZrHxK0k7omJKNV86/VjpsXu5EIHZLK0T7JSWgvNlJwh56kW9JFu9v0qJciFzepg==", - "license": "ISC", - "dependencies": { - "@electric-sql/pglite": "0.4.1", - "@electric-sql/pglite-socket": "0.1.1", - "@electric-sql/pglite-tools": "0.3.1", - "@hono/node-server": "1.19.11", - "@prisma/get-platform": "7.2.0", - "@prisma/query-plan-executor": "7.2.0", - "@prisma/streams-local": "0.1.2", - "foreground-child": "3.3.1", - "get-port-please": "3.2.0", - "hono": "^4.12.8", - "http-status-codes": "2.3.0", - "pathe": "2.0.3", - "proper-lockfile": "4.1.2", - "remeda": "2.33.4", - "std-env": "3.10.0", - "valibot": "1.2.0", - "zeptomatch": "2.1.0" - } - }, - "node_modules/@prisma/driver-adapter-utils": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/@prisma/driver-adapter-utils/-/driver-adapter-utils-7.8.0.tgz", - "integrity": "sha512-/Q13o0ZT0rjc1Xk0Q9KhZYwuq2EW/vSbWUBKfgEKkaCuB/Sg6bqnjmTZqC5cD4d6y1vfFAEwBRzfzoSMIVJ55A==", - "license": "Apache-2.0", - "dependencies": { - "@prisma/debug": "7.8.0" - } - }, - "node_modules/@prisma/engines": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-7.8.0.tgz", - "integrity": "sha512-jx3rCnNNrt5uzbkKlegtQ2GZHxSlihMCzutgT/BP6UIDF1r9tDI39hV/0T/cHZgzJ3ELbuQPXlVZy+Y1n0pcgw==", - "hasInstallScript": true, - "license": "Apache-2.0", - "dependencies": { - "@prisma/debug": "7.8.0", - "@prisma/engines-version": "7.8.0-6.3c6e192761c0362d496ed980de936e2f3cebcd3a", - "@prisma/fetch-engine": "7.8.0", - "@prisma/get-platform": "7.8.0" - } - }, - "node_modules/@prisma/engines-version": { - "version": "7.8.0-6.3c6e192761c0362d496ed980de936e2f3cebcd3a", - "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-7.8.0-6.3c6e192761c0362d496ed980de936e2f3cebcd3a.tgz", - "integrity": "sha512-fJPQxCkLgA5EayWaW8eArgCvjJ+N+Kz3VyeNKMEeYiQC4alNkxRKFVAGxv/ZUzuJISKqdw+zGeDbS6mn6RCPOA==", - "license": "Apache-2.0" - }, - "node_modules/@prisma/engines/node_modules/@prisma/get-platform": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-7.8.0.tgz", - "integrity": "sha512-WlxgRGnolL8VH2EmkH1R/DkKNr/mVdS3G2h42IZFFZ3eUrH9OT6t73kIOSlkkrv50wG123Iq8d96ufv5LlZktw==", - "license": "Apache-2.0", - "dependencies": { - "@prisma/debug": "7.8.0" - } - }, - "node_modules/@prisma/fetch-engine": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-7.8.0.tgz", - "integrity": "sha512-gwB0Euiz/DDRyxFRpLXYlK3RfaZUj1c5dAYMuhZYfApg7arknJlcb9bIsOHDppJmbqYaVA+yBIiFMDBfprsNPQ==", - "license": "Apache-2.0", - "dependencies": { - "@prisma/debug": "7.8.0", - "@prisma/engines-version": "7.8.0-6.3c6e192761c0362d496ed980de936e2f3cebcd3a", - "@prisma/get-platform": "7.8.0" - } - }, - "node_modules/@prisma/fetch-engine/node_modules/@prisma/get-platform": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-7.8.0.tgz", - "integrity": "sha512-WlxgRGnolL8VH2EmkH1R/DkKNr/mVdS3G2h42IZFFZ3eUrH9OT6t73kIOSlkkrv50wG123Iq8d96ufv5LlZktw==", - "license": "Apache-2.0", - "dependencies": { - "@prisma/debug": "7.8.0" - } - }, - "node_modules/@prisma/get-platform": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-7.2.0.tgz", - "integrity": "sha512-k1V0l0Td1732EHpAfi2eySTezyllok9dXb6UQanajkJQzPUGi3vO2z7jdkz67SypFTdmbnyGYxvEvYZdZsMAVA==", - "license": "Apache-2.0", - "dependencies": { - "@prisma/debug": "7.2.0" - } - }, - "node_modules/@prisma/get-platform/node_modules/@prisma/debug": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-7.2.0.tgz", - "integrity": "sha512-YSGTiSlBAVJPzX4ONZmMotL+ozJwQjRmZweQNIq/ER0tQJKJynNkRB3kyvt37eOfsbMCXk3gnLF6J9OJ4QWftw==", - "license": "Apache-2.0" - }, - "node_modules/@prisma/query-plan-executor": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@prisma/query-plan-executor/-/query-plan-executor-7.2.0.tgz", - "integrity": "sha512-EOZmNzcV8uJ0mae3DhTsiHgoNCuu1J9mULQpGCh62zN3PxPTd+qI9tJvk5jOst8WHKQNwJWR3b39t0XvfBB0WQ==", - "license": "Apache-2.0" - }, - "node_modules/@prisma/streams-local": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/@prisma/streams-local/-/streams-local-0.1.2.tgz", - "integrity": "sha512-l49yTxKKF2odFxaAXTmwmkBKL3+bVQ1tFOooGifu4xkdb9NMNLxHj27XAhTylWZod8I+ISGM5erU1xcl/oBCtg==", - "license": "Apache-2.0", - "dependencies": { - "ajv": "^8.12.0", - "better-result": "^2.7.0", - "env-paths": "^3.0.0", - "proper-lockfile": "^4.1.2" - }, - "engines": { - "bun": ">=1.3.6", - "node": ">=22.0.0" - } - }, - "node_modules/@prisma/streams-local/node_modules/ajv": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", - "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/@prisma/streams-local/node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "license": "MIT" - }, - "node_modules/@prisma/studio-core": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@prisma/studio-core/-/studio-core-0.27.3.tgz", - "integrity": "sha512-AADjNFPdsrglxHQVTmHFqv6DuKQZ5WY4p5/gVFY017twvNrSwpLJ9lqUbYYxEu2W7nbvVxTZA8deJ8LseNALsw==", - "license": "Apache-2.0", - "dependencies": { - "@radix-ui/react-toggle": "1.1.10", - "chart.js": "4.5.1" - }, - "engines": { - "node": "^20.19 || ^22.12 || >=24.0", - "pnpm": "8" - }, - "peerDependencies": { - "@types/react": "^18.0.0 || ^19.0.0", - "react": "^18.0.0 || ^19.0.0", - "react-dom": "^18.0.0 || ^19.0.0" - } - }, - "node_modules/@radix-ui/primitive": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz", - "integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==", - "license": "MIT" - }, - "node_modules/@radix-ui/react-compose-refs": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.2.tgz", - "integrity": "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==", - "license": "MIT", - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-primitive": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz", - "integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-slot": "1.2.3" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-slot": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz", - "integrity": "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-compose-refs": "1.1.2" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-toggle": { - "version": "1.1.10", - "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.1.10.tgz", - "integrity": "sha512-lS1odchhFTeZv3xwHH31YPObmJn8gOg7Lq12inrr0+BH/l3Tsq32VfjqH1oh80ARM3mlkfMic15n0kg4sD1poQ==", - "license": "MIT", - "dependencies": { - "@radix-ui/primitive": "1.1.3", - "@radix-ui/react-primitive": "2.1.3", - "@radix-ui/react-use-controllable-state": "1.2.2" - }, - "peerDependencies": { - "@types/react": "*", - "@types/react-dom": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", - "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "@types/react-dom": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-use-controllable-state": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@radix-ui/react-use-controllable-state/-/react-use-controllable-state-1.2.2.tgz", - "integrity": "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-use-effect-event": "0.0.2", - "@radix-ui/react-use-layout-effect": "1.1.1" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-use-effect-event": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/@radix-ui/react-use-effect-event/-/react-use-effect-event-0.0.2.tgz", - "integrity": "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA==", - "license": "MIT", - "dependencies": { - "@radix-ui/react-use-layout-effect": "1.1.1" - }, - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@radix-ui/react-use-layout-effect": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz", - "integrity": "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==", - "license": "MIT", - "peerDependencies": { - "@types/react": "*", - "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, - "node_modules/@rtsao/scc": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz", - "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==", - "dev": true, - "license": "MIT" - }, - "node_modules/@stablelib/base64": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", - "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", - "license": "MIT" - }, - "node_modules/@standard-schema/spec": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", - "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", - "license": "MIT" - }, - "node_modules/@swc/helpers": { - "version": "0.5.15", - "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz", - "integrity": "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==", - "license": "Apache-2.0", - "dependencies": { - "tslib": "^2.8.0" - } - }, - "node_modules/@tailwindcss/node": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.2.4.tgz", - "integrity": "sha512-Ai7+yQPxz3ddrDQzFfBKdHEVBg0w3Zl83jnjuwxnZOsnH9pGn93QHQtpU0p/8rYWxvbFZHneni6p1BSLK4DkGA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/remapping": "^2.3.5", - "enhanced-resolve": "^5.19.0", - "jiti": "^2.6.1", - "lightningcss": "1.32.0", - "magic-string": "^0.30.21", - "source-map-js": "^1.2.1", - "tailwindcss": "4.2.4" - } - }, - "node_modules/@tailwindcss/oxide": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.2.4.tgz", - "integrity": "sha512-9El/iI069DKDSXwTvB9J4BwdO5JhRrOweGaK25taBAvBXyXqJAX+Jqdvs8r8gKpsI/1m0LeJLyQYTf/WLrBT1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 20" - }, - "optionalDependencies": { - "@tailwindcss/oxide-android-arm64": "4.2.4", - "@tailwindcss/oxide-darwin-arm64": "4.2.4", - "@tailwindcss/oxide-darwin-x64": "4.2.4", - "@tailwindcss/oxide-freebsd-x64": "4.2.4", - "@tailwindcss/oxide-linux-arm-gnueabihf": "4.2.4", - "@tailwindcss/oxide-linux-arm64-gnu": "4.2.4", - "@tailwindcss/oxide-linux-arm64-musl": "4.2.4", - "@tailwindcss/oxide-linux-x64-gnu": "4.2.4", - "@tailwindcss/oxide-linux-x64-musl": "4.2.4", - "@tailwindcss/oxide-wasm32-wasi": "4.2.4", - "@tailwindcss/oxide-win32-arm64-msvc": "4.2.4", - "@tailwindcss/oxide-win32-x64-msvc": "4.2.4" - } - }, - "node_modules/@tailwindcss/oxide-android-arm64": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.2.4.tgz", - "integrity": "sha512-e7MOr1SAn9U8KlZzPi1ZXGZHeC5anY36qjNwmZv9pOJ8E4Q6jmD1vyEHkQFmNOIN7twGPEMXRHmitN4zCMN03g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-darwin-arm64": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.2.4.tgz", - "integrity": "sha512-tSC/Kbqpz/5/o/C2sG7QvOxAKqyd10bq+ypZNf+9Fi2TvbVbv1zNpcEptcsU7DPROaSbVgUXmrzKhurFvo5eDg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-darwin-x64": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.2.4.tgz", - "integrity": "sha512-yPyUXn3yO/ufR6+Kzv0t4fCg2qNr90jxXc5QqBpjlPNd0NqyDXcmQb/6weunH/MEDXW5dhyEi+agTDiqa3WsGg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-freebsd-x64": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.2.4.tgz", - "integrity": "sha512-BoMIB4vMQtZsXdGLVc2z+P9DbETkiopogfWZKbWwM8b/1Vinbs4YcUwo+kM/KeLkX3Ygrf4/PsRndKaYhS8Eiw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.2.4.tgz", - "integrity": "sha512-7pIHBLTHYRAlS7V22JNuTh33yLH4VElwKtB3bwchK/UaKUPpQ0lPQiOWcbm4V3WP2I6fNIJ23vABIvoy2izdwA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.2.4.tgz", - "integrity": "sha512-+E4wxJ0ZGOzSH325reXTWB48l42i93kQqMvDyz5gqfRzRZ7faNhnmvlV4EPGJU3QJM/3Ab5jhJ5pCRUsKn6OQw==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-arm64-musl": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.2.4.tgz", - "integrity": "sha512-bBADEGAbo4ASnppIziaQJelekCxdMaxisrk+fB7Thit72IBnALp9K6ffA2G4ruj90G9XRS2VQ6q2bCKbfFV82g==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-x64-gnu": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.2.4.tgz", - "integrity": "sha512-7Mx25E4WTfnht0TVRTyC00j3i0M+EeFe7wguMDTlX4mRxafznw0CA8WJkFjWYH5BlgELd1kSjuU2JiPnNZbJDA==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-linux-x64-musl": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.2.4.tgz", - "integrity": "sha512-2wwJRF7nyhOR0hhHoChc04xngV3iS+akccHTGtz965FwF0up4b2lOdo6kI1EbDaEXKgvcrFBYcYQQ/rrnWFVfA==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-wasm32-wasi": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.2.4.tgz", - "integrity": "sha512-FQsqApeor8Fo6gUEklzmaa9994orJZZDBAlQpK2Mq+DslRKFJeD6AjHpBQ0kZFQohVr8o85PPh8eOy86VlSCmw==", - "bundleDependencies": [ - "@napi-rs/wasm-runtime", - "@emnapi/core", - "@emnapi/runtime", - "@tybys/wasm-util", - "@emnapi/wasi-threads", - "tslib" - ], - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "^1.8.1", - "@emnapi/runtime": "^1.8.1", - "@emnapi/wasi-threads": "^1.1.0", - "@napi-rs/wasm-runtime": "^1.1.1", - "@tybys/wasm-util": "^0.10.1", - "tslib": "^2.8.1" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.2.4.tgz", - "integrity": "sha512-L9BXqxC4ToVgwMFqj3pmZRqyHEztulpUJzCxUtLjobMCzTPsGt1Fa9enKbOpY2iIyVtaHNeNvAK8ERP/64sqGQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/oxide-win32-x64-msvc": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.2.4.tgz", - "integrity": "sha512-ESlKG0EpVJQwRjXDDa9rLvhEAh0mhP1sF7sap9dNZT0yyl9SAG6T7gdP09EH0vIv0UNTlo6jPWyujD6559fZvw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 20" - } - }, - "node_modules/@tailwindcss/postcss": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.2.4.tgz", - "integrity": "sha512-wgAVj6nUWAolAu8YFvzT2cTBIElWHkjZwFYovF+xsqKsW2ADxM/X2opxj5NsF/qVccAOjRNe8X2IdPzMsWyHTg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@alloc/quick-lru": "^5.2.0", - "@tailwindcss/node": "4.2.4", - "@tailwindcss/oxide": "4.2.4", - "postcss": "^8.5.6", - "tailwindcss": "4.2.4" - } - }, - "node_modules/@tybys/wasm-util": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", - "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@types/bcryptjs": { - "version": "2.4.6", - "resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz", - "integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", - "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/json-schema": { - "version": "7.0.15", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", - "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/json5": { - "version": "0.0.29", - "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", - "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "20.19.39", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.39.tgz", - "integrity": "sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw==", - "license": "MIT", - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/@types/nodemailer": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.2.tgz", - "integrity": "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/pdfkit": { - "version": "0.17.6", - "resolved": "https://registry.npmjs.org/@types/pdfkit/-/pdfkit-0.17.6.tgz", - "integrity": "sha512-tIwzxk2uWKp0Cq9JIluQXJid77lYhF52EsIOwhsMF4iWLA6YneoBR1xVKYYdAysHuepUB0OX4tdwMiUDdGKmig==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/pg": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.20.0.tgz", - "integrity": "sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==", - "license": "MIT", - "dependencies": { - "@types/node": "*", - "pg-protocol": "*", - "pg-types": "^2.2.0" - } - }, - "node_modules/@types/react": { - "version": "19.2.14", - "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz", - "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==", - "license": "MIT", - "dependencies": { - "csstype": "^3.2.2" - } - }, - "node_modules/@types/react-dom": { - "version": "19.2.3", - "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz", - "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", - "devOptional": true, - "license": "MIT", - "peerDependencies": { - "@types/react": "^19.2.0" - } - }, - "node_modules/@types/web-push": { - "version": "3.6.4", - "resolved": "https://registry.npmjs.org/@types/web-push/-/web-push-3.6.4.tgz", - "integrity": "sha512-GnJmSr40H3RAnj0s34FNTcJi1hmWFV5KXugE0mYWnYhgTAHLJ/dJKAwDmvPJYMke0RplY2XE9LnM4hqSqKIjhQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.59.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.59.0.tgz", - "integrity": "sha512-HyAZtpdkgZwpq8Sz3FSUvCR4c+ScbuWa9AksK2Jweub7w4M3yTz4O11AqVJzLYjy/B9ZWPyc81I+mOdJU/bDQw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.59.0", - "@typescript-eslint/type-utils": "8.59.0", - "@typescript-eslint/utils": "8.59.0", - "@typescript-eslint/visitor-keys": "8.59.0", - "ignore": "^7.0.5", - "natural-compare": "^1.4.0", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "@typescript-eslint/parser": "^8.59.0", - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", - "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/@typescript-eslint/parser": { - "version": "8.59.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.59.0.tgz", - "integrity": "sha512-TI1XGwKbDpo9tRW8UDIXCOeLk55qe9ZFGs8MTKU6/M08HWTw52DD/IYhfQtOEhEdPhLMT26Ka/x7p70nd3dzDg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/scope-manager": "8.59.0", - "@typescript-eslint/types": "8.59.0", - "@typescript-eslint/typescript-estree": "8.59.0", - "@typescript-eslint/visitor-keys": "8.59.0", - "debug": "^4.4.3" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/project-service": { - "version": "8.59.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.59.0.tgz", - "integrity": "sha512-Lw5ITrR5s5TbC19YSvlr63ZfLaJoU6vtKTHyB0GQOpX0W7d5/Ir6vUahWi/8Sps/nOukZQ0IB3SmlxZnjaKVnw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.59.0", - "@typescript-eslint/types": "^8.59.0", - "debug": "^4.4.3" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/scope-manager": { - "version": "8.59.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.59.0.tgz", - "integrity": "sha512-UzR16Ut8IpA3Mc4DbgAShlPPkVm8xXMWafXxB0BocaVRHs8ZGakAxGRskF7FId3sdk9lgGD73GSFaWmWFDE4dg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.59.0", - "@typescript-eslint/visitor-keys": "8.59.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.59.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.59.0.tgz", - "integrity": "sha512-91Sbl3s4Kb3SybliIY6muFBmHVv+pYXfybC4Oolp3dvk8BvIE3wOPc+403CWIT7mJNkfQRGtdqghzs2+Z91Tqg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/type-utils": { - "version": "8.59.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.59.0.tgz", - "integrity": "sha512-3TRiZaQSltGqGeNrJzzr1+8YcEobKH9rHnqIp/1psfKFmhRQDNMGP5hBufanYTGznwShzVLs3Mz+gDN7HkWfXg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.59.0", - "@typescript-eslint/typescript-estree": "8.59.0", - "@typescript-eslint/utils": "8.59.0", - "debug": "^4.4.3", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/types": { - "version": "8.59.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.59.0.tgz", - "integrity": "sha512-nLzdsT1gdOgFxxxwrlNVUBzSNBEEHJ86bblmk4QAS6stfig7rcJzWKqCyxFy3YRRHXDWEkb2NralA1nOYkkm/A==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.59.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.59.0.tgz", - "integrity": "sha512-O9Re9P1BmBLFJyikRbQpLku/QA3/AueZNO9WePLBwQrvkixTmDe8u76B6CYUAITRl/rHawggEqUGn5QIkVRLMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/project-service": "8.59.0", - "@typescript-eslint/tsconfig-utils": "8.59.0", - "@typescript-eslint/types": "8.59.0", - "@typescript-eslint/visitor-keys": "8.59.0", - "debug": "^4.4.3", - "minimatch": "^10.2.2", - "semver": "^7.7.3", - "tinyglobby": "^0.2.15", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", - "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { - "version": "10.2.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", - "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.5" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { - "version": "7.7.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", - "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@typescript-eslint/utils": { - "version": "8.59.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.59.0.tgz", - "integrity": "sha512-I1R/K7V07XsMJ12Oaxg/O9GfrysGTmCRhvZJBv0RE0NcULMzjqVpR5kRRQjHsz3J/bElU7HwCO7zkqL+MSUz+g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.59.0", - "@typescript-eslint/types": "8.59.0", - "@typescript-eslint/typescript-estree": "8.59.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.59.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.59.0.tgz", - "integrity": "sha512-/uejZt4dSere1bx12WLlPfv8GktzcaDtuJ7s42/HEZ5zGj9oxRaD4bj7qwSunXkf+pbAhFt2zjpHYUiT5lHf0Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.59.0", - "eslint-visitor-keys": "^5.0.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", - "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@unrs/resolver-binding-android-arm-eabi": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.11.1.tgz", - "integrity": "sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@unrs/resolver-binding-android-arm64": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.11.1.tgz", - "integrity": "sha512-lCxkVtb4wp1v+EoN+HjIG9cIIzPkX5OtM03pQYkG+U5O/wL53LC4QbIeazgiKqluGeVEeBlZahHalCaBvU1a2g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@unrs/resolver-binding-darwin-arm64": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.11.1.tgz", - "integrity": "sha512-gPVA1UjRu1Y/IsB/dQEsp2V1pm44Of6+LWvbLc9SDk1c2KhhDRDBUkQCYVWe6f26uJb3fOK8saWMgtX8IrMk3g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@unrs/resolver-binding-darwin-x64": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.11.1.tgz", - "integrity": "sha512-cFzP7rWKd3lZaCsDze07QX1SC24lO8mPty9vdP+YVa3MGdVgPmFc59317b2ioXtgCMKGiCLxJ4HQs62oz6GfRQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@unrs/resolver-binding-freebsd-x64": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.11.1.tgz", - "integrity": "sha512-fqtGgak3zX4DCB6PFpsH5+Kmt/8CIi4Bry4rb1ho6Av2QHTREM+47y282Uqiu3ZRF5IQioJQ5qWRV6jduA+iGw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.11.1.tgz", - "integrity": "sha512-u92mvlcYtp9MRKmP+ZvMmtPN34+/3lMHlyMj7wXJDeXxuM0Vgzz0+PPJNsro1m3IZPYChIkn944wW8TYgGKFHw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-arm-musleabihf": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.11.1.tgz", - "integrity": "sha512-cINaoY2z7LVCrfHkIcmvj7osTOtm6VVT16b5oQdS4beibX2SYBwgYLmqhBjA1t51CarSaBuX5YNsWLjsqfW5Cw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-arm64-gnu": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.11.1.tgz", - "integrity": "sha512-34gw7PjDGB9JgePJEmhEqBhWvCiiWCuXsL9hYphDF7crW7UgI05gyBAi6MF58uGcMOiOqSJ2ybEeCvHcq0BCmQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-arm64-musl": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.11.1.tgz", - "integrity": "sha512-RyMIx6Uf53hhOtJDIamSbTskA99sPHS96wxVE/bJtePJJtpdKGXO1wY90oRdXuYOGOTuqjT8ACccMc4K6QmT3w==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-ppc64-gnu": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.11.1.tgz", - "integrity": "sha512-D8Vae74A4/a+mZH0FbOkFJL9DSK2R6TFPC9M+jCWYia/q2einCubX10pecpDiTmkJVUH+y8K3BZClycD8nCShA==", - "cpu": [ - "ppc64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-riscv64-gnu": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.11.1.tgz", - "integrity": "sha512-frxL4OrzOWVVsOc96+V3aqTIQl1O2TjgExV4EKgRY09AJ9leZpEg8Ak9phadbuX0BA4k8U5qtvMSQQGGmaJqcQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-riscv64-musl": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.11.1.tgz", - "integrity": "sha512-mJ5vuDaIZ+l/acv01sHoXfpnyrNKOk/3aDoEdLO/Xtn9HuZlDD6jKxHlkN8ZhWyLJsRBxfv9GYM2utQ1SChKew==", - "cpu": [ - "riscv64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-s390x-gnu": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.11.1.tgz", - "integrity": "sha512-kELo8ebBVtb9sA7rMe1Cph4QHreByhaZ2QEADd9NzIQsYNQpt9UkM9iqr2lhGr5afh885d/cB5QeTXSbZHTYPg==", - "cpu": [ - "s390x" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-x64-gnu": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.11.1.tgz", - "integrity": "sha512-C3ZAHugKgovV5YvAMsxhq0gtXuwESUKc5MhEtjBpLoHPLYM+iuwSj3lflFwK3DPm68660rZ7G8BMcwSro7hD5w==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-x64-musl": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.11.1.tgz", - "integrity": "sha512-rV0YSoyhK2nZ4vEswT/QwqzqQXw5I6CjoaYMOX0TqBlWhojUf8P94mvI7nuJTeaCkkds3QE4+zS8Ko+GdXuZtA==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-wasm32-wasi": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.11.1.tgz", - "integrity": "sha512-5u4RkfxJm+Ng7IWgkzi3qrFOvLvQYnPBmjmZQ8+szTK/b31fQCnleNl1GgEt7nIsZRIf5PLhPwT0WM+q45x/UQ==", - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@napi-rs/wasm-runtime": "^0.2.11" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@unrs/resolver-binding-win32-arm64-msvc": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.11.1.tgz", - "integrity": "sha512-nRcz5Il4ln0kMhfL8S3hLkxI85BXs3o8EYoattsJNdsX4YUU89iOkVn7g0VHSRxFuVMdM4Q1jEpIId1Ihim/Uw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@unrs/resolver-binding-win32-ia32-msvc": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.11.1.tgz", - "integrity": "sha512-DCEI6t5i1NmAZp6pFonpD5m7i6aFrpofcp4LA2i8IIq60Jyo28hamKBxNrZcyOwVOZkgsRp9O2sXWBWP8MnvIQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@unrs/resolver-binding-win32-x64-msvc": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.11.1.tgz", - "integrity": "sha512-lrW200hZdbfRtztbygyaq/6jP6AKE8qQN2KvPcJ+x7wiD038YtnYtZ82IMNJ69GJibV7bwL3y9FgK+5w/pYt6g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/acorn": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", - "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", - "dev": true, - "license": "MIT", - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-jsx": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, - "node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, - "node_modules/ajv": { - "version": "6.15.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", - "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/archiver": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/archiver/-/archiver-5.3.2.tgz", - "integrity": "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw==", - "license": "MIT", - "dependencies": { - "archiver-utils": "^2.1.0", - "async": "^3.2.4", - "buffer-crc32": "^0.2.1", - "readable-stream": "^3.6.0", - "readdir-glob": "^1.1.2", - "tar-stream": "^2.2.0", - "zip-stream": "^4.1.0" - }, - "engines": { - "node": ">= 10" - } - }, - "node_modules/archiver-utils": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-2.1.0.tgz", - "integrity": "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw==", - "license": "MIT", - "dependencies": { - "glob": "^7.1.4", - "graceful-fs": "^4.2.0", - "lazystream": "^1.0.0", - "lodash.defaults": "^4.2.0", - "lodash.difference": "^4.5.0", - "lodash.flatten": "^4.4.0", - "lodash.isplainobject": "^4.0.6", - "lodash.union": "^4.6.0", - "normalize-path": "^3.0.0", - "readable-stream": "^2.0.0" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/archiver-utils/node_modules/isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", - "license": "MIT" - }, - "node_modules/archiver-utils/node_modules/readable-stream": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", - "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", - "license": "MIT", - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "node_modules/archiver-utils/node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "license": "MIT" - }, - "node_modules/archiver-utils/node_modules/string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.1.0" - } - }, - "node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, - "license": "Python-2.0" - }, - "node_modules/aria-query": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz", - "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/array-buffer-byte-length": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", - "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3", - "is-array-buffer": "^3.0.5" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/array-includes": { - "version": "3.1.9", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.9.tgz", - "integrity": "sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "call-bound": "^1.0.4", - "define-properties": "^1.2.1", - "es-abstract": "^1.24.0", - "es-object-atoms": "^1.1.1", - "get-intrinsic": "^1.3.0", - "is-string": "^1.1.1", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/array.prototype.findlast": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/array.prototype.findlast/-/array.prototype.findlast-1.2.5.tgz", - "integrity": "sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.7", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.2", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.0.0", - "es-shim-unscopables": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/array.prototype.findlastindex": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.6.tgz", - "integrity": "sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "call-bound": "^1.0.4", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.9", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "es-shim-unscopables": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/array.prototype.flat": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.3.tgz", - "integrity": "sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.5", - "es-shim-unscopables": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/array.prototype.flatmap": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.3.tgz", - "integrity": "sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.5", - "es-shim-unscopables": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/array.prototype.tosorted": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/array.prototype.tosorted/-/array.prototype.tosorted-1.1.4.tgz", - "integrity": "sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.7", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.3", - "es-errors": "^1.3.0", - "es-shim-unscopables": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/arraybuffer.prototype.slice": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz", - "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "array-buffer-byte-length": "^1.0.1", - "call-bind": "^1.0.8", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.5", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "is-array-buffer": "^3.0.4" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/asn1.js": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", - "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", - "license": "MIT", - "dependencies": { - "bn.js": "^4.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "safer-buffer": "^2.1.0" - } - }, - "node_modules/ast-types-flow": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.8.tgz", - "integrity": "sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/async": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", - "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", - "license": "MIT" - }, - "node_modules/async-function": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz", - "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/available-typed-arrays": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", - "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "possible-typed-array-names": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/aws-ssl-profiles": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", - "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", - "license": "MIT", - "engines": { - "node": ">= 6.0.0" - } - }, - "node_modules/axe-core": { - "version": "4.11.3", - "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.11.3.tgz", - "integrity": "sha512-zBQouZixDTbo3jMGqHKyePxYxr1e5W8UdTmBQ7sNtaA9M2bE32daxxPLS/jojhKOHxQ7LWwPjfiwf/fhaJWzlg==", - "dev": true, - "license": "MPL-2.0", - "engines": { - "node": ">=4" - } - }, - "node_modules/axobject-query": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", - "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "license": "MIT" - }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/baseline-browser-mapping": { - "version": "2.10.23", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.23.tgz", - "integrity": "sha512-xwVXGqevyKPsiuQdLj+dZMVjidjJV508TBqexND5HrF89cGdCYCJFB3qhcxRHSeMctdCfbR1jrxBajhDy7o29g==", - "license": "Apache-2.0", - "bin": { - "baseline-browser-mapping": "dist/cli.cjs" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/bcryptjs": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz", - "integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==", - "license": "BSD-3-Clause", - "bin": { - "bcrypt": "bin/bcrypt" - } - }, - "node_modules/better-result": { - "version": "2.8.2", - "resolved": "https://registry.npmjs.org/better-result/-/better-result-2.8.2.tgz", - "integrity": "sha512-YOf0VSj5nUPI27doTtXF+BBnsiRq3qY7avHqfIWnppxTLGyvkLq1QV2RTxkwoZwJ60ywLfZ0raFF4J/G886i7A==", - "license": "MIT" - }, - "node_modules/big-integer": { - "version": "1.6.52", - "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", - "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", - "license": "Unlicense", - "engines": { - "node": ">=0.6" - } - }, - "node_modules/binary": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/binary/-/binary-0.3.0.tgz", - "integrity": "sha512-D4H1y5KYwpJgK8wk1Cue5LLPgmwHKYSChkbspQg5JtVuR5ulGckxfR62H3AE9UDkdMC8yyXlqYihuz3Aqg2XZg==", - "license": "MIT", - "dependencies": { - "buffers": "~0.1.1", - "chainsaw": "~0.1.0" - }, - "engines": { - "node": "*" - } - }, - "node_modules/bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "license": "MIT", - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } - }, - "node_modules/bluebird": { - "version": "3.4.7", - "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz", - "integrity": "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA==", - "license": "MIT" - }, - "node_modules/bn.js": { - "version": "4.12.5", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.5.tgz", - "integrity": "sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ==", - "license": "MIT" - }, - "node_modules/brace-expansion": { - "version": "1.1.14", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz", - "integrity": "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==", - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/brotli": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz", - "integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==", - "license": "MIT", - "dependencies": { - "base64-js": "^1.1.2" - } - }, - "node_modules/browserify-zlib": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", - "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", - "license": "MIT", - "dependencies": { - "pako": "~1.0.5" - } - }, - "node_modules/browserslist": { - "version": "4.28.2", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz", - "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "baseline-browser-mapping": "^2.10.12", - "caniuse-lite": "^1.0.30001782", - "electron-to-chromium": "^1.5.328", - "node-releases": "^2.0.36", - "update-browserslist-db": "^1.2.3" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, - "node_modules/buffer-crc32": { - "version": "0.2.13", - "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", - "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", - "license": "MIT", - "engines": { - "node": "*" - } - }, - "node_modules/buffer-equal-constant-time": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", - "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", - "license": "BSD-3-Clause" - }, - "node_modules/buffer-indexof-polyfill": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/buffer-indexof-polyfill/-/buffer-indexof-polyfill-1.0.2.tgz", - "integrity": "sha512-I7wzHwA3t1/lwXQh+A5PbNvJxgfo5r3xulgpYDB5zckTu/Z9oUK9biouBKQUjEqzaz3HnAT6TYoovmE+GqSf7A==", - "license": "MIT", - "engines": { - "node": ">=0.10" - } - }, - "node_modules/buffers": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/buffers/-/buffers-0.1.1.tgz", - "integrity": "sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ==", - "engines": { - "node": ">=0.2.0" - } - }, - "node_modules/c12": { - "version": "3.3.4", - "resolved": "https://registry.npmjs.org/c12/-/c12-3.3.4.tgz", - "integrity": "sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA==", - "license": "MIT", - "dependencies": { - "chokidar": "^5.0.0", - "confbox": "^0.2.4", - "defu": "^6.1.6", - "dotenv": "^17.3.1", - "exsolve": "^1.0.8", - "giget": "^3.2.0", - "jiti": "^2.6.1", - "ohash": "^2.0.11", - "pathe": "^2.0.3", - "perfect-debounce": "^2.1.0", - "pkg-types": "^2.3.0", - "rc9": "^3.0.1" - }, - "peerDependencies": { - "magicast": "*" - }, - "peerDependenciesMeta": { - "magicast": { - "optional": true - } - } - }, - "node_modules/call-bind": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", - "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "get-intrinsic": "^1.3.0", - "set-function-length": "^1.2.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/call-bound": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", - "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "get-intrinsic": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/caniuse-lite": { - "version": "1.0.30001791", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001791.tgz", - "integrity": "sha512-yk0l/YSrOnFZk3UROpDLQD9+kC1l4meK/wed583AXrzoarMGJcbRi2Q4RaUYbKxYAsZ8sWmaSa/DsLmdBeI1vQ==", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "CC-BY-4.0" - }, - "node_modules/chainsaw": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/chainsaw/-/chainsaw-0.1.0.tgz", - "integrity": "sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ==", - "license": "MIT/X11", - "dependencies": { - "traverse": ">=0.3.0 <0.4" - }, - "engines": { - "node": "*" - } - }, - "node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/chart.js": { - "version": "4.5.1", - "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz", - "integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==", - "license": "MIT", - "dependencies": { - "@kurkle/color": "^0.3.0" - }, - "engines": { - "pnpm": ">=8" - } - }, - "node_modules/chokidar": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", - "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", - "license": "MIT", - "dependencies": { - "readdirp": "^5.0.0" - }, - "engines": { - "node": ">= 20.19.0" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/client-only": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", - "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==", - "license": "MIT" - }, - "node_modules/clone": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", - "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==", - "license": "MIT", - "engines": { - "node": ">=0.8" - } - }, - "node_modules/clsx": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", - "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, - "license": "MIT" - }, - "node_modules/compress-commons": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/compress-commons/-/compress-commons-4.1.2.tgz", - "integrity": "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg==", - "license": "MIT", - "dependencies": { - "buffer-crc32": "^0.2.13", - "crc32-stream": "^4.0.2", - "normalize-path": "^3.0.0", - "readable-stream": "^3.6.0" - }, - "engines": { - "node": ">= 10" - } - }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "license": "MIT" - }, - "node_modules/confbox": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz", - "integrity": "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==", - "license": "MIT" - }, - "node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "dev": true, - "license": "MIT" - }, - "node_modules/core-util-is": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", - "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", - "license": "MIT" - }, - "node_modules/crc-32": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", - "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", - "license": "Apache-2.0", - "bin": { - "crc32": "bin/crc32.njs" - }, - "engines": { - "node": ">=0.8" - } - }, - "node_modules/crc32-stream": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/crc32-stream/-/crc32-stream-4.0.3.tgz", - "integrity": "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw==", - "license": "MIT", - "dependencies": { - "crc-32": "^1.2.0", - "readable-stream": "^3.4.0" - }, - "engines": { - "node": ">= 10" - } - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/csstype": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", - "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "license": "MIT" - }, - "node_modules/damerau-levenshtein": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz", - "integrity": "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==", - "dev": true, - "license": "BSD-2-Clause" - }, - "node_modules/data-view-buffer": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz", - "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3", - "es-errors": "^1.3.0", - "is-data-view": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/data-view-byte-length": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz", - "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3", - "es-errors": "^1.3.0", - "is-data-view": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/inspect-js" - } - }, - "node_modules/data-view-byte-offset": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz", - "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "is-data-view": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/dayjs": { - "version": "1.11.20", - "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.20.tgz", - "integrity": "sha512-YbwwqR/uYpeoP4pu043q+LTDLFBLApUP6VxRihdfNTqu4ubqMlGDLd6ErXhEgsyvY0K6nCs7nggYumAN+9uEuQ==", - "license": "MIT" - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/deep-is": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/deepmerge-ts": { - "version": "7.1.5", - "resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-7.1.5.tgz", - "integrity": "sha512-HOJkrhaYsweh+W+e74Yn7YStZOilkoPb6fycpwNLKzSPtruFs48nYis0zy5yJz1+ktUhHxoRDJ27RQAWLIJVJw==", - "license": "BSD-3-Clause", - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/define-data-property": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", - "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-define-property": "^1.0.0", - "es-errors": "^1.3.0", - "gopd": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/define-properties": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", - "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", - "dev": true, - "license": "MIT", - "dependencies": { - "define-data-property": "^1.0.1", - "has-property-descriptors": "^1.0.0", - "object-keys": "^1.1.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/defu": { - "version": "6.1.7", - "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", - "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", - "license": "MIT" - }, - "node_modules/denque": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", - "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", - "license": "Apache-2.0", - "engines": { - "node": ">=0.10" - } - }, - "node_modules/destr": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", - "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", - "license": "MIT" - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/dfa": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz", - "integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==", - "license": "MIT" - }, - "node_modules/doctrine": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", - "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "esutils": "^2.0.2" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/dotenv": { - "version": "17.4.2", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", - "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://dotenvx.com" - } - }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/duplexer2": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", - "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==", - "license": "BSD-3-Clause", - "dependencies": { - "readable-stream": "^2.0.2" - } - }, - "node_modules/duplexer2/node_modules/isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", - "license": "MIT" - }, - "node_modules/duplexer2/node_modules/readable-stream": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", - "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", - "license": "MIT", - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "node_modules/duplexer2/node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "license": "MIT" - }, - "node_modules/duplexer2/node_modules/string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.1.0" - } - }, - "node_modules/ecdsa-sig-formatter": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", - "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", - "license": "Apache-2.0", - "dependencies": { - "safe-buffer": "^5.0.1" - } - }, - "node_modules/effect": { - "version": "3.20.0", - "resolved": "https://registry.npmjs.org/effect/-/effect-3.20.0.tgz", - "integrity": "sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw==", - "license": "MIT", - "dependencies": { - "@standard-schema/spec": "^1.0.0", - "fast-check": "^3.23.1" - } - }, - "node_modules/electron-to-chromium": { - "version": "1.5.344", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.344.tgz", - "integrity": "sha512-4MxfbmNDm+KPh066EZy+eUnkcDPcZ35wNmOWzFuh/ijvHsve6kbLTLURy88uCNK5FbpN+yk2nQY6BYh1GEt+wg==", - "dev": true, - "license": "ISC" - }, - "node_modules/emoji-regex": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", - "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", - "dev": true, - "license": "MIT" - }, - "node_modules/empathic": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.0.0.tgz", - "integrity": "sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA==", - "license": "MIT", - "engines": { - "node": ">=14" - } - }, - "node_modules/end-of-stream": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", - "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", - "license": "MIT", - "dependencies": { - "once": "^1.4.0" - } - }, - "node_modules/enhanced-resolve": { - "version": "5.21.0", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.21.0.tgz", - "integrity": "sha512-otxSQPw4lkOZWkHpB3zaEQs6gWYEsmX4xQF68ElXC/TWvGxGMSGOvoNbaLXm6/cS/fSfHtsEdw90y20PCd+sCA==", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.4", - "tapable": "^2.3.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/env-paths": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", - "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", - "license": "MIT", - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/es-abstract": { - "version": "1.24.2", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.2.tgz", - "integrity": "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==", - "dev": true, - "license": "MIT", - "dependencies": { - "array-buffer-byte-length": "^1.0.2", - "arraybuffer.prototype.slice": "^1.0.4", - "available-typed-arrays": "^1.0.7", - "call-bind": "^1.0.8", - "call-bound": "^1.0.4", - "data-view-buffer": "^1.0.2", - "data-view-byte-length": "^1.0.2", - "data-view-byte-offset": "^1.0.1", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "es-set-tostringtag": "^2.1.0", - "es-to-primitive": "^1.3.0", - "function.prototype.name": "^1.1.8", - "get-intrinsic": "^1.3.0", - "get-proto": "^1.0.1", - "get-symbol-description": "^1.1.0", - "globalthis": "^1.0.4", - "gopd": "^1.2.0", - "has-property-descriptors": "^1.0.2", - "has-proto": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "internal-slot": "^1.1.0", - "is-array-buffer": "^3.0.5", - "is-callable": "^1.2.7", - "is-data-view": "^1.0.2", - "is-negative-zero": "^2.0.3", - "is-regex": "^1.2.1", - "is-set": "^2.0.3", - "is-shared-array-buffer": "^1.0.4", - "is-string": "^1.1.1", - "is-typed-array": "^1.1.15", - "is-weakref": "^1.1.1", - "math-intrinsics": "^1.1.0", - "object-inspect": "^1.13.4", - "object-keys": "^1.1.1", - "object.assign": "^4.1.7", - "own-keys": "^1.0.1", - "regexp.prototype.flags": "^1.5.4", - "safe-array-concat": "^1.1.3", - "safe-push-apply": "^1.0.0", - "safe-regex-test": "^1.1.0", - "set-proto": "^1.0.0", - "stop-iteration-iterator": "^1.1.0", - "string.prototype.trim": "^1.2.10", - "string.prototype.trimend": "^1.0.9", - "string.prototype.trimstart": "^1.0.8", - "typed-array-buffer": "^1.0.3", - "typed-array-byte-length": "^1.0.3", - "typed-array-byte-offset": "^1.0.4", - "typed-array-length": "^1.0.7", - "unbox-primitive": "^1.1.0", - "which-typed-array": "^1.1.19" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-iterator-helpers": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.3.2.tgz", - "integrity": "sha512-HVLACW1TppGYjJ8H6/jqH/pqOtKRw6wMlrB23xfExmFWxFquAIWCmwoLsOyN96K4a5KbmOf5At9ZUO3GZbetAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.9", - "call-bound": "^1.0.4", - "define-properties": "^1.2.1", - "es-abstract": "^1.24.2", - "es-errors": "^1.3.0", - "es-set-tostringtag": "^2.1.0", - "function-bind": "^1.1.2", - "get-intrinsic": "^1.3.0", - "globalthis": "^1.0.4", - "gopd": "^1.2.0", - "has-property-descriptors": "^1.0.2", - "has-proto": "^1.2.0", - "has-symbols": "^1.1.0", - "internal-slot": "^1.1.0", - "iterator.prototype": "^1.1.5", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-set-tostringtag": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", - "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-shim-unscopables": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.1.0.tgz", - "integrity": "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==", - "dev": true, - "license": "MIT", - "dependencies": { - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-to-primitive": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.3.0.tgz", - "integrity": "sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-callable": "^1.2.7", - "is-date-object": "^1.0.5", - "is-symbol": "^1.0.4" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/esbuild": { - "version": "0.27.7", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz", - "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.27.7", - "@esbuild/android-arm": "0.27.7", - "@esbuild/android-arm64": "0.27.7", - "@esbuild/android-x64": "0.27.7", - "@esbuild/darwin-arm64": "0.27.7", - "@esbuild/darwin-x64": "0.27.7", - "@esbuild/freebsd-arm64": "0.27.7", - "@esbuild/freebsd-x64": "0.27.7", - "@esbuild/linux-arm": "0.27.7", - "@esbuild/linux-arm64": "0.27.7", - "@esbuild/linux-ia32": "0.27.7", - "@esbuild/linux-loong64": "0.27.7", - "@esbuild/linux-mips64el": "0.27.7", - "@esbuild/linux-ppc64": "0.27.7", - "@esbuild/linux-riscv64": "0.27.7", - "@esbuild/linux-s390x": "0.27.7", - "@esbuild/linux-x64": "0.27.7", - "@esbuild/netbsd-arm64": "0.27.7", - "@esbuild/netbsd-x64": "0.27.7", - "@esbuild/openbsd-arm64": "0.27.7", - "@esbuild/openbsd-x64": "0.27.7", - "@esbuild/openharmony-arm64": "0.27.7", - "@esbuild/sunos-x64": "0.27.7", - "@esbuild/win32-arm64": "0.27.7", - "@esbuild/win32-ia32": "0.27.7", - "@esbuild/win32-x64": "0.27.7" - } - }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/eslint": { - "version": "9.39.4", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.4.tgz", - "integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.8.0", - "@eslint-community/regexpp": "^4.12.1", - "@eslint/config-array": "^0.21.2", - "@eslint/config-helpers": "^0.4.2", - "@eslint/core": "^0.17.0", - "@eslint/eslintrc": "^3.3.5", - "@eslint/js": "9.39.4", - "@eslint/plugin-kit": "^0.4.1", - "@humanfs/node": "^0.16.6", - "@humanwhocodes/module-importer": "^1.0.1", - "@humanwhocodes/retry": "^0.4.2", - "@types/estree": "^1.0.6", - "ajv": "^6.14.0", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.6", - "debug": "^4.3.2", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^8.4.0", - "eslint-visitor-keys": "^4.2.1", - "espree": "^10.4.0", - "esquery": "^1.5.0", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^8.0.0", - "find-up": "^5.0.0", - "glob-parent": "^6.0.2", - "ignore": "^5.2.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.1.5", - "natural-compare": "^1.4.0", - "optionator": "^0.9.3" - }, - "bin": { - "eslint": "bin/eslint.js" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://eslint.org/donate" - }, - "peerDependencies": { - "jiti": "*" - }, - "peerDependenciesMeta": { - "jiti": { - "optional": true - } - } - }, - "node_modules/eslint-config-next": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.2.4.tgz", - "integrity": "sha512-A6ekXYFj/YQxBPMl45g3e+U8zJo+X2+ZQwcz34pPKjpc/3S4roBA2Rd9xWB4FKuSxhofo1/95WjzmUY+wHrOhg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@next/eslint-plugin-next": "16.2.4", - "eslint-import-resolver-node": "^0.3.6", - "eslint-import-resolver-typescript": "^3.5.2", - "eslint-plugin-import": "^2.32.0", - "eslint-plugin-jsx-a11y": "^6.10.0", - "eslint-plugin-react": "^7.37.0", - "eslint-plugin-react-hooks": "^7.0.0", - "globals": "16.4.0", - "typescript-eslint": "^8.46.0" - }, - "peerDependencies": { - "eslint": ">=9.0.0", - "typescript": ">=3.3.1" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/eslint-config-next/node_modules/globals": { - "version": "16.4.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-16.4.0.tgz", - "integrity": "sha512-ob/2LcVVaVGCYN+r14cnwnoDPUufjiYgSqRhiFD0Q1iI4Odora5RE8Iv1D24hAz5oMophRGkGz+yuvQmmUMnMw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/eslint-import-resolver-node": { - "version": "0.3.10", - "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.10.tgz", - "integrity": "sha512-tRrKqFyCaKict5hOd244sL6EQFNycnMQnBe+j8uqGNXYzsImGbGUU4ibtoaBmv5FLwJwcFJNeg1GeVjQfbMrDQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^3.2.7", - "is-core-module": "^2.16.1", - "resolve": "^2.0.0-next.6" - } - }, - "node_modules/eslint-import-resolver-node/node_modules/debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.1" - } - }, - "node_modules/eslint-import-resolver-typescript": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.10.1.tgz", - "integrity": "sha512-A1rHYb06zjMGAxdLSkN2fXPBwuSaQ0iO5M/hdyS0Ajj1VBaRp0sPD3dn1FhME3c/JluGFbwSxyCfqdSbtQLAHQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "@nolyfill/is-core-module": "1.0.39", - "debug": "^4.4.0", - "get-tsconfig": "^4.10.0", - "is-bun-module": "^2.0.0", - "stable-hash": "^0.0.5", - "tinyglobby": "^0.2.13", - "unrs-resolver": "^1.6.2" - }, - "engines": { - "node": "^14.18.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint-import-resolver-typescript" - }, - "peerDependencies": { - "eslint": "*", - "eslint-plugin-import": "*", - "eslint-plugin-import-x": "*" - }, - "peerDependenciesMeta": { - "eslint-plugin-import": { - "optional": true - }, - "eslint-plugin-import-x": { - "optional": true - } - } - }, - "node_modules/eslint-module-utils": { - "version": "2.12.1", - "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.12.1.tgz", - "integrity": "sha512-L8jSWTze7K2mTg0vos/RuLRS5soomksDPoJLXIslC7c8Wmut3bx7CPpJijDcBZtxQ5lrbUdM+s0OlNbz0DCDNw==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^3.2.7" - }, - "engines": { - "node": ">=4" - }, - "peerDependenciesMeta": { - "eslint": { - "optional": true - } - } - }, - "node_modules/eslint-module-utils/node_modules/debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.1" - } - }, - "node_modules/eslint-plugin-import": { - "version": "2.32.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.32.0.tgz", - "integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@rtsao/scc": "^1.1.0", - "array-includes": "^3.1.9", - "array.prototype.findlastindex": "^1.2.6", - "array.prototype.flat": "^1.3.3", - "array.prototype.flatmap": "^1.3.3", - "debug": "^3.2.7", - "doctrine": "^2.1.0", - "eslint-import-resolver-node": "^0.3.9", - "eslint-module-utils": "^2.12.1", - "hasown": "^2.0.2", - "is-core-module": "^2.16.1", - "is-glob": "^4.0.3", - "minimatch": "^3.1.2", - "object.fromentries": "^2.0.8", - "object.groupby": "^1.0.3", - "object.values": "^1.2.1", - "semver": "^6.3.1", - "string.prototype.trimend": "^1.0.9", - "tsconfig-paths": "^3.15.0" - }, - "engines": { - "node": ">=4" - }, - "peerDependencies": { - "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9" - } - }, - "node_modules/eslint-plugin-import/node_modules/debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.1" - } - }, - "node_modules/eslint-plugin-jsx-a11y": { - "version": "6.10.2", - "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.10.2.tgz", - "integrity": "sha512-scB3nz4WmG75pV8+3eRUQOHZlNSUhFNq37xnpgRkCCELU3XMvXAxLk1eqWWyE22Ki4Q01Fnsw9BA3cJHDPgn2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "aria-query": "^5.3.2", - "array-includes": "^3.1.8", - "array.prototype.flatmap": "^1.3.2", - "ast-types-flow": "^0.0.8", - "axe-core": "^4.10.0", - "axobject-query": "^4.1.0", - "damerau-levenshtein": "^1.0.8", - "emoji-regex": "^9.2.2", - "hasown": "^2.0.2", - "jsx-ast-utils": "^3.3.5", - "language-tags": "^1.0.9", - "minimatch": "^3.1.2", - "object.fromentries": "^2.0.8", - "safe-regex-test": "^1.0.3", - "string.prototype.includes": "^2.0.1" - }, - "engines": { - "node": ">=4.0" - }, - "peerDependencies": { - "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9" - } - }, - "node_modules/eslint-plugin-react": { - "version": "7.37.5", - "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.37.5.tgz", - "integrity": "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==", - "dev": true, - "license": "MIT", - "dependencies": { - "array-includes": "^3.1.8", - "array.prototype.findlast": "^1.2.5", - "array.prototype.flatmap": "^1.3.3", - "array.prototype.tosorted": "^1.1.4", - "doctrine": "^2.1.0", - "es-iterator-helpers": "^1.2.1", - "estraverse": "^5.3.0", - "hasown": "^2.0.2", - "jsx-ast-utils": "^2.4.1 || ^3.0.0", - "minimatch": "^3.1.2", - "object.entries": "^1.1.9", - "object.fromentries": "^2.0.8", - "object.values": "^1.2.1", - "prop-types": "^15.8.1", - "resolve": "^2.0.0-next.5", - "semver": "^6.3.1", - "string.prototype.matchall": "^4.0.12", - "string.prototype.repeat": "^1.0.0" - }, - "engines": { - "node": ">=4" - }, - "peerDependencies": { - "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" - } - }, - "node_modules/eslint-plugin-react-hooks": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz", - "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.24.4", - "@babel/parser": "^7.24.4", - "hermes-parser": "^0.25.1", - "zod": "^3.25.0 || ^4.0.0", - "zod-validation-error": "^3.5.0 || ^4.0.0" - }, - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0" - } - }, - "node_modules/eslint-scope": { - "version": "8.4.0", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", - "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-visitor-keys": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", - "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/espree": { - "version": "10.4.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", - "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "acorn": "^8.15.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^4.2.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/esquery": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", - "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "estraverse": "^5.1.0" - }, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "estraverse": "^5.2.0" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/exceljs": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/exceljs/-/exceljs-4.4.0.tgz", - "integrity": "sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg==", - "license": "MIT", - "dependencies": { - "archiver": "^5.0.0", - "dayjs": "^1.8.34", - "fast-csv": "^4.3.1", - "jszip": "^3.10.1", - "readable-stream": "^3.6.0", - "saxes": "^5.0.1", - "tmp": "^0.2.0", - "unzipper": "^0.10.11", - "uuid": "^8.3.0" - }, - "engines": { - "node": ">=8.3.0" - } - }, - "node_modules/exsolve": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.0.8.tgz", - "integrity": "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==", - "license": "MIT" - }, - "node_modules/fast-check": { - "version": "3.23.2", - "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.23.2.tgz", - "integrity": "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/dubzzz" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fast-check" - } - ], - "license": "MIT", - "dependencies": { - "pure-rand": "^6.1.0" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/fast-csv": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/fast-csv/-/fast-csv-4.3.6.tgz", - "integrity": "sha512-2RNSpuwwsJGP0frGsOmTb9oUF+VkFSM4SyLTDgwf2ciHWTarN0lQTC+F2f/t5J9QjW+c65VFIAAu85GsvMIusw==", - "license": "MIT", - "dependencies": { - "@fast-csv/format": "4.3.5", - "@fast-csv/parse": "4.3.6" - }, - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "license": "MIT" - }, - "node_modules/fast-glob": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz", - "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.4" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fast-glob/node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-sha256": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", - "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", - "license": "Unlicense" - }, - "node_modules/fast-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", - "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/fastq": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", - "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", - "dev": true, - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" - } - }, - "node_modules/file-entry-cache": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", - "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "flat-cache": "^4.0.0" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", - "dev": true, - "license": "MIT", - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/find-up": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", - "dev": true, - "license": "MIT", - "dependencies": { - "locate-path": "^6.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/flat-cache": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", - "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", - "dev": true, - "license": "MIT", - "dependencies": { - "flatted": "^3.2.9", - "keyv": "^4.5.4" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/flatted": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", - "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", - "dev": true, - "license": "ISC" - }, - "node_modules/fontkit": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz", - "integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==", - "license": "MIT", - "dependencies": { - "@swc/helpers": "^0.5.12", - "brotli": "^1.3.2", - "clone": "^2.1.2", - "dfa": "^1.2.0", - "fast-deep-equal": "^3.1.3", - "restructure": "^3.0.0", - "tiny-inflate": "^1.0.3", - "unicode-properties": "^1.4.0", - "unicode-trie": "^2.0.0" - } - }, - "node_modules/for-each": { - "version": "0.3.5", - "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", - "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-callable": "^1.2.7" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/foreground-child": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", - "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", - "license": "ISC", - "dependencies": { - "cross-spawn": "^7.0.6", - "signal-exit": "^4.0.1" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/fs-constants": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", - "license": "MIT" - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "license": "ISC" - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/fstream": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.12.tgz", - "integrity": "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==", - "deprecated": "This package is no longer supported.", - "license": "ISC", - "dependencies": { - "graceful-fs": "^4.1.2", - "inherits": "~2.0.0", - "mkdirp": ">=0.5 0", - "rimraf": "2" - }, - "engines": { - "node": ">=0.6" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/function.prototype.name": { - "version": "1.1.8", - "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.8.tgz", - "integrity": "sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "call-bound": "^1.0.3", - "define-properties": "^1.2.1", - "functions-have-names": "^1.2.3", - "hasown": "^2.0.2", - "is-callable": "^1.2.7" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/functions-have-names": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", - "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/generate-function": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", - "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", - "license": "MIT", - "dependencies": { - "is-property": "^1.0.2" - } - }, - "node_modules/generator-function": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz", - "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-port-please": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/get-port-please/-/get-port-please-3.2.0.tgz", - "integrity": "sha512-I9QVvBw5U/hw3RmWpYKRumUeaDgxTPd401x364rLmWBJcOQ753eov1eTgzDqRG9bqFIfDc7gfzcQEWrUri3o1A==", - "license": "MIT" - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/get-symbol-description": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", - "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-tsconfig": { - "version": "4.14.0", - "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.14.0.tgz", - "integrity": "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==", - "dev": true, - "license": "MIT", - "dependencies": { - "resolve-pkg-maps": "^1.0.0" - }, - "funding": { - "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" - } - }, - "node_modules/giget": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/giget/-/giget-3.2.0.tgz", - "integrity": "sha512-GvHTWcykIR/fP8cj8dMpuMMkvaeJfPvYnhq0oW+chSeIr+ldX21ifU2Ms6KBoyKZQZmVaUAAhQ2EZ68KJF8a7A==", - "license": "MIT", - "bin": { - "giget": "dist/cli.mjs" - } - }, - "node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/globals": { - "version": "14.0.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", - "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/globalthis": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", - "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "define-properties": "^1.2.1", - "gopd": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "license": "ISC" - }, - "node_modules/grammex": { - "version": "3.1.12", - "resolved": "https://registry.npmjs.org/grammex/-/grammex-3.1.12.tgz", - "integrity": "sha512-6ufJOsSA7LcQehIJNCO7HIBykfM7DXQual0Ny780/DEcJIpBlHRvcqEBWGPYd7hrXL2GJ3oJI1MIhaXjWmLQOQ==", - "license": "MIT" - }, - "node_modules/graphmatch": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/graphmatch/-/graphmatch-1.1.1.tgz", - "integrity": "sha512-5ykVn/EXM1hF0XCaWh05VbYvEiOL2lY1kBxZtaYsyvjp7cmWOU1XsAdfQBwClraEofXDT197lFbXOEVMHpvQOg==", - "license": "MIT" - }, - "node_modules/has-bigints": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", - "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/has-property-descriptors": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", - "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-define-property": "^1.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-proto": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.2.0.tgz", - "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-tostringtag": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", - "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-symbols": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", - "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/hermes-estree": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", - "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", - "dev": true, - "license": "MIT" - }, - "node_modules/hermes-parser": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", - "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", - "dev": true, - "license": "MIT", - "dependencies": { - "hermes-estree": "0.25.1" - } - }, - "node_modules/hono": { - "version": "4.12.15", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.15.tgz", - "integrity": "sha512-qM0jDhFEaCBb4TxoW7f53Qrpv9RBiayUHo0S52JudprkhvpjIrGoU1mnnr29Fvd1U335ZFPZQY1wlkqgfGXyLg==", - "license": "MIT", - "engines": { - "node": ">=16.9.0" - } - }, - "node_modules/http_ece": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.2.0.tgz", - "integrity": "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==", - "license": "MIT", - "engines": { - "node": ">=16" - } - }, - "node_modules/http-status-codes": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/http-status-codes/-/http-status-codes-2.3.0.tgz", - "integrity": "sha512-RJ8XvFvpPM/Dmc5SV+dC4y5PCeOhT3x1Hq0NU3rjGeg5a/CqlhZ7uudknPwZFz4aeAXDcbAyaeP7GAo9lvngtA==", - "license": "MIT" - }, - "node_modules/https-proxy-agent": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", - "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/iconv-lite": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", - "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/immediate": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", - "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", - "license": "MIT" - }, - "node_modules/import-fresh": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", - "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.19" - } - }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "license": "ISC", - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/internal-slot": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", - "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "hasown": "^2.0.2", - "side-channel": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/is-array-buffer": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", - "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "call-bound": "^1.0.3", - "get-intrinsic": "^1.2.6" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-async-function": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz", - "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "async-function": "^1.0.0", - "call-bound": "^1.0.3", - "get-proto": "^1.0.1", - "has-tostringtag": "^1.0.2", - "safe-regex-test": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-bigint": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz", - "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-bigints": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-boolean-object": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz", - "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3", - "has-tostringtag": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-bun-module": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-bun-module/-/is-bun-module-2.0.0.tgz", - "integrity": "sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "semver": "^7.7.1" - } - }, - "node_modules/is-bun-module/node_modules/semver": { - "version": "7.7.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", - "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/is-callable": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", - "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-core-module": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", - "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", - "dev": true, - "license": "MIT", - "dependencies": { - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-data-view": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.2.tgz", - "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "get-intrinsic": "^1.2.6", - "is-typed-array": "^1.1.13" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-date-object": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz", - "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "has-tostringtag": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-finalizationregistry": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz", - "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-generator-function": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", - "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.4", - "generator-function": "^2.0.0", - "get-proto": "^1.0.1", - "has-tostringtag": "^1.0.2", - "safe-regex-test": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-map": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", - "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-negative-zero": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", - "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/is-number-object": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz", - "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3", - "has-tostringtag": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-property": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", - "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", - "license": "MIT" - }, - "node_modules/is-regex": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", - "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "gopd": "^1.2.0", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-set": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz", - "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-shared-array-buffer": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz", - "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-string": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", - "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3", - "has-tostringtag": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-symbol": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz", - "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "has-symbols": "^1.1.0", - "safe-regex-test": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-typed-array": { - "version": "1.1.15", - "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", - "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "which-typed-array": "^1.1.16" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-weakmap": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", - "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-weakref": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz", - "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-weakset": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz", - "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3", - "get-intrinsic": "^1.2.6" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/isarray": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", - "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", - "dev": true, - "license": "MIT" - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "license": "ISC" - }, - "node_modules/iterator.prototype": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/iterator.prototype/-/iterator.prototype-1.1.5.tgz", - "integrity": "sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "define-data-property": "^1.1.4", - "es-object-atoms": "^1.0.0", - "get-intrinsic": "^1.2.6", - "get-proto": "^1.0.0", - "has-symbols": "^1.1.0", - "set-function-name": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/jiti": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", - "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==", - "license": "MIT", - "bin": { - "jiti": "lib/jiti-cli.mjs" - } - }, - "node_modules/jose": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz", - "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/panva" - } - }, - "node_modules/js-md5": { - "version": "0.8.3", - "resolved": "https://registry.npmjs.org/js-md5/-/js-md5-0.8.3.tgz", - "integrity": "sha512-qR0HB5uP6wCuRMrWPTrkMaev7MJZwJuuw4fnwAzRgP4J4/F8RwtodOKpGp4XpqsLBFzzgqIO42efFAyz2Et6KQ==", - "license": "MIT" - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/js-yaml": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", - "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/jsesc": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", - "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", - "dev": true, - "license": "MIT", - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/json-buffer": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", - "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-schema-to-ts": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", - "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", - "license": "MIT", - "dependencies": { - "@babel/runtime": "^7.18.3", - "ts-algebra": "^2.0.0" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "dev": true, - "license": "MIT" - }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "dev": true, - "license": "MIT", - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/jsx-ast-utils": { - "version": "3.3.5", - "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz", - "integrity": "sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "array-includes": "^3.1.6", - "array.prototype.flat": "^1.3.1", - "object.assign": "^4.1.4", - "object.values": "^1.1.6" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/jszip": { - "version": "3.10.1", - "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", - "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", - "license": "(MIT OR GPL-3.0-or-later)", - "dependencies": { - "lie": "~3.3.0", - "pako": "~1.0.2", - "readable-stream": "~2.3.6", - "setimmediate": "^1.0.5" - } - }, - "node_modules/jszip/node_modules/isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", - "license": "MIT" - }, - "node_modules/jszip/node_modules/readable-stream": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", - "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", - "license": "MIT", - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "node_modules/jszip/node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "license": "MIT" - }, - "node_modules/jszip/node_modules/string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.1.0" - } - }, - "node_modules/jwa": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", - "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", - "license": "MIT", - "dependencies": { - "buffer-equal-constant-time": "^1.0.1", - "ecdsa-sig-formatter": "1.0.11", - "safe-buffer": "^5.0.1" - } - }, - "node_modules/jws": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", - "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", - "license": "MIT", - "dependencies": { - "jwa": "^2.0.1", - "safe-buffer": "^5.0.1" - } - }, - "node_modules/keyv": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", - "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", - "dev": true, - "license": "MIT", - "dependencies": { - "json-buffer": "3.0.1" - } - }, - "node_modules/language-subtag-registry": { - "version": "0.3.23", - "resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.23.tgz", - "integrity": "sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==", - "dev": true, - "license": "CC0-1.0" - }, - "node_modules/language-tags": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/language-tags/-/language-tags-1.0.9.tgz", - "integrity": "sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA==", - "dev": true, - "license": "MIT", - "dependencies": { - "language-subtag-registry": "^0.3.20" - }, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/lazystream": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz", - "integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==", - "license": "MIT", - "dependencies": { - "readable-stream": "^2.0.5" - }, - "engines": { - "node": ">= 0.6.3" - } - }, - "node_modules/lazystream/node_modules/isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", - "license": "MIT" - }, - "node_modules/lazystream/node_modules/readable-stream": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", - "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", - "license": "MIT", - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "node_modules/lazystream/node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "license": "MIT" - }, - "node_modules/lazystream/node_modules/string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.1.0" - } - }, - "node_modules/levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/lie": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", - "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", - "license": "MIT", - "dependencies": { - "immediate": "~3.0.5" - } - }, - "node_modules/lightningcss": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", - "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", - "dev": true, - "license": "MPL-2.0", - "dependencies": { - "detect-libc": "^2.0.3" - }, - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - }, - "optionalDependencies": { - "lightningcss-android-arm64": "1.32.0", - "lightningcss-darwin-arm64": "1.32.0", - "lightningcss-darwin-x64": "1.32.0", - "lightningcss-freebsd-x64": "1.32.0", - "lightningcss-linux-arm-gnueabihf": "1.32.0", - "lightningcss-linux-arm64-gnu": "1.32.0", - "lightningcss-linux-arm64-musl": "1.32.0", - "lightningcss-linux-x64-gnu": "1.32.0", - "lightningcss-linux-x64-musl": "1.32.0", - "lightningcss-win32-arm64-msvc": "1.32.0", - "lightningcss-win32-x64-msvc": "1.32.0" - } - }, - "node_modules/lightningcss-android-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", - "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", - "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", - "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-freebsd-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", - "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", - "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", - "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", - "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", - "cpu": [ - "arm64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", - "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "glibc" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", - "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", - "cpu": [ - "x64" - ], - "dev": true, - "libc": [ - "musl" - ], - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", - "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", - "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/linebreak": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz", - "integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==", - "license": "MIT", - "dependencies": { - "base64-js": "0.0.8", - "unicode-trie": "^2.0.0" - } - }, - "node_modules/linebreak/node_modules/base64-js": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz", - "integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/listenercount": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/listenercount/-/listenercount-1.0.1.tgz", - "integrity": "sha512-3mk/Zag0+IJxeDrxSgaDPy4zZ3w05PRZeJNnlWhzFz5OkX49J4krc+A8X2d2M69vGMBEX0uyl8M+W+8gH+kBqQ==", - "license": "ISC" - }, - "node_modules/locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^5.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/lodash.defaults": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", - "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", - "license": "MIT" - }, - "node_modules/lodash.difference": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz", - "integrity": "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA==", - "license": "MIT" - }, - "node_modules/lodash.escaperegexp": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz", - "integrity": "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==", - "license": "MIT" - }, - "node_modules/lodash.flatten": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz", - "integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==", - "license": "MIT" - }, - "node_modules/lodash.groupby": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/lodash.groupby/-/lodash.groupby-4.6.0.tgz", - "integrity": "sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==", - "license": "MIT" - }, - "node_modules/lodash.isboolean": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", - "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", - "license": "MIT" - }, - "node_modules/lodash.isequal": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", - "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==", - "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.", - "license": "MIT" - }, - "node_modules/lodash.isfunction": { - "version": "3.0.9", - "resolved": "https://registry.npmjs.org/lodash.isfunction/-/lodash.isfunction-3.0.9.tgz", - "integrity": "sha512-AirXNj15uRIMMPihnkInB4i3NHeb4iBtNg9WRWuK2o31S+ePwwNmDPaTL3o7dTJ+VXNZim7rFs4rxN4YU1oUJw==", - "license": "MIT" - }, - "node_modules/lodash.isnil": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/lodash.isnil/-/lodash.isnil-4.0.0.tgz", - "integrity": "sha512-up2Mzq3545mwVnMhTDMdfoG1OurpA/s5t88JmQX809eH3C8491iu2sfKhTfhQtKY78oPNhiaHJUpT/dUDAAtng==", - "license": "MIT" - }, - "node_modules/lodash.isplainobject": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", - "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", - "license": "MIT" - }, - "node_modules/lodash.isundefined": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/lodash.isundefined/-/lodash.isundefined-3.0.1.tgz", - "integrity": "sha512-MXB1is3s899/cD8jheYYE2V9qTHwKvt+npCwpD+1Sxm3Q3cECXCiYHjeHWXNwr6Q0SOBPrYUDxendrO6goVTEA==", - "license": "MIT" - }, - "node_modules/lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.union": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz", - "integrity": "sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw==", - "license": "MIT" - }, - "node_modules/lodash.uniq": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", - "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==", - "license": "MIT" - }, - "node_modules/long": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", - "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", - "license": "Apache-2.0" - }, - "node_modules/loose-envify": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", - "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "js-tokens": "^3.0.0 || ^4.0.0" - }, - "bin": { - "loose-envify": "cli.js" - } - }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^3.0.2" - } - }, - "node_modules/lru.min": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz", - "integrity": "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA==", - "license": "MIT", - "engines": { - "bun": ">=1.0.0", - "deno": ">=1.30.0", - "node": ">=8.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wellwelwel" - } - }, - "node_modules/lucide-react": { - "version": "1.11.0", - "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.11.0.tgz", - "integrity": "sha512-UOhjdztXCgdBReRcIhsvz2siIBogfv/lhJEIViCpLt924dO+GDms9T7DNoucI23s6kEPpe988m5N0D2ajnzb2g==", - "license": "ISC", - "peerDependencies": { - "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" - } - }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" - } - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/minimalistic-assert": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", - "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", - "license": "ISC" - }, - "node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/mkdirp": { - "version": "0.5.6", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", - "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", - "license": "MIT", - "dependencies": { - "minimist": "^1.2.6" - }, - "bin": { - "mkdirp": "bin/cmd.js" - } - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/mysql2": { - "version": "3.15.3", - "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.15.3.tgz", - "integrity": "sha512-FBrGau0IXmuqg4haEZRBfHNWB5mUARw6hNwPDXXGg0XzVJ50mr/9hb267lvpVMnhZ1FON3qNd4Xfcez1rbFwSg==", - "license": "MIT", - "dependencies": { - "aws-ssl-profiles": "^1.1.1", - "denque": "^2.1.0", - "generate-function": "^2.3.1", - "iconv-lite": "^0.7.0", - "long": "^5.2.1", - "lru.min": "^1.0.0", - "named-placeholders": "^1.1.3", - "seq-queue": "^0.0.5", - "sqlstring": "^2.3.2" - }, - "engines": { - "node": ">= 8.0" - } - }, - "node_modules/named-placeholders": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", - "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", - "license": "MIT", - "dependencies": { - "lru.min": "^1.1.0" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/nanoid": { - "version": "3.3.11", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", - "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/napi-postinstall": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.4.tgz", - "integrity": "sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==", - "dev": true, - "license": "MIT", - "bin": { - "napi-postinstall": "lib/cli.js" - }, - "engines": { - "node": "^12.20.0 || ^14.18.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/napi-postinstall" - } - }, - "node_modules/natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true, - "license": "MIT" - }, - "node_modules/next": { - "version": "16.2.4", - "resolved": "https://registry.npmjs.org/next/-/next-16.2.4.tgz", - "integrity": "sha512-kPvz56wF5frc+FxlHI5qnklCzbq53HTwORaWBGdT0vNoKh1Aya9XC8aPauH4NJxqtzbWsS5mAbctm4cr+EkQ2Q==", - "license": "MIT", - "dependencies": { - "@next/env": "16.2.4", - "@swc/helpers": "0.5.15", - "baseline-browser-mapping": "^2.9.19", - "caniuse-lite": "^1.0.30001579", - "postcss": "8.4.31", - "styled-jsx": "5.1.6" - }, - "bin": { - "next": "dist/bin/next" - }, - "engines": { - "node": ">=20.9.0" - }, - "optionalDependencies": { - "@next/swc-darwin-arm64": "16.2.4", - "@next/swc-darwin-x64": "16.2.4", - "@next/swc-linux-arm64-gnu": "16.2.4", - "@next/swc-linux-arm64-musl": "16.2.4", - "@next/swc-linux-x64-gnu": "16.2.4", - "@next/swc-linux-x64-musl": "16.2.4", - "@next/swc-win32-arm64-msvc": "16.2.4", - "@next/swc-win32-x64-msvc": "16.2.4", - "sharp": "^0.34.5" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.1.0", - "@playwright/test": "^1.51.1", - "babel-plugin-react-compiler": "*", - "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", - "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", - "sass": "^1.3.0" - }, - "peerDependenciesMeta": { - "@opentelemetry/api": { - "optional": true - }, - "@playwright/test": { - "optional": true - }, - "babel-plugin-react-compiler": { - "optional": true - }, - "sass": { - "optional": true - } - } - }, - "node_modules/next/node_modules/@img/sharp-darwin-arm64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz", - "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==", - "cpu": [ - "arm64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-darwin-arm64": "1.2.4" - } - }, - "node_modules/next/node_modules/@img/sharp-darwin-x64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz", - "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-darwin-x64": "1.2.4" - } - }, - "node_modules/next/node_modules/@img/sharp-libvips-darwin-arm64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz", - "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==", - "cpu": [ - "arm64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "darwin" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-libvips-darwin-x64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz", - "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==", - "cpu": [ - "x64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "darwin" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-libvips-linux-arm": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz", - "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==", - "cpu": [ - "arm" - ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-libvips-linux-arm64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz", - "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==", - "cpu": [ - "arm64" - ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-libvips-linux-ppc64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz", - "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==", - "cpu": [ - "ppc64" - ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-libvips-linux-riscv64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz", - "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==", - "cpu": [ - "riscv64" - ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-libvips-linux-s390x": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz", - "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==", - "cpu": [ - "s390x" - ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-libvips-linux-x64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz", - "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==", - "cpu": [ - "x64" - ], - "libc": [ - "glibc" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-libvips-linuxmusl-arm64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz", - "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==", - "cpu": [ - "arm64" - ], - "libc": [ - "musl" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-libvips-linuxmusl-x64": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz", - "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==", - "cpu": [ - "x64" - ], - "libc": [ - "musl" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-linux-arm": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz", - "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==", - "cpu": [ - "arm" - ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-arm": "1.2.4" - } - }, - "node_modules/next/node_modules/@img/sharp-linux-arm64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz", - "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==", - "cpu": [ - "arm64" - ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-arm64": "1.2.4" - } - }, - "node_modules/next/node_modules/@img/sharp-linux-ppc64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz", - "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==", - "cpu": [ - "ppc64" - ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-ppc64": "1.2.4" - } - }, - "node_modules/next/node_modules/@img/sharp-linux-riscv64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz", - "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==", - "cpu": [ - "riscv64" - ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-riscv64": "1.2.4" - } - }, - "node_modules/next/node_modules/@img/sharp-linux-s390x": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz", - "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==", - "cpu": [ - "s390x" - ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-s390x": "1.2.4" - } - }, - "node_modules/next/node_modules/@img/sharp-linux-x64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz", - "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==", - "cpu": [ - "x64" - ], - "libc": [ - "glibc" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.2.4" - } - }, - "node_modules/next/node_modules/@img/sharp-linuxmusl-arm64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz", - "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==", - "cpu": [ - "arm64" - ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" - } - }, - "node_modules/next/node_modules/@img/sharp-linuxmusl-x64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz", - "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==", - "cpu": [ - "x64" - ], - "libc": [ - "musl" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-x64": "1.2.4" - } - }, - "node_modules/next/node_modules/@img/sharp-wasm32": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz", - "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==", - "cpu": [ - "wasm32" - ], - "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", - "optional": true, - "dependencies": { - "@emnapi/runtime": "^1.7.0" - }, - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-win32-arm64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz", - "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==", - "cpu": [ - "arm64" - ], - "license": "Apache-2.0 AND LGPL-3.0-or-later", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-win32-ia32": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz", - "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==", - "cpu": [ - "ia32" - ], - "license": "Apache-2.0 AND LGPL-3.0-or-later", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/@img/sharp-win32-x64": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", - "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0 AND LGPL-3.0-or-later", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/next/node_modules/postcss": { - "version": "8.4.31", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", - "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.6", - "picocolors": "^1.0.0", - "source-map-js": "^1.0.2" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/next/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "license": "ISC", - "optional": true, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/next/node_modules/sharp": { - "version": "0.34.5", - "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz", - "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==", - "hasInstallScript": true, - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "@img/colour": "^1.0.0", - "detect-libc": "^2.1.2", - "semver": "^7.7.3" - }, - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-darwin-arm64": "0.34.5", - "@img/sharp-darwin-x64": "0.34.5", - "@img/sharp-libvips-darwin-arm64": "1.2.4", - "@img/sharp-libvips-darwin-x64": "1.2.4", - "@img/sharp-libvips-linux-arm": "1.2.4", - "@img/sharp-libvips-linux-arm64": "1.2.4", - "@img/sharp-libvips-linux-ppc64": "1.2.4", - "@img/sharp-libvips-linux-riscv64": "1.2.4", - "@img/sharp-libvips-linux-s390x": "1.2.4", - "@img/sharp-libvips-linux-x64": "1.2.4", - "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", - "@img/sharp-libvips-linuxmusl-x64": "1.2.4", - "@img/sharp-linux-arm": "0.34.5", - "@img/sharp-linux-arm64": "0.34.5", - "@img/sharp-linux-ppc64": "0.34.5", - "@img/sharp-linux-riscv64": "0.34.5", - "@img/sharp-linux-s390x": "0.34.5", - "@img/sharp-linux-x64": "0.34.5", - "@img/sharp-linuxmusl-arm64": "0.34.5", - "@img/sharp-linuxmusl-x64": "0.34.5", - "@img/sharp-wasm32": "0.34.5", - "@img/sharp-win32-arm64": "0.34.5", - "@img/sharp-win32-ia32": "0.34.5", - "@img/sharp-win32-x64": "0.34.5" - } - }, - "node_modules/node-exports-info": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/node-exports-info/-/node-exports-info-1.6.0.tgz", - "integrity": "sha512-pyFS63ptit/P5WqUkt+UUfe+4oevH+bFeIiPPdfb0pFeYEu/1ELnJu5l+5EcTKYL5M7zaAa7S8ddywgXypqKCw==", - "dev": true, - "license": "MIT", - "dependencies": { - "array.prototype.flatmap": "^1.3.3", - "es-errors": "^1.3.0", - "object.entries": "^1.1.9", - "semver": "^6.3.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/node-releases": { - "version": "2.0.38", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.38.tgz", - "integrity": "sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==", - "dev": true, - "license": "MIT" - }, - "node_modules/nodemailer": { - "version": "10.1.7", - "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.1.7.tgz", - "integrity": "sha512-OQa6FDln5fLttmqSbjDiRYvFDOFNrBqfiOwHPlEbURil3b+vPB1v8xpi+Sp46drzNDlsTnNsS502vthmz56r4w==", - "license": "MIT-0", - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-inspect": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", - "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/object-keys": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", - "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/object.assign": { - "version": "4.1.7", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz", - "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "call-bound": "^1.0.3", - "define-properties": "^1.2.1", - "es-object-atoms": "^1.0.0", - "has-symbols": "^1.1.0", - "object-keys": "^1.1.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/object.entries": { - "version": "1.1.9", - "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.9.tgz", - "integrity": "sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "call-bound": "^1.0.4", - "define-properties": "^1.2.1", - "es-object-atoms": "^1.1.1" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/object.fromentries": { - "version": "2.0.8", - "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz", - "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.7", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.2", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/object.groupby": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz", - "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.7", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/object.values": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.1.tgz", - "integrity": "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "call-bound": "^1.0.3", - "define-properties": "^1.2.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/ohash": { - "version": "2.0.11", - "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.11.tgz", - "integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==", - "license": "MIT" - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/optionator": { - "version": "0.9.4", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", - "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.5" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/own-keys": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz", - "integrity": "sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==", - "dev": true, - "license": "MIT", - "dependencies": { - "get-intrinsic": "^1.2.6", - "object-keys": "^1.1.1", - "safe-push-apply": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/p-limit": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "yocto-queue": "^0.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^3.0.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/pako": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", - "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", - "license": "(MIT AND Zlib)" - }, - "node_modules/parent-module": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, - "license": "MIT", - "dependencies": { - "callsites": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true, - "license": "MIT" - }, - "node_modules/pathe": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", - "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", - "license": "MIT" - }, - "node_modules/pdfkit": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.18.0.tgz", - "integrity": "sha512-NvUwSDZ0eYEzqAiWwVQkRkjYUkZ48kcsHuCO31ykqPPIVkwoSDjDGiwIgHHNtsiwls3z3P/zy4q00hl2chg2Ug==", - "license": "MIT", - "dependencies": { - "@noble/ciphers": "^1.0.0", - "@noble/hashes": "^1.6.0", - "fontkit": "^2.0.4", - "js-md5": "^0.8.3", - "linebreak": "^1.1.0", - "png-js": "^1.0.0" - } - }, - "node_modules/perfect-debounce": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-2.1.0.tgz", - "integrity": "sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==", - "license": "MIT" - }, - "node_modules/pg": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz", - "integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==", - "license": "MIT", - "dependencies": { - "pg-connection-string": "^2.12.0", - "pg-pool": "^3.13.0", - "pg-protocol": "^1.13.0", - "pg-types": "2.2.0", - "pgpass": "1.0.5" - }, - "engines": { - "node": ">= 16.0.0" - }, - "optionalDependencies": { - "pg-cloudflare": "^1.3.0" - }, - "peerDependencies": { - "pg-native": ">=3.0.1" - }, - "peerDependenciesMeta": { - "pg-native": { - "optional": true - } - } - }, - "node_modules/pg-cloudflare": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz", - "integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==", - "license": "MIT", - "optional": true - }, - "node_modules/pg-connection-string": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz", - "integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==", - "license": "MIT" - }, - "node_modules/pg-int8": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", - "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", - "license": "ISC", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/pg-pool": { - "version": "3.13.0", - "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz", - "integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==", - "license": "MIT", - "peerDependencies": { - "pg": ">=8.0" - } - }, - "node_modules/pg-protocol": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz", - "integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==", - "license": "MIT" - }, - "node_modules/pg-types": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", - "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", - "license": "MIT", - "dependencies": { - "pg-int8": "1.0.1", - "postgres-array": "~2.0.0", - "postgres-bytea": "~1.0.0", - "postgres-date": "~1.0.4", - "postgres-interval": "^1.1.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/pg-types/node_modules/postgres-array": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", - "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/pgpass": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", - "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", - "license": "MIT", - "dependencies": { - "split2": "^4.1.0" - } - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", - "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pkg-types": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.0.tgz", - "integrity": "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig==", - "license": "MIT", - "dependencies": { - "confbox": "^0.2.2", - "exsolve": "^1.0.7", - "pathe": "^2.0.3" - } - }, - "node_modules/png-js": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/png-js/-/png-js-1.1.0.tgz", - "integrity": "sha512-PM/uYGzGdNSzqeOgly68+6wKQDL1SY0a/N+OEa/+br6LnHWOAJB0Npiamnodfq3jd2LS/i2fMeOKSAILjA+m5Q==", - "dependencies": { - "browserify-zlib": "^0.2.0" - } - }, - "node_modules/possible-typed-array-names": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", - "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/postcss": { - "version": "8.5.12", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.12.tgz", - "integrity": "sha512-W62t/Se6rA0Az3DfCL0AqJwXuKwBeYg6nOaIgzP+xZ7N5BFCI7DYi1qs6ygUYT6rvfi6t9k65UMLJC+PHZpDAA==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.11", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/postgres": { - "version": "3.4.7", - "resolved": "https://registry.npmjs.org/postgres/-/postgres-3.4.7.tgz", - "integrity": "sha512-Jtc2612XINuBjIl/QTWsV5UvE8UHuNblcO3vVADSrKsrc6RqGX6lOW1cEo3CM2v0XG4Nat8nI+YM7/f26VxXLw==", - "license": "Unlicense", - "engines": { - "node": ">=12" - }, - "funding": { - "type": "individual", - "url": "https://github.com/sponsors/porsager" - } - }, - "node_modules/postgres-array": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-3.0.4.tgz", - "integrity": "sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==", - "license": "MIT", - "engines": { - "node": ">=12" - } - }, - "node_modules/postgres-bytea": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", - "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-date": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", - "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-interval": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", - "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", - "license": "MIT", - "dependencies": { - "xtend": "^4.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/prisma": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/prisma/-/prisma-7.8.0.tgz", - "integrity": "sha512-yfN4yrw7HV9kEJhoy1+jgah0jafEIQsf7uWouSsM8MvJtlubsk+kM7AIBWZ8+GJl74Yj3c+nbYqBkMOxtsZ3Lw==", - "hasInstallScript": true, - "license": "Apache-2.0", - "dependencies": { - "@prisma/config": "7.8.0", - "@prisma/dev": "0.24.3", - "@prisma/engines": "7.8.0", - "@prisma/studio-core": "0.27.3", - "mysql2": "3.15.3", - "postgres": "3.4.7" - }, - "bin": { - "prisma": "build/index.js" - }, - "engines": { - "node": "^20.19 || ^22.12 || >=24.0" - }, - "peerDependencies": { - "better-sqlite3": ">=9.0.0", - "typescript": ">=5.4.0" - }, - "peerDependenciesMeta": { - "better-sqlite3": { - "optional": true - }, - "typescript": { - "optional": true - } - } - }, - "node_modules/process-nextick-args": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", - "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", - "license": "MIT" - }, - "node_modules/prop-types": { - "version": "15.8.1", - "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", - "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", - "dev": true, - "license": "MIT", - "dependencies": { - "loose-envify": "^1.4.0", - "object-assign": "^4.1.1", - "react-is": "^16.13.1" - } - }, - "node_modules/proper-lockfile": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz", - "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==", - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.4", - "retry": "^0.12.0", - "signal-exit": "^3.0.2" - } - }, - "node_modules/proper-lockfile/node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "license": "ISC" - }, - "node_modules/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/pure-rand": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", - "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/dubzzz" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fast-check" - } - ], - "license": "MIT" - }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/rc9": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/rc9/-/rc9-3.0.1.tgz", - "integrity": "sha512-gMDyleLWVE+i6Sgtc0QbbY6pEKqYs97NGi6isHQPqYlLemPoO8dxQ3uGi0f4NiP98c+jMW6cG1Kx9dDwfvqARQ==", - "license": "MIT", - "dependencies": { - "defu": "^6.1.6", - "destr": "^2.0.5" - } - }, - "node_modules/react": { - "version": "19.2.4", - "resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz", - "integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-dom": { - "version": "19.2.4", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz", - "integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==", - "license": "MIT", - "dependencies": { - "scheduler": "^0.27.0" - }, - "peerDependencies": { - "react": "^19.2.4" - } - }, - "node_modules/react-is": { - "version": "16.13.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", - "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "license": "MIT", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/readdir-glob": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/readdir-glob/-/readdir-glob-1.1.3.tgz", - "integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==", - "license": "Apache-2.0", - "dependencies": { - "minimatch": "^5.1.0" - } - }, - "node_modules/readdir-glob/node_modules/brace-expansion": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz", - "integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==", - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/readdir-glob/node_modules/minimatch": { - "version": "5.1.9", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", - "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/readdirp": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.0.0.tgz", - "integrity": "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==", - "license": "MIT", - "engines": { - "node": ">= 20.19.0" - }, - "funding": { - "type": "individual", - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/reflect.getprototypeof": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", - "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.9", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.0.0", - "get-intrinsic": "^1.2.7", - "get-proto": "^1.0.1", - "which-builtin-type": "^1.2.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/regexp.prototype.flags": { - "version": "1.5.4", - "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", - "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "define-properties": "^1.2.1", - "es-errors": "^1.3.0", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "set-function-name": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/remeda": { - "version": "2.33.4", - "resolved": "https://registry.npmjs.org/remeda/-/remeda-2.33.4.tgz", - "integrity": "sha512-ygHswjlc/opg2VrtiYvUOPLjxjtdKvjGz1/plDhkG66hjNjFr1xmfrs2ClNFo/E6TyUFiwYNh53bKV26oBoMGQ==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/remeda" - } - }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/resolve": { - "version": "2.0.0-next.6", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.6.tgz", - "integrity": "sha512-3JmVl5hMGtJ3kMmB3zi3DL25KfkCEyy3Tw7Gmw7z5w8M9WlwoPFnIvwChzu1+cF3iaK3sp18hhPz8ANeimdJfA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "is-core-module": "^2.16.1", - "node-exports-info": "^1.6.0", - "object-keys": "^1.1.1", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/resolve-pkg-maps": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", - "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" - } - }, - "node_modules/restructure": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz", - "integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==", - "license": "MIT" - }, - "node_modules/retry": { - "version": "0.12.0", - "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", - "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==", - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/reusify": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", - "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", - "dev": true, - "license": "MIT", - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, - "node_modules/rimraf": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", - "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", - "license": "ISC", - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - } - }, - "node_modules/run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, - "node_modules/safe-array-concat": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.4.tgz", - "integrity": "sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.9", - "call-bound": "^1.0.4", - "get-intrinsic": "^1.3.0", - "has-symbols": "^1.1.0", - "isarray": "^2.0.5" - }, - "engines": { - "node": ">=0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/safe-push-apply": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz", - "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "isarray": "^2.0.5" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/safe-regex-test": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz", - "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "is-regex": "^1.2.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "license": "MIT" - }, - "node_modules/saxes": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz", - "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==", - "license": "ISC", - "dependencies": { - "xmlchars": "^2.2.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/scheduler": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", - "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", - "license": "MIT" - }, - "node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/seq-queue": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz", - "integrity": "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q==" - }, - "node_modules/set-function-length": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", - "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", - "dev": true, - "license": "MIT", - "dependencies": { - "define-data-property": "^1.1.4", - "es-errors": "^1.3.0", - "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.4", - "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/set-function-name": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", - "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "define-data-property": "^1.1.4", - "es-errors": "^1.3.0", - "functions-have-names": "^1.2.3", - "has-property-descriptors": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/set-proto": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/set-proto/-/set-proto-1.0.0.tgz", - "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==", - "dev": true, - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/setimmediate": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", - "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", - "license": "MIT" - }, - "node_modules/sharp": { - "version": "0.35.5", - "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", - "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", - "license": "Apache-2.0", - "dependencies": { - "@img/colour": "^1.1.0", - "detect-libc": "^2.1.2", - "semver": "^7.8.5" - }, - "engines": { - "node": ">=20.9.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-darwin-arm64": "0.35.5", - "@img/sharp-darwin-x64": "0.35.5", - "@img/sharp-freebsd-wasm32": "0.35.5", - "@img/sharp-libvips-darwin-arm64": "1.3.4", - "@img/sharp-libvips-darwin-x64": "1.3.4", - "@img/sharp-libvips-linux-arm": "1.3.4", - "@img/sharp-libvips-linux-arm64": "1.3.4", - "@img/sharp-libvips-linux-ppc64": "1.3.4", - "@img/sharp-libvips-linux-riscv64": "1.3.4", - "@img/sharp-libvips-linux-s390x": "1.3.4", - "@img/sharp-libvips-linux-x64": "1.3.4", - "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", - "@img/sharp-libvips-linuxmusl-x64": "1.3.4", - "@img/sharp-linux-arm": "0.35.5", - "@img/sharp-linux-arm64": "0.35.5", - "@img/sharp-linux-ppc64": "0.35.5", - "@img/sharp-linux-riscv64": "0.35.5", - "@img/sharp-linux-s390x": "0.35.5", - "@img/sharp-linux-x64": "0.35.5", - "@img/sharp-linuxmusl-arm64": "0.35.5", - "@img/sharp-linuxmusl-x64": "0.35.5", - "@img/sharp-webcontainers-wasm32": "0.35.5", - "@img/sharp-win32-arm64": "0.35.5", - "@img/sharp-win32-ia32": "0.35.5", - "@img/sharp-win32-x64": "0.35.5" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/sharp/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/side-channel": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", - "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", - "side-channel-map": "^1.0.1", - "side-channel-weakmap": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-list": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", - "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.4" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-map": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", - "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-weakmap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", - "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3", - "side-channel-map": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/split2": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", - "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", - "license": "ISC", - "engines": { - "node": ">= 10.x" - } - }, - "node_modules/sqlstring": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz", - "integrity": "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/stable-hash": { - "version": "0.0.5", - "resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.5.tgz", - "integrity": "sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==", - "dev": true, - "license": "MIT" - }, - "node_modules/standardwebhooks": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.0.0.tgz", - "integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==", - "license": "MIT", - "dependencies": { - "@stablelib/base64": "^1.0.0", - "fast-sha256": "^1.3.0" - } - }, - "node_modules/std-env": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", - "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", - "license": "MIT" - }, - "node_modules/stop-iteration-iterator": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", - "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "internal-slot": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/string.prototype.includes": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/string.prototype.includes/-/string.prototype.includes-2.0.1.tgz", - "integrity": "sha512-o7+c9bW6zpAdJHTtujeePODAhkuicdAryFsfVKwA+wGw89wJ4GTY484WTucM9hLtDEOpOvI+aHnzqnC5lHp4Rg==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.7", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.3" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/string.prototype.matchall": { - "version": "4.0.12", - "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz", - "integrity": "sha512-6CC9uyBL+/48dYizRf7H7VAYCMCNTBeM78x/VTUe9bFEaxBepPJDa1Ow99LqI/1yF7kuy7Q3cQsYMrcjGUcskA==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "call-bound": "^1.0.3", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.6", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.0.0", - "get-intrinsic": "^1.2.6", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "internal-slot": "^1.1.0", - "regexp.prototype.flags": "^1.5.3", - "set-function-name": "^2.0.2", - "side-channel": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/string.prototype.repeat": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/string.prototype.repeat/-/string.prototype.repeat-1.0.0.tgz", - "integrity": "sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==", - "dev": true, - "license": "MIT", - "dependencies": { - "define-properties": "^1.1.3", - "es-abstract": "^1.17.5" - } - }, - "node_modules/string.prototype.trim": { - "version": "1.2.10", - "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.10.tgz", - "integrity": "sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "call-bound": "^1.0.2", - "define-data-property": "^1.1.4", - "define-properties": "^1.2.1", - "es-abstract": "^1.23.5", - "es-object-atoms": "^1.0.0", - "has-property-descriptors": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/string.prototype.trimend": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.9.tgz", - "integrity": "sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "call-bound": "^1.0.2", - "define-properties": "^1.2.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/string.prototype.trimstart": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", - "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.7", - "define-properties": "^1.2.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/styled-jsx": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz", - "integrity": "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==", - "license": "MIT", - "dependencies": { - "client-only": "0.0.1" - }, - "engines": { - "node": ">= 12.0.0" - }, - "peerDependencies": { - "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" - }, - "peerDependenciesMeta": { - "@babel/core": { - "optional": true - }, - "babel-plugin-macros": { - "optional": true - } - } - }, - "node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/tailwindcss": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.2.4.tgz", - "integrity": "sha512-HhKppgO81FQof5m6TEnuBWCZGgfRAWbaeOaGT00KOy/Pf/j6oUihdvBpA7ltCeAvZpFhW3j0PTclkxsd4IXYDA==", - "dev": true, - "license": "MIT" - }, - "node_modules/tapable": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", - "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, - "node_modules/tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", - "license": "MIT", - "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/tiny-inflate": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", - "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==", - "license": "MIT" - }, - "node_modules/tinyglobby": { - "version": "0.2.16", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", - "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==", - "dev": true, - "license": "MIT", - "dependencies": { - "fdir": "^6.5.0", - "picomatch": "^4.0.4" - }, - "engines": { - "node": ">=12.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/SuperchupuDev" - } - }, - "node_modules/tinyglobby/node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/tinyglobby/node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/tmp": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", - "integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==", - "license": "MIT", - "engines": { - "node": ">=14.14" - } - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/traverse": { - "version": "0.3.9", - "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.3.9.tgz", - "integrity": "sha512-iawgk0hLP3SxGKDfnDJf8wTz4p2qImnyihM5Hh/sGvQ3K37dPi/w8sRhdNIxYA1TwFwc5mDhIJq+O0RsvXBKdQ==", - "license": "MIT/X11", - "engines": { - "node": "*" - } - }, - "node_modules/ts-algebra": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", - "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", - "license": "MIT" - }, - "node_modules/ts-api-utils": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", - "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12" - }, - "peerDependencies": { - "typescript": ">=4.8.4" - } - }, - "node_modules/tsconfig-paths": { - "version": "3.15.0", - "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz", - "integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/json5": "^0.0.29", - "json5": "^1.0.2", - "minimist": "^1.2.6", - "strip-bom": "^3.0.0" - } - }, - "node_modules/tsconfig-paths/node_modules/json5": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", - "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", - "dev": true, - "license": "MIT", - "dependencies": { - "minimist": "^1.2.0" - }, - "bin": { - "json5": "lib/cli.js" - } - }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "license": "0BSD" - }, - "node_modules/tsx": { - "version": "4.21.0", - "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz", - "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", - "dev": true, - "license": "MIT", - "dependencies": { - "esbuild": "~0.27.0", - "get-tsconfig": "^4.7.5" - }, - "bin": { - "tsx": "dist/cli.mjs" - }, - "engines": { - "node": ">=18.0.0" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - } - }, - "node_modules/type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/typed-array-buffer": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", - "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3", - "es-errors": "^1.3.0", - "is-typed-array": "^1.1.14" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/typed-array-byte-length": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz", - "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.8", - "for-each": "^0.3.3", - "gopd": "^1.2.0", - "has-proto": "^1.2.0", - "is-typed-array": "^1.1.14" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/typed-array-byte-offset": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.4.tgz", - "integrity": "sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "available-typed-arrays": "^1.0.7", - "call-bind": "^1.0.8", - "for-each": "^0.3.3", - "gopd": "^1.2.0", - "has-proto": "^1.2.0", - "is-typed-array": "^1.1.15", - "reflect.getprototypeof": "^1.0.9" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/typed-array-length": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.7.tgz", - "integrity": "sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.7", - "for-each": "^0.3.3", - "gopd": "^1.0.1", - "is-typed-array": "^1.1.13", - "possible-typed-array-names": "^1.0.0", - "reflect.getprototypeof": "^1.0.6" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "devOptional": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/typescript-eslint": { - "version": "8.59.0", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.59.0.tgz", - "integrity": "sha512-BU3ONW9X+v90EcCH9ZS6LMackcVtxRLlI3XrYyqZIwVSHIk7Qf7bFw1z0M9Q0IUxhTMZCf8piY9hTYaNEIASrw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/eslint-plugin": "8.59.0", - "@typescript-eslint/parser": "8.59.0", - "@typescript-eslint/typescript-estree": "8.59.0", - "@typescript-eslint/utils": "8.59.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/unbox-primitive": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz", - "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.3", - "has-bigints": "^1.0.2", - "has-symbols": "^1.1.0", - "which-boxed-primitive": "^1.1.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "license": "MIT" - }, - "node_modules/unicode-properties": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz", - "integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==", - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.0", - "unicode-trie": "^2.0.0" - } - }, - "node_modules/unicode-trie": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz", - "integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==", - "license": "MIT", - "dependencies": { - "pako": "^0.2.5", - "tiny-inflate": "^1.0.0" - } - }, - "node_modules/unicode-trie/node_modules/pako": { - "version": "0.2.9", - "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz", - "integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==", - "license": "MIT" - }, - "node_modules/unrs-resolver": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.11.1.tgz", - "integrity": "sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "dependencies": { - "napi-postinstall": "^0.3.0" - }, - "funding": { - "url": "https://opencollective.com/unrs-resolver" - }, - "optionalDependencies": { - "@unrs/resolver-binding-android-arm-eabi": "1.11.1", - "@unrs/resolver-binding-android-arm64": "1.11.1", - "@unrs/resolver-binding-darwin-arm64": "1.11.1", - "@unrs/resolver-binding-darwin-x64": "1.11.1", - "@unrs/resolver-binding-freebsd-x64": "1.11.1", - "@unrs/resolver-binding-linux-arm-gnueabihf": "1.11.1", - "@unrs/resolver-binding-linux-arm-musleabihf": "1.11.1", - "@unrs/resolver-binding-linux-arm64-gnu": "1.11.1", - "@unrs/resolver-binding-linux-arm64-musl": "1.11.1", - "@unrs/resolver-binding-linux-ppc64-gnu": "1.11.1", - "@unrs/resolver-binding-linux-riscv64-gnu": "1.11.1", - "@unrs/resolver-binding-linux-riscv64-musl": "1.11.1", - "@unrs/resolver-binding-linux-s390x-gnu": "1.11.1", - "@unrs/resolver-binding-linux-x64-gnu": "1.11.1", - "@unrs/resolver-binding-linux-x64-musl": "1.11.1", - "@unrs/resolver-binding-wasm32-wasi": "1.11.1", - "@unrs/resolver-binding-win32-arm64-msvc": "1.11.1", - "@unrs/resolver-binding-win32-ia32-msvc": "1.11.1", - "@unrs/resolver-binding-win32-x64-msvc": "1.11.1" - } - }, - "node_modules/unzipper": { - "version": "0.10.14", - "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.10.14.tgz", - "integrity": "sha512-ti4wZj+0bQTiX2KmKWuwj7lhV+2n//uXEotUmGuQqrbVZSEGFMbI68+c6JCQ8aAmUWYvtHEz2A8K6wXvueR/6g==", - "license": "MIT", - "dependencies": { - "big-integer": "^1.6.17", - "binary": "~0.3.0", - "bluebird": "~3.4.1", - "buffer-indexof-polyfill": "~1.0.0", - "duplexer2": "~0.1.4", - "fstream": "^1.0.12", - "graceful-fs": "^4.2.2", - "listenercount": "~1.0.1", - "readable-stream": "~2.3.6", - "setimmediate": "~1.0.4" - } - }, - "node_modules/unzipper/node_modules/isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", - "license": "MIT" - }, - "node_modules/unzipper/node_modules/readable-stream": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", - "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", - "license": "MIT", - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "node_modules/unzipper/node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "license": "MIT" - }, - "node_modules/unzipper/node_modules/string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.1.0" - } - }, - "node_modules/update-browserslist-db": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", - "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "escalade": "^3.2.0", - "picocolors": "^1.1.1" - }, - "bin": { - "update-browserslist-db": "cli.js" - }, - "peerDependencies": { - "browserslist": ">= 4.21.0" - } - }, - "node_modules/uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "punycode": "^2.1.0" - } - }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "license": "MIT" - }, - "node_modules/uuid": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", - "license": "MIT", - "bin": { - "uuid": "dist/bin/uuid" - } - }, - "node_modules/valibot": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/valibot/-/valibot-1.2.0.tgz", - "integrity": "sha512-mm1rxUsmOxzrwnX5arGS+U4T25RdvpPjPN4yR0u9pUBov9+zGVtO84tif1eY4r6zWxVxu3KzIyknJy3rxfRZZg==", - "license": "MIT", - "peerDependencies": { - "typescript": ">=5" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/web-push": { - "version": "3.6.7", - "resolved": "https://registry.npmjs.org/web-push/-/web-push-3.6.7.tgz", - "integrity": "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==", - "license": "MPL-2.0", - "dependencies": { - "asn1.js": "^5.3.0", - "http_ece": "1.2.0", - "https-proxy-agent": "^7.0.0", - "jws": "^4.0.0", - "minimist": "^1.2.5" - }, - "bin": { - "web-push": "src/cli.js" - }, - "engines": { - "node": ">= 16" - } - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/which-boxed-primitive": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", - "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-bigint": "^1.1.0", - "is-boolean-object": "^1.2.1", - "is-number-object": "^1.1.1", - "is-string": "^1.1.1", - "is-symbol": "^1.1.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/which-builtin-type": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.2.1.tgz", - "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "function.prototype.name": "^1.1.6", - "has-tostringtag": "^1.0.2", - "is-async-function": "^2.0.0", - "is-date-object": "^1.1.0", - "is-finalizationregistry": "^1.1.0", - "is-generator-function": "^1.0.10", - "is-regex": "^1.2.1", - "is-weakref": "^1.0.2", - "isarray": "^2.0.5", - "which-boxed-primitive": "^1.1.0", - "which-collection": "^1.0.2", - "which-typed-array": "^1.1.16" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/which-collection": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz", - "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-map": "^2.0.3", - "is-set": "^2.0.3", - "is-weakmap": "^2.0.2", - "is-weakset": "^2.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/which-typed-array": { - "version": "1.1.20", - "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.20.tgz", - "integrity": "sha512-LYfpUkmqwl0h9A2HL09Mms427Q1RZWuOHsukfVcKRq9q95iQxdw0ix1JQrqbcDR9PH1QDwf5Qo8OZb5lksZ8Xg==", - "dev": true, - "license": "MIT", - "dependencies": { - "available-typed-arrays": "^1.0.7", - "call-bind": "^1.0.8", - "call-bound": "^1.0.4", - "for-each": "^0.3.5", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-tostringtag": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/word-wrap": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", - "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "license": "ISC" - }, - "node_modules/xmlchars": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", - "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", - "license": "MIT" - }, - "node_modules/xtend": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", - "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", - "license": "MIT", - "engines": { - "node": ">=0.4" - } - }, - "node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true, - "license": "ISC" - }, - "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/zeptomatch": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/zeptomatch/-/zeptomatch-2.1.0.tgz", - "integrity": "sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA==", - "license": "MIT", - "dependencies": { - "grammex": "^3.1.11", - "graphmatch": "^1.1.0" - } - }, - "node_modules/zip-stream": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-4.1.1.tgz", - "integrity": "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ==", - "license": "MIT", - "dependencies": { - "archiver-utils": "^3.0.4", - "compress-commons": "^4.1.2", - "readable-stream": "^3.6.0" - }, - "engines": { - "node": ">= 10" - } - }, - "node_modules/zip-stream/node_modules/archiver-utils": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-3.0.4.tgz", - "integrity": "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw==", - "license": "MIT", - "dependencies": { - "glob": "^7.2.3", - "graceful-fs": "^4.2.0", - "lazystream": "^1.0.0", - "lodash.defaults": "^4.2.0", - "lodash.difference": "^4.5.0", - "lodash.flatten": "^4.4.0", - "lodash.isplainobject": "^4.0.6", - "lodash.union": "^4.6.0", - "normalize-path": "^3.0.0", - "readable-stream": "^3.6.0" - }, - "engines": { - "node": ">= 10" - } - }, - "node_modules/zod": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", - "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, - "node_modules/zod-validation-error": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz", - "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.0.0" - }, - "peerDependencies": { - "zod": "^3.25.0 || ^4.0.0" - } - }, - "node_modules/zustand": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.12.tgz", - "integrity": "sha512-i77ae3aZq4dhMlRhJVCYgMLKuSiZAaUPAct2AksxQ+gOtimhGMdXljRT21P5BNpeT4kXlLIckvkPM029OljD7g==", - "license": "MIT", - "engines": { - "node": ">=12.20.0" - }, - "peerDependencies": { - "@types/react": ">=18.0.0", - "immer": ">=9.0.6", - "react": ">=18.0.0", - "use-sync-external-store": ">=1.2.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - }, - "immer": { - "optional": true - }, - "react": { - "optional": true - }, - "use-sync-external-store": { - "optional": true - } - } - } - } -} diff --git a/package.json b/package.json deleted file mode 100644 index 8118f06..0000000 --- a/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "name": "cotizador-uj", - "version": "0.1.0", - "private": true, - "bin": { - "cotizador": "cli/cotizador.mjs" - }, - "scripts": { - "dev": "next dev", - "build": "next build", - "start": "next start", - "lint": "eslint", - "db:migrate": "npx prisma migrate dev", - "db:seed": "npx tsx prisma/seed.ts", - "db:studio": "npx prisma studio", - "db:generate": "npx prisma generate", - "cli": "node cli/cotizador.mjs", - "test": "node --import tsx --test tests/*.test.ts" - }, - "prisma": { - "seed": "npx tsx prisma/seed.ts" - }, - "dependencies": { - "@anthropic-ai/sdk": "^0.115.0", - "@prisma/adapter-pg": "^7.8.0", - "@prisma/client": "^7.8.0", - "bcryptjs": "^3.0.3", - "clsx": "^2.1.1", - "dotenv": "^17.4.2", - "exceljs": "^4.4.0", - "jose": "^6.2.3", - "lucide-react": "^1.11.0", - "next": "16.2.4", - "nodemailer": "^10.1.7", - "pdfkit": "^0.18.0", - "pg": "^8.20.0", - "prisma": "^7.8.0", - "react": "19.2.4", - "react-dom": "19.2.4", - "sharp": "^0.35.5", - "web-push": "^3.6.7", - "zod": "^4.3.6", - "zustand": "^5.0.12" - }, - "devDependencies": { - "@tailwindcss/postcss": "^4", - "@types/bcryptjs": "^2.4.6", - "@types/node": "^20", - "@types/nodemailer": "^8.0.2", - "@types/pdfkit": "^0.17.6", - "@types/react": "^19", - "@types/react-dom": "^19", - "@types/web-push": "^3.6.4", - "eslint": "^9", - "eslint-config-next": "16.2.4", - "tailwindcss": "^4", - "tsx": "^4.21.0", - "typescript": "^5" - } -} diff --git a/postcss.config.mjs b/postcss.config.mjs deleted file mode 100644 index 61e3684..0000000 --- a/postcss.config.mjs +++ /dev/null @@ -1,7 +0,0 @@ -const config = { - plugins: { - "@tailwindcss/postcss": {}, - }, -}; - -export default config; diff --git a/prisma.config.ts b/prisma.config.ts deleted file mode 100644 index 8359142..0000000 --- a/prisma.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -import "dotenv/config"; -import { defineConfig } from "prisma/config"; - -// El CLI de Prisma (migrate deploy) necesita una URL. Si DATABASE_URL no está -// definida (p. ej. despliegue Dockerfile en Coolify), se arma desde las DB_* -// que ya usan la app y el seed — así ambas vías apuntan a la misma BD. -function databaseUrl(): string { - if (process.env["DATABASE_URL"]) return process.env["DATABASE_URL"]; - const host = process.env["DB_HOST"] || "localhost"; - const port = process.env["DB_PORT"] || "5432"; - const user = encodeURIComponent(process.env["DB_USER"] || "postgres"); - const password = encodeURIComponent(process.env["DB_PASSWORD"] || "postgres"); - // Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data. - const name = process.env["DB_DATABASE"] || process.env["DB_NAME"] || "cotizador_e3"; - return `postgresql://${user}:${password}@${host}:${port}/${name}`; -} - -export default defineConfig({ - schema: "prisma/schema.prisma", - migrations: { - path: "prisma/migrations", - seed: "npx tsx prisma/seed.ts", - }, - datasource: { - url: databaseUrl(), - }, -}); diff --git a/prisma/migrations/20260427090524_init/migration.sql b/prisma/migrations/20260427090524_init/migration.sql deleted file mode 100644 index 6b4ace4..0000000 --- a/prisma/migrations/20260427090524_init/migration.sql +++ /dev/null @@ -1,161 +0,0 @@ --- CreateTable -CREATE TABLE "User" ( - "id" TEXT NOT NULL, - "email" TEXT NOT NULL, - "password" TEXT NOT NULL, - "name" TEXT NOT NULL, - "role" TEXT NOT NULL DEFAULT 'asesor', - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "User_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "Cliente" ( - "id" TEXT NOT NULL, - "nombre" TEXT NOT NULL, - "empresa" TEXT, - "email" TEXT, - "telefono" TEXT, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "Cliente_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "Cotizacion" ( - "id" TEXT NOT NULL, - "numero" TEXT NOT NULL, - "fecha" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "vigencia" TIMESTAMP(3) NOT NULL, - "moneda" TEXT NOT NULL DEFAULT 'MXN', - "tipoCambio" TEXT NOT NULL DEFAULT 'NA', - "proyecto" TEXT NOT NULL DEFAULT 'MKT Digital', - "esquemaPago" TEXT NOT NULL DEFAULT 'Pago Unico/Mensual', - "estado" TEXT NOT NULL DEFAULT 'borrador', - "incluirBonos" BOOLEAN NOT NULL DEFAULT false, - "incluirFinanciamiento" BOOLEAN NOT NULL DEFAULT false, - "observaciones" TEXT, - "clienteId" TEXT NOT NULL, - "asesorId" TEXT NOT NULL, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "Cotizacion_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "ServicioCatalogo" ( - "id" TEXT NOT NULL, - "nombre" TEXT NOT NULL, - "descripcion" TEXT, - "fase" INTEGER NOT NULL DEFAULT 1, - "tipoPago" TEXT NOT NULL DEFAULT 'unico', - "precioBase" DOUBLE PRECISION NOT NULL, - "tiempoEntrega" TEXT NOT NULL DEFAULT '4 - 10 dias', - "entregablesDefault" JSONB NOT NULL DEFAULT '[]', - "categoria" TEXT NOT NULL DEFAULT 'otros', - "variante" TEXT, - "activo" BOOLEAN NOT NULL DEFAULT true, - "orden" INTEGER NOT NULL DEFAULT 0, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "ServicioCatalogo_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "ServicioCotizado" ( - "id" TEXT NOT NULL, - "cotizacionId" TEXT NOT NULL, - "servicioCatalogoId" TEXT NOT NULL, - "fase" INTEGER NOT NULL, - "tipoPago" TEXT NOT NULL, - "precio" DOUBLE PRECISION NOT NULL, - "tiempoEntrega" TEXT NOT NULL, - "entregables" JSONB NOT NULL DEFAULT '[]', - "notas" TEXT, - "seleccionado" BOOLEAN NOT NULL DEFAULT true, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "ServicioCotizado_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "PlanBucefaloCotizacion" ( - "id" TEXT NOT NULL, - "cotizacionId" TEXT NOT NULL, - "nivel" TEXT NOT NULL DEFAULT 'basico', - "precio" DOUBLE PRECISION NOT NULL, - "seleccionado" BOOLEAN NOT NULL DEFAULT true, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "PlanBucefaloCotizacion_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "Configuracion" ( - "id" TEXT NOT NULL, - "clave" TEXT NOT NULL, - "valor" TEXT NOT NULL, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "Configuracion_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "Bono" ( - "id" TEXT NOT NULL, - "numero" INTEGER NOT NULL, - "titulo" TEXT NOT NULL, - "descripcion" TEXT NOT NULL, - "activo" BOOLEAN NOT NULL DEFAULT true, - - CONSTRAINT "Bono_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "FinanciamientoPlan" ( - "id" TEXT NOT NULL, - "meses" INTEGER NOT NULL, - "tasa" DOUBLE PRECISION NOT NULL, - "comision" DOUBLE PRECISION NOT NULL, - "montoMinimo" DOUBLE PRECISION NOT NULL, - "iva" DOUBLE PRECISION NOT NULL DEFAULT 0.16, - - CONSTRAINT "FinanciamientoPlan_pkey" PRIMARY KEY ("id") -); - --- CreateIndex -CREATE UNIQUE INDEX "User_email_key" ON "User"("email"); - --- CreateIndex -CREATE UNIQUE INDEX "Cotizacion_numero_key" ON "Cotizacion"("numero"); - --- CreateIndex -CREATE UNIQUE INDEX "PlanBucefaloCotizacion_cotizacionId_key" ON "PlanBucefaloCotizacion"("cotizacionId"); - --- CreateIndex -CREATE UNIQUE INDEX "Configuracion_clave_key" ON "Configuracion"("clave"); - --- CreateIndex -CREATE UNIQUE INDEX "FinanciamientoPlan_meses_key" ON "FinanciamientoPlan"("meses"); - --- AddForeignKey -ALTER TABLE "Cotizacion" ADD CONSTRAINT "Cotizacion_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE RESTRICT ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "Cotizacion" ADD CONSTRAINT "Cotizacion_asesorId_fkey" FOREIGN KEY ("asesorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "ServicioCotizado" ADD CONSTRAINT "ServicioCotizado_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "ServicioCotizado" ADD CONSTRAINT "ServicioCotizado_servicioCatalogoId_fkey" FOREIGN KEY ("servicioCatalogoId") REFERENCES "ServicioCatalogo"("id") ON DELETE RESTRICT ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "PlanBucefaloCotizacion" ADD CONSTRAINT "PlanBucefaloCotizacion_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/migrations/20260430154327_add_packages_categories/migration.sql b/prisma/migrations/20260430154327_add_packages_categories/migration.sql deleted file mode 100644 index 4276b32..0000000 --- a/prisma/migrations/20260430154327_add_packages_categories/migration.sql +++ /dev/null @@ -1,69 +0,0 @@ --- AlterTable -ALTER TABLE "ServicioCatalogo" ADD COLUMN "categoriaId" TEXT; - --- CreateTable -CREATE TABLE "Categoria" ( - "id" TEXT NOT NULL, - "nombre" TEXT NOT NULL, - "descripcion" TEXT, - "color" TEXT NOT NULL DEFAULT '#6b7280', - "activo" BOOLEAN NOT NULL DEFAULT true, - "orden" INTEGER NOT NULL DEFAULT 0, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "Categoria_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "Paquete" ( - "id" TEXT NOT NULL, - "nombre" TEXT NOT NULL, - "descripcion" TEXT, - "activo" BOOLEAN NOT NULL DEFAULT true, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "Paquete_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "FasePaquete" ( - "id" TEXT NOT NULL, - "paqueteId" TEXT NOT NULL, - "nombre" TEXT NOT NULL, - "orden" INTEGER NOT NULL DEFAULT 0, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "FasePaquete_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "ServicioPaquete" ( - "id" TEXT NOT NULL, - "servicioCatalogoId" TEXT NOT NULL, - "fasePaqueteId" TEXT NOT NULL, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "ServicioPaquete_pkey" PRIMARY KEY ("id") -); - --- CreateIndex -CREATE UNIQUE INDEX "Categoria_nombre_key" ON "Categoria"("nombre"); - --- CreateIndex -CREATE UNIQUE INDEX "ServicioPaquete_servicioCatalogoId_fasePaqueteId_key" ON "ServicioPaquete"("servicioCatalogoId", "fasePaqueteId"); - --- AddForeignKey -ALTER TABLE "FasePaquete" ADD CONSTRAINT "FasePaquete_paqueteId_fkey" FOREIGN KEY ("paqueteId") REFERENCES "Paquete"("id") ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "ServicioCatalogo" ADD CONSTRAINT "ServicioCatalogo_categoriaId_fkey" FOREIGN KEY ("categoriaId") REFERENCES "Categoria"("id") ON DELETE SET NULL ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "ServicioPaquete" ADD CONSTRAINT "ServicioPaquete_servicioCatalogoId_fkey" FOREIGN KEY ("servicioCatalogoId") REFERENCES "ServicioCatalogo"("id") ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "ServicioPaquete" ADD CONSTRAINT "ServicioPaquete_fasePaqueteId_fkey" FOREIGN KEY ("fasePaqueteId") REFERENCES "FasePaquete"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/migrations/20260430180000_remove_categoria_string/migration.sql b/prisma/migrations/20260430180000_remove_categoria_string/migration.sql deleted file mode 100644 index 5a96924..0000000 --- a/prisma/migrations/20260430180000_remove_categoria_string/migration.sql +++ /dev/null @@ -1,2 +0,0 @@ --- AlterTable -ALTER TABLE "ServicioCatalogo" DROP COLUMN "categoria"; diff --git a/prisma/migrations/20260601000000_add_servicio_personalizado_horas/migration.sql b/prisma/migrations/20260601000000_add_servicio_personalizado_horas/migration.sql deleted file mode 100644 index a5bbb97..0000000 --- a/prisma/migrations/20260601000000_add_servicio_personalizado_horas/migration.sql +++ /dev/null @@ -1,6 +0,0 @@ --- AlterTable: permitir servicios sin catalogo (partidas personalizadas) y campos de cobro por horas -ALTER TABLE "ServicioCotizado" ALTER COLUMN "servicioCatalogoId" DROP NOT NULL; -ALTER TABLE "ServicioCotizado" ADD COLUMN "nombre" TEXT; -ALTER TABLE "ServicioCotizado" ADD COLUMN "esPersonalizado" BOOLEAN NOT NULL DEFAULT false; -ALTER TABLE "ServicioCotizado" ADD COLUMN "horas" DOUBLE PRECISION; -ALTER TABLE "ServicioCotizado" ADD COLUMN "tarifaHora" DOUBLE PRECISION; diff --git a/prisma/migrations/20260603085717_add_modelo_cobro_retainer/migration.sql b/prisma/migrations/20260603085717_add_modelo_cobro_retainer/migration.sql deleted file mode 100644 index 14157e2..0000000 --- a/prisma/migrations/20260603085717_add_modelo_cobro_retainer/migration.sql +++ /dev/null @@ -1,10 +0,0 @@ --- DropForeignKey -ALTER TABLE "ServicioCotizado" DROP CONSTRAINT "ServicioCotizado_servicioCatalogoId_fkey"; - --- AlterTable -ALTER TABLE "ServicioCotizado" ADD COLUMN "horasIncluidas" DOUBLE PRECISION, -ADD COLUMN "modeloCobro" TEXT NOT NULL DEFAULT 'fijo', -ADD COLUMN "montoMinimo" DOUBLE PRECISION; - --- AddForeignKey -ALTER TABLE "ServicioCotizado" ADD CONSTRAINT "ServicioCotizado_servicioCatalogoId_fkey" FOREIGN KEY ("servicioCatalogoId") REFERENCES "ServicioCatalogo"("id") ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/prisma/migrations/20260603090526_add_nivel_servicio/migration.sql b/prisma/migrations/20260603090526_add_nivel_servicio/migration.sql deleted file mode 100644 index a61cf13..0000000 --- a/prisma/migrations/20260603090526_add_nivel_servicio/migration.sql +++ /dev/null @@ -1,2 +0,0 @@ --- AlterTable -ALTER TABLE "ServicioCatalogo" ADD COLUMN "nivel" TEXT; diff --git a/prisma/migrations/20260609224848_doble_propuesta/migration.sql b/prisma/migrations/20260609224848_doble_propuesta/migration.sql deleted file mode 100644 index 522849e..0000000 --- a/prisma/migrations/20260609224848_doble_propuesta/migration.sql +++ /dev/null @@ -1,6 +0,0 @@ --- AlterTable -ALTER TABLE "Cotizacion" ADD COLUMN "esDoble" BOOLEAN NOT NULL DEFAULT false, -ADD COLUMN "opcionesMetadata" JSONB; - --- AlterTable -ALTER TABLE "ServicioCotizado" ADD COLUMN "opcion" TEXT; diff --git a/prisma/migrations/20260610012632_add_performance_indexes/migration.sql b/prisma/migrations/20260610012632_add_performance_indexes/migration.sql deleted file mode 100644 index 287924d..0000000 --- a/prisma/migrations/20260610012632_add_performance_indexes/migration.sql +++ /dev/null @@ -1,32 +0,0 @@ --- CreateIndex -CREATE INDEX "Cliente_nombre_empresa_idx" ON "Cliente"("nombre", "empresa"); - --- CreateIndex -CREATE INDEX "Cotizacion_clienteId_idx" ON "Cotizacion"("clienteId"); - --- CreateIndex -CREATE INDEX "Cotizacion_asesorId_idx" ON "Cotizacion"("asesorId"); - --- CreateIndex -CREATE INDEX "Cotizacion_estado_idx" ON "Cotizacion"("estado"); - --- CreateIndex -CREATE INDEX "Cotizacion_createdAt_idx" ON "Cotizacion"("createdAt"); - --- CreateIndex -CREATE INDEX "FasePaquete_paqueteId_idx" ON "FasePaquete"("paqueteId"); - --- CreateIndex -CREATE INDEX "ServicioCatalogo_categoriaId_idx" ON "ServicioCatalogo"("categoriaId"); - --- CreateIndex -CREATE INDEX "ServicioCatalogo_activo_fase_orden_idx" ON "ServicioCatalogo"("activo", "fase", "orden"); - --- CreateIndex -CREATE INDEX "ServicioCotizado_cotizacionId_idx" ON "ServicioCotizado"("cotizacionId"); - --- CreateIndex -CREATE INDEX "ServicioCotizado_servicioCatalogoId_idx" ON "ServicioCotizado"("servicioCatalogoId"); - --- CreateIndex -CREATE INDEX "ServicioPaquete_fasePaqueteId_idx" ON "ServicioPaquete"("fasePaqueteId"); diff --git a/prisma/migrations/20260630000000_add_registro_horas_incluir_iva/migration.sql b/prisma/migrations/20260630000000_add_registro_horas_incluir_iva/migration.sql deleted file mode 100644 index e923d12..0000000 --- a/prisma/migrations/20260630000000_add_registro_horas_incluir_iva/migration.sql +++ /dev/null @@ -1,46 +0,0 @@ --- Feature "registro de horas / cobro por tiempo": recupera el modelo RegistroHoras y --- las columnas incluirIva / rfc / beneficios que existian en desarrollo pero no habian --- llegado a la rama desplegada. Idempotente (IF NOT EXISTS) para poder aplicarse tanto --- en la BD web (limpia) como en una BD que ya tenga estos objetos. - --- AlterTable: Cliente.rfc -ALTER TABLE "Cliente" ADD COLUMN IF NOT EXISTS "rfc" TEXT; - --- AlterTable: Cotizacion.incluirIva -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "incluirIva" BOOLEAN NOT NULL DEFAULT true; - --- AlterTable: ServicioCotizado.beneficios -ALTER TABLE "ServicioCotizado" ADD COLUMN IF NOT EXISTS "beneficios" JSONB NOT NULL DEFAULT '[]'; - --- CreateTable: RegistroHoras -CREATE TABLE IF NOT EXISTS "RegistroHoras" ( - "id" TEXT NOT NULL, - "cotizacionId" TEXT NOT NULL, - "fecha" TIMESTAMP(3) NOT NULL, - "horaInicio" TEXT NOT NULL, - "horaFin" TEXT NOT NULL, - "horas" DOUBLE PRECISION NOT NULL, - "tarifaHora" DOUBLE PRECISION NOT NULL DEFAULT 0, - "descripcion" TEXT NOT NULL, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "RegistroHoras_pkey" PRIMARY KEY ("id") -); - --- CreateIndex -CREATE INDEX IF NOT EXISTS "RegistroHoras_cotizacionId_idx" ON "RegistroHoras"("cotizacionId"); -CREATE INDEX IF NOT EXISTS "RegistroHoras_fecha_idx" ON "RegistroHoras"("fecha"); - --- AddForeignKey (guarda porque ADD CONSTRAINT no admite IF NOT EXISTS en PostgreSQL) -DO $$ -BEGIN - IF NOT EXISTS ( - SELECT 1 FROM pg_constraint WHERE conname = 'RegistroHoras_cotizacionId_fkey' - ) THEN - ALTER TABLE "RegistroHoras" - ADD CONSTRAINT "RegistroHoras_cotizacionId_fkey" - FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") - ON DELETE CASCADE ON UPDATE CASCADE; - END IF; -END $$; diff --git a/prisma/migrations/20260708000000_registro_horas_estado_pago/migration.sql b/prisma/migrations/20260708000000_registro_horas_estado_pago/migration.sql deleted file mode 100644 index 459a98d..0000000 --- a/prisma/migrations/20260708000000_registro_horas_estado_pago/migration.sql +++ /dev/null @@ -1,10 +0,0 @@ --- Estado de cobro por partida de horas: separa lo pendiente ("por_pagar") de lo ya --- cobrado ("pagada") para poder emitir notas por pagar y conservar recibos pagados sin --- que los totales se mezclen. Idempotente (IF NOT EXISTS). - --- AlterTable: RegistroHoras.estadoPago / fechaPago -ALTER TABLE "RegistroHoras" ADD COLUMN IF NOT EXISTS "estadoPago" TEXT NOT NULL DEFAULT 'por_pagar'; -ALTER TABLE "RegistroHoras" ADD COLUMN IF NOT EXISTS "fechaPago" TIMESTAMP(3); - --- CreateIndex -CREATE INDEX IF NOT EXISTS "RegistroHoras_estadoPago_idx" ON "RegistroHoras"("estadoPago"); diff --git a/prisma/migrations/20260728000000_add_observaciones_internas/migration.sql b/prisma/migrations/20260728000000_add_observaciones_internas/migration.sql deleted file mode 100644 index b827e15..0000000 --- a/prisma/migrations/20260728000000_add_observaciones_internas/migration.sql +++ /dev/null @@ -1,20 +0,0 @@ --- Fase 0-C, Despliegue A: separar el texto que ve el cliente del contexto interno. --- --- ESTA MIGRACION ES PURAMENTE ADITIVA. No modifica ni una sola fila existente. --- El movimiento de datos (observaciones -> observacionesInternas) seria un --- Despliegue B posterior y NO se incluye aqui, por dos razones: --- --- 1. Rollback seguro. No hay migraciones `down` en este repo ni servicio de --- backup en docker-compose.coolify.yml. Si un UPDATE vaciara "observaciones" --- y el despliegue se revirtiera, el codigo anterior leeria NULL en todas las --- filas y el asesor veria sus notas desaparecidas: sin error y sin log. --- --- 2. El dato real no lo necesita. Al momento de escribir esto la unica fila de --- produccion con "observaciones" no vacias (UJ2606AG777, aprobada) contiene --- condiciones de pago dirigidas al cliente en segunda persona. Moverlas a --- "internas" ocultaria terminos ya acordados en un documento emitido. --- Esa fila ya esta clasificada correctamente donde esta. --- --- IF NOT EXISTS hace la sentencia idempotente si alguien la aplica a mano. - -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "observacionesInternas" TEXT; diff --git a/prisma/migrations/20260729000000_add_propuesta_ia/migration.sql b/prisma/migrations/20260729000000_add_propuesta_ia/migration.sql deleted file mode 100644 index b1aec1a..0000000 --- a/prisma/migrations/20260729000000_add_propuesta_ia/migration.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Propuesta consultiva con IA: tabla nueva. --- ADITIVA. No toca ninguna tabla ni fila existente. - -CREATE TABLE IF NOT EXISTS "PropuestaIA" ( - "id" TEXT NOT NULL, - "cotizacionId" TEXT NOT NULL, - "estado" TEXT NOT NULL DEFAULT 'borrador', - "contenidoIA" JSONB NOT NULL, - "contenidoEditado" JSONB, - "traza" JSONB, - "avisos" JSONB NOT NULL DEFAULT '[]', - "modelo" TEXT NOT NULL, - "aprobadaPor" TEXT, - "aprobadaAt" TIMESTAMP(3), - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "PropuestaIA_pkey" PRIMARY KEY ("id") -); - -CREATE INDEX IF NOT EXISTS "PropuestaIA_cotizacionId_idx" ON "PropuestaIA"("cotizacionId"); - -ALTER TABLE "PropuestaIA" - ADD CONSTRAINT "PropuestaIA_cotizacionId_fkey" - FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") - ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/migrations/20260729010000_propuesta_ia_transcripcion/migration.sql b/prisma/migrations/20260729010000_propuesta_ia_transcripcion/migration.sql deleted file mode 100644 index da66249..0000000 --- a/prisma/migrations/20260729010000_propuesta_ia_transcripcion/migration.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Guardar la transcripcion usada al generar la propuesta. --- ADITIVA: columna nullable, no toca ninguna fila existente. -ALTER TABLE "PropuestaIA" ADD COLUMN IF NOT EXISTS "transcripcion" TEXT; diff --git a/prisma/migrations/20261020000000_pagos_recurrentes_panel_cliente/migration.sql b/prisma/migrations/20261020000000_pagos_recurrentes_panel_cliente/migration.sql deleted file mode 100644 index c545a47..0000000 --- a/prisma/migrations/20261020000000_pagos_recurrentes_panel_cliente/migration.sql +++ /dev/null @@ -1,109 +0,0 @@ --- AlterTable -ALTER TABLE "User" ADD COLUMN "clienteId" TEXT; - --- CreateTable -CREATE TABLE "ProgramaPago" ( - "id" TEXT NOT NULL, - "clienteId" TEXT NOT NULL, - "cotizacionId" TEXT, - "concepto" TEXT NOT NULL, - "monto" DOUBLE PRECISION NOT NULL, - "moneda" TEXT NOT NULL DEFAULT 'MXN', - "frecuencia" TEXT NOT NULL DEFAULT 'semanal', - "diaSemana" INTEGER, - "diaMes" INTEGER, - "fechaInicio" TIMESTAMP(3) NOT NULL, - "fechaFin" TIMESTAMP(3), - "activo" BOOLEAN NOT NULL DEFAULT true, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "ProgramaPago_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "PagoRecurrente" ( - "id" TEXT NOT NULL, - "programaId" TEXT NOT NULL, - "fecha" TIMESTAMP(3) NOT NULL, - "monto" DOUBLE PRECISION NOT NULL, - "estado" TEXT NOT NULL DEFAULT 'pendiente', - "verificadoAt" TIMESTAMP(3), - "rechazadoAt" TIMESTAMP(3), - "rechazoMotivo" TEXT, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "PagoRecurrente_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "ComprobantePago" ( - "id" TEXT NOT NULL, - "pagoId" TEXT NOT NULL, - "archivoRuta" TEXT NOT NULL, - "archivoNombre" TEXT NOT NULL, - "mime" TEXT NOT NULL, - "tamano" INTEGER NOT NULL, - "subidoAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - - CONSTRAINT "ComprobantePago_pkey" PRIMARY KEY ("id") -); - --- CreateTable -CREATE TABLE "SuscripcionPush" ( - "id" TEXT NOT NULL, - "userId" TEXT NOT NULL, - "endpoint" TEXT NOT NULL, - "p256dh" TEXT NOT NULL, - "auth" TEXT NOT NULL, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "SuscripcionPush_pkey" PRIMARY KEY ("id") -); - --- CreateIndex -CREATE INDEX "ProgramaPago_clienteId_idx" ON "ProgramaPago"("clienteId"); - --- CreateIndex -CREATE INDEX "ProgramaPago_activo_idx" ON "ProgramaPago"("activo"); - --- CreateIndex -CREATE INDEX "PagoRecurrente_estado_idx" ON "PagoRecurrente"("estado"); - --- CreateIndex -CREATE INDEX "PagoRecurrente_fecha_idx" ON "PagoRecurrente"("fecha"); - --- CreateIndex -CREATE UNIQUE INDEX "PagoRecurrente_programaId_fecha_key" ON "PagoRecurrente"("programaId", "fecha"); - --- CreateIndex -CREATE UNIQUE INDEX "ComprobantePago_pagoId_key" ON "ComprobantePago"("pagoId"); - --- CreateIndex -CREATE UNIQUE INDEX "SuscripcionPush_endpoint_key" ON "SuscripcionPush"("endpoint"); - --- CreateIndex -CREATE INDEX "SuscripcionPush_userId_idx" ON "SuscripcionPush"("userId"); - --- CreateIndex -CREATE UNIQUE INDEX "User_clienteId_key" ON "User"("clienteId"); - --- AddForeignKey -ALTER TABLE "User" ADD CONSTRAINT "User_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE SET NULL ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "ProgramaPago" ADD CONSTRAINT "ProgramaPago_clienteId_fkey" FOREIGN KEY ("clienteId") REFERENCES "Cliente"("id") ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "ProgramaPago" ADD CONSTRAINT "ProgramaPago_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE SET NULL ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "PagoRecurrente" ADD CONSTRAINT "PagoRecurrente_programaId_fkey" FOREIGN KEY ("programaId") REFERENCES "ProgramaPago"("id") ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "ComprobantePago" ADD CONSTRAINT "ComprobantePago_pagoId_fkey" FOREIGN KEY ("pagoId") REFERENCES "PagoRecurrente"("id") ON DELETE CASCADE ON UPDATE CASCADE; - --- AddForeignKey -ALTER TABLE "SuscripcionPush" ADD CONSTRAINT "SuscripcionPush_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/migrations/20261026201926_recordatorios_pagos_pendientes/migration.sql b/prisma/migrations/20261026201926_recordatorios_pagos_pendientes/migration.sql deleted file mode 100644 index 68f1075..0000000 --- a/prisma/migrations/20261026201926_recordatorios_pagos_pendientes/migration.sql +++ /dev/null @@ -1,3 +0,0 @@ --- AlterTable -ALTER TABLE "PagoRecurrente" ADD COLUMN "recordatoriosEnviados" INTEGER NOT NULL DEFAULT 0, -ADD COLUMN "ultimoRecordatorioAt" TIMESTAMP(3); diff --git a/prisma/migrations/20261027001210_clientes_puesto_y_nota_de_pago/migration.sql b/prisma/migrations/20261027001210_clientes_puesto_y_nota_de_pago/migration.sql deleted file mode 100644 index 2557df1..0000000 --- a/prisma/migrations/20261027001210_clientes_puesto_y_nota_de_pago/migration.sql +++ /dev/null @@ -1,5 +0,0 @@ --- AlterTable -ALTER TABLE "Cliente" ADD COLUMN "puesto" TEXT; - --- AlterTable -ALTER TABLE "PagoRecurrente" ADD COLUMN "nota" TEXT; diff --git a/prisma/migrations/20261125000000_agent_api_approval_webhooks/migration.sql b/prisma/migrations/20261125000000_agent_api_approval_webhooks/migration.sql deleted file mode 100644 index 4d77830..0000000 --- a/prisma/migrations/20261125000000_agent_api_approval_webhooks/migration.sql +++ /dev/null @@ -1,139 +0,0 @@ --- AlterTable: campos opcionales de aprobacion, envio, cierre y autoria de agente en Cotizacion -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobadaPorId" TEXT; -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobadaAt" TIMESTAMP(3); -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aprobacionMetodo" TEXT; -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaAt" TIMESTAMP(3); -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaPor" TEXT; -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaCanal" TEXT; -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "enviadaDestino" TEXT; -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "aceptadaAt" TIMESTAMP(3); -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "rechazadaAt" TIMESTAMP(3); -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "vencidaAt" TIMESTAMP(3); -ALTER TABLE "Cotizacion" ADD COLUMN IF NOT EXISTS "creadaPorAgente" TEXT; - --- CreateTable: AgentApiKey -CREATE TABLE IF NOT EXISTS "AgentApiKey" ( - "id" TEXT NOT NULL, - "nombre" TEXT NOT NULL, - "prefijo" TEXT NOT NULL, - "keyHash" TEXT NOT NULL, - "scopes" TEXT[], - "rateLimitPerMin" INTEGER NOT NULL DEFAULT 60, - "activo" BOOLEAN NOT NULL DEFAULT true, - "revokedAt" TIMESTAMP(3), - "lastUsedAt" TIMESTAMP(3), - "createdById" TEXT, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "AgentApiKey_pkey" PRIMARY KEY ("id") -); - --- CreateTable: AuditLog -CREATE TABLE IF NOT EXISTS "AuditLog" ( - "id" TEXT NOT NULL, - "actorTipo" TEXT NOT NULL, - "actorId" TEXT, - "actorNombre" TEXT NOT NULL, - "accion" TEXT NOT NULL, - "recursoTipo" TEXT NOT NULL, - "recursoId" TEXT, - "ip" TEXT, - "requestId" TEXT, - "exito" BOOLEAN NOT NULL DEFAULT true, - "detalle" JSONB, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - - CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id") -); - --- CreateTable: ApprovalToken -CREATE TABLE IF NOT EXISTS "ApprovalToken" ( - "id" TEXT NOT NULL, - "cotizacionId" TEXT NOT NULL, - "tokenHash" TEXT NOT NULL, - "expiraAt" TIMESTAMP(3) NOT NULL, - "usadoAt" TIMESTAMP(3), - "usadoIp" TEXT, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - - CONSTRAINT "ApprovalToken_pkey" PRIMARY KEY ("id") -); - --- CreateTable: IdempotencyKey -CREATE TABLE IF NOT EXISTS "IdempotencyKey" ( - "id" TEXT NOT NULL, - "key" TEXT NOT NULL, - "method" TEXT NOT NULL, - "path" TEXT NOT NULL, - "requestHash" TEXT NOT NULL, - "statusCode" INTEGER NOT NULL, - "responseBody" JSONB NOT NULL, - "expiraAt" TIMESTAMP(3) NOT NULL, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - - CONSTRAINT "IdempotencyKey_pkey" PRIMARY KEY ("id") -); - --- CreateTable: WebhookEndpoint -CREATE TABLE IF NOT EXISTS "WebhookEndpoint" ( - "id" TEXT NOT NULL, - "nombre" TEXT NOT NULL, - "url" TEXT NOT NULL, - "secret" TEXT NOT NULL, - "eventos" TEXT[], - "activo" BOOLEAN NOT NULL DEFAULT true, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - "updatedAt" TIMESTAMP(3) NOT NULL, - - CONSTRAINT "WebhookEndpoint_pkey" PRIMARY KEY ("id") -); - --- CreateTable: WebhookDelivery -CREATE TABLE IF NOT EXISTS "WebhookDelivery" ( - "id" TEXT NOT NULL, - "endpointId" TEXT, - "url" TEXT NOT NULL, - "evento" TEXT NOT NULL, - "payload" JSONB NOT NULL, - "statusCode" INTEGER, - "exito" BOOLEAN NOT NULL DEFAULT false, - "intentos" INTEGER NOT NULL DEFAULT 1, - "error" TEXT, - "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, - - CONSTRAINT "WebhookDelivery_pkey" PRIMARY KEY ("id") -); - --- CreateIndex -CREATE UNIQUE INDEX IF NOT EXISTS "AgentApiKey_nombre_key" ON "AgentApiKey"("nombre"); -CREATE UNIQUE INDEX IF NOT EXISTS "AgentApiKey_keyHash_key" ON "AgentApiKey"("keyHash"); - -CREATE INDEX IF NOT EXISTS "AuditLog_createdAt_idx" ON "AuditLog"("createdAt"); -CREATE INDEX IF NOT EXISTS "AuditLog_accion_idx" ON "AuditLog"("accion"); -CREATE INDEX IF NOT EXISTS "AuditLog_recursoTipo_recursoId_idx" ON "AuditLog"("recursoTipo", "recursoId"); -CREATE INDEX IF NOT EXISTS "AuditLog_actorNombre_idx" ON "AuditLog"("actorNombre"); - -CREATE UNIQUE INDEX IF NOT EXISTS "ApprovalToken_tokenHash_key" ON "ApprovalToken"("tokenHash"); -CREATE INDEX IF NOT EXISTS "ApprovalToken_cotizacionId_idx" ON "ApprovalToken"("cotizacionId"); - -CREATE UNIQUE INDEX IF NOT EXISTS "IdempotencyKey_key_key" ON "IdempotencyKey"("key"); -CREATE INDEX IF NOT EXISTS "IdempotencyKey_expiraAt_idx" ON "IdempotencyKey"("expiraAt"); - -CREATE UNIQUE INDEX IF NOT EXISTS "WebhookEndpoint_nombre_key" ON "WebhookEndpoint"("nombre"); - -CREATE INDEX IF NOT EXISTS "WebhookDelivery_evento_idx" ON "WebhookDelivery"("evento"); -CREATE INDEX IF NOT EXISTS "WebhookDelivery_createdAt_idx" ON "WebhookDelivery"("createdAt"); - --- AddForeignKey (idempotent) -DO $$ BEGIN - ALTER TABLE "ApprovalToken" ADD CONSTRAINT "ApprovalToken_cotizacionId_fkey" FOREIGN KEY ("cotizacionId") REFERENCES "Cotizacion"("id") ON DELETE CASCADE ON UPDATE CASCADE; -EXCEPTION - WHEN duplicate_object THEN null; -END $$; - -DO $$ BEGIN - ALTER TABLE "WebhookDelivery" ADD CONSTRAINT "WebhookDelivery_endpointId_fkey" FOREIGN KEY ("endpointId") REFERENCES "WebhookEndpoint"("id") ON DELETE SET NULL ON UPDATE CASCADE; -EXCEPTION - WHEN duplicate_object THEN null; -END $$; diff --git a/prisma/migrations/20261125120000_solo_admin_and_archiving/migration.sql b/prisma/migrations/20261125120000_solo_admin_and_archiving/migration.sql deleted file mode 100644 index 780c1f3..0000000 --- a/prisma/migrations/20261125120000_solo_admin_and_archiving/migration.sql +++ /dev/null @@ -1,23 +0,0 @@ --- Migracion aditiva: soloAdmin en ServicioCatalogo (oculto para bots) y archivo reversible en Cliente y Cotizacion - -ALTER TABLE "ServicioCatalogo" - ADD COLUMN IF NOT EXISTS "soloAdmin" BOOLEAN NOT NULL DEFAULT false; - --- Marcar planes/servicios de Bucefalo CRM como soloAdmin = true (visibles solo en web admin, ocultos a agentes) -UPDATE "ServicioCatalogo" -SET "soloAdmin" = true -WHERE id IN ('configuracion-y-puesta-en-marc-12', 'plan-mensual-crm-bucefalo-18') - OR LOWER(nombre) LIKE '%bucefalo%' - OR LOWER(nombre) LIKE '%bucéfalo%'; - -ALTER TABLE "Cliente" - ADD COLUMN IF NOT EXISTS "archivado" BOOLEAN NOT NULL DEFAULT false, - ADD COLUMN IF NOT EXISTS "archivadoAt" TIMESTAMP(3); - -CREATE INDEX IF NOT EXISTS "Cliente_archivado_idx" ON "Cliente"("archivado"); - -ALTER TABLE "Cotizacion" - ADD COLUMN IF NOT EXISTS "archivado" BOOLEAN NOT NULL DEFAULT false, - ADD COLUMN IF NOT EXISTS "archivadoAt" TIMESTAMP(3); - -CREATE INDEX IF NOT EXISTS "Cotizacion_archivado_idx" ON "Cotizacion"("archivado"); diff --git a/prisma/migrations/20261125160000_pago_vencido_notificado_at/migration.sql b/prisma/migrations/20261125160000_pago_vencido_notificado_at/migration.sql deleted file mode 100644 index 9f74d53..0000000 --- a/prisma/migrations/20261125160000_pago_vencido_notificado_at/migration.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Additive idempotency stamp for pago.vencido webhook emission -ALTER TABLE "PagoRecurrente" ADD COLUMN IF NOT EXISTS "vencidoNotificadoAt" TIMESTAMP(3); -CREATE INDEX IF NOT EXISTS "PagoRecurrente_vencidoNotificadoAt_idx" ON "PagoRecurrente"("vencidoNotificadoAt"); diff --git a/prisma/migrations/migration_lock.toml b/prisma/migrations/migration_lock.toml deleted file mode 100644 index 044d57c..0000000 --- a/prisma/migrations/migration_lock.toml +++ /dev/null @@ -1,3 +0,0 @@ -# Please do not edit this file manually -# It should be added in your version-control system (e.g., Git) -provider = "postgresql" diff --git a/prisma/schema.prisma b/prisma/schema.prisma deleted file mode 100644 index 11f0cda..0000000 --- a/prisma/schema.prisma +++ /dev/null @@ -1,505 +0,0 @@ -generator client { - provider = "prisma-client" - output = "../src/generated/prisma" -} - -datasource db { - provider = "postgresql" -} - -model User { - id String @id @default(cuid()) - email String @unique - password String - name String - // "admin" | "asesor" | "cliente". Un usuario con role="cliente" DEBE tener - // clienteId: su sesion da acceso unicamente al panel /cliente de ese Cliente. - role String @default("asesor") - clienteId String? @unique - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - cotizaciones Cotizacion[] @relation("AsesorCotizaciones") - cliente Cliente? @relation("ClienteUsuario", fields: [clienteId], references: [id]) - suscripcionesPush SuscripcionPush[] -} - -model Cliente { - id String @id @default(cuid()) - nombre String - empresa String? - // Cargo de la persona de contacto (ej. "Director"). Solo informativo. - puesto String? - email String? - telefono String? - rfc String? - archivado Boolean @default(false) - archivadoAt DateTime? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - cotizaciones Cotizacion[] - // Cuenta de acceso al panel de cliente (role="cliente"). Una por cliente. - usuario User? @relation("ClienteUsuario") - programasPago ProgramaPago[] - - @@index([nombre, empresa]) - @@index([archivado]) -} - -model Cotizacion { - id String @id @default(cuid()) - numero String @unique - fecha DateTime @default(now()) - vigencia DateTime - moneda String @default("MXN") - tipoCambio String @default("NA") - proyecto String @default("MKT Digital") - esquemaPago String @default("Pago Unico/Mensual") - estado String @default("borrador") - incluirBonos Boolean @default(false) - incluirFinanciamiento Boolean @default(false) - incluirIva Boolean @default(true) - esDoble Boolean @default(false) - opcionesMetadata Json? - // Texto que SI ve el cliente: se imprime en el PDF y en el Excel. - observaciones String? - // Contexto de discovery, notas del asesor, riesgos. NO sale de la app: ningun - // exportador declara este campo en su interfaz de datos (CotizacionPDFData / - // ExcelData) y la herramienta MCP obtener_cotizacion usa lista blanca de - // columnas. La garantia es estructural, no depende de recordar filtrarlo. - observacionesInternas String? - clienteId String - asesorId String - aprobadaPorId String? - aprobadaAt DateTime? - aprobacionMetodo String? - enviadaAt DateTime? - enviadaPor String? - enviadaCanal String? - enviadaDestino String? - aceptadaAt DateTime? - rechazadaAt DateTime? - vencidaAt DateTime? - creadaPorAgente String? - archivado Boolean @default(false) - archivadoAt DateTime? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - cliente Cliente @relation(fields: [clienteId], references: [id]) - asesor User @relation("AsesorCotizaciones", fields: [asesorId], references: [id]) - servicios ServicioCotizado[] - planBucefalo PlanBucefaloCotizacion? - registrosHoras RegistroHoras[] - propuestasIA PropuestaIA[] - programasPago ProgramaPago[] - approvalTokens ApprovalToken[] - - @@index([clienteId]) - @@index([asesorId]) - @@index([estado]) - @@index([archivado]) - @@index([createdAt]) -} - -model Categoria { - id String @id @default(cuid()) - nombre String @unique - descripcion String? - color String @default("#6b7280") - activo Boolean @default(true) - orden Int @default(0) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - servicios ServicioCatalogo[] -} - -model Paquete { - id String @id @default(cuid()) - nombre String - descripcion String? - activo Boolean @default(true) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - fases FasePaquete[] -} - -model FasePaquete { - id String @id @default(cuid()) - paqueteId String - nombre String - orden Int @default(0) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - paquete Paquete @relation(fields: [paqueteId], references: [id], onDelete: Cascade) - servicios ServicioPaquete[] - - @@index([paqueteId]) -} - -model ServicioCatalogo { - id String @id @default(cuid()) - nombre String - descripcion String? - fase Int @default(1) - tipoPago String @default("unico") - precioBase Float - tiempoEntrega String @default("4 - 10 dias") - entregablesDefault Json @default("[]") - categoriaId String? - variante String? - nivel String? - activo Boolean @default(true) - // Si es true, queda oculto para todas las claves de agentes/bots y solo puede - // agregarlo un administrador humano desde la web (p. ej. planes de Bucefalo CRM). - soloAdmin Boolean @default(false) - orden Int @default(0) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - servicios ServicioCotizado[] - categoriaRel Categoria? @relation(fields: [categoriaId], references: [id]) - paquetes ServicioPaquete[] - - @@index([categoriaId]) - @@index([activo, fase, orden]) -} - -model ServicioPaquete { - id String @id @default(cuid()) - servicioCatalogoId String - fasePaqueteId String - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - servicio ServicioCatalogo @relation(fields: [servicioCatalogoId], references: [id], onDelete: Cascade) - fasePaquete FasePaquete @relation(fields: [fasePaqueteId], references: [id], onDelete: Cascade) - - @@unique([servicioCatalogoId, fasePaqueteId]) - @@index([fasePaqueteId]) -} - -model ServicioCotizado { - id String @id @default(cuid()) - cotizacionId String - servicioCatalogoId String? - nombre String? - esPersonalizado Boolean @default(false) - horas Float? - tarifaHora Float? - modeloCobro String @default("fijo") - montoMinimo Float? - horasIncluidas Float? - opcion String? - fase Int - tipoPago String - precio Float - tiempoEntrega String - entregables Json @default("[]") - beneficios Json @default("[]") - notas String? - seleccionado Boolean @default(true) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - cotizacion Cotizacion @relation(fields: [cotizacionId], references: [id], onDelete: Cascade) - servicioCatalogo ServicioCatalogo? @relation(fields: [servicioCatalogoId], references: [id]) - - @@index([cotizacionId]) - @@index([servicioCatalogoId]) -} - -model PlanBucefaloCotizacion { - id String @id @default(cuid()) - cotizacionId String @unique - nivel String @default("basico") - precio Float - seleccionado Boolean @default(true) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - cotizacion Cotizacion @relation(fields: [cotizacionId], references: [id], onDelete: Cascade) -} - -// Registro de horas trabajadas contra una cotizacion aprobada con cobro por tiempo -// (modeloCobro horas/retainer/demanda). Se usa para emitir notas de pago al cliente: -// cada entrada es un dia con un rango horario, una descripcion breve y una tarifa -// (snapshot). `horas` se calcula del rango (calcularHorasRango) y se persiste. -model RegistroHoras { - id String @id @default(cuid()) - cotizacionId String - fecha DateTime - horaInicio String - horaFin String - horas Float - tarifaHora Float @default(0) - descripcion String - // Estado de cobro de la partida de horas: "por_pagar" (default) o "pagada". - // Permite separar lo pendiente (nota por pagar al cliente) de lo ya cobrado - // (recibo/historial) sin que los totales se mezclen. fechaPago = cuando se marco pagada. - estadoPago String @default("por_pagar") - fechaPago DateTime? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - cotizacion Cotizacion @relation(fields: [cotizacionId], references: [id], onDelete: Cascade) - - @@index([cotizacionId]) - @@index([fecha]) - @@index([estadoPago]) -} - -// Documento consultivo generado por IA a partir del contexto humano de la cotizacion. -// Se guarda por separado lo que produjo el modelo y lo que edito el asesor, para poder -// mostrar que cambio y para no perder el original al editar. -model PropuestaIA { - id String @id @default(cuid()) - cotizacionId String - estado String @default("borrador") // borrador | aprobada - contenidoIA Json - contenidoEditado Json? - // Transcripcion sanitizada usada al generar. Sin esto, el PATCH revalida con - // fuentes incompletas y R3 no puede comprobar que la cita destacada sea literal. - transcripcion String? - // Traza de la generacion: modelo, intentos por paso, tokens y aciertos de cache. - traza Json? - // Hallazgos de validacion y de contenido que el asesor debe revisar antes de enviar. - avisos Json @default("[]") - modelo String - aprobadaPor String? - aprobadaAt DateTime? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - cotizacion Cotizacion @relation(fields: [cotizacionId], references: [id], onDelete: Cascade) - - @@index([cotizacionId]) -} - -model Configuracion { - id String @id @default(cuid()) - clave String @unique - valor String - updatedAt DateTime @updatedAt -} - -model Bono { - id String @id @default(cuid()) - numero Int - titulo String - descripcion String - activo Boolean @default(true) -} - -model FinanciamientoPlan { - id String @id @default(cuid()) - meses Int @unique - tasa Float - comision Float - montoMinimo Float - iva Float @default(0.16) -} - -// Programa de cobros recurrentes configurado por el administrador. -// Ejemplo real: Instituto Santiago Tapia — cada sabado se genera un cobro de $750 -// por la administracion web. La generacion es idempotente: un PagoRecurrente por -// (programaId, fecha), calculado desde fechaInicio con la cadencia. -model ProgramaPago { - id String @id @default(cuid()) - clienteId String - // Vinculo opcional con la cotizacion que origina el servicio recurrente. - cotizacionId String? - concepto String - monto Float - moneda String @default("MXN") - // "semanal" | "quincenal" | "mensual" - frecuencia String @default("semanal") - // Dia de la semana 0=domingo..6=sabado (requerido si frecuencia=semanal). - diaSemana Int? - // Dia del mes 1..31 (requerido si frecuencia=mensual; quincenal usa dia 1 y 15). - diaMes Int? - fechaInicio DateTime - fechaFin DateTime? - activo Boolean @default(true) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - cliente Cliente @relation(fields: [clienteId], references: [id], onDelete: Cascade) - cotizacion Cotizacion? @relation(fields: [cotizacionId], references: [id], onDelete: SetNull) - pagos PagoRecurrente[] - - @@index([clienteId]) - @@index([activo]) -} - -// Un cobro generado para un periodo concreto (ej. sabado 2026-07-04). -// estados: pendiente (sin comprobante) | en_revision (comprobante subido, -// esperando admin) | verificado (admin aprobo, o registro el pago a mano) | -// rechazado (admin rechazo y borro el archivo; el cliente puede volver a subir) | -// anulado (el admin lo dejo sin cargo; no cuenta como adeudo). -model PagoRecurrente { - id String @id @default(cuid()) - programaId String - // Fecha del periodo (medianoche America/Mexico_City al momento de generar). - fecha DateTime - monto Float - estado String @default("pendiente") - // Fecha en que el admin valido el comprobante (estado=verificado). - verificadoAt DateTime? - rechazadoAt DateTime? - rechazoMotivo String? - // Ultimo recordatorio de pago enviado al cliente mientras el cobro sigue - // por pagar (pendiente/rechazado). El scheduler lo usa para no repetir el - // aviso antes de COBROS_RECORDATORIO_DIAS; el envio manual lo ignora. - ultimoRecordatorioAt DateTime? - recordatoriosEnviados Int @default(0) - // Sello idempotente para el webhook pago.vencido: se escribe atomicamente la - // primera vez que el cobro se notifica como vencido (1 evento por cobro). - vencidoNotificadoAt DateTime? - // Nota interna del admin (no la ve el cliente): forma de pago o abonos al - // registrar un pago manual, o el motivo al anular un cobro. - nota String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - programa ProgramaPago @relation(fields: [programaId], references: [id], onDelete: Cascade) - comprobante ComprobantePago? - - @@unique([programaId, fecha]) - @@index([estado]) - @@index([fecha]) - @@index([vencidoNotificadoAt]) -} - -// Comprobante de pago subido por el cliente (imagen o PDF). El archivo vive en -// UPLOAD_DIR/comprobantes/ y se sirve solo por un route handler autenticado -// (nunca desde /public). Al rechazar, el admin borra el archivo del servidor -// y se elimina este registro; el cliente vuelve a "pendiente". -model ComprobantePago { - id String @id @default(cuid()) - pagoId String @unique - archivoRuta String // relativa a UPLOAD_DIR, ej. "comprobantes//.webp" - archivoNombre String // nombre original que vio el cliente - mime String // image/webp | application/pdf - tamano Int // bytes finales en disco - subidoAt DateTime @default(now()) - - pago PagoRecurrente @relation(fields: [pagoId], references: [id], onDelete: Cascade) -} - -// Suscripcion Web Push del navegador del cliente (endpoint VAPID + claves p256dh/auth). -model SuscripcionPush { - id String @id @default(cuid()) - userId String - endpoint String @unique - p256dh String - auth String - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - usuario User @relation(fields: [userId], references: [id], onDelete: Cascade) - - @@index([userId]) -} - -// ============================================================================ -// API para Agentes, Auditoria, Aprobacion, Idempotencia y Webhooks -// ============================================================================ - -model AgentApiKey { - id String @id @default(cuid()) - nombre String @unique - prefijo String - keyHash String @unique - scopes String[] - rateLimitPerMin Int @default(60) - activo Boolean @default(true) - revokedAt DateTime? - lastUsedAt DateTime? - createdById String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt -} - -model AuditLog { - id String @id @default(cuid()) - actorTipo String - actorId String? - actorNombre String - accion String - recursoTipo String - recursoId String? - ip String? - requestId String? - exito Boolean @default(true) - detalle Json? - createdAt DateTime @default(now()) - - @@index([createdAt]) - @@index([accion]) - @@index([recursoTipo, recursoId]) - @@index([actorNombre]) -} - -model ApprovalToken { - id String @id @default(cuid()) - cotizacionId String - tokenHash String @unique - expiraAt DateTime - usadoAt DateTime? - usadoIp String? - createdAt DateTime @default(now()) - - cotizacion Cotizacion @relation(fields: [cotizacionId], references: [id], onDelete: Cascade) - - @@index([cotizacionId]) -} - -model IdempotencyKey { - id String @id @default(cuid()) - key String @unique - method String - path String - requestHash String - statusCode Int - responseBody Json - expiraAt DateTime - createdAt DateTime @default(now()) - - @@index([expiraAt]) -} - -model WebhookEndpoint { - id String @id @default(cuid()) - nombre String @unique - url String - secret String - eventos String[] - activo Boolean @default(true) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - entregas WebhookDelivery[] -} - -model WebhookDelivery { - id String @id @default(cuid()) - endpointId String? - url String - evento String - payload Json - statusCode Int? - exito Boolean @default(false) - intentos Int @default(1) - error String? - createdAt DateTime @default(now()) - - endpoint WebhookEndpoint? @relation(fields: [endpointId], references: [id], onDelete: SetNull) - - @@index([evento]) - @@index([createdAt]) -} diff --git a/prisma/seed.ts b/prisma/seed.ts deleted file mode 100644 index ae16122..0000000 --- a/prisma/seed.ts +++ /dev/null @@ -1,2046 +0,0 @@ -import { PrismaClient } from "../src/generated/prisma/client"; -import { PrismaPg } from "@prisma/adapter-pg"; -import { hash } from "bcryptjs"; - -const adapter = new PrismaPg({ - host: process.env.DB_HOST || "localhost", - port: parseInt(process.env.DB_PORT || "5432"), - user: process.env.DB_USER || "postgres", - password: process.env.DB_PASSWORD || "postgres", - // Se conserva el nombre fisico de BD en produccion para no romper el volumen postgres_data. - database: process.env.DB_DATABASE || process.env.DB_NAME || "cotizador_e3", -}); -const prisma = new PrismaClient({ adapter }); - -async function main() { - console.log("Seeding database..."); - - // Credentials come from env. Without SEED_*_PASSWORD the user is created - // with a default password only if it doesn't exist yet (never overwritten). - const adminEmail = process.env.SEED_ADMIN_EMAIL || "admin@urieljareth.com"; - const adminPassword = process.env.SEED_ADMIN_PASSWORD; - if (!adminPassword) { - console.warn( - ` AVISO: SEED_ADMIN_PASSWORD no definida. Si el usuario ${adminEmail} no existe, se creará con password "admin123" — cámbiala de inmediato.` - ); - } - const adminHash = await hash(adminPassword || "admin123", 10); - - await prisma.user.upsert({ - where: { email: adminEmail }, - update: adminPassword ? { password: adminHash } : {}, - create: { - email: adminEmail, - password: adminHash, - name: process.env.SEED_ADMIN_NAME || "Administrador", - role: "admin", - }, - }); - - const asesorEmail = process.env.SEED_ASESOR_EMAIL; - if (asesorEmail) { - const asesorPassword = process.env.SEED_ASESOR_PASSWORD; - const asesorHash = await hash(asesorPassword || "asesor123", 10); - await prisma.user.upsert({ - where: { email: asesorEmail }, - update: asesorPassword ? { password: asesorHash } : {}, - create: { - email: asesorEmail, - password: asesorHash, - name: process.env.SEED_ASESOR_NAME || "Asesor", - role: "asesor", - }, - }); - } - - // ── CATEGORIAS (must be created BEFORE servicios for FK) ── - const categorias = [ - { nombre: "SEO", descripcion: "Optimizacion para motores de busqueda", color: "#10b981", orden: 1 }, - { nombre: "Marketing", descripcion: "Estrategia y marketing digital", color: "#6366f1", orden: 2 }, - { nombre: "Paid Media", descripcion: "Publicidad pagada en plataformas digitales", color: "#f59e0b", orden: 3 }, - { nombre: "Desarrollo Web", descripcion: "Diseno y desarrollo de sitios web y ecommerce", color: "#3b82f6", orden: 4 }, - { nombre: "Automatizaciones", descripcion: "Automatizacion de procesos y flujos de trabajo", color: "#8b5cf6", orden: 5 }, - { nombre: "CRM", descripcion: "Gestion de relaciones con clientes", color: "#ec4899", orden: 6 }, - { nombre: "Desarrollo Personalizado", descripcion: "Soluciones a medida y desarrollo custom", color: "#14b8a6", orden: 7 }, - ]; - - const catMap: Record = {}; - for (const cat of categorias) { - const created = await prisma.categoria.upsert({ - where: { nombre: cat.nombre }, - update: { color: cat.color, orden: cat.orden }, - create: cat, - }); - catMap[cat.nombre] = created.id; - } - - const catAlias: Record = { - auditoria: "Marketing", - estrategia: "Marketing", - diseno: "Desarrollo Web", - sitio_web: "Desarrollo Web", - ecommerce: "Desarrollo Web", - ads: "Paid Media", - redes: "Marketing", - seo: "SEO", - contenido: "Marketing", - crm: "CRM", - acompanamiento: "Marketing", - otros: "Desarrollo Personalizado", - }; - - const servicios = [ - { - nombre: "Auditoria en Redes Sociales", - descripcion: "Auditoria completa de presencia en redes sociales", - fase: 0, - tipoPago: "unico", - precioBase: 2990, - tiempoEntrega: "4 - 10 dias", - categoria: "auditoria", - orden: 1, - entregablesDefault: [ - "Revision de presencia en redes sociales", - "Analisis de contenido publicado", - "Evaluacion de engagement", - "Documento de Evaluacion Total de Auditoria", - "Junta de Resultados", - ], - }, - { - nombre: "Auditoria en Sitio Web", - descripcion: "Auditoria tecnica y de rendimiento de sitio web", - fase: 0, - tipoPago: "unico", - precioBase: 2990, - tiempoEntrega: "4 - 10 dias", - categoria: "auditoria", - orden: 2, - entregablesDefault: [ - "Seguridad de dominio (vulnerabilidades)", - "Velocidad de sitio web (core web vital)", - "Diseno responsivo", - "Performance del sitio", - "Revison de SEO On Page y Off Page", - "Chequeo de listado del sitio en listas negras", - "Chequeo de Malware y Codigo Malicioso", - "Revision de Firewall en el Sitio", - "Recomendaciones SEO", - "Revision de Google Search Console", - "Revision de pixeles de Google y FB Ads", - "Documento de Evaluacion Total de Auditoria", - "Junta de Resultados", - ], - }, - { - nombre: "Auditoria en Ecommerce", - descripcion: "Auditoria completa de tienda en linea", - fase: 0, - tipoPago: "unico", - precioBase: 2990, - tiempoEntrega: "4 - 10 dias", - categoria: "auditoria", - orden: 3, - entregablesDefault: [ - "Revision de Seguridad de dominio", - "Revision de Certificado SSL", - "Revision de Metodos de Pago", - "Revision de Metodos de Envio", - "Revision de Velocidad de Sitio Web", - "Revision de Categorizacion de Productos", - "Revision de Filtrado de Productos", - "Revision de Carritos Abandonados", - "Revision de Correos Transaccionales", - "Revision de Pasos de Checkout", - "Documento de Evaluacion Total de Auditoria", - "Junta de Resultados", - ], - }, - { - nombre: "Auditoria de cuentas Google Ads y Meta Ads", - descripcion: "Auditoria de cuentas publicitarias", - fase: 0, - tipoPago: "unico", - precioBase: 2990, - tiempoEntrega: "4 - 10 dias", - categoria: "auditoria", - orden: 4, - entregablesDefault: [ - "Revision de Configuracion General de Google Ads", - "Revision de Configuracion de Facebook/Instagram Ads", - "Revision de la Segmentacion de Publicos Personalizados", - "Revision de Configuracion de Campanas", - "Revision de Configuracion de Grupo de Anuncios", - "Revision de Conversiones y Eventos Personalizados", - "Revision de Integracion e Implementacion de Pixeles", - "Revision de Estrategia de Presupuesto", - "Revision de Anuncios Graficos", - "Revision de Extensiones en los Anuncios", - "Documento de Evaluacion Total de Auditoria", - "Junta de Resultados", - ], - }, - { - nombre: "Estudio Digital de Mercado", - descripcion: "Estudio completo de mercado digital", - fase: 1, - tipoPago: "unico", - precioBase: 4900, - tiempoEntrega: "4 - 10 dias", - categoria: "estrategia", - orden: 5, - entregablesDefault: [ - "Estudio de Competencia Organica", - "Estudio de Competencia Pagada", - "Estudio de Demanda", - "Estudio de Tendencia", - "Estudio de Segmentacion de Mercado", - "Junta de Analisis de Resultados y Conclusiones", - ], - }, - { - nombre: "Diseno de Identidad Corporativa", - descripcion: "Creacion de identidad corporativa completa", - fase: 1, - tipoPago: "unico", - precioBase: 11900, - tiempoEntrega: "7 - 15 dias", - categoria: "diseno", - orden: 6, - entregablesDefault: [ - "Creacion de Logotipo y Favicon", - "Manual de Identidad Corporativa (colores, tipografias, usos)", - "Plantillas para Redes Sociales (posts, historias, carruseles)", - "Plantilla para portada de Redes Sociales", - "Entrega de archivos editables", - "Entrega de Mockups", - "Aplicativos Digitales (firma electronica, diapositivas, wallpaper)", - "Aplicativos Fisicos (tarjetas, hojas membretadas)", - "Presentacion de Propuestas", - "Tres juntas de revision", - ], - }, - { - nombre: "Diseno de Sitio Web (WordPress)", - descripcion: "Diseno y desarrollo de sitio web en WordPress", - fase: 1, - tipoPago: "unico", - precioBase: 35000, - tiempoEntrega: "4 - 8 semanas", - categoria: "sitio_web", - variante: "wordpress", - orden: 7, - entregablesDefault: [ - "Desarrollo y Estructuracion Jerarquica de Sitio Web", - "Creacion de Paginas Basicas (TyC, PyP, Gracias, 404)", - "Optimizacion Avanzada SEO en cada Pagina", - "Sitio adaptado a ordenadores, tabletas y celulares (responsive)", - "Configuracion Avanzada de Velocidad de Carga", - "Diseno y Optimizacion de elementos graficos", - "Integracion y Configuracion de Contacto por WhatsApp y Llamada", - "Configuracion de Plugins de Seguridad", - "Capacitacion Basica de Sitio", - "Poliza de mantenimiento", - "Respaldo de seguridad semanal", - "Creacion y Optimizacion de Blog optimizado para SEO", - "Integracion de Formulario", - "Documento Estadisticas de Sitio Web (mensual)", - "Indexacion en Motores de Busqueda", - "Configuracion de Google Analytics 4, Tag Manager, Google Ads, Pixel y Capi de Facebook", - "Configuracion de Google Search Console", - "Revision de TyC, Politicas y Privacidad", - "Creacion de Textos Comerciales", - "Soporte de Primer y Segundo Nivel", - "Dominio, Certificado SSL, Hosting Incluido (5GB) - 1 Ano", - "Incluye tres revisiones del Proyecto", - ], - }, - { - nombre: "Diseno de Ecommerce (WooCommerce)", - descripcion: "Tienda en linea con WooCommerce", - fase: 1, - tipoPago: "unico", - precioBase: 19900, - tiempoEntrega: "4 - 8 semanas", - categoria: "ecommerce", - variante: "woocommerce", - orden: 8, - entregablesDefault: [ - "Desarrollo y Estructuracion de Ecommerce", - "Creacion de Paginas Basicas (TyC, PyP, Gracias, 404)", - "Optimizacion Avanzada SEO en cada Pagina de Productos y Categorias", - "Diseno Responsivo (UI / UX)", - "Configuracion Avanzada de Velocidad de Carga", - "Diseno y Optimizacion de elementos graficos para cada Pagina", - "Integracion y Configuracion de Contacto por WhatsApp y Llamada", - "Integracion de Formulario", - "Integracion de Plugins de Seguridad", - "Capacitacion Basica de Sitio", - "Integracion de Metodos de Pago", - "Integracion de Metodos de Envio", - "Configuracion Jerarquica de Categoria por Nivel", - "Configuracion de Enlazado de Categorias", - "Configuracion de Carritos Abandonados", - "Documento Estadisticas de Sitio Web (mensual)", - "Indexacion en Motores de Busqueda", - "Configuracion de Google Analytics 4, Tag Manager, Google Ads, Pixel y Capi de Facebook para Ecommerce", - "Configuracion de Google Search Console", - "Incluye tres revisiones del Proyecto", - "Dominio, Certificado SSL, Hosting Incluido (5GB) - 1 Ano", - "Creacion de Textos Comerciales", - "Desarrollo y Estructuracion de Blog", - ], - }, - { - nombre: "Diseno Tienda en Linea (Shopify)", - descripcion: "Tienda en linea con Shopify", - fase: 1, - tipoPago: "unico", - precioBase: 21900, - tiempoEntrega: "4 - 8 semanas", - categoria: "ecommerce", - variante: "shopify", - orden: 9, - entregablesDefault: [ - "Desarrollo y Estructuracion de Ecommerce", - "Configuracion de Paginas Basicas (TyC, AyP, Contacto, Nosotros, 404)", - "Configuracion de Paginas de Ecommerce (Mi cuenta, Inicio de sesion, Politicas)", - "Configuracion y Personalizacion de Template", - "Optimizacion SEO en cada Pagina de Productos y Categorias", - "Diseno Responsivo (UI / UX)", - "Configuracion de Velocidad de Carga en Sitio Web", - "Diseno y Optimizacion de elementos graficos para cada Pagina", - "Integracion y Configuracion de App de Contacto por WhatsApp", - "Integracion de Apps para Metodos de Pago", - "Integracion de Apps para Metodos de Envio", - "Configuracion y Estructura de Menu Principal", - "Soporte de Primer y Segundo Nivel", - "Creacion de Categorias de Tienda", - "Configuracion de Correos Base para Ecommerce", - "Configuracion de Carritos Abandonados", - "Indexacion en Motores de Busqueda", - "Configuracion de Google Search Console", - "Implementacion de Google Analytics 4", - "Capi y Pixel de Facebook", - "Creacion de Textos Comerciales", - "Capacitacion Basica de Tienda", - "Incluye tres revisiones del Proyecto", - "Dominio", - ], - }, - { - nombre: "Creacion y Optimizacion de Redes Sociales", - descripcion: "Creacion y brandeo de perfiles en redes sociales", - fase: 1, - tipoPago: "unico", - precioBase: 2500, - tiempoEntrega: "4 - 10 dias", - categoria: "redes", - orden: 10, - entregablesDefault: [ - "Creacion de Redes Sociales (Facebook, Instagram)", - "Brandeo de las Redes y Optimizacion", - ], - }, - { - nombre: "Creacion y Optimizacion de la Ficha de Google My Business", - descripcion: "Configuracion y optimizacion de perfil de Google", - fase: 1, - tipoPago: "unico", - precioBase: 2000, - tiempoEntrega: "4 - 10 dias", - categoria: "seo", - orden: 11, - entregablesDefault: [ - "Creacion y Configuracion de Perfil de Negocio de Google", - "Optimizacion de Perfil de Negocio de Google", - "Generacion de Mapas Fractales", - "Plantillas para Publicaciones en Perfil de Negocio", - "Reporte de resultados", - ], - }, - { - nombre: "Configuracion y Puesta en Marcha del CRM Bucefalo", - descripcion: "Configuracion inicial de cuenta CRM Bucefalo", - soloAdmin: true, - fase: 1, - tipoPago: "unico", - precioBase: 3900, - tiempoEntrega: "4 - 10 dias", - categoria: "crm", - orden: 12, - entregablesDefault: [ - "Configuracion de cuenta CRM Bucefalo", - "Curso de Capacitacion", - "Configuracion de Automatizaciones", - "Configuracion de Pipeline de Oportunidades", - "Configuracion de Campos Personalizados", - "Integracion de Calendario", - "Configuracion de Reportes", - ], - }, - { - nombre: "Configuracion, Optimizacion y Puesta en Marcha de Google Ads y Meta Ads", - descripcion: "Setup completo de ambas plataformas publicitarias", - fase: 1, - tipoPago: "unico", - precioBase: 4000, - tiempoEntrega: "4 - 10 dias", - categoria: "ads", - orden: 13, - entregablesDefault: [ - "Configuracion y estructura de las Campanas de Google Ads", - "Configuracion de Conversiones", - "Configuracion de la Segmentacion de Publicos Personalizados", - "Configuracion de listas de terminos de busqueda negativos", - "Configuracion de listas de terminos busqueda", - "Configuracion de Anuncios publicitarios", - "Configuracion de Extensiones en los anuncios", - "Configuracion de Cuenta Facebook Ads e Instagram Ads", - "Configuracion de Pixeles de Conversion", - "Configuracion de Anuncios Publicitarios para Meta", - "Configuracion de Conversiones Personalizadas", - ], - }, - { - nombre: "Tablero de Inspiracion", - descripcion: "Estrategia creativa para campanas publicitarias", - fase: 2, - tipoPago: "unico", - precioBase: 2900, - tiempoEntrega: "6 - 10 dias", - categoria: "estrategia", - orden: 14, - entregablesDefault: [ - "Estrategia Creativa", - "Segmentacion de Mercado", - "Complexogramo", - "Analisis de Competencia", - "Analisis de los mejores Anuncios Locales, Nacionales e Internacionales", - ], - }, - { - nombre: "Configuracion y Optimizacion Google Ads", - descripcion: "Configuracion y optimizacion mensual de Google Ads", - fase: 2, - tipoPago: "mensual", - precioBase: 4900, - tiempoEntrega: "4 - 10 dias", - categoria: "ads", - orden: 15, - entregablesDefault: [ - "Revision de la Segmentacion de Publicos Personalizados", - "Revision de Listas de Terminos de Busqueda Negativos", - "Revision de Listas de Terminos Busqueda", - "Revision de Anuncios Publicitarios", - "Revision de Anuncios Graficos", - "Una Sesion de Acompanamiento para Google", - ], - }, - { - nombre: "Manejo y Optimizacion de Meta Ads", - descripcion: "Manejo y optimizacion mensual de Meta Ads", - fase: 2, - tipoPago: "mensual", - precioBase: 1500, - tiempoEntrega: "4 - 10 dias", - categoria: "ads", - orden: 16, - entregablesDefault: [ - "Revision de la Configuracion de Conversiones", - "Revision de la Segmentacion de Publicos Personalizados", - "Revision de Conversiones Personalizadas", - "Revision de Anuncios Publicitarios", - "Una Sesion de Acompanamiento para la Creacion de Portafolio Comercial / Facebook", - ], - }, - { - nombre: "Manejo Basico de Redes Sociales", - descripcion: "Manejo mensual basico de redes sociales", - fase: 2, - tipoPago: "mensual", - precioBase: 3000, - tiempoEntrega: "4 - 10 dias", - categoria: "redes", - orden: 17, - entregablesDefault: [ - "Realizacion de Parrilla, Diseno y Programacion", - "3 - 5 Post Mensuales", - ], - }, - { - nombre: "Plan Mensual CRM Bucefalo", - descripcion: "Suscripcion mensual al CRM Bucefalo", - soloAdmin: true, - fase: 2, - tipoPago: "mensual", - precioBase: 3900, - tiempoEntrega: "Mensual", - categoria: "crm", - orden: 18, - entregablesDefault: [ - "Uso completo del CRM segun plan contratado", - "Soporte tecnico", - "Actualizaciones del sistema", - ], - }, - { - nombre: "Desarrollo de Plan de Contenido", - descripcion: "Plan estrategico de contenido", - fase: 3, - tipoPago: "unico", - precioBase: 2900, - tiempoEntrega: "6 - 10 dias", - categoria: "contenido", - orden: 19, - entregablesDefault: [ - "Analisis situacional de la marca", - "Objetivos de la marca", - "Analisis de Audiencia y Competencia", - "Estrategias de Contenido", - "Propuesta de Contenido", - "Plan de Acciones", - "Canales de Distribucion", - "Medicion y Metricas", - ], - }, - { - nombre: "Generacion de Contenido", - descripcion: "Generacion mensual de contenido para redes", - fase: 3, - tipoPago: "mensual", - precioBase: 8000, - tiempoEntrega: "Mensual", - categoria: "contenido", - orden: 20, - entregablesDefault: [ - "Manejo de Parrilla Mensual (Facebook, Instagram, Pinterest, YouTube, Tik Tok)", - "Publicaciones Estaticas para Redes Sociales", - "Post para Blog", - "Video YouTube largo, Generacion de Reels, Shorts", - "Escucha Social (analisis de opiniones de clientes)", - "Junta de Reporte mensual", - ], - }, - { - nombre: "Posicionamiento SEO", - descripcion: "Posicionamiento SEO mensual", - fase: 3, - tipoPago: "mensual", - precioBase: 2900, - tiempoEntrega: "4 - 10 dias", - categoria: "seo", - orden: 21, - entregablesDefault: [ - "Posicionamiento de KW (3 palabras clave)", - "Traqueo de las Palabras Clave", - "Creacion de Enlaces Externos al Sitio", - "Citaciones para el Sitio", - "Reporte de resultados (mensual)", - ], - }, - { - nombre: "Estrategia SEO Completa", - descripcion: "Estrategia SEO completa con contenido y backlinks", - fase: 3, - tipoPago: "mensual", - precioBase: 2900, - tiempoEntrega: "Mensual", - categoria: "seo", - orden: 22, - entregablesDefault: [ - "Busqueda y definicion de KW a atacar", - "Definicion de tematica y KW por Mes (calendario semestral)", - "Monitoreo de posiciones en SERPS de KW", - "Busqueda de backlinks de la competencia", - "Gestion con medios y webs para el correcto enlazado", - "Indexacion a Backlinks y monitoreo", - "Generacion de contenido SEO para Post del blog o Landing", - "Generacion de Imagenes y video para ilustracion", - "Generacion de Url (post o Landing) para posicionamiento", - "Optimizacion SEO de todas las Url nuevas", - "Enlazado Interno de todo el sitio web", - "Optimizacion de usabilidad del sitio", - "Optimizacion de Copy", - "Optimizacion de EEAT", - "Optimizacion de enlazado interno", - "Optimizacion de prominencia Semantica", - "Reporte mensual", - ], - }, - { - nombre: "Plan de Acompanamiento Integral", - descripcion: "Servicio integral de acompanamiento estrategico y operativo durante un periodo minimo obligatorio de 9 meses (3 meses operando Uriel Jareth Consulting, 3 operando en conjunto y 3 meses operando en acompanamiento)", - fase: 0, - tipoPago: "mensual", - precioBase: 9000, - tiempoEntrega: "Minimo 9 meses", - categoria: "acompanamiento", - orden: 23, - entregablesDefault: [ - "Manejo de Google Ads (Performance Max, Demand Gen, IA Max for Search)", - "Implementacion con first-party data y third-party data", - "Reportes mensuales con analisis de resultados Google Ads", - "Manejo de Meta Ads (Advantage+, campanas por objetivo, remarketing dinamico)", - "Segmentacion y automatizacion con IA", - "Reportes mensuales con analisis de resultados Meta Ads", - ], - }, - - // ────────────────────────────────────────────────────────────── - // SERVICIOS NIVELADOS (Catalogo Uriel Jareth Consulting - Cotizacion Final) - // Precios convertidos de USD a MXN al tipo de cambio 17.30 - // Niveles: Emprendedor / PYME / Empresario / Corporativo - // ────────────────────────────────────────────────────────────── - - // ── LOGO E IDENTIDAD (Fase 1, unico) ── - { - nombre: "Logo e Identidad", - descripcion: "Diseno de identidad de marca y logotipo", - fase: 1, - tipoPago: "unico", - precioBase: 6903, // 399 USD - tiempoEntrega: "7 - 15 dias", - categoria: "diseno", - nivel: "Emprendedor", - orden: 101, - entregablesDefault: [ - "Investigacion de Tendencias, Mercado, Competencia y Demanda", - "Creacion y Propuesta del Naming: 2", - "Propuesta del Logotipo: 2", - "Creacion Logotipo", - "Diseno de Aplicativos Fisicos: 2", - "Diseno de Aplicativos Digitales: 4", - "Manual de Identidad", - "Atencion y asesoria al cliente", - "Revisiones", - ], - }, - { - nombre: "Logo e Identidad", - descripcion: "Diseno de identidad de marca y logotipo", - fase: 1, - tipoPago: "unico", - precioBase: 12093, // 699 USD - tiempoEntrega: "7 - 15 dias", - categoria: "diseno", - nivel: "PYME", - orden: 102, - entregablesDefault: [ - "Investigacion de Tendencias, Mercado, Competencia y Demanda", - "Creacion y Propuesta del Naming: 3", - "Propuesta del Logotipo: 3", - "Creacion Logotipo", - "Aplicativos Fisicos: 4", - "Aplicativos Digitales: 4", - "Manual de Identidad", - "Atencion y asesoria al cliente", - "Revisiones", - "Kit Basico para Redes Sociales (1 portada, 1 foto de perfil, 1 template RSS)", - ], - }, - { - nombre: "Logo e Identidad", - descripcion: "Diseno de identidad de marca y logotipo", - fase: 1, - tipoPago: "unico", - precioBase: 17283, // 999 USD - tiempoEntrega: "7 - 15 dias", - categoria: "diseno", - nivel: "Empresario", - orden: 103, - entregablesDefault: [ - "Investigacion de Tendencias, Mercado, Competencia y Demanda", - "Creacion y Propuesta del Naming: 4", - "Propuesta del Logotipo: 4", - "Creacion Logotipo", - "Aplicativos Fisicos: 6", - "Aplicativos Digitales: 4", - "Manual de Identidad", - "Atencion y asesoria al cliente", - "Revisiones", - "Kit Basico para Redes Sociales (1 portada, 1 foto de perfil, 4 templates RSS)", - ], - }, - { - nombre: "Logo e Identidad", - descripcion: "Diseno de identidad de marca y logotipo", - fase: 1, - tipoPago: "unico", - precioBase: 42368, // 2449 USD - tiempoEntrega: "10 - 20 dias", - categoria: "diseno", - nivel: "Corporativo", - orden: 104, - entregablesDefault: [ - "Investigacion de Tendencias, Mercado, Competencia y Demanda", - "Creacion y Propuesta del Naming: 5", - "Propuesta del Logotipo: 5", - "Creacion Logotipo", - "Aplicativos Fisicos: 10", - "Aplicativos Digitales: 4", - "Manual de Identidad", - "Atencion y asesoria al cliente", - "Revisiones", - "Kit Basico para Redes Sociales (3 portadas, 1 foto de perfil, 6 templates RSS)", - "Iconografia", - "Registro del IMPI (10 anos)", - ], - }, - - // ── PAGINA WEB (Fase 1, unico) ── - { - nombre: "Pagina Web", - descripcion: "Creacion, configuracion y optimizacion de sitio web", - fase: 1, - tipoPago: "unico", - precioBase: 7768, // 449 USD - tiempoEntrega: "15 - 30 dias", - categoria: "sitio_web", - nivel: "Emprendedor", - orden: 111, - entregablesDefault: [ - "Propuesta de Diseno: 2", - "Creacion, Configuracion y Optimizacion de Sitio Web", - "Configuracion de Chat en Sitio Web", - "Optimizacion Basico SEO", - "Optimizacion basica de Velocidad de Carga", - "Estadisticas de Sitio Web (mensual)", - "Cambios de Informacion al Mes (No Acumulable): 1", - "Capacitacion basica para Manejo de Sitio Web", - "Reuniones de Trabajo", - "Alta en Buscadores", - "Cuentas de E-mail con Dominio", - "Paginas base (Gracias/Politicas/Terminos/Contacto/Nosotros/404)", - "Diseno Responsivo", - "Integracion de Formulario", - "Espacio 12 GB", - "Certificado Seguridad SSL (1 ano)", - "Integracion de Hosting (1 ano)", - "Asesoria y Adquisicion de Dominio (1 ano)", - ], - }, - { - nombre: "Pagina Web", - descripcion: "Creacion, configuracion y optimizacion de sitio web", - fase: 1, - tipoPago: "unico", - precioBase: 13996, // 809 USD - tiempoEntrega: "15 - 30 dias", - categoria: "sitio_web", - nivel: "PYME", - orden: 112, - entregablesDefault: [ - "Propuesta de Diseno: 4", - "Creacion, Configuracion y Optimizacion de Sitio Web", - "Configuracion de Chat en Sitio Web", - "Optimizacion Basico SEO", - "Optimizacion basica de Velocidad de Carga", - "Estadisticas de Sitio Web (mensual)", - "Cambios de Informacion al Mes (No Acumulable): 2", - "Capacitacion basica para Manejo de Sitio Web", - "Reuniones de Trabajo", - "Alta en Buscadores", - "Cuentas de E-mail con Dominio", - "Paginas base (Gracias/Politicas/Terminos/Contacto/Nosotros/404)", - "Diseno Responsivo", - "Integracion de Formulario", - "Espacio 12 GB", - "Certificado Seguridad SSL (1 ano)", - "Integracion de Hosting (1 ano)", - "Asesoria y Adquisicion de Dominio (1 ano)", - ], - }, - { - nombre: "Pagina Web", - descripcion: "Creacion, configuracion y optimizacion de sitio web", - fase: 1, - tipoPago: "unico", - precioBase: 21781, // 1259 USD - tiempoEntrega: "20 - 35 dias", - categoria: "sitio_web", - nivel: "Empresario", - orden: 113, - entregablesDefault: [ - "Propuesta de Diseno: 6", - "Creacion, Configuracion y Optimizacion de Sitio Web", - "Configuracion de Chat en Sitio Web", - "Optimizacion Basico SEO", - "Optimizacion basica de Velocidad de Carga", - "Estadisticas de Sitio Web (mensual)", - "Cambios de Informacion al Mes (No Acumulable): 3", - "Investigacion Tendencias, Mercado, Competencia y Demanda", - "Capacitacion basica para Manejo de Sitio Web", - "Reuniones de Trabajo", - "Alta en Buscadores", - "Cuentas de E-mail con Dominio", - "Paginas base (Gracias/Politicas/Terminos/Contacto/Nosotros/404)", - "Diseno Responsivo", - "Integracion de Formulario", - "Espacio 12 GB", - "Integracion Base de Datos para Correo", - "Certificado Seguridad SSL (1 ano)", - "Integracion de Hosting (1 ano)", - "Asesoria y Adquisicion de Dominio (1 ano)", - ], - }, - { - nombre: "Pagina Web", - descripcion: "Creacion, configuracion y optimizacion de sitio web", - fase: 1, - tipoPago: "unico", - precioBase: 39254, // 2269 USD - tiempoEntrega: "25 - 45 dias", - categoria: "sitio_web", - nivel: "Corporativo", - orden: 114, - entregablesDefault: [ - "Propuesta de Diseno: 8", - "Creacion, Configuracion y Optimizacion de Sitio Web", - "Configuracion de Chat en Sitio Web", - "Optimizacion Avanzado SEO", - "Optimizacion Avanzado de Velocidad de Carga", - "Optimizacion SEO Local", - "Estadisticas de Sitio Web (mensual)", - "Cambios de Informacion al Mes (No Acumulable): 5", - "Investigacion Tendencias, Mercado, Competencia y Demanda", - "Escritura Comercial", - "Capacitacion basica para Manejo de Sitio Web", - "Reuniones de Trabajo", - "Alta en Buscadores", - "Cuentas de E-mail con Dominio", - "Paginas base (incluye Bolsa de Trabajo)", - "Diseno Responsivo", - "Integracion de Formulario", - "Espacio 12 GB", - "Integracion Base de Datos para Correo", - "Certificado Seguridad SSL (1 ano)", - "Integracion de Hosting (1 ano)", - "Asesoria y Adquisicion de Dominio (1 ano)", - "Integracion CRM", - ], - }, - - // ── TIENDA EN LINEA (Fase 1, unico) ── (hoja "Tienda en linea") - { - nombre: "Tienda en Linea", - descripcion: "Desarrollo de tienda en linea (Magento, Shopify, WordPress)", - fase: 1, - tipoPago: "unico", - precioBase: 17283, // 999 USD - tiempoEntrega: "20 - 40 dias", - categoria: "ecommerce", - nivel: "Emprendedor", - orden: 121, - entregablesDefault: [ - "Configuracion en Tienda en Linea (Magento, Shopify, WordPress)", - "Eleccion de plantilla y Estructura de diseno (UX, UI)", - "Desarrollo y Estructura de tienda Optimizada para SEO", - "Creacion y Configuracion de Categorias", - "Diseno y Configuracion de Blog", - "Carga de Productos: 100", - "Capacitacion", - "Atencion y asesoria al cliente", - "Certificado Seguridad SSL (1 ano)", - "Integracion de Hosting (1 ano)", - "Asesoria y Adquisicion de Dominio (1 ano)", - "Integracion de metodos de pago", - "Integracion de metodos de envio", - "Integracion de Chat", - "Integracion y Configuracion de Google Analytics", - "Integracion y Configuracion de Search Console", - ], - }, - { - nombre: "Tienda en Linea", - descripcion: "Desarrollo de tienda en linea (Magento, Shopify, WordPress)", - fase: 1, - tipoPago: "unico", - precioBase: 26106, // 1509 USD - tiempoEntrega: "25 - 45 dias", - categoria: "ecommerce", - nivel: "PYME", - orden: 122, - entregablesDefault: [ - "Configuracion en Tienda en Linea (Magento, Shopify, WordPress)", - "Eleccion de plantilla y Estructura de diseno (UX, UI)", - "Desarrollo y Estructura de tienda Optimizada para SEO", - "Creacion y Configuracion de Categorias", - "Diseno y Configuracion de Blog", - "Carga de Productos: 250", - "Configuracion de productos seleccionados y recomendados (upsell, cross selling)", - "Capacitacion", - "Atencion y asesoria al cliente", - "Certificado Seguridad SSL (1 ano)", - "Integracion de Hosting (1 ano)", - "Asesoria y Adquisicion de Dominio (1 ano)", - "Integracion de metodos de pago", - "Integracion de metodos de envio", - "Integracion de Chat", - "Integracion y Configuracion de Google Analytics", - "Integracion y Configuracion de Search Console", - "Estrategias para recuperacion de carritos abandonados", - ], - }, - { - nombre: "Tienda en Linea", - descripcion: "Desarrollo de tienda en linea (Magento, Shopify, WordPress)", - fase: 1, - tipoPago: "unico", - precioBase: 26106, // 1509 USD - tiempoEntrega: "30 - 50 dias", - categoria: "ecommerce", - nivel: "Empresario", - orden: 123, - entregablesDefault: [ - "Configuracion en Tienda en Linea (Magento, Shopify, WordPress)", - "Eleccion de plantilla y Estructura de diseno (UX, UI)", - "Desarrollo y Estructura de tienda Optimizada para SEO", - "Creacion y Configuracion de Categorias", - "Diseno y Configuracion de Blog", - "Carga de Productos: 500", - "Configuracion de productos seleccionados y recomendados (upsell, cross selling)", - "Desarrollo de Contenido SEO", - "Asesoramiento para estrategias de promociones y descuentos", - "Capacitacion", - "Atencion y asesoria al cliente", - "Certificado Seguridad SSL (1 ano)", - "Integracion de Hosting (1 ano)", - "Asesoria y Adquisicion de Dominio (1 ano)", - "Integracion de metodos de pago", - "Integracion de metodos de envio", - "Integracion de Chat", - "Integracion y Configuracion de Google Analytics", - "Integracion y Configuracion de Search Console", - "Estrategias para recuperacion de carritos abandonados", - ], - }, - - // ── E-COMMERCE (Fase 1, unico) ── (hoja "Hemeroteca", version mas completa) - { - nombre: "E-commerce", - descripcion: "Tienda en linea completa: plataforma, hosting, dominio y puesta en marcha", - fase: 1, - tipoPago: "unico", - precioBase: 17283, // 999 USD - tiempoEntrega: "20 - 40 dias", - categoria: "ecommerce", - variante: "Hemeroteca", - nivel: "Emprendedor", - orden: 131, - entregablesDefault: [ - "Asesoria y Eleccion de Plataforma", - "Hosting, Eleccion y Asesoria de Dominio", - "Certificado SSL", - "Asesoria y Eleccion de Plantilla Base", - "Configuracion en Tienda en Linea", - "Integracion Metodos de Pago", - "Integracion Metodos de Envio", - "Integracion de Chat: 1", - "Configuracion Paginas Transaccionales", - "Integracion Google Analytics", - "Integracion Search Console", - "Estructura Tienda en Linea Optimizada", - "Creacion y Configuracion de Categorias", - "Diseno y Configuracion de Blog", - "Carga de Productos: 100", - "Diseno y Personalizacion de Tienda", - "Capacitacion y Puesta en Marcha", - "Soporte por Correo Electronico (24 hrs)", - "Juntas de Retroalimentacion cada Mes", - ], - }, - { - nombre: "E-commerce", - descripcion: "Tienda en linea completa: plataforma, hosting, dominio y puesta en marcha", - fase: 1, - tipoPago: "unico", - precioBase: 26106, // 1509 USD - tiempoEntrega: "25 - 45 dias", - categoria: "ecommerce", - variante: "Hemeroteca", - nivel: "PYME", - orden: 132, - entregablesDefault: [ - "Asesoria y Eleccion de Plataforma", - "Hosting, Eleccion y Asesoria de Dominio", - "Certificado SSL", - "Asesoria y Eleccion de Plantilla Base", - "Configuracion en Tienda en Linea", - "Integracion Metodos de Pago", - "Integracion Metodos de Envio", - "Integracion de Chat: 2", - "Configuracion Paginas Transaccionales", - "Integracion Google Analytics", - "Integracion Search Console", - "Estructura Tienda en Linea Optimizada", - "Creacion y Configuracion de Categorias", - "Diseno y Configuracion de Blog", - "Carga de Productos: 250", - "Diseno y Personalizacion de Tienda", - "Capacitacion y Puesta en Marcha", - "Soporte por Correo Electronico (12 hrs)", - "Juntas de Retroalimentacion cada Mes", - ], - }, - { - nombre: "E-commerce", - descripcion: "Tienda en linea completa: plataforma, hosting, dominio y puesta en marcha", - fase: 1, - tipoPago: "unico", - precioBase: 34756, // 2009 USD - tiempoEntrega: "30 - 50 dias", - categoria: "ecommerce", - variante: "Hemeroteca", - nivel: "Empresario", - orden: 133, - entregablesDefault: [ - "Asesoria y Eleccion de Plataforma", - "Hosting, Eleccion y Asesoria de Dominio", - "Certificado SSL", - "Asesoria y Eleccion de Plantilla Base", - "Configuracion en Tienda en Linea", - "Integracion Metodos de Pago", - "Integracion Metodos de Envio", - "Integracion de Chat: 3", - "Configuracion Paginas Transaccionales", - "Integracion Google Analytics", - "Integracion Search Console", - "Estructura Tienda en Linea Optimizada", - "Creacion y Configuracion de Categorias", - "Diseno y Configuracion de Blog", - "Carga de Productos: 500", - "Diseno y Personalizacion de Tienda", - "Capacitacion y Puesta en Marcha", - "Soporte por Correo Electronico (8 hrs)", - "Juntas de Retroalimentacion cada Mes", - "Diseno Responsivo UX", - "Configuracion de Carritos Abandonados", - "Up-Selling, Cross-Selling", - ], - }, - { - nombre: "E-commerce", - descripcion: "Tienda en linea completa: plataforma, hosting, dominio y puesta en marcha", - fase: 1, - tipoPago: "unico", - precioBase: 43579, // 2519 USD - tiempoEntrega: "35 - 60 dias", - categoria: "ecommerce", - variante: "Hemeroteca", - nivel: "Corporativo", - orden: 134, - entregablesDefault: [ - "Asesoria y Eleccion de Plataforma", - "Hosting, Eleccion y Asesoria de Dominio", - "Certificado SSL", - "Asesoria y Eleccion de Plantilla Base", - "Configuracion en Tienda en Linea", - "Integracion Metodos de Pago", - "Integracion Metodos de Envio", - "Integracion de Chat: 4", - "Configuracion Paginas Transaccionales", - "Integracion Google Analytics", - "Integracion Search Console", - "Estructura Tienda en Linea Optimizada", - "Creacion y Configuracion de Categorias", - "Diseno y Configuracion de Blog", - "Carga de Productos: ilimitados", - "Diseno y Personalizacion de Tienda", - "Capacitacion y Puesta en Marcha", - "Soporte por Correo Electronico (inmediata)", - "Juntas de Retroalimentacion cada Mes", - "Diseno Responsivo UX", - "Configuracion de Carritos Abandonados", - "Up-Selling, Cross-Selling", - "Desarrollo Contenido SEO", - "Asesoramiento Promociones y Descuentos", - "Configuracion Programas de Lealtad", - ], - }, - - // ── MENU DIGITAL (Fase 1, unico) ── - { - nombre: "Menu Digital", - descripcion: "Menu digital con QR personalizado", - fase: 1, - tipoPago: "unico", - precioBase: 1713, // 99 USD - tiempoEntrega: "7 - 15 dias", - categoria: "sitio_web", - nivel: "Emprendedor", - orden: 141, - entregablesDefault: [ - "Diseno de Menu Digital", - "QR Personalizado / Dinamico", - "Diseno de Pegatinas", - "Un Idioma (Espanol)", - "Lecturas Ilimitadas", - "Alojamiento de Menu y QR", - "Soporte por Ticket", - "Juntas de Retroalimentacion Cada Mes", - ], - }, - { - nombre: "Menu Digital", - descripcion: "Menu digital con QR personalizado", - fase: 1, - tipoPago: "unico", - precioBase: 3443, // 199 USD - tiempoEntrega: "7 - 15 dias", - categoria: "sitio_web", - nivel: "PYME", - orden: 142, - entregablesDefault: [ - "Diseno de Menu Digital", - "QR Personalizado / Dinamico", - "Diseno de Pegatinas", - "Un Idioma (Espanol)", - "Lecturas Ilimitadas", - "Alojamiento de Menu y QR", - "Soporte por Ticket", - "Juntas de Retroalimentacion Cada Mes", - "Integracion de Redes Sociales", - "Hasta 100 Productos", - "Actualizaciones por Ano: 10", - "Boton de WhatsApp", - "Promocion Mensual", - "Captacion de Base de Datos", - "E-mail Marketing Automation", - "Templates a Elegir: 5", - ], - }, - { - nombre: "Menu Digital", - descripcion: "Menu digital con QR personalizado", - fase: 1, - tipoPago: "unico", - precioBase: 5173, // 299 USD - tiempoEntrega: "10 - 20 dias", - categoria: "sitio_web", - nivel: "Empresario", - orden: 143, - entregablesDefault: [ - "Diseno de Menu Digital", - "QR Personalizado / Dinamico", - "Diseno de Pegatinas", - "Un Idioma (Espanol)", - "Lecturas Ilimitadas", - "Alojamiento de Menu y QR", - "Soporte por Ticket", - "Juntas de Retroalimentacion Cada Mes", - "Integracion de Redes Sociales", - "Hasta 100 Productos", - "Actualizaciones por Ano: 10", - "Boton de WhatsApp", - "Promocion Mensual", - "Captacion de Base de Datos", - "E-mail Marketing Automation", - "Templates a Elegir: 5", - "Pagina Web (Menu Digital)", - "Pago en Linea", - "Personalizacion de Productos", - "Guia de Nutricion por Producto", - "Multiples Addons", - "Notificacion de Nueva Orden", - "Mensajes de Horarios de Atencion", - "Multiples Menus o Secciones", - "100% Responsivo", - "Etiquetas Personalizables", - ], - }, - - // ── GOOGLE ADS (Fase 2, mensual) ── - { - nombre: "Google Ads", - descripcion: "Creacion, configuracion y optimizacion de campanas Google Ads", - fase: 2, - tipoPago: "mensual", - precioBase: 2578, // 149 USD - tiempoEntrega: "Servicio mensual", - categoria: "ads", - nivel: "Emprendedor", - orden: 201, - entregablesDefault: [ - "Creacion y Configuracion de cuenta Google Ads", - "Investigacion y Optimizacion de palabras clave positivas y negativas", - "Creacion de Campanas Publicitarias: 1 a 3", - "Optimizacion de presupuesto de Campanas diaria", - "Integracion con Google Analytics", - "Integracion de etiqueta de pixeles de conversion", - "Reporte de Resultado mensual y junta de retroalimentacion", - "Atencion y asesoria al cliente", - ], - }, - { - nombre: "Google Ads", - descripcion: "Creacion, configuracion y optimizacion de campanas Google Ads", - fase: 2, - tipoPago: "mensual", - precioBase: 5173, // 299 USD - tiempoEntrega: "Servicio mensual", - categoria: "ads", - nivel: "PYME", - orden: 202, - entregablesDefault: [ - "Creacion y Configuracion de cuenta Google Ads", - "Investigacion y Optimizacion de palabras clave positivas y negativas", - "Creacion de Campanas Publicitarias: 1 a 6", - "Optimizacion de presupuesto de Campanas diaria", - "Configuracion de Anuncios de Remarketing", - "Integracion con Google Analytics", - "Integracion de etiqueta de pixeles de conversion", - "Reporte de Resultado mensual y junta de retroalimentacion", - "Atencion y asesoria al cliente", - ], - }, - { - nombre: "Google Ads", - descripcion: "Creacion, configuracion y optimizacion de campanas Google Ads", - fase: 2, - tipoPago: "mensual", - precioBase: 10363, // 599 USD - tiempoEntrega: "Servicio mensual", - categoria: "ads", - nivel: "Empresario", - orden: 203, - entregablesDefault: [ - "Creacion y Configuracion de cuenta Google Ads", - "Investigacion y Optimizacion de palabras clave positivas y negativas", - "Creacion de Campanas Publicitarias: 10", - "Optimizacion de presupuesto de Campanas diaria", - "Configuracion de Anuncios de Remarketing", - "Configuracion de Anuncios para Red Display", - "Automatizacion de envio de Ficha de Prospectos", - "Integracion con Google Analytics", - "Integracion de etiqueta de pixeles de conversion", - "Integracion de Herramientas de automatizacion", - "Reporte de Resultado mensual y junta de retroalimentacion", - "Atencion y asesoria al cliente", - ], - }, - { - nombre: "Google Ads", - descripcion: "Creacion, configuracion y optimizacion de campanas Google Ads", - fase: 2, - tipoPago: "mensual", - precioBase: 17456, // 1009 USD - tiempoEntrega: "Servicio mensual", - categoria: "ads", - nivel: "Corporativo", - orden: 204, - entregablesDefault: [ - "Creacion y Configuracion de cuenta Google Ads", - "Investigacion y Optimizacion de palabras clave positivas y negativas", - "Creacion de Campanas Publicitarias: 15", - "Optimizacion de presupuesto de Campanas diaria", - "Configuracion de Anuncios de Remarketing", - "Configuracion de Anuncios para Red Display", - "Configuracion de Google Merchant Center", - "Configuracion y Optimizacion del Fit de productos", - "Configuracion de Campanas para Shopping", - "Configuracion de cuenta BING", - "Configuracion de Campanas BING", - "Automatizacion de envio de Ficha de Prospectos", - "Integracion con Google Analytics", - "Integracion de etiqueta de pixeles de conversion", - "Integracion de Herramientas de automatizacion", - "Reporte de Resultado mensual y junta de retroalimentacion", - "Atencion y asesoria al cliente", - ], - }, - - // ── FB & IG ADS (Fase 2, mensual) ── - { - nombre: "Facebook & Instagram Ads", - descripcion: "Creacion y optimizacion de campanas en Meta (Facebook e Instagram)", - fase: 2, - tipoPago: "mensual", - precioBase: 2578, // 149 USD - tiempoEntrega: "Servicio mensual", - categoria: "ads", - nivel: "Emprendedor", - orden: 211, - entregablesDefault: [ - "Investigacion, Segmentacion y Optimizacion del Publico Objetivo", - "Creacion y Configuracion del Administrador de Anuncios", - "Creacion de Artes para Anuncios Publicitarios", - "Creacion y Configuracion de Campanas Publicitarias: 1 a 3", - "Configuracion de lista de Remarketing", - "Optimizacion de presupuesto diario y campanas publicitarias", - "Instalacion de Pixeles en Pag. Web", - "Reporte de Resultado mensual y junta de retroalimentacion", - "Atencion y asesoria al cliente", - ], - }, - { - nombre: "Facebook & Instagram Ads", - descripcion: "Creacion y optimizacion de campanas en Meta (Facebook e Instagram)", - fase: 2, - tipoPago: "mensual", - precioBase: 5173, // 299 USD - tiempoEntrega: "Servicio mensual", - categoria: "ads", - nivel: "PYME", - orden: 212, - entregablesDefault: [ - "Investigacion, Segmentacion y Optimizacion del Publico Objetivo", - "Creacion y Configuracion del Administrador de Anuncios", - "Creacion de Artes para Anuncios Publicitarios", - "Creacion y Configuracion de Campanas Publicitarias: 1 a 6", - "Configuracion de lista de Remarketing", - "Optimizacion de presupuesto diario y campanas publicitarias", - "Instalacion de Pixeles en Pag. Web", - "Reporte de Resultado mensual y junta de retroalimentacion", - "Atencion y asesoria al cliente", - ], - }, - { - nombre: "Facebook & Instagram Ads", - descripcion: "Creacion y optimizacion de campanas en Meta (Facebook e Instagram)", - fase: 2, - tipoPago: "mensual", - precioBase: 6903, // 399 USD - tiempoEntrega: "Servicio mensual", - categoria: "ads", - nivel: "Empresario", - orden: 213, - entregablesDefault: [ - "Investigacion, Segmentacion y Optimizacion del Publico Objetivo", - "Creacion y Configuracion del Administrador de Anuncios", - "Creacion de Artes para Anuncios Publicitarios", - "Creacion y Configuracion de Campanas Publicitarias: 1 a 8", - "Configuracion de lista de Remarketing", - "Optimizacion de presupuesto diario y campanas publicitarias", - "Instalacion de Pixeles en Pag. Web", - "Integracion de herramientas de automatizacion", - "Reporte de Resultado mensual y junta de retroalimentacion", - "Atencion y asesoria al cliente", - ], - }, - { - nombre: "Facebook & Instagram Ads", - descripcion: "Creacion y optimizacion de campanas en Meta (Facebook e Instagram)", - fase: 2, - tipoPago: "mensual", - precioBase: 13131, // 759 USD - tiempoEntrega: "Servicio mensual", - categoria: "ads", - nivel: "Corporativo", - orden: 214, - entregablesDefault: [ - "Investigacion, Segmentacion y Optimizacion del Publico Objetivo", - "Creacion y Configuracion del Administrador de Anuncios", - "Creacion de Artes para Anuncios Publicitarios", - "Creacion y Configuracion de Campanas Publicitarias: 1 a 15", - "Creacion de Anuncios para Shopping", - "Configuracion de lista de Remarketing", - "Configuracion de catalogo de Productos de Facebook", - "Optimizacion de presupuesto diario y campanas publicitarias", - "Instalacion de Pixeles en Pag. Web", - "Integracion de herramientas de automatizacion", - "Reporte de Resultado mensual y junta de retroalimentacion", - "Atencion y asesoria al cliente", - ], - }, - - // ── MANEJO DE REDES SOCIALES (Fase 2, mensual) ── - { - nombre: "Manejo de Redes Sociales", - descripcion: "Gestion y contenido de redes sociales", - fase: 2, - tipoPago: "mensual", - precioBase: 6903, // 399 USD - tiempoEntrega: "Servicio mensual", - categoria: "redes", - nivel: "Emprendedor", - orden: 221, - entregablesDefault: [ - "Creacion, Configuracion y/o Optimizacion de pagina de Facebook", - "Medicion de conversiones", - "Estrategia de contenido Publicitario", - "Creacion de embudo de conversion", - "Desarrollo de Cover", - "Creacion de artes y copys para Post", - "Posteos de Publicacion al mes: 10", - "Asesoria al cliente por correo electronico (24 hrs)", - "Informes periodicos", - "Integracion de Google Analytics", - ], - }, - { - nombre: "Manejo de Redes Sociales", - descripcion: "Gestion y contenido de redes sociales", - fase: 2, - tipoPago: "mensual", - precioBase: 12093, // 699 USD - tiempoEntrega: "Servicio mensual", - categoria: "redes", - nivel: "PYME", - orden: 222, - entregablesDefault: [ - "Creacion, Configuracion y/o Optimizacion de pagina de Facebook", - "Medicion de conversiones", - "Estrategia de contenido Publicitario", - "Creacion de embudo de conversion", - "Desarrollo de Cover", - "Creacion de artes y copys para Post", - "Posteos de Publicacion al mes: 15", - "Asesoria al cliente por correo electronico (24 hrs)", - "Informes periodicos", - "Integracion de Google Analytics", - "Integracion Search Console", - "Desarrollo Tienda en Linea Optimizada", - "Video", - ], - }, - { - nombre: "Manejo de Redes Sociales", - descripcion: "Gestion y contenido de redes sociales", - fase: 2, - tipoPago: "mensual", - precioBase: 17456, // 1009 USD - tiempoEntrega: "Servicio mensual", - categoria: "redes", - nivel: "Empresario", - orden: 223, - entregablesDefault: [ - "Creacion, Configuracion y/o Optimizacion de pagina de Facebook", - "Medicion de conversiones", - "Estrategia de contenido Publicitario", - "Creacion de embudo de conversion", - "Desarrollo de Cover", - "Creacion de artes y copys para Post", - "Posteos de Publicacion al mes: 15", - "Asesoria al cliente por correo electronico (24 hrs)", - "Informes periodicos", - "Integracion de Google Analytics", - "Integracion Search Console", - "Desarrollo Tienda en Linea Optimizada", - "Video", - "Gifs", - "Dinamicas", - ], - }, - { - nombre: "Manejo de Redes Sociales", - descripcion: "Gestion y contenido de redes sociales", - fase: 2, - tipoPago: "mensual", - precioBase: 42195, // 2439 USD - tiempoEntrega: "Servicio mensual", - categoria: "redes", - nivel: "Corporativo", - orden: 224, - entregablesDefault: [ - "Creacion, Configuracion y/o Optimizacion de pagina de Facebook", - "Medicion de conversiones", - "Estrategia de contenido Publicitario", - "Creacion de embudo de conversion", - "Desarrollo de Cover", - "Creacion de artes y copys para Post", - "Posteos de Publicacion al mes: 15", - "Asesoria al cliente por correo electronico (24 hrs)", - "Informes periodicos", - "Integracion de Google Analytics", - "Integracion Search Console", - "Desarrollo Tienda en Linea Optimizada", - "Video", - "Gifs", - "Dinamicas", - "Concursos", - "Manejo Inmediato de Crisis", - ], - }, - - // ── SEO (Fase 3, mensual) ── - // NOTA: el Excel origen traia Empresario y Corporativo a 199 USD (error de copia: - // mismo precio que Emprendedor pese a tener mas features). Corregido al patron - // lineal +$100/nivel (5/10/15/20 keywords -> 199/299/399/499 USD). - { - nombre: "Posicionamiento SEO", - descripcion: "Estrategia y posicionamiento SEO mensual", - fase: 3, - tipoPago: "mensual", - precioBase: 3443, // 199 USD - tiempoEntrega: "Servicio mensual", - categoria: "seo", - nivel: "Emprendedor", - orden: 301, - entregablesDefault: [ - "No. KeyWords: 5", - "Estudio y definicion de Palabras Clave", - "Analisis de la competencia", - "Optimizacion tecnica de la estructura del Sitio a nivel SEO", - "Optimizacion de la velocidad de carga en Sitio", - "Creacion y Optimizacion del Sitemap.xml", - "Reporte mensual de trafico y posicion Web", - "Integracion y Configuracion de Google Search Console", - "Integracion y Configuracion de Google Analytics", - "Plan para desarrollo de contenido Estrategico para SEO", - "Estrategia y Generacion de BackLinks", - "Alta de Buscadores", - "Generacion de trafico social a tu Sitio Web", - "Sindicacion en Redes Sociales Externas", - "Atencion y asesoria al cliente", - ], - }, - { - nombre: "Posicionamiento SEO", - descripcion: "Estrategia y posicionamiento SEO mensual", - fase: 3, - tipoPago: "mensual", - precioBase: 5173, // 299 USD - tiempoEntrega: "Servicio mensual", - categoria: "seo", - nivel: "PYME", - orden: 302, - entregablesDefault: [ - "No. KeyWords: 10", - "Estudio y definicion de Palabras Clave", - "Analisis de la competencia", - "Optimizacion tecnica de la estructura del Sitio a nivel SEO", - "Optimizacion de la velocidad de carga en Sitio", - "Optimizacion de SEO local (Google My Business)", - "Creacion y Optimizacion del Sitemap.xml", - "Reporte mensual de trafico y posicion Web", - "Integracion y Configuracion de Google Search Console", - "Integracion y Configuracion de Google Analytics", - "Plan para desarrollo de contenido Estrategico para SEO", - "Estrategia y Generacion de BackLinks", - "Alta de Buscadores", - "Generacion de trafico social a tu Sitio Web", - "Sindicacion en Redes Sociales Externas", - "Atencion y asesoria al cliente", - ], - }, - { - nombre: "Posicionamiento SEO", - descripcion: "Estrategia y posicionamiento SEO mensual", - fase: 3, - tipoPago: "mensual", - precioBase: 6903, // 399 USD (corregido) - tiempoEntrega: "Servicio mensual", - categoria: "seo", - nivel: "Empresario", - orden: 303, - entregablesDefault: [ - "No. KeyWords: 15", - "Estudio y definicion de Palabras Clave", - "Analisis de la competencia", - "Optimizacion tecnica de la estructura del Sitio a nivel SEO", - "Optimizacion de la velocidad de carga en Sitio", - "Optimizacion de SEO local (Google My Business)", - "Creacion y Optimizacion del Sitemap.xml", - "Reporte mensual de trafico y posicion Web", - "Integracion y Configuracion de Google Search Console: 15", - "Integracion y Configuracion de Google Analytics", - "Plan para desarrollo de contenido Estrategico para SEO", - "Estrategia y Generacion de BackLinks", - "Alta de Buscadores", - "Generacion de trafico social a tu Sitio Web", - "Sindicacion en Redes Sociales Externas", - "Desarrollo de contenido para Sitios Externos", - "Atencion y asesoria al cliente", - ], - }, - { - nombre: "Posicionamiento SEO", - descripcion: "Estrategia y posicionamiento SEO mensual", - fase: 3, - tipoPago: "mensual", - precioBase: 8633, // 499 USD (corregido) - tiempoEntrega: "Servicio mensual", - categoria: "seo", - nivel: "Corporativo", - orden: 304, - entregablesDefault: [ - "No. KeyWords: 20", - "Estudio y definicion de Palabras Clave", - "Analisis de la competencia", - "Optimizacion tecnica de la estructura del Sitio a nivel SEO", - "Optimizacion de la velocidad de carga en Sitio", - "Optimizacion de SEO local (Google My Business)", - "Creacion y Optimizacion del Sitemap.xml", - "Reporte mensual de trafico y posicion Web", - "Integracion y Configuracion de Google Search Console: 15", - "Integracion y Configuracion de Google Analytics", - "Plan para desarrollo de contenido Estrategico para SEO", - "Estrategia y Generacion de BackLinks", - "Alta de Buscadores", - "Generacion de trafico social a tu Sitio Web", - "Sindicacion en Redes Sociales Externas", - "Desarrollo de contenido para Sitios Externos", - "Atencion y asesoria al cliente", - ], - }, - - // ── ESTRATEGIA EMPRESARIAL EN ECOMMERCE (Fase 0, unico, sin niveles ni precio en Excel) ── - { - nombre: "Estrategia Empresarial en Ecommerce", - descripcion: "Auditoria y estrategia integral para ecommerce (SEO, tecnica y seguridad Shopify, estudios de mercado/competencia y embudos de venta)", - fase: 0, - tipoPago: "unico", - precioBase: 12900, - tiempoEntrega: "10 - 20 dias", - categoria: "estrategia", - orden: 100, - entregablesDefault: [ - "Auditoria completa de situacion actual del SEO del Sitio", - "Auditoria Tecnica de Shopify", - "Auditoria en Seguridad de Shopify", - "Estudio de canales de comunicacion y captacion", - "Estudio de Segmentos de Mercado para Landing Pages de prospeccion", - "Estudio de Keyword Research para Categorizacion Jerarquica de Ecommerce", - "Estudio de Keyword Research para creacion de Landing Page para prospeccion", - "Estudio de competencia organica", - "Estudio de competencia pagada", - "Estudio de tendencias", - "Adicional: Embudo de ventas para Ecommerce", - "Adicional: Embudo de ventas para captacion", - ], - }, - ]; - - for (const servicio of servicios) { - const catNombre = catAlias[servicio.categoria] || "Desarrollo Personalizado"; - const servicioId = - servicio.nombre.toLowerCase().replace(/\s+/g, "-").substring(0, 30) + "-" + servicio.orden; - await prisma.servicioCatalogo.upsert({ - where: { id: servicioId }, - update: {}, - create: { - id: servicioId, - nombre: servicio.nombre, - descripcion: servicio.descripcion, - fase: servicio.fase, - tipoPago: servicio.tipoPago, - precioBase: servicio.precioBase, - tiempoEntrega: servicio.tiempoEntrega, - entregablesDefault: servicio.entregablesDefault, - categoriaId: catMap[catNombre] || null, - variante: ("variante" in servicio ? servicio.variante : null) || null, - nivel: ("nivel" in servicio ? servicio.nivel : null) || null, - orden: servicio.orden, - }, - }); - } - - const allServicios = await prisma.servicioCatalogo.findMany(); - - // ── PAQUETE GENERAL ── - const paquete = await prisma.paquete.upsert({ - where: { id: "paquete-general" }, - update: {}, - create: { - id: "paquete-general", - nombre: "General", - descripcion: "Paquete completo de servicios de marketing digital", - activo: true, - }, - }); - - const fasesGeneral = [ - { nombre: "Auditoria / Acompanamiento", orden: 0 }, - { nombre: "Setup e Infraestructura", orden: 1 }, - { nombre: "Publicidad y Manejo", orden: 2 }, - { nombre: "Contenido y SEO", orden: 3 }, - ]; - - const faseMap: Record = {}; - for (const fg of fasesGeneral) { - const faseId = `fase-general-${fg.orden}`; - const created = await prisma.fasePaquete.upsert({ - where: { id: faseId }, - update: { nombre: fg.nombre, orden: fg.orden }, - create: { - id: faseId, - paqueteId: paquete.id, - nombre: fg.nombre, - orden: fg.orden, - }, - }); - faseMap[fg.orden] = created.id; - } - - for (const s of allServicios) { - const fasePaqueteId = faseMap[s.fase]; - if (fasePaqueteId) { - await prisma.servicioPaquete.upsert({ - where: { - servicioCatalogoId_fasePaqueteId: { - servicioCatalogoId: s.id, - fasePaqueteId, - }, - }, - update: {}, - create: { - servicioCatalogoId: s.id, - fasePaqueteId, - }, - }); - } - } - - // ── PAQUETES RECOMENDADOS PYME ── - // Resuelve un servicio del catalogo por nombre (+ nivel opcional). El nivel - // desambigua servicios con nombre repetido (ej. "Posicionamiento SEO" existe - // generico con nivel null y tambien por nivel). Lanza error si no resuelve - // exactamente 1 servicio para que cualquier nombre mal escrito reviente aqui. - const findServId = (nombre: string, nivel: string | null = null): string => { - const matches = allServicios.filter( - (s) => s.nombre === nombre && (s.nivel ?? null) === (nivel ?? null) - ); - if (matches.length !== 1) { - throw new Error( - `Paquete PyME: '${nombre}' (nivel=${nivel}) resolvio ${matches.length} servicios` - ); - } - return matches[0].id; - }; - - type ServRef = { nombre: string; nivel?: string | null }; - type PaqueteDef = { - id: string; - nombre: string; - descripcion: string; - fases: { orden: number; nombre: string; servicios: ServRef[] }[]; - }; - - const FASE_NOMBRES = [ - "Auditoria / Acompanamiento", - "Setup e Infraestructura", - "Publicidad y Manejo", - "Contenido y SEO", - ]; - - const paquetesPyme: PaqueteDef[] = [ - { - id: "paquete-arranque", - nombre: "Arranque Esencial", - descripcion: - "Inicio - cualquier giro. Minimo viable para una PyME que arranca: presencia profesional en redes y Google, y primeros clientes.", - fases: [ - { orden: 0, nombre: FASE_NOMBRES[0], servicios: [{ nombre: "Auditoria en Redes Sociales" }] }, - { - orden: 1, - nombre: FASE_NOMBRES[1], - servicios: [ - { nombre: "Creacion y Optimizacion de Redes Sociales" }, - { nombre: "Creacion y Optimizacion de la Ficha de Google My Business" }, - ], - }, - { orden: 2, nombre: FASE_NOMBRES[2], servicios: [{ nombre: "Manejo Basico de Redes Sociales" }] }, - ], - }, - { - id: "paquete-marca", - nombre: "Marca + Presencia", - descripcion: - "Inicio - marca nueva o personal. Imagen profesional (identidad), redes y primeras campanas de alcance antes de invertir en pauta fuerte.", - fases: [ - { orden: 0, nombre: FASE_NOMBRES[0], servicios: [{ nombre: "Auditoria en Redes Sociales" }] }, - { - orden: 1, - nombre: FASE_NOMBRES[1], - servicios: [ - { nombre: "Logo e Identidad", nivel: "Emprendedor" }, - { nombre: "Creacion y Optimizacion de Redes Sociales" }, - { nombre: "Creacion y Optimizacion de la Ficha de Google My Business" }, - ], - }, - { - orden: 2, - nombre: FASE_NOMBRES[2], - servicios: [ - { nombre: "Manejo Basico de Redes Sociales" }, - { nombre: "Manejo y Optimizacion de Meta Ads" }, - ], - }, - { orden: 3, nombre: FASE_NOMBRES[3], servicios: [{ nombre: "Desarrollo de Plan de Contenido" }] }, - ], - }, - { - id: "paquete-local", - nombre: "Negocio Local en Crecimiento", - descripcion: - "Crecimiento - giro local (restaurante, consultorio, tienda fisica, servicios). Visibilidad local y captacion por WhatsApp/llamada: web, ficha de Google, redes, Meta Ads y SEO local.", - fases: [ - { orden: 0, nombre: FASE_NOMBRES[0], servicios: [{ nombre: "Auditoria en Sitio Web" }] }, - { - orden: 1, - nombre: FASE_NOMBRES[1], - servicios: [ - { nombre: "Pagina Web", nivel: "Emprendedor" }, - { nombre: "Creacion y Optimizacion de la Ficha de Google My Business" }, - { nombre: "Creacion y Optimizacion de Redes Sociales" }, - ], - }, - { - orden: 2, - nombre: FASE_NOMBRES[2], - servicios: [ - { nombre: "Manejo Basico de Redes Sociales" }, - { nombre: "Manejo y Optimizacion de Meta Ads" }, - ], - }, - { orden: 3, nombre: FASE_NOMBRES[3], servicios: [{ nombre: "Posicionamiento SEO" }] }, - ], - }, - { - id: "paquete-leads-b2b", - nombre: "Servicios / B2B: Generacion de Leads", - descripcion: - "Crecimiento - servicios profesionales / B2B. Motor de prospeccion: sitio web solido, CRM Bucefalo, campanas de Google Ads, contenido y SEO.", - fases: [ - { - orden: 0, - nombre: FASE_NOMBRES[0], - servicios: [{ nombre: "Auditoria en Sitio Web" }, { nombre: "Estudio Digital de Mercado" }], - }, - { - orden: 1, - nombre: FASE_NOMBRES[1], - servicios: [ - { nombre: "Diseno de Sitio Web (WordPress)" }, - { nombre: "Configuracion y Puesta en Marcha del CRM Bucefalo" }, - { nombre: "Configuracion, Optimizacion y Puesta en Marcha de Google Ads y Meta Ads" }, - ], - }, - { - orden: 2, - nombre: FASE_NOMBRES[2], - servicios: [ - { nombre: "Configuracion y Optimizacion Google Ads" }, - { nombre: "Plan Mensual CRM Bucefalo" }, - ], - }, - { - orden: 3, - nombre: FASE_NOMBRES[3], - servicios: [{ nombre: "Desarrollo de Plan de Contenido" }, { nombre: "Posicionamiento SEO" }], - }, - ], - }, - { - id: "paquete-ecommerce", - nombre: "Ecommerce Lanzamiento", - descripcion: - "Inicio / Crecimiento - ecommerce. Vender en linea desde cero con buen setup de medicion y pauta: tienda WooCommerce, CRM y campanas de Google y Meta.", - fases: [ - { orden: 0, nombre: FASE_NOMBRES[0], servicios: [{ nombre: "Auditoria en Ecommerce" }] }, - { - orden: 1, - nombre: FASE_NOMBRES[1], - servicios: [ - { nombre: "Diseno de Ecommerce (WooCommerce)" }, - { nombre: "Configuracion, Optimizacion y Puesta en Marcha de Google Ads y Meta Ads" }, - { nombre: "Configuracion y Puesta en Marcha del CRM Bucefalo" }, - ], - }, - { - orden: 2, - nombre: FASE_NOMBRES[2], - servicios: [ - { nombre: "Manejo y Optimizacion de Meta Ads" }, - { nombre: "Configuracion y Optimizacion Google Ads" }, - ], - }, - ], - }, - { - id: "paquete-360", - nombre: "Escalamiento 360 Integral", - descripcion: - "Escalamiento - negocio consolidado, cualquier giro. Paquete tope: ads en niveles altos, redes profesionales, contenido, SEO completo y acompanamiento estrategico. El asesor recorta segun presupuesto.", - fases: [ - { - orden: 0, - nombre: FASE_NOMBRES[0], - servicios: [ - { nombre: "Auditoria en Sitio Web" }, - { nombre: "Auditoria de cuentas Google Ads y Meta Ads" }, - { nombre: "Estudio Digital de Mercado" }, - { nombre: "Plan de Acompanamiento Integral" }, - ], - }, - { - orden: 1, - nombre: FASE_NOMBRES[1], - servicios: [ - { nombre: "Diseno de Identidad Corporativa" }, - { nombre: "Diseno de Sitio Web (WordPress)" }, - { nombre: "Configuracion y Puesta en Marcha del CRM Bucefalo" }, - { nombre: "Configuracion, Optimizacion y Puesta en Marcha de Google Ads y Meta Ads" }, - ], - }, - { - orden: 2, - nombre: FASE_NOMBRES[2], - servicios: [ - { nombre: "Google Ads", nivel: "Empresario" }, - { nombre: "Facebook & Instagram Ads", nivel: "Empresario" }, - { nombre: "Manejo de Redes Sociales", nivel: "PYME" }, - { nombre: "Plan Mensual CRM Bucefalo" }, - ], - }, - { - orden: 3, - nombre: FASE_NOMBRES[3], - servicios: [ - { nombre: "Desarrollo de Plan de Contenido" }, - { nombre: "Generacion de Contenido" }, - { nombre: "Estrategia SEO Completa" }, - ], - }, - ], - }, - ]; - - for (const pq of paquetesPyme) { - const paqueteRec = await prisma.paquete.upsert({ - where: { id: pq.id }, - update: { nombre: pq.nombre, descripcion: pq.descripcion, activo: true }, - create: { id: pq.id, nombre: pq.nombre, descripcion: pq.descripcion, activo: true }, - }); - - for (const fase of pq.fases) { - const faseId = `fase-${pq.id}-${fase.orden}`; - const faseCreated = await prisma.fasePaquete.upsert({ - where: { id: faseId }, - update: { nombre: fase.nombre, orden: fase.orden }, - create: { id: faseId, paqueteId: paqueteRec.id, nombre: fase.nombre, orden: fase.orden }, - }); - - for (const ref of fase.servicios) { - const servicioCatalogoId = findServId(ref.nombre, ref.nivel ?? null); - await prisma.servicioPaquete.upsert({ - where: { - servicioCatalogoId_fasePaqueteId: { - servicioCatalogoId, - fasePaqueteId: faseCreated.id, - }, - }, - update: {}, - create: { servicioCatalogoId, fasePaqueteId: faseCreated.id }, - }); - } - } - } - - const bonos = [ - { numero: 1, titulo: "Servicio Centinela Web", descripcion: "30 minutos mensuales en servicios Centinela (Sitio Web)" }, - { numero: 2, titulo: "Workshop Buyer Persona", descripcion: "Workshop Estrategico de Buyer Persona" }, - { numero: 3, titulo: "Workshop Propuesta de Valor", descripcion: "Workshop de Propuestas de Valor y Oferta Irresistible" }, - { numero: 4, titulo: "Membresia Premium", descripcion: "1 ano de Membresia Premium" }, - { numero: 5, titulo: "Mes Gratis Bucefalo", descripcion: "Un mes gratis de Bucefalo CRM, Marketing y Ventas" }, - { numero: 6, titulo: "Script de Ventas", descripcion: "Script de Ventas con mas de 100 complementos" }, - ]; - - if ((await prisma.bono.count()) === 0) { - for (const bono of bonos) { - await prisma.bono.create({ data: bono }); - } - } - - const planes = [ - { meses: 3, tasa: 0.077, comision: 2.5, montoMinimo: 300, iva: 0.16 }, - { meses: 6, tasa: 0.107, comision: 2.5, montoMinimo: 600, iva: 0.16 }, - { meses: 9, tasa: 0.137, comision: 2.5, montoMinimo: 900, iva: 0.16 }, - { meses: 12, tasa: 0.167, comision: 2.5, montoMinimo: 1200, iva: 0.16 }, - ]; - - for (const plan of planes) { - await prisma.financiamientoPlan.upsert({ - where: { meses: plan.meses }, - update: {}, - create: plan, - }); - } - - const configs = [ - { - clave: "razon_social", - valor: "URIEL JARETH ALVARADO ORTIZ", - }, - { - clave: "rfc", - valor: "AAOU970201SU7", - }, - { - clave: "domicilio_fiscal", - valor: "", - }, - { - clave: "cuenta_nacional", - valor: "012227015788120440", - }, - { - clave: "clabe_interbancaria", - valor: "012227015788120440", - }, - { - clave: "cuenta_internacional", - valor: "Beneficiario: URIEL JARETH ALVARADO ORTIZ\nCLABE: 012227015788120440\nBanco: BBVA", - }, - { - clave: "cuenta_internacional_swift", - valor: "Beneficiario: URIEL JARETH ALVARADO ORTIZ\nCodigo SWIFT / BIC: BCMRMXMMPYM\nCLABE: 012227015788120440\nBanco: BBVA Mexico", - }, - { - clave: "hora_centinela", - valor: "700", - }, - { - clave: "anualidad_hosting", - valor: "5000", - }, - { - clave: "iva", - valor: "0.16", - }, - { - clave: "terminos_condiciones", - valor: "- Esta cotizacion tiene una vigencia de 15 dias habiles.\n- Cualquier ajuste al proyecto despues de la aprobacion del contenido afectara la fecha de entrega y por consiguiente el costo.\n- El cliente debera proporcionar la informacion solicitada por Uriel Jareth Consulting en tiempo y forma.\n- Si la falta de informacion provoca un excedente en los plazos de entrega del proyecto, las horas adicionales de servicio se cotizaran por separado.\n- Los pagos correspondientes a los servicios mensuales deberan realizarse en los primeros 5 dias del mes.\n- Todo el material e informacion necesarios para la realizacion del sitio web deberan ser entregados en un plazo maximo de 40 dias naturales a partir del arranque del proyecto.", - }, - { - clave: "no_incluye", - valor: "- Generacion de disenos, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado. (Estos servicios son Extras, pueden ser realizados por Uriel Jareth Consulting y se cotizan como adicionales mediante cotizacion).\n- Redaccion de entradas de Blog.\n- Integracion de Servicios de terceros ajenos a los cotizados.\n- Servicio de Recuperacion de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads (En Caso de Requerir el Servicio se Aplicara uso de Hora Centinela).\n- Creacion de Redes Sociales (En Caso de Requerir el Servicio Incluira un Costo Adicional).", - }, - { - clave: "notas_adicionales", - valor: "- El presente proyecto debera tener un responsable oficial, a quien se le compartiran los avances y con quien se mantendra la comunicacion.\n- La Hora Centinela tiene un precio de $700.00 MXN.\n- Nuestros servicios incluyen la entrega de archivos finales listos para su uso (JPG, PNG, PDF, etc.). Los archivos editables/fuente (AI, PSD) son propiedad intelectual de la agencia y no estan incluidos, salvo en proyectos de Branding/Logotipos.\n- SI EL PROYECTO SE PAUSA POR RAZONES AJENAS A URIEL JARETH CONSULTING O FALTA DE CONTINUIDAD, ESTO GENERARA COSTO EXTRA PARA RETOMAR EL PROYECTO (SE CONSIDERARA UN COSTO QUE PUEDE IR DEL 15% AL 30% CON BASE A LA COTIZACION INICIAL).", - }, - { - clave: "color_primario", - valor: "#0400C4", - }, - { - clave: "color_secundario", - valor: "#0F172A", - }, - { - clave: "logo_base64", - valor: "", - }, - ]; - - for (const config of configs) { - await prisma.configuracion.upsert({ - where: { clave: config.clave }, - update: { valor: config.valor }, - create: config, - }); - } - - console.log("Seed completed successfully!"); -} - -main() - .catch((e) => { - console.error(e); - process.exit(1); - }) - .finally(async () => { - await prisma.$disconnect(); - }); diff --git a/public/file.svg b/public/file.svg deleted file mode 100644 index 004145c..0000000 --- a/public/file.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/public/globe.svg b/public/globe.svg deleted file mode 100644 index 567f17b..0000000 --- a/public/globe.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/public/next.svg b/public/next.svg deleted file mode 100644 index 5174b28..0000000 --- a/public/next.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/public/vercel.svg b/public/vercel.svg deleted file mode 100644 index 7705396..0000000 --- a/public/vercel.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/public/window.svg b/public/window.svg deleted file mode 100644 index b2b2a44..0000000 --- a/public/window.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/scripts/provision-agent-keys.ts b/scripts/provision-agent-keys.ts deleted file mode 100644 index d8ee85d..0000000 --- a/scripts/provision-agent-keys.ts +++ /dev/null @@ -1,248 +0,0 @@ -/** - * Provisioning CLI de claves de agente (AgentApiKey) para Uriel Jareth Consulting. - * - * Uso dentro del contenedor web o en local con variables DB_* cargadas: - * npx tsx scripts/provision-agent-keys.ts --list - * npx tsx scripts/provision-agent-keys.ts --nombre sales-agent --scopes catalogo:leer,clientes:leer,clientes:escribir,cotizaciones:leer,cotizaciones:borrador,cotizaciones:enviar --rate-limit 60 - * npx tsx scripts/provision-agent-keys.ts --nombre sales-agent --rotate - * npx tsx scripts/provision-agent-keys.ts --preset [--rotate] - * - * Imprime JSON limpio en stdout para que un operador/orquestador guarde las - * claves directamente en accesos/cotizador.env sin exponerlas en logs. - */ -import { createHash, randomBytes } from "node:crypto"; -import { PrismaClient } from "../src/generated/prisma/client"; -import { PrismaPg } from "@prisma/adapter-pg"; - -const VALID_SCOPES = new Set([ - "catalogo:leer", - "clientes:leer", - "clientes:escribir", - "cotizaciones:leer", - "cotizaciones:leer_aceptadas", - "cotizaciones:borrador", - "cotizaciones:enviar", - "cobros:leer", - "cobros:registrar", -]); - -const PRESETS: Array<{ nombre: string; scopes: string[]; rateLimitPerMin: number }> = [ - { - nombre: "sales-agent", - scopes: [ - "catalogo:leer", - "clientes:leer", - "clientes:escribir", - "cotizaciones:leer", - "cotizaciones:borrador", - "cotizaciones:enviar", - ], - rateLimitPerMin: 60, - }, - { - nombre: "jefe-operaciones", - scopes: [ - "catalogo:leer", - "clientes:leer", - "cotizaciones:leer", - "cobros:leer", - ], - rateLimitPerMin: 120, - }, - { - nombre: "cobranza", - scopes: [ - "clientes:leer", - "cobros:leer", - ], - rateLimitPerMin: 60, - }, - { - nombre: "entrega", - scopes: [ - "clientes:leer", - "cotizaciones:leer_aceptadas", - ], - rateLimitPerMin: 60, - }, - { - nombre: "n8n-ecosystem", - scopes: [ - "catalogo:leer", - "clientes:leer", - "cotizaciones:leer", - "cotizaciones:enviar", - "cobros:leer", - ], - rateLimitPerMin: 180, - }, -]; - -function generateKey() { - const rawKey = `ujc_live_${randomBytes(32).toString("hex")}`; - const prefijo = rawKey.slice(0, 14); - const keyHash = createHash("sha256").update(rawKey, "utf8").digest("hex"); - return { rawKey, prefijo, keyHash }; -} - -function parseArgs(argv: string[]) { - const args: Record = {}; - for (let i = 0; i < argv.length; i++) { - const token = argv[i]; - if (!token.startsWith("--")) continue; - const key = token.slice(2); - const next = argv[i + 1]; - if (!next || next.startsWith("--")) { - args[key] = true; - } else { - args[key] = next; - i++; - } - } - return args; -} - -async function main() { - const args = parseArgs(process.argv.slice(2)); - - const adapter = new PrismaPg({ - host: process.env.DB_HOST || "localhost", - port: parseInt(process.env.DB_PORT || "5432", 10), - user: process.env.DB_USER || "postgres", - password: process.env.DB_PASSWORD || "postgres", - database: process.env.DB_DATABASE || process.env.DB_NAME || "cotizador_e3", - }); - const prisma = new PrismaClient({ adapter }); - - try { - if (args.list) { - const keys = await prisma.agentApiKey.findMany({ - orderBy: { createdAt: "asc" }, - select: { - id: true, - nombre: true, - prefijo: true, - scopes: true, - rateLimitPerMin: true, - activo: true, - revokedAt: true, - lastUsedAt: true, - createdAt: true, - }, - }); - console.log(JSON.stringify({ ok: true, keys }, null, 2)); - return; - } - - const targets: Array<{ nombre: string; scopes: string[]; rateLimitPerMin: number }> = []; - - if (args.preset) { - targets.push(...PRESETS); - } else if (typeof args.nombre === "string" && args.nombre.trim()) { - const nombre = args.nombre.trim(); - const rawScopes = - typeof args.scopes === "string" - ? args.scopes - .split(",") - .map((s) => s.trim()) - .filter(Boolean) - : []; - const rateLimitPerMin = - typeof args["rate-limit"] === "string" ? parseInt(args["rate-limit"], 10) || 60 : 60; - - for (const sc of rawScopes) { - if (!VALID_SCOPES.has(sc)) { - throw new Error(`Scope invalido: "${sc}". Validos: ${Array.from(VALID_SCOPES).join(", ")}`); - } - } - targets.push({ nombre, scopes: rawScopes, rateLimitPerMin }); - } else { - console.error( - "Uso: npx tsx scripts/provision-agent-keys.ts --list | --preset [--rotate] | --nombre --scopes [--rate-limit 60] [--rotate]" - ); - process.exit(2); - } - - const rotate = Boolean(args.rotate); - const results: Array> = []; - - for (const target of targets) { - const existing = await prisma.agentApiKey.findUnique({ - where: { nombre: target.nombre }, - }); - - if (existing && !rotate) { - results.push({ - nombre: existing.nombre, - action: "exists", - id: existing.id, - prefijo: existing.prefijo, - scopes: existing.scopes, - rateLimitPerMin: existing.rateLimitPerMin, - activo: existing.activo, - }); - continue; - } - - const scopesFinal = - target.scopes.length > 0 ? Array.from(new Set(target.scopes)) : existing?.scopes ?? []; - if (scopesFinal.length === 0) { - throw new Error(`Debes indicar --scopes al crear la clave "${target.nombre}"`); - } - - const { rawKey, prefijo, keyHash } = generateKey(); - - if (existing) { - const updated = await prisma.agentApiKey.update({ - where: { id: existing.id }, - data: { - prefijo, - keyHash, - scopes: scopesFinal, - rateLimitPerMin: target.rateLimitPerMin || existing.rateLimitPerMin, - activo: true, - revokedAt: null, - }, - }); - results.push({ - nombre: updated.nombre, - action: "rotated", - id: updated.id, - prefijo: updated.prefijo, - scopes: updated.scopes, - rateLimitPerMin: updated.rateLimitPerMin, - rawKey, - }); - } else { - const created = await prisma.agentApiKey.create({ - data: { - nombre: target.nombre, - prefijo, - keyHash, - scopes: scopesFinal, - rateLimitPerMin: target.rateLimitPerMin, - activo: true, - }, - }); - results.push({ - nombre: created.nombre, - action: "created", - id: created.id, - prefijo: created.prefijo, - scopes: created.scopes, - rateLimitPerMin: created.rateLimitPerMin, - rawKey, - }); - } - } - - console.log(JSON.stringify({ ok: true, results }, null, 2)); - } finally { - await prisma.$disconnect(); - } -} - -main().catch((err) => { - console.error(JSON.stringify({ ok: false, error: err instanceof Error ? err.message : String(err) })); - process.exit(1); -}); diff --git a/scripts/verificar-propuesta-cliente.ts b/scripts/verificar-propuesta-cliente.ts deleted file mode 100644 index 66ee55b..0000000 --- a/scripts/verificar-propuesta-cliente.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { crearCliente, modelo, normalizarRespuesta } from "@/lib/propuesta/cliente-ia"; - -// No llama a la API. Comprueba el contrato local y que el fallo sin clave sea claro. - -let fallas = 0; -function check(n: string, ok: boolean, d = "") { - console.log(`${ok ? " OK " : " FALLA"} | ${n}${d ? " -> " + d : ""}`); - if (!ok) fallas++; -} - -const guardada = process.env.MINIMAX_API_KEY; -const guardadaBase = process.env.MINIMAX_BASE_URL; - -delete process.env.MINIMAX_API_KEY; -let msg = ""; -try { - crearCliente(); -} catch (e) { - msg = e instanceof Error ? e.message : String(e); -} -check("sin clave falla en vez de llamar a ciegas", msg.length > 0); -check("el error nombra la variable correcta", msg.includes("MINIMAX_API_KEY")); -check("el error advierte del prefijo ANTHROPIC_", msg.includes("ANTHROPIC_API_KEY")); - -process.env.MINIMAX_API_KEY = "clave-de-prueba"; -delete process.env.MINIMAX_BASE_URL; -const c = crearCliente(); -check("baseURL apunta a MiniMax por defecto", String(c.baseURL).includes("api.minimax.io"), String(c.baseURL)); -check("modelo por defecto es MiniMax-M3", modelo() === "MiniMax-M3", modelo()); - -// Aunque el shell tenga ANTHROPIC_BASE_URL, el cliente no debe hacerle caso. -process.env.ANTHROPIC_BASE_URL = "https://api.anthropic.com"; -const c2 = crearCliente(); -check("ANTHROPIC_BASE_URL del shell no secuestra el baseURL", - !String(c2.baseURL).includes("api.anthropic.com"), String(c2.baseURL)); -delete process.env.ANTHROPIC_BASE_URL; - -process.env.MINIMAX_BASE_URL = "https://ejemplo.local/anthropic"; -check("MINIMAX_BASE_URL si se respeta", String(crearCliente().baseURL).includes("ejemplo.local")); - -process.env.MINIMAX_MODEL = "MiniMax-M2"; -check("MINIMAX_MODEL se respeta", modelo() === "MiniMax-M2"); -delete process.env.MINIMAX_MODEL; - -if (guardada) process.env.MINIMAX_API_KEY = guardada; -else delete process.env.MINIMAX_API_KEY; -if (guardadaBase) process.env.MINIMAX_BASE_URL = guardadaBase; -else delete process.env.MINIMAX_BASE_URL; - -// ── Normalizacion de rarezas de MiniMax, observadas contra la API real ── -const igual = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b); - -check("desenvuelve {item: X} cuando item es la unica clave", - igual(normalizarRespuesta({ item: { a: 1 } }), { a: 1 })); -check("desenvuelve dentro de arrays", - igual(normalizarRespuesta([{ item: { a: 1 } }, { item: { a: 2 } }]), [{ a: 1 }, { a: 2 }])); -check("desenvuelve en profundidad", - igual(normalizarRespuesta({ lista: [{ item: { x: [{ item: 5 }] } }] }), { lista: [{ x: [5] }] })); -check("NO toca un objeto con item junto a otras claves", - igual(normalizarRespuesta({ item: 1, otro: 2 }), { item: 1, otro: 2 })); -check("deja intactos los valores simples", - normalizarRespuesta("texto") === "texto" && normalizarRespuesta(5) === 5 && normalizarRespuesta(null) === null); -check("no altera un objeto normal", - igual(normalizarRespuesta({ a: 1, b: [1, 2] }), { a: 1, b: [1, 2] })); -check("el caso real observado: alcance envuelto", - igual(normalizarRespuesta({ alcance: [{ item: { refPartida: "P01", descripcionResultado: "x" } }] }), - { alcance: [{ refPartida: "P01", descripcionResultado: "x" }] })); - -console.log(fallas === 0 ? "\ntodo paso\n" : `\n${fallas} fallas\n`); -process.exit(fallas === 0 ? 0 : 1); diff --git a/scripts/verificar-propuesta-economia.ts b/scripts/verificar-propuesta-economia.ts deleted file mode 100644 index b25eace..0000000 --- a/scripts/verificar-propuesta-economia.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { calcularRatio } from "@/lib/propuesta/economia"; - -let fallas = 0; -function check(n: string, ok: boolean, d = "") { - console.log(`${ok ? " OK " : " FALLA"} | ${n}${d ? " -> " + d : ""}`); - if (!ok) fallas++; -} - -check("sin valor anual no hay ratio", calcularRatio(100000, null) === null); -check("valor anual cero no divide entre cero", calcularRatio(100000, 0) === null); -check("valor anual negativo no produce ratio", calcularRatio(100000, -5) === null); - -check("ratio 5% = subcotizado", calcularRatio(50000, 1000000)?.lectura === "subcotizado"); -check("ratio 20% = en rango", calcularRatio(200000, 1000000)?.lectura === "en_rango"); -check("ratio 35% = alto", calcularRatio(350000, 1000000)?.lectura === "alto"); -check("ratio 60% = objecion probable", calcularRatio(600000, 1000000)?.lectura === "objecion_probable"); - -// Los cortes exactos: 0.10 entra en rango, 0.25 sigue en rango, 0.40 sigue alto. -check("corte 10% cae en rango", calcularRatio(100000, 1000000)?.lectura === "en_rango"); -check("corte 25% cae en rango", calcularRatio(250000, 1000000)?.lectura === "en_rango"); -check("corte 40% cae en alto", calcularRatio(400000, 1000000)?.lectura === "alto"); - -check("ratio redondeado a 3 decimales", calcularRatio(123456, 1000000)?.ratio === 0.123); - -console.log(fallas === 0 ? "\ntodo paso\n" : `\n${fallas} fallas\n`); -process.exit(fallas === 0 ? 0 : 1); diff --git a/scripts/verificar-propuesta-pdf.ts b/scripts/verificar-propuesta-pdf.ts deleted file mode 100644 index 1cd2a85..0000000 --- a/scripts/verificar-propuesta-pdf.ts +++ /dev/null @@ -1,232 +0,0 @@ -import zlib from "node:zlib"; -import { generarPropuestaPDF, generarAnexoInternoPDF, type DatosPropuestaPDF } from "@/lib/propuesta/pdf"; -import type { PropuestaConsultiva } from "@/lib/propuesta/schemas"; -import type { DatosEconomicos } from "@/lib/propuesta/economia"; - -/** Extrae el texto de un PDF de PDFKit. Con las fuentes base (Helvetica) no hay - * subsetting ni ToUnicode: el texto va como hex de UN byte por caracter dentro de - * streams comprimidos con Flate. */ -function textoDePdf(pdf: Buffer): string { - const crudo = pdf.toString("latin1"); - let salida = ""; - const re = /stream\r?\n/g; - let m: RegExpExecArray | null; - while ((m = re.exec(crudo)) !== null) { - const ini = m.index + m[0].length; - const fin = crudo.indexOf("endstream", ini); - if (fin === -1) continue; - let bloque = ""; - try { - bloque = zlib.inflateSync(Buffer.from(crudo.slice(ini, fin), "latin1")).toString("latin1"); - } catch { - continue; - } - // PDFKit alterna dos codificaciones segun el contenido de la cadena: - // hex `<48656c6c6f>` y literal `(Hello) Tj`. Hay que leer las dos. - // OJO: no se puede meter un separador entre trozos hex. PDFKit aplica kerning y - // parte una misma palabra en varios elementos de un arreglo TJ - // (`[<4d41> -20 <524341444f52>]`), asi que un espacio de mas convierte - // "MARCADORVERDE" en "MARCA DORVERDE" y ninguna busqueda lo encuentra. - for (const t of bloque.matchAll(/<([0-9a-fA-F]{2,})>/g)) { - const hex = t[1]; - for (let i = 0; i + 2 <= hex.length; i += 2) { - const b = parseInt(hex.slice(i, i + 2), 16); - if (b >= 32 && b < 256) salida += String.fromCharCode(b); - } - } - salida += " "; - for (const t of bloque.matchAll(/\(((?:[^()\\]|\\.)*)\)\s*Tj/g)) { - salida += t[1].replace(/\\([()\\])/g, "$1") + " "; - } - } - return salida; -} - -let fallas = 0; -function check(n: string, ok: boolean, d = "") { - console.log(`${ok ? " OK " : " FALLA"} | ${n}${d ? " -> " + d : ""}`); - if (!ok) fallas++; -} - -const econ: DatosEconomicos = { - partidas: [ - { refPartida: "P01", servicioCotizadoId: "c1", nombre: "Sitio web institucional", fase: 1, tipoPago: "unico", precio: 12000, tiempoEntrega: "2 semanas", modeloCobro: "fijo", horas: null, tarifaHora: null, entregables: [] }, - { refPartida: "P02", servicioCotizadoId: "c2", nombre: "Manejo de pauta", fase: 2, tipoPago: "mensual", precio: 8000, tiempoEntrega: "Mensual", modeloCobro: "fijo", horas: null, tarifaHora: null, entregables: [] }, - ], - totales: { subtotalUnico: 12000, subtotalMensual: 8000, ivaUnico: 1920, ivaMensual: 1280, totalUnico: 13920, totalMensual: 9280, totalPrimerAnio: 125280, incluyeIva: true }, - moneda: "MXN", - planBucefalo: null, -}; - -const propuesta: PropuestaConsultiva = { - hechos: { - citas: [{ id: "C01", textoLiteral: "MARCADORCITA nadie contesta el fin de semana", quienLoDijo: "el socio" }], - hechos: [{ id: "H01", enunciado: "Sin control de atencion", confianza: "confirmado", citas: ["C01"] }], - materialesPendientes: [{ texto: "MARCADORMATERIAL accesos al dominio", bloqueaEntrega: true }], - decisionesPendientes: [{ texto: "MARCADORDECISION definir responsable", quienDecide: "el socio" }], - mencionesFueraDeAlcance: ["MARCADORFUERA app movil"], - redFlags: [{ senal: "MARCADORFLAG pidio descuento antes de ver el alcance", severidad: "alta" }], - }, - diagnostico: { - hallazgos: [ - { id: "D01", urgencia: "rojo", titulo: "MARCADORHALLAZGO", descripcion: "Se pierden prospectos cada fin de semana.", confianza: "confirmado", citas: ["C01"], hechos: ["H01"] }, - { id: "D02", urgencia: "verde", titulo: "MARCADORVERDE", descripcion: "Ya tienen la base de clientes ordenada.", confianza: "confirmado", citas: ["C01"], hechos: ["H01"] }, - ], - valorProblema: { - dimensiones: [{ tipo: "tiempo", descripcion: "MARCADORVALOR horas perdidas", factores: [{ nombre: "h", valor: 8, confianza: "confirmado" }, { nombre: "s", valor: 52, confianza: "confirmado" }, { nombre: "c", valor: 400, confianza: "estimado" }], montoAnualMXN: 166400, confianza: "estimado", hechos: ["H01"] }], - notaMetodologia: "MARCADORMETODO ocho horas por semana a costo cargado.", - }, - resultados: [{ enunciado: "MARCADORRESULTADO cero mensajes sin respuesta", metrica: "tiempo", lineaBase: null, periodoMedicion: "mensual" }], - }, - redaccion: { - hero: { titulo: "MARCADORTITULO", subtitulo: "MARCADORSUB ordenar la atencion para dejar de perder prospectos." }, - citaDestacadaId: "C01", - alcance: [ - { refPartida: "P01", descripcionResultado: "MARCADORALCANCE un lugar a donde mandar prospectos." }, - { refPartida: "P02", descripcionResultado: "MARCADORALCANCE2 cada peso a las busquedas que compran." }, - ], - beneficios: [{ etiqueta: "Respuesta", texto: "MARCADORBENEFICIO cada mensaje con responsable.", hallazgoId: "D01" }], - exclusiones: [{ texto: "MARCADOREXCLUSION no incluye migrar el historico.", razon: "fase 2" }], - backlogEvolucion: [{ problema: "MARCADORBACKLOG automatizar reportes", momentoSugerido: "tras la fase 1" }], - notasInternas: ["MARCADORINTERNO el socio decide, no el que vino a la reunion"], - }, -}; - -const datos: DatosPropuestaPDF = { - propuesta, - economia: econ, - cliente: "Cliente Prueba", - empresa: "Empresa SA", - asesor: "Asesor", - numero: "UJ2607TEST", - fecha: new Date("2026-07-29"), - vigencia: new Date("2026-08-19"), - proyecto: "MKT Digital", - branding: { colorPrimario: "#0400C4" }, -}; - -async function main() { - const pdf = await generarPropuestaPDF(datos); - const txt = textoDePdf(pdf); - check("se genera el documento del cliente", pdf.length > 2000, `${pdf.length} bytes`); - - for (const marca of [ - "MARCADORTITULO", "MARCADORSUB", "MARCADORCITA", "MARCADORHALLAZGO", "MARCADORVERDE", - "MARCADORVALOR", "MARCADORMETODO", "MARCADORRESULTADO", "MARCADORALCANCE", "MARCADORALCANCE2", - "MARCADORBENEFICIO", "MARCADOREXCLUSION", "MARCADORMATERIAL", "MARCADORDECISION", "MARCADORBACKLOG", - ]) { - check(`el documento del cliente incluye ${marca}`, txt.includes(marca)); - } - - // Lo que NUNCA debe salir al cliente. - check("NO lleva notas internas", !txt.includes("MARCADORINTERNO")); - check("NO lleva red flags", !txt.includes("MARCADORFLAG")); - check("NO lleva menciones fuera de alcance", !txt.includes("MARCADORFUERA")); - - // El dinero lo pone el codigo, no la IA. - check("imprime el precio de P01", txt.includes("12,000")); - check("imprime el precio de P02", txt.includes("8,000")); - check("imprime el total unico con IVA", txt.includes("13,920")); - check("imprime la mensualidad con IVA", txt.includes("9,280")); - // El desglose debe cuadrar: lineas sin IVA + IVA como renglon propio. - check("imprime el subtotal sin IVA", txt.includes("Subtotal pago unico") && txt.includes("12,000")); - check("imprime el IVA como renglon propio", txt.includes("IVA 16%") && txt.includes("1,920")); - check("imprime el total con IVA", txt.includes("Total pago unico")); - check("la nota NO dice que las lineas incluyan IVA", !txt.includes("Importes con IVA incluido")); - check("la nota aclara que las partidas van sin IVA", txt.includes("no incluyen IVA")); - - check("etiqueta el semaforo", txt.includes("Problema critico") && txt.includes("Ventaja existente")); - check("etiqueta la confianza", txt.includes("Confirmado") && txt.includes("Estimado")); - check("el backlog se marca como no comprometido", txt.includes("No comprometido")); - - // Sin IVA no debe aparecer el renglon de IVA. - const sinIva = await generarPropuestaPDF({ ...datos, economia: { ...econ, totales: { ...econ.totales, incluyeIva: false } } }); - const txtSinIva = textoDePdf(sinIva); - check("sin IVA no se imprime el renglon de IVA", !txtSinIva.includes("IVA 16%")); - check("sin IVA el total lo declara", txtSinIva.includes("sin IVA")); - - // El plan Bucefalo tiene que aparecer: esta en la cotizacion y en los otros dos exportadores. - const conPlan = await generarPropuestaPDF({ ...datos, economia: { ...econ, planBucefalo: { nivel: "premium", precio: 4500 } } }); - const txtPlan = textoDePdf(conPlan); - check("el plan Bucefalo aparece en el documento", txtPlan.includes("Bucefalo")); - check("el plan aparece con su nivel", txtPlan.includes("Premium")); - check("el plan aparece con su precio mensual", txtPlan.includes("4,500")); - - // Una partida que la IA invento no se dibuja (R2 ya la marco). - const conFantasma = await generarPropuestaPDF({ - ...datos, - propuesta: { ...propuesta, redaccion: { ...propuesta.redaccion, alcance: [...propuesta.redaccion.alcance, { refPartida: "P99", descripcionResultado: "MARCADORFANTASMA inventada" }] } }, - }); - check("una partida inventada no se dibuja", !textoDePdf(conFantasma).includes("MARCADORFANTASMA")); - - // Completitud: la cotizacion manda, no lo que la IA alcanzo a describir. - // Verificado con UJ2606UR001 en produccion: 58 partidas, la IA describio 40. - const econGrande = { ...econ, partidas: [...econ.partidas, - { refPartida: "P03", servicioCotizadoId: "c3", nombre: "MARCADORNODESCRITA servicio extra", fase: 3, tipoPago: "unico" as const, precio: 5000, tiempoEntrega: "1 semana", modeloCobro: "fijo", horas: null, tarifaHora: null, entregables: ["Entregable A", "Entregable B"] }, - ] }; - const conNoDescrita = await generarPropuestaPDF({ ...datos, economia: econGrande }); - const txtND = textoDePdf(conNoDescrita); - check("una partida SIN descripcion de la IA igual aparece", txtND.includes("MARCADORNODESCRITA")); - check("y aparece con su precio", txtND.includes("5,000")); - check("y con su detalle del catalogo como respaldo", txtND.includes("Entregable A")); - - // ── Anexo interno ── - const anexo = await generarAnexoInternoPDF(datos); - const txtA = textoDePdf(anexo); - check("se genera el anexo interno", anexo.length > 1000, `${anexo.length} bytes`); - check("el anexo se marca NO ENVIAR", txtA.includes("NO ENVIAR")); - check("el anexo lleva las notas internas", txtA.includes("MARCADORINTERNO")); - check("el anexo lleva las red flags", txtA.includes("MARCADORFLAG")); - check("el anexo lleva lo que quedo fuera", txtA.includes("MARCADORFUERA")); - // 125280 / 166400 = 75.3% -> objecion probable - check("el anexo calcula el ratio", txtA.includes("75.3"), "125280/166400"); - check("el anexo interpreta el ratio", txtA.includes("objecion probable")); - check("el anexo sugiere responder con alcance", txtA.includes("no con descuento")); - check("el anexo desglosa de donde sale el valor anual", txtA.includes("De donde sale el valor anual")); - check("el anexo muestra los factores con su confianza", txtA.includes("confirmado") && txtA.includes("estimado")); - - // R5b: una cifra sostenida solo por estimaciones debe llevar alerta visible. - const soloEstimado = await generarAnexoInternoPDF({ - ...datos, - propuesta: { ...propuesta, diagnostico: { ...propuesta.diagnostico, valorProblema: { ...propuesta.diagnostico.valorProblema, - dimensiones: [{ ...propuesta.diagnostico.valorProblema.dimensiones[0], factores: [{ nombre: "a", valor: 8, confianza: "estimado" as const }, { nombre: "b", valor: 20800, confianza: "estimado" as const }], montoAnualMXN: 166400 }] } } }, - }); - check("el anexo alerta si la cifra descansa solo en estimaciones", textoDePdf(soloEstimado).includes("puede cuadrar y aun asi estar inflada")); - check("el anexo NO alerta si hay factores confirmados", !txtA.includes("puede cuadrar y aun asi estar inflada")); - - // Robustez del branding: la API de configuracion no valida los valores. - for (const malo of [" + + diff --git a/web/package-lock.json b/web/package-lock.json new file mode 100644 index 0000000..c67d859 --- /dev/null +++ b/web/package-lock.json @@ -0,0 +1,2710 @@ +{ + "name": "cotizador-uj-web", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "cotizador-uj-web", + "version": "0.1.0", + "dependencies": { + "clsx": "^2.1.1", + "lucide-react": "^1.11.0", + "react": "^19.2.4", + "react-dom": "^19.2.4", + "react-router-dom": "^7.5.0", + "zustand": "^5.0.12" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.1.0", + "@types/node": "^22.0.0", + "@types/react": "^19.2.4", + "@types/react-dom": "^19.2.4", + "@vitejs/plugin-react": "^4.4.0", + "tailwindcss": "^4.1.0", + "typescript": "^5.8.0", + "vite": "^6.3.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.16.tgz", + "integrity": "sha512-qK40pOeReBJY7B0JX6CCIfauMLAa0IlvuVYJ+aZBYLVJwmNUTvsQcEu0En9hVMmNjeSUSQYwvpi1JgXn5imIQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.16", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.16", + "@babel/helpers": "^7.29.16", + "@babel/parser": "^7.29.15", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.16", + "@babel/types": "^7.29.15", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.16.tgz", + "integrity": "sha512-yRtddtrcYdLJt0l70aP7usb2YpMHNXAdAvJW2hXdka5boR4vKMS/F5BTR5sULkbht9xPk/EKzbY2mCczMutZqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.15", + "@babel/types": "^7.29.15", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.16.tgz", + "integrity": "sha512-jzdW9nRNJXbNAfcbtfZA75vcQK8c/PRniwNL1KIQukiptryb5JlCl+nwi3idOSj611tMgiZxb9PuKg1FI0BvVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.16" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.15.tgz", + "integrity": "sha512-C2FuapQ2Kh1OnVHAoLi5rD3GBJ8COb9Q609T6HEpLqaBAo560PDP5OxBE5dCI/h951MBO/+bCUYU5SZ+8ZlV+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.16.tgz", + "integrity": "sha512-JGNbyEyvOAvceLDQoO6b/w/HbW6KX3sdWgrPCFcAyHfhfsqRoRN14vfaG3GZ90g2dVK7UEe65giopuldeimBjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.15" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.15.tgz", + "integrity": "sha512-RpKWyisHoP81twtSCgmE02iU0RnPcq1DN5bBEbpUePrjA9Q3wXhufnCJrrayPpoZieqFh3zyZQqwtSK0gGccRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.15" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.16", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.16.tgz", + "integrity": "sha512-a16ah9dTLOLUq5BL7NElJ7keefg/276vgfTfExDf1PizddYboqRnQXDTooVPb0VArIqrKe8KLlghnTxlZFEZtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.16", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.15", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.15", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.15.tgz", + "integrity": "sha512-/XKpKDakL//LZ66bq1XsZOswuqeI5MZqPLDu18o3XdkU1fNJ7bdPtzgnc4ZNS+bBGHV0FJG8jjb8SwcC3nNVQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.15", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.9.tgz", + "integrity": "sha512-Z1hkXtnYKf3sHDD8F2Ll7g9ZGwgAdVNThyz3KiTGSWkjKgYPz/a3TEPoR7ZXE9YlLvbpaO8g+3zisGbU40WQsg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.9.tgz", + "integrity": "sha512-9FG3WZfMVLlbYB8Vyy2w2t50IMbGQ1dWfiCvkacTtXAmXxkHDkxCdomxW6869YEMD1gTsgDF5i9RXASw/8iaZw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.9.tgz", + "integrity": "sha512-nsxur8e5bfr8YdUwupKED/XJD6X02FVIQkv2zDVJQkesfI0/Lt4vMDFjlWNqWgHbZ38nt8xhk/gbJWdzVtWCfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.68.9.tgz", + "integrity": "sha512-tkqdvGDK6pmcd419n4zHSFkJcnEIuluYKZArnzWq+O02RYe5jymtAF/c92VP6/JR9nawrV6+LC23GhSPeNZUmA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.9.tgz", + "integrity": "sha512-1vWrRYmFBNs1UKMogcvl5Vg9mdOA3yQgGQGJrQaxHgnR2Qj57L5QiAJBKk1Ednwanxa6dzxGvBaw4I+Evuxz6g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.9.tgz", + "integrity": "sha512-4YhNOyTvFKzrL0/abahYjSG1mIEFqFR+xtVom2T8prSk96z8aNgN3f8GUGCtkkC2eYbZvN9tUAGvgMgVq5FfXg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.9.tgz", + "integrity": "sha512-Ng7i+xFFd6I21dpTyA/1VKOuKVUCw5+s9kjeffTmg0OkP3Ldnf2F+XcmNfFAqIirK4Nadi505MVG6delN4XqMw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.9.tgz", + "integrity": "sha512-J9JGwMHb6B2Pi6ewp6kVMhzKHSblqC5QS5gV5u8NKw7semdTzETwwZeJLLUfV3YQqAAQxXNz5FGZDGukcwgO4A==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.9.tgz", + "integrity": "sha512-cD3CbynGfXBU0BKX6AJ2TCqyd14ChhDQsH2P6BMAKSQaDXGzY1DUPZoQWcNXeJnsTqmoEWo59VlKgnZ9iAAd1w==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.9.tgz", + "integrity": "sha512-pEMURtf2ARso1VzpDp66G7FGdvpHcOKAT1+9TEqbbkWZ2ek91/KUGSP7RUSH1io8JpZiBkvoNhwELdgHH9b38g==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.9.tgz", + "integrity": "sha512-x3Ei7a0FYjMe2FMonmgjtRqVlCmrek2NgWC57b4mUbpwtHI9mZV58F0aEdTeA90U0liRks/NRXGQSVETsGP1kg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.9.tgz", + "integrity": "sha512-teiOZq8Eka0Yb3IJypBc4dq2U3u5l6P1vZ4sVjOPWJhOFBeOc3bjUnxv2RHn88jsL2qwX4tXuPc0MoqTO+8gww==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.9.tgz", + "integrity": "sha512-51rITRfuF6LN+kZgAdYwk7qkQFlO87Tm1L/nO34kWEIuu8tJmMn1EBdBNdCOM68f93dILWY64QZECKcW2j2i7Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.9.tgz", + "integrity": "sha512-nA1dtgROg2B4FPJbp3cpldu1dfbAs/uGFGsy+ZgZyIojvrGldgdeasnsKHNRuDI6gF47mb63rge6GKZHCiItuA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.9.tgz", + "integrity": "sha512-BG9NS84ehLVomSi35jSFDeMCRL+Mkz0PsBrjuAkgGHT/k+ZZIQ6rlQBmrAa11q/voQsiH8UeaUzi4FZFQn3syw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.9.tgz", + "integrity": "sha512-771hNPYszO5g7FeqxR4LO8Qmi2xpjRcXjXfMYsgXLFz+5bNkCR4OPllgyz65v9wlTX4ZoVmbh8pCZhpm2LsykA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.9.tgz", + "integrity": "sha512-zLCA6Rw0J04hsqogzzsUxEUr5jaInUgqkKnw3WsSHuCSQPbXWexrgphDDRJZGMeSCn2GQP7gJtzq/I5NwzVc3w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.9.tgz", + "integrity": "sha512-TDl99JOOD8/uz6I3ECtboFOTZzodZ4VzJqfVjHqCo12fF+F/3bcf4dC5UC3lsGXQCGBMCxGZqrjj3h7fQijf1Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.9.tgz", + "integrity": "sha512-oagkVYyesngXT4SmFKcGigT1rOZm/uYYowzg7JPP2k9wngF8cw8Kaunzn+HjejJl+Ec2ZD1F68hiXw2FB4cHYA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.9.tgz", + "integrity": "sha512-uDyXfmD1FCL+6WtyjhHDjqBKl4j0Kej11iQybR6+h72o5fFL6xyEmWsQWoMngJph9tOeiCeD45f+X0OccYyRlQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.9.tgz", + "integrity": "sha512-sHr4zSqntivPmVau57RrRBMEoTqW8V/iLLfWghbvWcLMOR9PuswVASI4cGA4rJ3PLt8rynrNGK5tVftrH2g+dw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.9.tgz", + "integrity": "sha512-WCZET31LREmsAQCWictbgAdkJLejg7Gzm7hYL51wEROMZ7gziQK38WEfLKRp1Rdm2jnwnLxoJu7ttpjHQWr9CQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.9.tgz", + "integrity": "sha512-UwlCeuUlZqWrLpw4LuMgfpp+2e0HOe7cnbkUPoICxCtAFVv3IaB1qKfGaC/iRG3T29hGuzX1Dr20/rqtuVN4bw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.9.tgz", + "integrity": "sha512-NgU7PKTSftWBK2wecMH/McGvM3a4nSa/I8zoS8o22sjPSScuGGyAfr1FoDQWEs+iuvFEQ/PKuRcZ3vO5u0Xqjw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.9.tgz", + "integrity": "sha512-xbFrHua9IPguaCF7I2bRiebq/OGdIJbHbTUruHMrVD91CcIxhNRpkl2JAiGEPpPaqW7hJLUbroXQ07Kde/ziGg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.9.tgz", + "integrity": "sha512-7xXs09Zvhwb0aaVJQ+t+NZYp/G7SMKxt+0BVsoNVP1ckLsTxazNBeqL8b91STBOOPj0o/6NEGLXnFaICm9Yi5Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@tailwindcss/node": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.5.tgz", + "integrity": "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.5", + "jiti": "^2.7.0", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.5.tgz", + "integrity": "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-x64": "4.3.5", + "@tailwindcss/oxide-freebsd-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-x64-musl": "4.3.5", + "@tailwindcss/oxide-wasm32-wasi": "4.3.5", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.5.tgz", + "integrity": "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.5.tgz", + "integrity": "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.5.tgz", + "integrity": "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.5.tgz", + "integrity": "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.5.tgz", + "integrity": "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.5.tgz", + "integrity": "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.5.tgz", + "integrity": "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.5.tgz", + "integrity": "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.5.tgz", + "integrity": "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.5.tgz", + "integrity": "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@emnapi/wasi-threads": "^1.2.3", + "@napi-rs/wasm-runtime": "^1.2.2", + "@tybys/wasm-util": "^0.10.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.2", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.3", + "dev": true, + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "dev": true, + "inBundle": true, + "license": "0BSD", + "optional": true + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.5.tgz", + "integrity": "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.5.tgz", + "integrity": "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/vite": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.5.tgz", + "integrity": "sha512-BCNiY0a1ZjdOHVqw7kyb7U72BwfMF3dfUuN+tQsLWky/J5JOI/r7abibglXfygrZhVO/3u3V+E25kkKTeMkXaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tailwindcss/node": "4.3.5", + "@tailwindcss/oxide": "4.3.5", + "tailwindcss": "4.3.5" + }, + "peerDependencies": { + "vite": "^5.2.0 || ^6 || ^7 || ^8" + } + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.11.tgz", + "integrity": "sha512-YBdNe5JcjYR0sPhJW1QIeRCmI11YhYvaRuGCs9+WCeTTb+Yhb2BE2XMe5/wAqF10FK5g3+q1PDhQABfT7aX0gg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.7.tgz", + "integrity": "sha512-F/Mcc4pD3YwXQCG50hb8BjB5RmrOere6hge7n2XHf0V8tpkZOVEjwYv9Ql7n0MpMn8Bv7+q12P9w6UHsBm0Sfw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/react": { + "version": "19.3.3", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.3.tgz", + "integrity": "sha512-K8uWpJc4teiuOPdiP1umjeA9rGMgVPiXuoL66fcS1QlwBT1WMqY8PORmub9FadopIs+RCW6siYEs7Lpq+vDlog==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.40", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.40.tgz", + "integrity": "sha512-WJhaQ3kW5+5BpOduI64ewvykhCyK/IHHG5jCIzivmW2nkYPRowUjs0DbBXY4CAr1LLrN7QEzZGL9727aXH9sJA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.6", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz", + "integrity": "sha512-CmVVIQ3RVc5HxYEc9X84GvxK/C8C1wH8TlKAiO7uTxF8PDwt7r8t9Qk3J9NkMOVzX5O/HbLv3yzxZg9HPrnI9w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.37", + "caniuse-lite": "^1.0.30001826", + "electron-to-chromium": "^1.5.486", + "node-releases": "^2.0.64", + "update-browserslist-db": "^1.4.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001829", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001829.tgz", + "integrity": "sha512-FeVvlaVr3r+cdHIYXyZhtVkqroSYjYaoNxItxQNjusurUE+IqODawDsbzk02HJgi2RdKiaGGFm+EKbXku+yITg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/csstype": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz", + "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.495", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.495.tgz", + "integrity": "sha512-dZcmtNbDI5oeT9uP9Z+D7h/H5C1mvBewDTLgZgo9WgyPmqOXSt2cmoCK99evPygUOn9lyXZ4w0Eb8APrkBjqBA==", + "dev": true, + "license": "ISC" + }, + "node_modules/enhanced-resolve": { + "version": "5.27.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", + "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/lucide-react": { + "version": "1.83.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.83.0.tgz", + "integrity": "sha512-bYosQeQphbbNtdWT4DvY1/wlen2CcsZEQI/pMykcQ8twiu+T7m7cY7s8hOTJiMEAs3nUxCkeCxTe4ohczS5jhA==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.66", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.66.tgz", + "integrity": "sha512-uSMWN9/XtWzxaE0d9ZNHe00Hda6028AXH3WRjTsK71neiPCSeL5nGSD9MXTQX/6Qx0k7Op1AyyinmIUw9fBzrg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.34", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.34.tgz", + "integrity": "sha512-P1Qzj0XXZjMda74C7qiVnBG90UKNbyNUAOeQRBW8X63RsIMV57gevRqjnkELdwtZ/S2/uQFksJhmwuN8xShLPw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.4" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", + "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-router": { + "version": "7.18.7", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.7.tgz", + "integrity": "sha512-nXl672FFobymVY/Ywbo0DnlXV/+VXOB5pOslCeuVqoegwwL7sau2yASdyGoWHvPRxAoqUBrAiFZRdli4nT7Wow==", + "license": "MIT", + "dependencies": { + "cookie": "^1.0.1", + "set-cookie-parser": "^2.6.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "@types/react": ">=18", + "react": ">=18", + "react-dom": ">=18" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/react-router-dom": { + "version": "7.18.7", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.7.tgz", + "integrity": "sha512-EBWBKV1TjvScebAIvidowN0Bfh9Bg7p54IDBRVJkFXz0wBKTBblDNLxUvCewx/GdzTiC7VWV/MOjWqsLWEMygA==", + "license": "MIT", + "dependencies": { + "react-router": "7.18.7" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + } + }, + "node_modules/rollup": { + "version": "4.68.9", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.9.tgz", + "integrity": "sha512-cv6sHP984hH1Wo4m1yBwyYOTtOVczamnB4KapDqQHCJZLVsMNDsEEP3/+6mHkt7NIAeVGPoE+fFKXRBL5dIjHg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.9", + "@rollup/rollup-android-arm64": "4.68.9", + "@rollup/rollup-android-x64": "4.68.9", + "@rollup/rollup-darwin-arm64": "4.68.9", + "@rollup/rollup-darwin-x64": "4.68.9", + "@rollup/rollup-freebsd-arm64": "4.68.9", + "@rollup/rollup-freebsd-x64": "4.68.9", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.9", + "@rollup/rollup-linux-arm-musleabihf": "4.68.9", + "@rollup/rollup-linux-arm64-gnu": "4.68.9", + "@rollup/rollup-linux-arm64-musl": "4.68.9", + "@rollup/rollup-linux-loong64-gnu": "4.68.9", + "@rollup/rollup-linux-loong64-musl": "4.68.9", + "@rollup/rollup-linux-ppc64-gnu": "4.68.9", + "@rollup/rollup-linux-ppc64-musl": "4.68.9", + "@rollup/rollup-linux-riscv64-gnu": "4.68.9", + "@rollup/rollup-linux-riscv64-musl": "4.68.9", + "@rollup/rollup-linux-s390x-gnu": "4.68.9", + "@rollup/rollup-linux-x64-gnu": "4.68.9", + "@rollup/rollup-linux-x64-musl": "4.68.9", + "@rollup/rollup-openbsd-x64": "4.68.9", + "@rollup/rollup-openharmony-arm64": "4.68.9", + "@rollup/rollup-win32-arm64-msvc": "4.68.9", + "@rollup/rollup-win32-ia32-msvc": "4.68.9", + "@rollup/rollup-win32-x64-gnu": "4.68.9", + "@rollup/rollup-win32-x64-msvc": "4.68.9", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/set-cookie-parser": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.3.tgz", + "integrity": "sha512-irZHtTqurLna57KQG/s+fzOwv/J6XSH4cs8M/vsrY3uCaQ3S6+QJguAH0WdN47SXlk82voMZ4naWMQf8fdEoIg==", + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz", + "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/tailwindcss": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz", + "integrity": "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.4.tgz", + "integrity": "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.4.0.tgz", + "integrity": "sha512-WPJuOnjI9FWDct4fB+ej4Mz8opLaw5CDcZ2t44tFZ0vIQVYWzBhWR3mkixuUj/A7+vY4V9+ApOZ2YYLwdgq46w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "6.4.6", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.6.tgz", + "integrity": "sha512-RtsraAwEG68idOA6iUOoIpOlcSKROnf815aIq9qHTSrDNpLoBrBa12suyfcEd8qn0xwOVQI1Yhm1GbmTjF600A==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/zustand": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.1.0.tgz", + "integrity": "sha512-ciJZlP48M1PTQbVQq81CGVFxHTLpZNrFjKqwjtCU34AWuXTZT/jrF3p9+fI84Cf1eSCMLapxqBy/SNTfwOBuqA==", + "license": "MIT", + "engines": { + "node": ">=12.20.0" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "immer": ">=9.0.6", + "react": ">=18.0.0", + "use-sync-external-store": ">=1.2.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + }, + "use-sync-external-store": { + "optional": true + } + } + } + } +} diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..cb443a1 --- /dev/null +++ b/web/package.json @@ -0,0 +1,29 @@ +{ + "name": "cotizador-uj-web", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "preview": "vite preview" + }, + "dependencies": { + "clsx": "^2.1.1", + "lucide-react": "^1.11.0", + "react": "^19.2.4", + "react-dom": "^19.2.4", + "react-router-dom": "^7.5.0", + "zustand": "^5.0.12" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.1.0", + "@types/node": "^22.0.0", + "@types/react": "^19.2.4", + "@types/react-dom": "^19.2.4", + "@vitejs/plugin-react": "^4.4.0", + "tailwindcss": "^4.1.0", + "typescript": "^5.8.0", + "vite": "^6.3.0" + } +} diff --git a/src/app/favicon.ico b/web/public/favicon.ico similarity index 100% rename from src/app/favicon.ico rename to web/public/favicon.ico diff --git a/public/sw.js b/web/public/sw.js similarity index 100% rename from public/sw.js rename to web/public/sw.js diff --git a/web/src/App.tsx b/web/src/App.tsx new file mode 100644 index 0000000..ef0fabc --- /dev/null +++ b/web/src/App.tsx @@ -0,0 +1,93 @@ +import { Navigate, Outlet, Route, Routes } from "react-router-dom"; +import { AuthProvider, useAuth } from "@/lib/auth"; +import { DialogProvider } from "@/components/ui/DialogProvider"; +import { LoadingScreen } from "@/components/ui/LoadingScreen"; +import Sidebar from "@/components/layout/Sidebar"; +import LoginPage from "@/pages/LoginPage"; +import AprobarTokenPage from "@/pages/AprobarTokenPage"; +import { DashboardPage } from "@/pages/app/DashboardPage"; +import { CotizacionesPage } from "@/pages/app/cotizaciones/CotizacionesPage"; +import { NuevaCotizacionPage } from "@/pages/app/cotizaciones/NuevaCotizacionPage"; +import { CotizacionDetailPage } from "@/pages/app/cotizaciones/CotizacionDetailPage"; +import { EditarCotizacionPage } from "@/pages/app/cotizaciones/EditarCotizacionPage"; +import { ClientesPage } from "@/pages/app/ClientesPage"; +import { CatalogoPage } from "@/pages/app/CatalogoPage"; +import { CobrosPage } from "@/pages/app/cobros/CobrosPage"; +import { ConfiguracionPage } from "@/pages/app/ConfiguracionPage"; +import { ClienteShell } from "@/pages/cliente/ClienteShell"; +import { ClienteInicioPage } from "@/pages/cliente/ClienteInicioPage"; +import { ClienteCotizacionesPage } from "@/pages/cliente/ClienteCotizacionesPage"; +import { ClienteCotizacionDetallePage } from "@/pages/cliente/ClienteCotizacionDetallePage"; +import { ClientePagosPage } from "@/pages/cliente/ClientePagosPage"; + +function StaffGuardLayout() { + const { user, loading } = useAuth(); + if (loading) return ; + if (!user) return ; + if (user.role === "cliente") return ; + + return ( + +
+ +
+
+ +
+
+
+
+ ); +} + +function ClienteGuardLayout() { + const { user, loading } = useAuth(); + if (loading) return ; + if (!user) return ; + if (user.role !== "cliente") return ; + + return ( + +
+ +
+ +
+
+
+ ); +} + +export function App() { + return ( + + + } /> + } /> + + }> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + + }> + } /> + } /> + } /> + } /> + + + } /> + + + ); +} + +export default App; diff --git a/src/components/CotizacionForm.tsx b/web/src/components/CotizacionForm.tsx similarity index 99% rename from src/components/CotizacionForm.tsx rename to web/src/components/CotizacionForm.tsx index a3c081f..cd6dd81 100644 --- a/src/components/CotizacionForm.tsx +++ b/web/src/components/CotizacionForm.tsx @@ -1,7 +1,5 @@ -"use client"; - import { useEffect, useMemo, useState } from "react"; -import { useRouter } from "next/navigation"; +import { useNavigate } from "react-router-dom"; import { Save, ChevronDown, @@ -153,7 +151,7 @@ export function CotizacionForm({ existingData, paquetes, }: CotizacionFormProps) { - const router = useRouter(); + const navigate = useNavigate(); const store = useCotizacionStore(); const showToast = useToast(); @@ -424,9 +422,9 @@ export function CotizacionForm({ if (res.ok) { if (mode === "new") { const data = await res.json(); - router.push(`/cotizaciones/${data.id}`); + navigate(`/cotizaciones/${data.id}`); } else { - router.push(`/cotizaciones/${existingData!.id}`); + navigate(`/cotizaciones/${existingData!.id}`); } } else { const err = await res.json(); diff --git a/src/components/EstadoBadge.tsx b/web/src/components/EstadoBadge.tsx similarity index 100% rename from src/components/EstadoBadge.tsx rename to web/src/components/EstadoBadge.tsx diff --git a/src/components/ExportButtons.tsx b/web/src/components/ExportButtons.tsx similarity index 100% rename from src/components/ExportButtons.tsx rename to web/src/components/ExportButtons.tsx diff --git a/src/components/PropuestaIAPanel.tsx b/web/src/components/PropuestaIAPanel.tsx similarity index 100% rename from src/components/PropuestaIAPanel.tsx rename to web/src/components/PropuestaIAPanel.tsx diff --git a/src/components/ServicioFormModal.tsx b/web/src/components/ServicioFormModal.tsx similarity index 100% rename from src/components/ServicioFormModal.tsx rename to web/src/components/ServicioFormModal.tsx diff --git a/src/components/layout/Sidebar.tsx b/web/src/components/layout/Sidebar.tsx similarity index 87% rename from src/components/layout/Sidebar.tsx rename to web/src/components/layout/Sidebar.tsx index 0494b22..89d031a 100644 --- a/src/components/layout/Sidebar.tsx +++ b/web/src/components/layout/Sidebar.tsx @@ -1,7 +1,4 @@ -"use client"; - -import Link from "next/link"; -import { usePathname, useRouter } from "next/navigation"; +import { Link, useLocation, useNavigate } from "react-router-dom"; import { LayoutDashboard, FileText, @@ -15,6 +12,7 @@ import { } from "lucide-react"; import { useState } from "react"; import clsx from "clsx"; +import { useAuth } from "@/lib/auth"; const navigation = [ { name: "Dashboard", href: "/", icon: LayoutDashboard }, @@ -26,14 +24,19 @@ const navigation = [ ]; export default function Sidebar() { - const pathname = usePathname(); - const router = useRouter(); + const { pathname } = useLocation(); + const navigate = useNavigate(); + const { setUser } = useAuth(); const [mobileOpen, setMobileOpen] = useState(false); const handleLogout = async () => { - await fetch("/api/auth/logout", { method: "POST" }); - router.push("/login"); - router.refresh(); + try { + await fetch("/api/auth/logout", { method: "POST" }); + } catch { + // Aunque falle la peticion, limpiamos la sesion local. + } + setUser(null); + navigate("/login", { replace: true }); }; return ( @@ -79,7 +82,7 @@ export default function Sidebar() { return ( setMobileOpen(false)} className={clsx( "flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors", diff --git a/src/components/ui/DialogProvider.tsx b/web/src/components/ui/DialogProvider.tsx similarity index 100% rename from src/components/ui/DialogProvider.tsx rename to web/src/components/ui/DialogProvider.tsx diff --git a/web/src/components/ui/LoadingScreen.tsx b/web/src/components/ui/LoadingScreen.tsx new file mode 100644 index 0000000..833f00c --- /dev/null +++ b/web/src/components/ui/LoadingScreen.tsx @@ -0,0 +1,44 @@ +import { Loader2 } from "lucide-react"; + +export function LoadingScreen({ + mensaje, + label, +}: { + mensaje?: string; + label?: string; +}) { + const texto = mensaje ?? label ?? "Cargando..."; + return ( +
+
+ + {texto} +
+
+ ); +} + +export function PageError({ + mensaje, + message, + onRetry, +}: { + mensaje?: string; + message?: string; + onRetry?: () => void; +}) { + const texto = mensaje ?? message ?? "No se pudo cargar la información"; + return ( +
+

{texto}

+ {onRetry && ( + + )} +
+ ); +} diff --git a/src/components/ui/Modal.tsx b/web/src/components/ui/Modal.tsx similarity index 100% rename from src/components/ui/Modal.tsx rename to web/src/components/ui/Modal.tsx diff --git a/src/app/globals.css b/web/src/index.css similarity index 93% rename from src/app/globals.css rename to web/src/index.css index 025df75..cab3eaf 100644 --- a/src/app/globals.css +++ b/web/src/index.css @@ -1,6 +1,9 @@ @import "tailwindcss"; :root { + --font-figtree: "Figtree", sans-serif; + --font-archivo: "Archivo", sans-serif; + --font-geist-mono: "Geist Mono", monospace; --background: #f8fafc; --foreground: #0f172a; --primary: #0400c4; diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts new file mode 100644 index 0000000..5adc849 --- /dev/null +++ b/web/src/lib/api.ts @@ -0,0 +1,90 @@ +export interface BrandingConfig { + colorPrimario?: string; + colorSecundario?: string; + logoBase64?: string; + logoMime?: string; +} + +export const DEFAULT_COLOR_PRIMARIO = "#0400C4"; +export const DEFAULT_COLOR_SECUNDARIO = "#0F172A"; + +export function parseBrandingFromConfig(map: Record): BrandingConfig { + const rawLogo = map.logo_base64; + return { + colorPrimario: map.color_primario || DEFAULT_COLOR_PRIMARIO, + colorSecundario: map.color_secundario || DEFAULT_COLOR_SECUNDARIO, + logoBase64: rawLogo + ? rawLogo.includes(":") + ? rawLogo.split(":").slice(1).join(":") + : rawLogo + : undefined, + logoMime: rawLogo + ? rawLogo.includes(":") + ? rawLogo.split(":")[0] + : "image/png" + : undefined, + }; +} + +export interface PaqueteServicioItem { + id: string; + nombre: string; + fase: number; + tipoPago: string; + precioBase: number; + tiempoEntrega: string; + entregablesDefault: string[]; + nivel: string | null; +} + +export interface PaqueteNormalizado { + id: string; + nombre: string; + descripcion: string | null; + fases: { + id: string; + nombre: string; + orden: number; + servicios: PaqueteServicioItem[]; + }[]; +} + +// Normaliza la respuesta de GET /api/paquetes tanto si `fases[].servicios` viene +// plano (ServicioCatalogo) como si viene envuelto en `{ servicio: ... }` (Prisma join). +export function normalizarPaquetes(raw: unknown): PaqueteNormalizado[] { + if (!Array.isArray(raw)) return []; + return raw.map((p: Record) => { + const fasesRaw = Array.isArray(p.fases) ? (p.fases as Record[]) : []; + return { + id: String(p.id ?? ""), + nombre: String(p.nombre ?? ""), + descripcion: typeof p.descripcion === "string" ? p.descripcion : null, + fases: fasesRaw.map((f) => { + const servsRaw = Array.isArray(f.servicios) ? (f.servicios as Record[]) : []; + return { + id: String(f.id ?? ""), + nombre: String(f.nombre ?? ""), + orden: Number(f.orden ?? 0), + servicios: servsRaw + .map((entry) => { + const s = (entry.servicio ?? entry) as Record | undefined; + if (!s) return null; + return { + id: String(s.id ?? ""), + nombre: String(s.nombre ?? ""), + fase: Number(s.fase ?? 1), + tipoPago: String(s.tipoPago ?? "unico"), + precioBase: Number(s.precioBase ?? 0), + tiempoEntrega: String(s.tiempoEntrega ?? ""), + entregablesDefault: Array.isArray(s.entregablesDefault) + ? (s.entregablesDefault as string[]) + : [], + nivel: typeof s.nivel === "string" ? s.nivel : null, + }; + }) + .filter((x): x is PaqueteServicioItem => x !== null), + }; + }), + }; + }); +} diff --git a/web/src/lib/auth.tsx b/web/src/lib/auth.tsx new file mode 100644 index 0000000..48f6179 --- /dev/null +++ b/web/src/lib/auth.tsx @@ -0,0 +1,67 @@ +import { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useState, +} from "react"; + +export interface SessionUser { + userId: string; + email: string; + name: string; + role: string; + clienteId?: string | null; + clienteNombre?: string | null; +} + +interface AuthContextValue { + user: SessionUser | null; + loading: boolean; + setUser: (user: SessionUser | null) => void; + refreshUser: () => Promise; +} + +const AuthContext = createContext(null); + +export function AuthProvider({ children }: { children: React.ReactNode }) { + const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); + + const refreshUser = useCallback(async (): Promise => { + try { + const res = await fetch("/api/auth/me", { credentials: "same-origin" }); + if (!res.ok) { + setUser(null); + return null; + } + const data = (await res.json()) as { user?: SessionUser | null }; + const u = data?.user ?? null; + setUser(u); + return u; + } catch { + setUser(null); + return null; + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { + void refreshUser(); + }, [refreshUser]); + + const value = useMemo( + () => ({ user, loading, setUser, refreshUser }), + [user, loading, refreshUser] + ); + + return {children}; +} + +export function useAuth(): AuthContextValue { + const ctx = useContext(AuthContext); + if (!ctx) throw new Error("useAuth debe usarse dentro de "); + return ctx; +} diff --git a/src/lib/calculators.ts b/web/src/lib/calculators.ts similarity index 100% rename from src/lib/calculators.ts rename to web/src/lib/calculators.ts diff --git a/src/lib/cobros-fechas.ts b/web/src/lib/cobros-fechas.ts similarity index 90% rename from src/lib/cobros-fechas.ts rename to web/src/lib/cobros-fechas.ts index c5ac5dd..cb6817a 100644 --- a/src/lib/cobros-fechas.ts +++ b/web/src/lib/cobros-fechas.ts @@ -1,10 +1,5 @@ // Utilidades PURAS de los cobros recurrentes: fechas de calendario, estados y -// formatos. Sin prisma ni fs — SEGURO PARA COMPONENTES "use client" (los -// componentes del navegador importan de aqui, NUNCA de @/lib/cobros, que si -// arrastra la BD y rompe el build de Next). -// -// La logica que toca la BD (generarCobros) vive en @/lib/cobros, que re-exporta -// todo lo de este archivo para el lado servidor. +// formatos. // // CONVENCION DE FECHAS: una fecha de cobro es una FECHA DE CALENDARIO en // America/Mexico_City, persistida como medianoche UTC de ese calendario @@ -12,7 +7,13 @@ // con formatFechaCobro(). Asi "sabado" es sabado en Mexico aunque el servidor // este en UTC. -import type { ProgramaPago } from "@/generated/prisma/client"; +export interface ProgramaPagoCalendario { + frecuencia: string; + diaSemana?: number | null; + diaMes?: number | null; + fechaInicio: Date | string; + fechaFin?: Date | string | null; +} export const ZONA_HORARIA = "America/Mexico_City"; @@ -126,6 +127,19 @@ export function formatMonto(monto: number, moneda: string = "MXN"): string { }).format(monto); } +// Suma por moneda: un cliente puede tener programas en MXN y USD y no se +// deben mezclar en un solo total. +export function totalesPorMoneda( + pagos: Array<{ monto: number; programa: { moneda: string } }> +): Record { + const totales: Record = {}; + for (const p of pagos) { + const moneda = p.programa.moneda || "MXN"; + totales[moneda] = (totales[moneda] ?? 0) + p.monto; + } + return totales; +} + // Totales por moneda en una linea: "$2,250" o "$1,500 + USD 100". export function formatTotales(totales: Record): string { const partes = Object.entries(totales).map(([moneda, total]) => formatMonto(total, moneda)); @@ -163,18 +177,22 @@ export function formatFechaCorta(date: Date): string { return `${String(d).padStart(2, "0")}/${String(m).padStart(2, "0")}/${y}`; } +function toDate(value: Date | string): Date { + return value instanceof Date ? value : new Date(value); +} + // Todas las fechas de periodo de un programa desde fechaInicio hasta `hasta` // (inclusive), respetando fechaFin si existe. Cadena: // semanal -> diaSemana (0=dom..6=sab; si no viene, el mismo dia que fechaInicio) // quincenal -> dias 1 y 15 de cada mes // mensual -> diaMes (se recorta al ultimo dia del mes si no existe) export function fechasPeriodo( - programa: Pick, + programa: ProgramaPagoCalendario, hasta: Date ): Date[] { - const inicio = aCalendario(programa.fechaInicio); + const inicio = aCalendario(toDate(programa.fechaInicio)); const inicioD = new Date(Date.UTC(inicio.y, inicio.m - 1, inicio.d)); - const fin = programa.fechaFin ? aCalendario(programa.fechaFin) : null; + const fin = programa.fechaFin ? aCalendario(toDate(programa.fechaFin)) : null; const finD = fin ? new Date(Date.UTC(fin.y, fin.m - 1, fin.d)) : null; const limite = finD && finD < hasta ? finD : hasta; if (inicioD > limite) return []; @@ -220,7 +238,7 @@ export function fechasPeriodo( // Proxima fecha de cobro >= `desde` (por defecto hoy MX) para el panel admin. export function proximaFecha( - programa: Pick, + programa: ProgramaPagoCalendario, desde: Date = hoyCalendario() ): Date | null { const ventana = fechasPeriodo(programa, sumarDias(desde, 366)); diff --git a/src/lib/store.ts b/web/src/lib/store.ts similarity index 100% rename from src/lib/store.ts rename to web/src/lib/store.ts diff --git a/web/src/main.tsx b/web/src/main.tsx new file mode 100644 index 0000000..1b40c4e --- /dev/null +++ b/web/src/main.tsx @@ -0,0 +1,13 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { BrowserRouter } from "react-router-dom"; +import App from "./App"; +import "./index.css"; + +createRoot(document.getElementById("root")!).render( + + + + + +); diff --git a/src/app/aprobar/[token]/AprobarClient.tsx b/web/src/pages/AprobarTokenPage.tsx similarity index 65% rename from src/app/aprobar/[token]/AprobarClient.tsx rename to web/src/pages/AprobarTokenPage.tsx index 27e220d..62ea5b4 100644 --- a/src/app/aprobar/[token]/AprobarClient.tsx +++ b/web/src/pages/AprobarTokenPage.tsx @@ -1,8 +1,7 @@ -"use client"; - -import { useState } from "react"; +import { useEffect, useState } from "react"; +import { useParams } from "react-router-dom"; import { CheckCircle2, AlertTriangle, Loader2, ShieldCheck } from "lucide-react"; -import { formatCurrency } from "@/lib/calculators"; +import { formatCurrency, formatDate } from "@/lib/calculators"; interface PartidaResumen { id: string; @@ -13,31 +12,102 @@ interface PartidaResumen { tiempoEntrega: string; } -interface ResumenProps { - token: string; - cotizacion: { - id: string; - numero: string; - proyecto: string; - moneda: string; - estado: string; - vigenciaTexto: string; - creadaPorAgente: string | null; - cliente: { nombre: string; empresa: string | null }; - totalUnico: number; - totalMensual: number; - incluirIva: boolean; - partidas: PartidaResumen[]; - }; - puedeAprobar: boolean; +interface AprobarCotizacionData { + id: string; + numero: string; + proyecto: string; + moneda: string; + estado: string; + vigencia?: string; + vigenciaTexto?: string; + creadaPorAgente: string | null; + cliente: { nombre: string; empresa: string | null }; + totales?: { totalUnico: number; totalMensual: number }; + totalUnico?: number; + totalMensual?: number; + incluirIva: boolean; + partidas: PartidaResumen[]; } -export function AprobarClient({ token, cotizacion, puedeAprobar }: ResumenProps) { - const [estado, setEstado] = useState(cotizacion.estado); +interface AprobarApiResponse { + cotizacion: AprobarCotizacionData; + puedeAprobar: boolean; + expiraAt?: string; +} + +export default function AprobarTokenPage() { + const { token = "" } = useParams<{ token: string }>(); + const [cargando, setCargando] = useState(true); + const [motivoInvalido, setMotivoInvalido] = useState(null); + const [data, setData] = useState(null); + const [estado, setEstado] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [aprobadaOk, setAprobadaOk] = useState(false); + useEffect(() => { + let vivo = true; + setCargando(true); + setMotivoInvalido(null); + fetch(`/api/aprobar/${encodeURIComponent(token)}`) + .then(async (res) => { + const body = await res.json().catch(() => ({})); + if (!vivo) return; + if (!res.ok) { + setMotivoInvalido( + body.error || "Este enlace de aprobación no está disponible." + ); + return; + } + const payload = body as AprobarApiResponse; + setData(payload); + setEstado(payload.cotizacion.estado); + }) + .catch(() => { + if (vivo) setMotivoInvalido("Error de conexión al verificar el enlace."); + }) + .finally(() => { + if (vivo) setCargando(false); + }); + return () => { + vivo = false; + }; + }, [token]); + + if (cargando) { + return ( +
+
+ + Verificando enlace de aprobación… +
+
+ ); + } + + if (motivoInvalido || !data) { + return ( +
+
+

+ Uriel Jareth Consulting +

+

Enlace no disponible

+

+ {motivoInvalido || "Este enlace de aprobación no es válido."} +

+
+
+ ); + } + + const { cotizacion, puedeAprobar } = data; + const totalUnico = cotizacion.totales?.totalUnico ?? cotizacion.totalUnico ?? 0; + const totalMensual = cotizacion.totales?.totalMensual ?? cotizacion.totalMensual ?? 0; + const vigenciaTexto = + cotizacion.vigenciaTexto || + (cotizacion.vigencia ? formatDate(new Date(cotizacion.vigencia)) : "—"); + const handleAprobar = async () => { setLoading(true); setError(null); @@ -47,9 +117,9 @@ export function AprobarClient({ token, cotizacion, puedeAprobar }: ResumenProps) headers: { "Content-Type": "application/json" }, body: JSON.stringify({ confirmar: true }), }); - const data = await res.json().catch(() => ({})); + const resBody = await res.json().catch(() => ({})); if (!res.ok) { - setError(data.error || "No se pudo aprobar la cotización"); + setError(resBody.error || "No se pudo aprobar la cotización"); return; } setEstado("aprobada"); @@ -117,7 +187,7 @@ export function AprobarClient({ token, cotizacion, puedeAprobar }: ResumenProps)
Vigencia - {cotizacion.vigenciaTexto} + {vigenciaTexto}
Origen @@ -155,16 +225,16 @@ export function AprobarClient({ token, cotizacion, puedeAprobar }: ResumenProps)
- {cotizacion.totalUnico > 0 && ( + {totalUnico > 0 && (
Total único ({cotizacion.incluirIva ? "c/IVA" : "s/IVA"}): - {formatCurrency(cotizacion.totalUnico)} {cotizacion.moneda} + {formatCurrency(totalUnico)} {cotizacion.moneda}
)} - {cotizacion.totalMensual > 0 && ( + {totalMensual > 0 && (
Total mensual ({cotizacion.incluirIva ? "c/IVA" : "s/IVA"}): - {formatCurrency(cotizacion.totalMensual)} {cotizacion.moneda}/mes + {formatCurrency(totalMensual)} {cotizacion.moneda}/mes
)}
diff --git a/src/app/login/LoginForm.tsx b/web/src/pages/LoginPage.tsx similarity index 78% rename from src/app/login/LoginForm.tsx rename to web/src/pages/LoginPage.tsx index 757eeee..e7b0dfb 100644 --- a/src/app/login/LoginForm.tsx +++ b/web/src/pages/LoginPage.tsx @@ -1,14 +1,12 @@ -"use client"; - import { useState } from "react"; -import { useRouter } from "next/navigation"; +import { useNavigate, useSearchParams } from "react-router-dom"; +import { useAuth } from "@/lib/auth"; -// /login?panel=cliente: el middleware manda aqui a quien abre /cliente sin -// sesion; el formulario es el mismo, solo cambia el encabezado. `esCliente` lo -// resuelve page.tsx en el servidor: con useSearchParams + Suspense el -// formulario completo salia del HTML y aparecia hasta cargar el JS. -export function LoginForm({ esCliente }: { esCliente: boolean }) { - const router = useRouter(); +export default function LoginPage() { + const [searchParams] = useSearchParams(); + const esCliente = searchParams.get("panel") === "cliente"; + const navigate = useNavigate(); + const { setUser, refreshUser } = useAuth(); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(""); @@ -28,12 +26,21 @@ export function LoginForm({ esCliente }: { esCliente: boolean }) { if (res.ok) { const data = await res.json(); - // Cada rol entra a su propio panel. - const destino = data?.user?.role === "cliente" ? "/cliente" : "/"; - router.push(destino); - router.refresh(); + const me = await refreshUser(); + const role = me?.role ?? data?.user?.role; + if (!me && data?.user) { + setUser({ + userId: data.user.userId ?? data.user.id ?? "", + email: data.user.email ?? email, + name: data.user.name ?? "", + role: data.user.role ?? "asesor", + clienteId: data.user.clienteId ?? null, + }); + } + const destino = role === "cliente" ? "/cliente" : "/"; + navigate(destino, { replace: true }); } else { - const data = await res.json(); + const data = await res.json().catch(() => ({})); setError(data.error || "No se pudo iniciar sesión"); } } catch { @@ -75,7 +82,6 @@ export function LoginForm({ esCliente }: { esCliente: boolean }) { onChange={(e) => setEmail(e.target.value)} required placeholder="tu@email.com" - suppressHydrationWarning className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" />
@@ -91,14 +97,12 @@ export function LoginForm({ esCliente }: { esCliente: boolean }) { onChange={(e) => setPassword(e.target.value)} required placeholder="Tu contraseña" - suppressHydrationWarning className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" />