Catalogo: crear y editar servicios desde el cotizador; CLI para LLMs
- CotizacionForm: "Nuevo servicio" (general y por fase) lo crea en el catalogo y lo deja seleccionado; el lapiz de cada servicio lo edita y actualiza la partida (el precio solo si no se ajusto a mano). - ServicioFormModal compartido con /catalogo: hace el POST/PATCH y muestra el error de la API sin cerrarse (antes un alta "Sin categoria" fallaba en silencio). - /api/catalogo: validacion con defaults, filtros en GET, GET por id, PATCH/PUT parciales, campos desconocidos rechazados con su nombre, errores con detalles por campo. - POST /api/cotizaciones acepta cuerpo minimo (numero, asesor, fechas y precio de Bucefalo CRM los completa el servidor); GET con filtros. - GET /api/clientes con busqueda. - Seguridad: las respuestas de cotizaciones ya no incluyen el hash de la contrasena del asesor. - cli/cotizador.mjs: CLI sin dependencias, JSON en stdout, codigos de salida fijos, `esquema` autodescriptivo, --dry-run y --confirmar. Docs en docs/CLI.md y skill en .claude/skills/cotizador-cli. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
78385a8ac8
commit
75180b0fe4
@@ -0,0 +1,36 @@
|
||||
---
|
||||
name: cotizador-cli
|
||||
description: Usa el CLI `cotizador` para operar el Cotizador E3 desde la terminal — crear y editar servicios del catálogo, dar de alta clientes, armar cotizaciones, cambiar su estado, descargar PDF/Excel y registrar horas. Úsalo cuando pidan "crea un servicio", "sube el precio de X", "cotiza a este cliente", "lista las cotizaciones enviadas", "descarga el PDF de UJ..." o cualquier operación sobre la plataforma sin abrir el navegador.
|
||||
---
|
||||
|
||||
# Operar el Cotizador E3 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 <comando>`.
|
||||
|
||||
## 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.
|
||||
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
|
||||
|
||||
- Salida JSON en stdout; errores JSON en stderr con `codigo` y a veces `sugerencia`: léela y síguela.
|
||||
- Usa `--campos` para traer solo lo que necesitas (`--campos id,nombre,precioBase`).
|
||||
- Antes de crear, editar o borrar algo que el usuario no haya pedido literalmente, corre el comando con `--dry-run` y muéstrale la petición.
|
||||
- `eliminar` exige `--confirmar`. No lo agregues por tu cuenta: es una acción irreversible y la decide el usuario.
|
||||
- Editar un servicio es parcial. `--entregable` reemplaza la lista; para sumar uno usa `--agregar-entregable`.
|
||||
- Para referirte a un servicio puedes usar su nombre exacto; si sale "ambiguo", usa el id de la sugerencia.
|
||||
|
||||
## 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 "<nombre o id>" --precio 5500
|
||||
node cli/cotizador.mjs cotizaciones crear --cliente "..." --empresa "..." --servicio "<nombre o id>" --servicio "<id>=4500"
|
||||
node cli/cotizador.mjs cotizaciones estado UJ2611AD001 enviada
|
||||
node cli/cotizador.mjs cotizaciones pdf UJ2611AD001 --salida ./cotizacion.pdf
|
||||
```
|
||||
|
||||
Guía completa: `docs/CLI.md`.
|
||||
@@ -11,6 +11,7 @@
|
||||
| `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 -- <comando>` | CLI `cotizador` (servicios, clientes, cotizaciones, horas). `node cli/cotizador.mjs esquema` lo describe en JSON. See `docs/CLI.md` |
|
||||
|
||||
**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.
|
||||
|
||||
@@ -50,6 +51,14 @@
|
||||
- **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.
|
||||
|
||||
### Catálogo de servicios (alta y edición)
|
||||
|
||||
- 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.
|
||||
|
||||
### 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`.
|
||||
@@ -75,6 +84,14 @@ A quoted line item is `fijo` (default), `horas`, `retainer`, or `demanda` — se
|
||||
- **`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-e3/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).
|
||||
@@ -107,8 +124,8 @@ src/
|
||||
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.4k lines), ExportButtons, EstadoBadge, layout/Sidebar, ui/DialogProvider
|
||||
lib/ # auth, db, store, calculators, schemas, config-helpers,
|
||||
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/
|
||||
@@ -117,6 +134,7 @@ prisma/
|
||||
# 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
|
||||
```
|
||||
|
||||
+1441
File diff suppressed because it is too large
Load Diff
+112
@@ -0,0 +1,112 @@
|
||||
# CLI `cotizador`
|
||||
|
||||
Opera el Cotizador E3 desde la terminal: catálogo de servicios, categorías, paquetes, clientes, cotizaciones y horas. Está hecho para que lo use una persona o una LLM: la salida es JSON, los errores son JSON con código de salida, y `cotizador esquema` describe todos los comandos en JSON.
|
||||
|
||||
- Código: `cli/cotizador.mjs` (Node 18+, sin dependencias).
|
||||
- Habla con la API de Next.js (`src/app/api`), la misma que usa la web, con la sesión de un usuario **staff** (admin o asesor). Las cuentas de rol `cliente` no sirven.
|
||||
|
||||
## Cómo ejecutarlo
|
||||
|
||||
```bash
|
||||
node cli/cotizador.mjs <comando> # desde la raíz del repo
|
||||
npm run cli -- <comando> # equivalente
|
||||
npm link && cotizador <comando> # instala el comando "cotizador" globalmente
|
||||
```
|
||||
|
||||
## Configuración
|
||||
|
||||
| Variable | Uso |
|
||||
|---|---|
|
||||
| `COTIZADOR_URL` | URL base. Default `http://localhost:3000`. Producción: `https://cotizador.urieljareth.org` |
|
||||
| `COTIZADOR_EMAIL` / `COTIZADOR_PASSWORD` | Login automático cuando no hay sesión o venció (útil para agentes) |
|
||||
| `COTIZADOR_TOKEN` | Token de sesión explícito (omite el archivo de sesiones) |
|
||||
| `COTIZADOR_HOME` | Carpeta de la sesión guardada. Default `~/.cotizador-e3` |
|
||||
|
||||
`cotizador login` guarda el token (dura 7 días) en `~/.cotizador-e3/sesiones.json`, una sesión por URL. La contraseña nunca se guarda.
|
||||
|
||||
```bash
|
||||
cotizador login --email [email protected] --password-stdin < pass.txt
|
||||
cotizador whoami
|
||||
```
|
||||
|
||||
## Convenciones (lo que una LLM necesita saber)
|
||||
|
||||
- **Salida**: JSON en stdout. `--campos id,nombre,precioBase` recorta campos (acepta rutas con punto: `planBucefalo.nivel`). `--formato tabla` es para humanos. `--compacto` deja el JSON en una línea.
|
||||
- **Errores**: JSON en stderr `{ ok:false, error, codigo, status?, detalles?, sugerencia? }`. `detalles` lista cada campo rechazado por el servidor. `sugerencia` dice qué ejecutar a continuación.
|
||||
- **Códigos de salida**: 0 ok · 1 error del servidor · 2 uso incorrecto · 3 sin sesión o sin permiso · 4 no encontrado · 5 validación · 6 duplicado · 7 sin conexión.
|
||||
- **Entrada**: flags `--kebab-case`. Para cuerpos completos, `--datos` acepta JSON en línea, `@archivo.json` o `-` (stdin). Las flags pisan lo que venga en `--datos`.
|
||||
- **Referencias**: donde se pide el id de un servicio también vale su nombre exacto. Las cotizaciones aceptan el número (`UJ2611AD001`). Las categorías, el id o el nombre.
|
||||
- **Escrituras seguras**: `--dry-run` muestra la petición sin enviarla. Borrar exige `--confirmar`. Una flag desconocida es error, no se ignora.
|
||||
- **Montos**: MXN sin IVA. El IVA (16 %) se calcula al cotizar.
|
||||
|
||||
## Servicios del catálogo
|
||||
|
||||
```bash
|
||||
cotizador servicios listar --fase 1 --campos id,nombre,precioBase # solo activos
|
||||
cotizador servicios listar --q "seo" --todos # incluye archivados
|
||||
cotizador servicios ver "Auditoria en Sitio Web"
|
||||
|
||||
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 editar "Auditoria SEO tecnica" --precio 7200 # solo cambia el precio
|
||||
cotizador servicios editar <id> --agregar-entregable "Checklist" # agrega sin reemplazar
|
||||
cotizador servicios editar <id> --entregable "A" --entregable "B" # reemplaza la lista
|
||||
|
||||
cotizador servicios archivar <id> # lo oculta al cotizar; reversible con "servicios activar"
|
||||
cotizador servicios eliminar <id> --confirmar
|
||||
```
|
||||
|
||||
Obligatorios al crear: `--nombre`, `--fase` (0-3), `--tipo-pago` (`unico`|`mensual`), `--precio`. Sin `--orden`, el servicio queda al final de su fase.
|
||||
|
||||
**Editar** es parcial: solo cambia lo que pasas. Las cotizaciones ya guardadas conservan su precio, entregables y tiempo de entrega; el **nombre** sí cambia en ellas, porque se lee del catálogo.
|
||||
|
||||
**Eliminar** borra el servicio solo si ninguna cotización lo usa. Si alguna lo usa, el servidor lo archiva (`archived: true`) para no romperla.
|
||||
|
||||
## Cotizaciones
|
||||
|
||||
```bash
|
||||
cotizador cotizaciones crear --cliente "Ana Ruiz" --empresa "Panaderia Sol" \
|
||||
--servicio "Auditoria en Sitio Web" --servicio <id>=4500 \
|
||||
--partida-horas "Soporte tecnico|10|700" --bucefalo estandar
|
||||
|
||||
cotizador cotizaciones listar --estado enviada --formato tabla
|
||||
cotizador cotizaciones ver UJ2611AD001
|
||||
cotizador cotizaciones estado UJ2611AD001 enviada
|
||||
cotizador cotizaciones pdf UJ2611AD001 --salida ./cotizacion.pdf
|
||||
cotizador cotizaciones excel UJ2611AD001
|
||||
```
|
||||
|
||||
Al crear, el servidor asigna el número (`UJ{AA}{MM}{iniciales}{consecutivo}`), el asesor (el usuario de la sesión), la fecha (hoy) y la vigencia (15 días hábiles). Si el cliente (nombre + empresa) no existe, se da de alta. `--servicio id=precio` ajusta el precio de esa partida sin tocar el catálogo. El precio del plan de Bucéfalo CRM sale de la lista de precios del servidor.
|
||||
|
||||
Para cotizaciones de doble propuesta, retainer o demanda, manda el cuerpo completo con `--datos` (el formato de cada partida está en `cotizador esquema` → `formatos.partidaCotizacion`). Las ediciones completas de una cotización existente se hacen en la web o con `cotizador api PUT /api/cotizaciones/<id> --datos @cuerpo.json`.
|
||||
|
||||
## Clientes, categorías, paquetes y horas
|
||||
|
||||
```bash
|
||||
cotizador clientes listar --q sol
|
||||
cotizador clientes crear --nombre "Ana Ruiz" --empresa "Panaderia Sol" --email [email protected]
|
||||
cotizador clientes editar <id> --telefono "442 000 0000"
|
||||
|
||||
cotizador categorias listar
|
||||
cotizador categorias crear --nombre "Automatizacion" --color "#0ea5e9"
|
||||
cotizador paquetes listar
|
||||
|
||||
cotizador horas registrar UJ2611AD001 --fecha 2026-11-20 --inicio 09:00 --fin 11:30 --descripcion "Ajustes de campanas"
|
||||
cotizador horas listar UJ2611AD001 --desde 2026-11-01
|
||||
```
|
||||
|
||||
## Lo que no cubre un comando
|
||||
|
||||
`cotizador api <METODO> <ruta> [--datos ...]` llama cualquier endpoint de `src/app/api` con la sesión del CLI:
|
||||
|
||||
```bash
|
||||
cotizador api GET /api/configuracion
|
||||
cotizador api POST /api/cobros/recordatorios --datos '{}'
|
||||
```
|
||||
|
||||
En Git Bash, MSYS convierte `/api/...` en una ruta de Windows; el CLI lo corrige solo. También acepta `api/...` sin la barra.
|
||||
|
||||
## Agregar un comando
|
||||
|
||||
Cada comando es una entrada del arreglo `COMANDOS` en `cli/cotizador.mjs`, con `comando`, `descripcion`, `flags`, `ejemplos`, `endpoint` y `run`. La ayuda, la validación de flags y `cotizador esquema` salen de esa misma definición, así que no hay que documentarlo en otro lado. La lógica de negocio sigue en el servidor (`calculators.ts`, rutas de la API): el CLI solo arma peticiones.
|
||||
+5
-1
@@ -2,6 +2,9 @@
|
||||
"name": "cotizador-e3",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"bin": {
|
||||
"cotizador": "cli/cotizador.mjs"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
@@ -10,7 +13,8 @@
|
||||
"db:migrate": "npx prisma migrate dev",
|
||||
"db:seed": "npx tsx prisma/seed.ts",
|
||||
"db:studio": "npx prisma studio",
|
||||
"db:generate": "npx prisma generate"
|
||||
"db:generate": "npx prisma generate",
|
||||
"cli": "node cli/cotizador.mjs"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "npx tsx prisma/seed.ts"
|
||||
|
||||
@@ -12,12 +12,12 @@ import {
|
||||
Package,
|
||||
LayoutGrid,
|
||||
Settings,
|
||||
Save,
|
||||
FileDown,
|
||||
Upload,
|
||||
} from "lucide-react";
|
||||
import { formatCurrency, FASES as FASES_LABELS } from "@/lib/calculators";
|
||||
import { formatCurrency } from "@/lib/calculators";
|
||||
import { useConfirm, usePrompt, useToast } from "@/components/ui/DialogProvider";
|
||||
import { ServicioFormModal } from "@/components/ServicioFormModal";
|
||||
import clsx from "clsx";
|
||||
|
||||
interface Servicio {
|
||||
@@ -69,8 +69,6 @@ interface Props {
|
||||
|
||||
type Tab = "categorias" | "paquetes" | "servicios";
|
||||
|
||||
const FASES = FASES_LABELS;
|
||||
|
||||
export function CatalogoClient({ initialServicios, initialCategorias, initialPaquetes }: Props) {
|
||||
const showConfirm = useConfirm();
|
||||
const showPrompt = usePrompt();
|
||||
@@ -519,28 +517,13 @@ export function CatalogoClient({ initialServicios, initialCategorias, initialPaq
|
||||
<ServicioFormModal
|
||||
servicio={servicioModal}
|
||||
categorias={categorias}
|
||||
onSave={async (data) => {
|
||||
onSaved={(guardado) => {
|
||||
if (servicioModal) {
|
||||
const res = await fetch(`/api/catalogo/${servicioModal.id}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (res.ok) {
|
||||
const updated = await res.json();
|
||||
setServicios((p) => p.map((s) => (s.id === servicioModal.id ? { ...s, ...updated, categoriaNombre: categorias.find((c) => c.id === data.categoriaId)?.nombre || s.categoriaNombre, categoriaColor: categorias.find((c) => c.id === data.categoriaId)?.color || s.categoriaColor } : s)));
|
||||
}
|
||||
setServicios((p) => p.map((s) => (s.id === guardado.id ? { ...s, ...guardado } : s)));
|
||||
showToast("Servicio actualizado", "success");
|
||||
} else {
|
||||
const res = await fetch("/api/catalogo", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (res.ok) {
|
||||
const created = await res.json();
|
||||
const cat = categorias.find((c) => c.id === data.categoriaId);
|
||||
setServicios((p) => [...p, { ...created, categoriaNombre: cat?.nombre || "Sin categoria", categoriaColor: cat?.color || "#6b7280" }]);
|
||||
}
|
||||
setServicios((p) => [...p, guardado]);
|
||||
showToast("Servicio creado", "success");
|
||||
}
|
||||
setServicioModal(null);
|
||||
setShowNewServicio(false);
|
||||
@@ -645,148 +628,3 @@ function AddServicioModal({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ServicioFormModal({
|
||||
servicio,
|
||||
categorias,
|
||||
onSave,
|
||||
onClose,
|
||||
}: {
|
||||
servicio: Servicio | null;
|
||||
categorias: Categoria[];
|
||||
onSave: (data: Record<string, unknown>) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [form, setForm] = useState({
|
||||
nombre: servicio?.nombre || "",
|
||||
descripcion: servicio?.descripcion || "",
|
||||
categoriaId: servicio?.categoriaId || "",
|
||||
tipoPago: servicio?.tipoPago || "unico",
|
||||
precioBase: servicio?.precioBase ?? 0,
|
||||
tiempoEntrega: servicio?.tiempoEntrega || "4 - 10 dias",
|
||||
entregablesDefault: servicio?.entregablesDefault?.join("\n") || "",
|
||||
variante: servicio?.variante || "",
|
||||
nivel: servicio?.nivel || "",
|
||||
fase: servicio?.fase ?? 1,
|
||||
orden: servicio?.orden ?? 0,
|
||||
activo: servicio?.activo ?? true,
|
||||
});
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!form.nombre.trim()) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const entregables = form.entregablesDefault
|
||||
.split("\n")
|
||||
.map((e) => e.trim())
|
||||
.filter(Boolean);
|
||||
await onSave({
|
||||
nombre: form.nombre.trim(),
|
||||
descripcion: form.descripcion.trim() || null,
|
||||
categoriaId: form.categoriaId || null,
|
||||
tipoPago: form.tipoPago,
|
||||
precioBase: Number(form.precioBase),
|
||||
tiempoEntrega: form.tiempoEntrega,
|
||||
entregablesDefault: entregables,
|
||||
variante: form.variante.trim() || null,
|
||||
nivel: form.nivel.trim() || null,
|
||||
fase: form.fase,
|
||||
orden: form.orden,
|
||||
activo: form.activo,
|
||||
});
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const update = (key: string, value: unknown) => setForm((p) => ({ ...p, [key]: value }));
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onClick={onClose}>
|
||||
<div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[85vh] flex flex-col" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="px-5 py-4 border-b border-border flex items-center justify-between">
|
||||
<h3 className="font-semibold">{servicio ? "Editar Servicio" : "Nuevo Servicio"}</h3>
|
||||
<button onClick={onClose}><X className="w-5 h-5 text-muted" /></button>
|
||||
</div>
|
||||
<div className="overflow-y-auto flex-1 p-5 space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Nombre *</label>
|
||||
<input type="text" value={form.nombre} onChange={(e) => update("nombre", e.target.value)} 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" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Descripcion</label>
|
||||
<textarea value={form.descripcion} onChange={(e) => update("descripcion", e.target.value)} rows={2} 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 resize-none" />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Categoria</label>
|
||||
<select value={form.categoriaId} onChange={(e) => update("categoriaId", e.target.value)} 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 bg-white">
|
||||
<option value="">Sin categoria</option>
|
||||
{categorias.map((c) => <option key={c.id} value={c.id}>{c.nombre}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Tipo de Pago</label>
|
||||
<select value={form.tipoPago} onChange={(e) => update("tipoPago", e.target.value)} 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 bg-white">
|
||||
<option value="unico">Unico</option>
|
||||
<option value="mensual">Mensual</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Precio Base</label>
|
||||
<input type="number" value={form.precioBase} onChange={(e) => update("precioBase", Number(e.target.value))} min={0} 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" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Fase</label>
|
||||
<select value={form.fase} onChange={(e) => update("fase", Number(e.target.value))} 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 bg-white">
|
||||
{Object.entries(FASES).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Tiempo Entrega</label>
|
||||
<input type="text" value={form.tiempoEntrega} onChange={(e) => update("tiempoEntrega", e.target.value)} 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" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Entregables (uno por linea)</label>
|
||||
<textarea value={form.entregablesDefault} onChange={(e) => update("entregablesDefault", e.target.value)} rows={4} placeholder="Entregable 1 Entregable 2 ..." 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 resize-none font-mono text-xs" />
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Nivel</label>
|
||||
<select value={form.nivel} onChange={(e) => update("nivel", e.target.value)} 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 bg-white">
|
||||
<option value="">Sin nivel</option>
|
||||
<option value="Emprendedor">Emprendedor</option>
|
||||
<option value="PYME">PYME</option>
|
||||
<option value="Empresario">Empresario</option>
|
||||
<option value="Corporativo">Corporativo</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Variante</label>
|
||||
<input type="text" value={form.variante} onChange={(e) => update("variante", e.target.value)} placeholder="Ej: WooCommerce, Shopify..." 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" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Orden</label>
|
||||
<input type="number" value={form.orden} onChange={(e) => update("orden", Number(e.target.value))} min={0} 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" />
|
||||
</div>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={form.activo} onChange={(e) => update("activo", e.target.checked)} className="rounded border-border" />
|
||||
Activo
|
||||
</label>
|
||||
</div>
|
||||
<div className="px-5 py-4 border-t border-border flex justify-end gap-3">
|
||||
<button onClick={onClose} className="px-4 py-2 border border-border rounded-lg text-sm hover:bg-gray-50">Cancelar</button>
|
||||
<button onClick={handleSave} disabled={saving || !form.nombre.trim()} className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium disabled:opacity-50 hover:bg-primary-dark">
|
||||
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
{servicio ? "Guardar Cambios" : "Crear Servicio"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,43 +1,90 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireStaff } from "@/lib/auth";
|
||||
import { servicioCatalogoPatchSchema } from "@/lib/schemas";
|
||||
import {
|
||||
categoriaExiste,
|
||||
errorInterno,
|
||||
errorValidacion,
|
||||
sinCamposDeSoloLectura,
|
||||
serializarServicio,
|
||||
servicioCatalogoInclude,
|
||||
} from "@/lib/catalogo";
|
||||
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
type Ctx = { params: Promise<{ id: string }> };
|
||||
|
||||
const noEncontrado = (id: string) =>
|
||||
NextResponse.json({ error: `No existe el servicio ${id}` }, { status: 404 });
|
||||
|
||||
// GET /api/catalogo/[id] — un servicio del catalogo.
|
||||
export async function GET(_request: NextRequest, { params }: Ctx) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const servicio = await prisma.servicioCatalogo.update({
|
||||
const servicio = await prisma.servicioCatalogo.findUnique({
|
||||
where: { id },
|
||||
data: {
|
||||
nombre: body.nombre,
|
||||
descripcion: body.descripcion || null,
|
||||
fase: body.fase,
|
||||
tipoPago: body.tipoPago,
|
||||
precioBase: body.precioBase,
|
||||
tiempoEntrega: body.tiempoEntrega,
|
||||
entregablesDefault: body.entregablesDefault || [],
|
||||
variante: body.variante || null,
|
||||
nivel: body.nivel || null,
|
||||
activo: body.activo !== false,
|
||||
orden: body.orden,
|
||||
categoriaId: body.categoriaId || null,
|
||||
},
|
||||
include: servicioCatalogoInclude,
|
||||
});
|
||||
return NextResponse.json(servicio);
|
||||
if (!servicio) return noEncontrado(id);
|
||||
return NextResponse.json(serializarServicio(servicio));
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
return errorInterno(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
// PATCH (y PUT, por compatibilidad) /api/catalogo/[id] — edicion PARCIAL: solo
|
||||
// cambian los campos enviados. Mandar `{ "precioBase": 4500 }` no toca nada mas.
|
||||
// Las cotizaciones ya guardadas conservan su precio, entregables y tiempo de
|
||||
// entrega; el nombre del servicio si se actualiza en ellas (se lee del catalogo).
|
||||
async function actualizar(request: NextRequest, { params }: Ctx) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
|
||||
const { id } = await params;
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = servicioCatalogoPatchSchema.safeParse(sinCamposDeSoloLectura(body));
|
||||
if (!parsed.success) return errorValidacion(parsed.error);
|
||||
const data = parsed.data;
|
||||
|
||||
const existe = await prisma.servicioCatalogo.findUnique({ where: { id }, select: { id: true } });
|
||||
if (!existe) return noEncontrado(id);
|
||||
|
||||
if (data.categoriaId && !(await categoriaExiste(data.categoriaId))) {
|
||||
return NextResponse.json(
|
||||
{ error: `categoriaId: no existe la categoria ${data.categoriaId}` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const servicio = await prisma.servicioCatalogo.update({
|
||||
where: { id },
|
||||
data,
|
||||
include: servicioCatalogoInclude,
|
||||
});
|
||||
return NextResponse.json(serializarServicio(servicio));
|
||||
} catch (error: unknown) {
|
||||
return errorInterno(error);
|
||||
}
|
||||
}
|
||||
|
||||
export const PATCH = actualizar;
|
||||
export const PUT = actualizar;
|
||||
|
||||
// DELETE /api/catalogo/[id] — si alguna cotizacion usa el servicio se ARCHIVA
|
||||
// (activo=false) para no romper esas cotizaciones; si no, se borra.
|
||||
// Respuesta: { ok: true, archived: boolean }.
|
||||
export async function DELETE(_request: NextRequest, { params }: Ctx) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
|
||||
const { id } = await params;
|
||||
const existe = await prisma.servicioCatalogo.findUnique({ where: { id }, select: { id: true } });
|
||||
if (!existe) return noEncontrado(id);
|
||||
|
||||
const inUse = await prisma.servicioCotizado.count({
|
||||
where: { servicioCatalogoId: id },
|
||||
});
|
||||
@@ -48,10 +95,10 @@ export async function DELETE(
|
||||
});
|
||||
return NextResponse.json({ ok: true, archived: true });
|
||||
}
|
||||
// ServicioPaquete cae en cascada: el servicio sale de los paquetes.
|
||||
await prisma.servicioCatalogo.delete({ where: { id } });
|
||||
return NextResponse.json({ ok: true, archived: false });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
return errorInterno(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,48 +1,101 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireStaff } from "@/lib/auth";
|
||||
import { servicioCatalogoSchema } from "@/lib/schemas";
|
||||
import {
|
||||
categoriaExiste,
|
||||
errorInterno,
|
||||
errorValidacion,
|
||||
sinCamposDeSoloLectura,
|
||||
serializarServicio,
|
||||
servicioCatalogoInclude,
|
||||
siguienteOrden,
|
||||
} from "@/lib/catalogo";
|
||||
|
||||
export async function GET() {
|
||||
// GET /api/catalogo — lista de servicios del catalogo.
|
||||
// Filtros opcionales: ?q=texto (nombre/descripcion), ?fase=0-3,
|
||||
// ?tipoPago=unico|mensual, ?categoriaId=..., ?activo=true|false.
|
||||
// Sin `activo` devuelve activos y archivados (la pagina /catalogo los muestra todos).
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
|
||||
const sp = request.nextUrl.searchParams;
|
||||
const q = sp.get("q")?.trim();
|
||||
const fase = sp.get("fase");
|
||||
const tipoPago = sp.get("tipoPago");
|
||||
const categoriaId = sp.get("categoriaId");
|
||||
const activo = sp.get("activo");
|
||||
|
||||
if (fase !== null && !/^[0-3]$/.test(fase)) {
|
||||
return NextResponse.json({ error: "fase debe ser 0, 1, 2 o 3" }, { status: 400 });
|
||||
}
|
||||
if (tipoPago !== null && tipoPago !== "unico" && tipoPago !== "mensual") {
|
||||
return NextResponse.json({ error: "tipoPago debe ser 'unico' o 'mensual'" }, { status: 400 });
|
||||
}
|
||||
|
||||
const servicios = await prisma.servicioCatalogo.findMany({
|
||||
where: {
|
||||
...(q && {
|
||||
OR: [
|
||||
{ nombre: { contains: q, mode: "insensitive" as const } },
|
||||
{ descripcion: { contains: q, mode: "insensitive" as const } },
|
||||
],
|
||||
}),
|
||||
...(fase !== null && { fase: Number(fase) }),
|
||||
...(tipoPago && { tipoPago }),
|
||||
...(categoriaId && { categoriaId }),
|
||||
...(activo === "true" && { activo: true }),
|
||||
...(activo === "false" && { activo: false }),
|
||||
},
|
||||
orderBy: [{ fase: "asc" }, { orden: "asc" }],
|
||||
include: servicioCatalogoInclude,
|
||||
});
|
||||
return NextResponse.json(servicios);
|
||||
return NextResponse.json(servicios.map(serializarServicio));
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
return errorInterno(error);
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/catalogo — alta de un servicio. Obligatorios: nombre, fase,
|
||||
// tipoPago, precioBase. Sin `orden` se coloca al final de su fase.
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const parsed = servicioCatalogoSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
const session = await requireStaff();
|
||||
if (!session) return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = servicioCatalogoSchema.safeParse(sinCamposDeSoloLectura(body));
|
||||
if (!parsed.success) return errorValidacion(parsed.error);
|
||||
const data = parsed.data;
|
||||
|
||||
if (data.categoriaId && !(await categoriaExiste(data.categoriaId))) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ error: `categoriaId: no existe la categoria ${data.categoriaId}` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const servicio = await prisma.servicioCatalogo.create({
|
||||
data: {
|
||||
nombre: parsed.data.nombre,
|
||||
descripcion: parsed.data.descripcion,
|
||||
fase: parsed.data.fase,
|
||||
tipoPago: parsed.data.tipoPago,
|
||||
precioBase: parsed.data.precioBase,
|
||||
tiempoEntrega: parsed.data.tiempoEntrega,
|
||||
entregablesDefault: parsed.data.entregablesDefault,
|
||||
categoriaId: parsed.data.categoriaId,
|
||||
variante: parsed.data.variante,
|
||||
nivel: parsed.data.nivel ?? null,
|
||||
activo: true,
|
||||
orden: parsed.data.orden,
|
||||
nombre: data.nombre,
|
||||
descripcion: data.descripcion ?? null,
|
||||
fase: data.fase,
|
||||
tipoPago: data.tipoPago,
|
||||
precioBase: data.precioBase,
|
||||
tiempoEntrega: data.tiempoEntrega,
|
||||
entregablesDefault: data.entregablesDefault,
|
||||
categoriaId: data.categoriaId ?? null,
|
||||
variante: data.variante ?? null,
|
||||
nivel: data.nivel ?? null,
|
||||
activo: data.activo ?? true,
|
||||
orden: data.orden ?? (await siguienteOrden(data.fase)),
|
||||
},
|
||||
include: servicioCatalogoInclude,
|
||||
});
|
||||
return NextResponse.json(servicio, { status: 201 });
|
||||
return NextResponse.json(serializarServicio(servicio), { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
return errorInterno(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,36 @@ import { requireStaff } from "@/lib/auth";
|
||||
import { clienteSchema } from "@/lib/schemas";
|
||||
import { buscarDuplicado, clienteSelect, mensajeDuplicado } from "@/lib/clientes";
|
||||
|
||||
// GET /api/clientes — lista de clientes. ?q=texto busca en nombre, empresa,
|
||||
// email y RFC.
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
}
|
||||
const q = request.nextUrl.searchParams.get("q")?.trim();
|
||||
const clientes = await prisma.cliente.findMany({
|
||||
where: q
|
||||
? {
|
||||
OR: [
|
||||
{ nombre: { contains: q, mode: "insensitive" } },
|
||||
{ empresa: { contains: q, mode: "insensitive" } },
|
||||
{ email: { contains: q, mode: "insensitive" } },
|
||||
{ rfc: { contains: q, mode: "insensitive" } },
|
||||
],
|
||||
}
|
||||
: undefined,
|
||||
orderBy: { nombre: "asc" },
|
||||
select: clienteSelect,
|
||||
});
|
||||
return NextResponse.json(clientes);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/clientes — alta directa de un cliente, sin pasar por una cotizacion
|
||||
// (ej. para programarle cobros recurrentes). Solo staff.
|
||||
export async function POST(request: NextRequest) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { ESTADOS_COTIZACION } from "@/lib/calculators";
|
||||
import { cotizacionPutSchema } from "@/lib/schemas";
|
||||
import { asesorPublicoSelect } from "@/lib/cotizaciones";
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
@@ -36,7 +37,7 @@ export async function GET(
|
||||
where: { id },
|
||||
include: {
|
||||
cliente: true,
|
||||
asesor: true,
|
||||
asesor: { select: asesorPublicoSelect },
|
||||
servicios: { include: { servicioCatalogo: true } },
|
||||
planBucefalo: true,
|
||||
},
|
||||
@@ -230,7 +231,7 @@ export async function PUT(
|
||||
|
||||
const updated = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: { cliente: true, asesor: true, servicios: true },
|
||||
include: { cliente: true, asesor: { select: asesorPublicoSelect }, servicios: true },
|
||||
});
|
||||
|
||||
return NextResponse.json(updated);
|
||||
|
||||
@@ -1,21 +1,37 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { cotizacionPostSchema } from "@/lib/schemas";
|
||||
import { requireStaff } from "@/lib/auth";
|
||||
import { bucefaloPrecio, calcularVigencia } from "@/lib/calculators";
|
||||
import { errorValidacion } from "@/lib/catalogo";
|
||||
import { asesorPublicoSelect, siguienteNumeroCotizacion } from "@/lib/cotizaciones";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const parsed = cotizacionPostSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
const session = await requireStaff();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = cotizacionPostSchema.safeParse(body);
|
||||
if (!parsed.success) return errorValidacion(parsed.error);
|
||||
|
||||
// Defaults del servidor para altas por API/CLI: asesor = usuario de la
|
||||
// sesion, fecha = hoy, vigencia = 15 dias habiles, numero = consecutivo.
|
||||
const asesorId = parsed.data.asesorId ?? session.userId;
|
||||
const asesor = await prisma.user.findUnique({
|
||||
where: { id: asesorId },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (!asesor) {
|
||||
return NextResponse.json({ error: `asesorId: no existe el usuario ${asesorId}` }, { status: 400 });
|
||||
}
|
||||
const fecha = parsed.data.fecha ?? new Date();
|
||||
const vigencia = parsed.data.vigencia ?? calcularVigencia(fecha);
|
||||
const numero = parsed.data.numero ?? (await siguienteNumeroCotizacion(asesor.name));
|
||||
|
||||
const {
|
||||
numero,
|
||||
fecha,
|
||||
vigencia,
|
||||
moneda,
|
||||
tipoCambio,
|
||||
proyecto,
|
||||
@@ -28,7 +44,6 @@ export async function POST(request: NextRequest) {
|
||||
observaciones,
|
||||
observacionesInternas,
|
||||
cliente,
|
||||
asesorId,
|
||||
servicios,
|
||||
planBucefalo,
|
||||
} = parsed.data;
|
||||
@@ -127,7 +142,7 @@ export async function POST(request: NextRequest) {
|
||||
data: {
|
||||
cotizacionId: cot.id,
|
||||
nivel: planBucefalo.nivel,
|
||||
precio: planBucefalo.precio,
|
||||
precio: planBucefalo.precio ?? bucefaloPrecio(planBucefalo.nivel),
|
||||
seleccionado: true,
|
||||
},
|
||||
});
|
||||
@@ -144,13 +159,44 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
// GET /api/cotizaciones — lista, de la mas reciente a la mas antigua.
|
||||
// Filtros opcionales: ?estado=borrador|enviada|aprobada|rechazada,
|
||||
// ?clienteId=..., ?q=texto (numero, cliente o empresa), ?limit=N.
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await requireStaff();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "No autorizado" }, { status: 403 });
|
||||
}
|
||||
|
||||
const sp = request.nextUrl.searchParams;
|
||||
const estado = sp.get("estado");
|
||||
const clienteId = sp.get("clienteId");
|
||||
const q = sp.get("q")?.trim();
|
||||
const limitRaw = sp.get("limit");
|
||||
const limit = limitRaw ? Number(limitRaw) : undefined;
|
||||
if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) {
|
||||
return NextResponse.json({ error: "limit debe ser un entero mayor a 0" }, { status: 400 });
|
||||
}
|
||||
|
||||
const cotizaciones = await prisma.cotizacion.findMany({
|
||||
where: {
|
||||
...(estado && { estado }),
|
||||
...(clienteId && { clienteId }),
|
||||
...(q && {
|
||||
OR: [
|
||||
{ numero: { contains: q, mode: "insensitive" as const } },
|
||||
{ proyecto: { contains: q, mode: "insensitive" as const } },
|
||||
{ cliente: { nombre: { contains: q, mode: "insensitive" as const } } },
|
||||
{ cliente: { empresa: { contains: q, mode: "insensitive" as const } } },
|
||||
],
|
||||
}),
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: limit,
|
||||
include: {
|
||||
cliente: true,
|
||||
asesor: true,
|
||||
asesor: { select: asesorPublicoSelect },
|
||||
servicios: { include: { servicioCatalogo: true } },
|
||||
planBucefalo: true,
|
||||
},
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
Trash2,
|
||||
Eye,
|
||||
Lock,
|
||||
Pencil,
|
||||
} from "lucide-react";
|
||||
import clsx from "clsx";
|
||||
import {
|
||||
@@ -40,6 +41,10 @@ import {
|
||||
ServicioSeleccionado,
|
||||
} from "@/lib/store";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
import {
|
||||
ServicioFormModal,
|
||||
type ServicioCatalogoDatos,
|
||||
} from "@/components/ServicioFormModal";
|
||||
import {
|
||||
ExportPDFButtonDraft,
|
||||
ExportExcelButtonDraft,
|
||||
@@ -58,8 +63,18 @@ export interface ServicioCatalogo {
|
||||
categoriaNombre: string;
|
||||
variante: string | null;
|
||||
orden: number;
|
||||
// Presentes cuando la pagina pasa el registro completo; el modal de edicion
|
||||
// los necesita para no reiniciar la categoria ni el nivel.
|
||||
categoriaId?: string | null;
|
||||
nivel?: string | null;
|
||||
activo?: boolean;
|
||||
}
|
||||
|
||||
// Modal de alta/edicion de un servicio del catalogo abierto desde el cotizador.
|
||||
type ModalServicio =
|
||||
| { modo: "nuevo"; fase?: number }
|
||||
| { modo: "editar"; servicio: ServicioCatalogo };
|
||||
|
||||
export interface Asesor {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -132,7 +147,7 @@ const BTN_PRIMARY =
|
||||
|
||||
export function CotizacionForm({
|
||||
mode,
|
||||
servicios,
|
||||
servicios: serviciosIniciales,
|
||||
asesores,
|
||||
nextSeq,
|
||||
existingData,
|
||||
@@ -150,6 +165,10 @@ export function CotizacionForm({
|
||||
);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [selectedPaquete, setSelectedPaquete] = useState<string>("");
|
||||
// Catalogo local: crece/cambia cuando se crea o edita un servicio sin salir
|
||||
// del cotizador.
|
||||
const [servicios, setServicios] = useState<ServicioCatalogo[]>(serviciosIniciales);
|
||||
const [modalServicio, setModalServicio] = useState<ModalServicio | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === "edit" && existingData) {
|
||||
@@ -217,6 +236,41 @@ export function CotizacionForm({
|
||||
}
|
||||
};
|
||||
|
||||
// Servicio nuevo creado desde el cotizador: entra al catalogo y queda
|
||||
// seleccionado en esta cotizacion.
|
||||
const handleServicioCreado = (nuevo: ServicioCatalogoDatos) => {
|
||||
setServicios((prev) => [...prev, nuevo]);
|
||||
setExpandedFases((prev) => new Set(prev).add(nuevo.fase));
|
||||
if (!selectedIds.has(nuevo.id)) handleToggleServicio(nuevo);
|
||||
setModalServicio(null);
|
||||
showToast(`"${nuevo.nombre}" se agrego al catalogo y a esta cotizacion`, "success");
|
||||
};
|
||||
|
||||
// Servicio editado: se actualiza el catalogo y, si esta cotizacion lo usa, su
|
||||
// partida. El precio solo se sigue si la partida tenia el precio base anterior
|
||||
// (un precio ajustado a mano para este cliente se respeta).
|
||||
const handleServicioEditado = (anterior: ServicioCatalogo, editado: ServicioCatalogoDatos) => {
|
||||
setServicios((prev) =>
|
||||
editado.activo
|
||||
? prev.map((s) => (s.id === editado.id ? { ...s, ...editado } : s))
|
||||
: prev.filter((s) => s.id !== editado.id)
|
||||
);
|
||||
const partida = store.draft.servicios.find((s) => s.catalogoId === editado.id);
|
||||
if (partida) {
|
||||
store.updateServicio(editado.id, {
|
||||
nombre: editado.nombre,
|
||||
fase: editado.fase,
|
||||
tipoPago: editado.tipoPago,
|
||||
tiempoEntrega: editado.tiempoEntrega,
|
||||
entregables: editado.entregablesDefault,
|
||||
...(partida.precio === anterior.precioBase && { precio: editado.precioBase }),
|
||||
});
|
||||
}
|
||||
setExpandedFases((prev) => new Set(prev).add(editado.fase));
|
||||
setModalServicio(null);
|
||||
showToast("Servicio actualizado en el catalogo", "success");
|
||||
};
|
||||
|
||||
const handlePrecioChange = (catalogoId: string, precio: number) => {
|
||||
store.updateServicio(catalogoId, { precio });
|
||||
};
|
||||
@@ -719,6 +773,18 @@ export function CotizacionForm({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between gap-3 mb-3">
|
||||
<h2 className="font-semibold text-lg">Servicios del catalogo</h2>
|
||||
<button
|
||||
onClick={() => setModalServicio({ modo: "nuevo" })}
|
||||
className="flex items-center gap-1 px-3 py-1.5 border border-primary text-primary rounded-lg text-sm font-medium hover:bg-primary-light/30"
|
||||
title="Crear un servicio en el catalogo y agregarlo a esta cotizacion"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Nuevo servicio
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{fases.map((fase) => {
|
||||
const serviciosFase = serviciosPorFase[fase];
|
||||
if (!serviciosFase?.length) return null;
|
||||
@@ -834,6 +900,16 @@ export function CotizacionForm({
|
||||
>
|
||||
{isExpandedServ ? "Ocultar" : "Ver"}
|
||||
</button>
|
||||
<button
|
||||
onClick={() =>
|
||||
setModalServicio({ modo: "editar", servicio: serv })
|
||||
}
|
||||
className="p-1 text-muted hover:text-primary rounded"
|
||||
title="Editar servicio del catalogo"
|
||||
aria-label={`Editar ${serv.nombre}`}
|
||||
>
|
||||
<Pencil className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<span className="font-semibold text-sm w-24 text-right shrink-0">
|
||||
{formatCurrency(
|
||||
@@ -865,6 +941,13 @@ export function CotizacionForm({
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<button
|
||||
onClick={() => setModalServicio({ modo: "nuevo", fase })}
|
||||
className="w-full flex items-center justify-center gap-1 px-4 py-2 border border-dashed border-border rounded-lg text-xs text-muted hover:text-primary hover:border-primary"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
Nuevo servicio en esta fase
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -1416,6 +1499,25 @@ export function CotizacionForm({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{modalServicio && (
|
||||
<ServicioFormModal
|
||||
servicio={modalServicio.modo === "editar" ? modalServicio.servicio : null}
|
||||
faseInicial={modalServicio.modo === "nuevo" ? modalServicio.fase : undefined}
|
||||
avanzado={false}
|
||||
textoCrear="Crear y agregar"
|
||||
aviso={
|
||||
modalServicio.modo === "editar"
|
||||
? "Editas el servicio del catalogo: el cambio aplica a las cotizaciones nuevas. En esta cotizacion se actualiza la partida (el precio solo si no lo ajustaste a mano); las cotizaciones ya guardadas conservan su precio y entregables."
|
||||
: "El servicio se guarda en el catalogo para reutilizarlo y queda agregado a esta cotizacion."
|
||||
}
|
||||
onSaved={(guardado) =>
|
||||
modalServicio.modo === "editar"
|
||||
? handleServicioEditado(modalServicio.servicio, guardado)
|
||||
: handleServicioCreado(guardado)
|
||||
}
|
||||
onClose={() => setModalServicio(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Loader2, Save, X, Info } from "lucide-react";
|
||||
import { FASES } from "@/lib/calculators";
|
||||
|
||||
// Servicio del catalogo tal como lo devuelve /api/catalogo (ver serializarServicio).
|
||||
export interface ServicioCatalogoDatos {
|
||||
id: string;
|
||||
nombre: string;
|
||||
descripcion: string | null;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precioBase: number;
|
||||
tiempoEntrega: string;
|
||||
entregablesDefault: string[];
|
||||
categoriaId: string | null;
|
||||
categoriaNombre: string;
|
||||
categoriaColor: string;
|
||||
variante: string | null;
|
||||
nivel: string | null;
|
||||
activo: boolean;
|
||||
orden: number;
|
||||
enCotizaciones?: number;
|
||||
}
|
||||
|
||||
export interface CategoriaOpcion {
|
||||
id: string;
|
||||
nombre: string;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
const NIVELES = ["Emprendedor", "PYME", "Empresario", "Corporativo"];
|
||||
|
||||
const INPUT =
|
||||
"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";
|
||||
|
||||
interface Props {
|
||||
// null = alta; con servicio = edicion.
|
||||
servicio: Partial<ServicioCatalogoDatos> & { id?: string } | null;
|
||||
// Si no se pasan, el modal las pide a /api/categorias.
|
||||
categorias?: CategoriaOpcion[];
|
||||
// Fase preseleccionada en un alta.
|
||||
faseInicial?: number;
|
||||
// Texto de ayuda arriba del formulario (ej. el alcance de la edicion).
|
||||
aviso?: string;
|
||||
// Texto del boton en un alta (ej. "Crear y agregar").
|
||||
textoCrear?: string;
|
||||
// Mostrar Orden/Activo (en el cotizador se omiten: el orden se asigna solo).
|
||||
avanzado?: boolean;
|
||||
onSaved: (servicio: ServicioCatalogoDatos) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
// Alta y edicion de un servicio del catalogo. Hace el POST/PATCH a
|
||||
// /api/catalogo y muestra el error de la API sin cerrarse si algo falla.
|
||||
export function ServicioFormModal({
|
||||
servicio,
|
||||
categorias: categoriasProp,
|
||||
faseInicial,
|
||||
aviso,
|
||||
textoCrear = "Crear servicio",
|
||||
avanzado = true,
|
||||
onSaved,
|
||||
onClose,
|
||||
}: Props) {
|
||||
const editando = !!servicio?.id;
|
||||
const [categorias, setCategorias] = useState<CategoriaOpcion[]>(categoriasProp ?? []);
|
||||
const [form, setForm] = useState({
|
||||
nombre: servicio?.nombre || "",
|
||||
descripcion: servicio?.descripcion || "",
|
||||
categoriaId: servicio?.categoriaId || "",
|
||||
tipoPago: servicio?.tipoPago || "unico",
|
||||
precioBase: servicio?.precioBase ?? 0,
|
||||
tiempoEntrega: servicio?.tiempoEntrega || "4 - 10 dias",
|
||||
entregablesDefault: servicio?.entregablesDefault?.join("\n") || "",
|
||||
variante: servicio?.variante || "",
|
||||
nivel: servicio?.nivel || "",
|
||||
fase: servicio?.fase ?? faseInicial ?? 1,
|
||||
orden: servicio?.orden ?? "",
|
||||
activo: servicio?.activo ?? true,
|
||||
});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (categoriasProp) return;
|
||||
let vivo = true;
|
||||
fetch("/api/categorias")
|
||||
.then((r) => (r.ok ? r.json() : []))
|
||||
.then((cats: CategoriaOpcion[]) => vivo && setCategorias(cats))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
vivo = false;
|
||||
};
|
||||
}, [categoriasProp]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === "Escape" && !saving && onClose();
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onClose, saving]);
|
||||
|
||||
const update = (key: keyof typeof form, value: unknown) =>
|
||||
setForm((p) => ({ ...p, [key]: value }));
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!form.nombre.trim()) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const entregables = form.entregablesDefault
|
||||
.split("\n")
|
||||
.map((e) => e.trim())
|
||||
.filter(Boolean);
|
||||
const payload: Record<string, unknown> = {
|
||||
nombre: form.nombre.trim(),
|
||||
descripcion: form.descripcion.trim() || null,
|
||||
categoriaId: form.categoriaId || null,
|
||||
tipoPago: form.tipoPago,
|
||||
precioBase: Number(form.precioBase) || 0,
|
||||
tiempoEntrega: form.tiempoEntrega.trim() || "4 - 10 dias",
|
||||
entregablesDefault: entregables,
|
||||
variante: form.variante.trim() || null,
|
||||
nivel: form.nivel || null,
|
||||
fase: Number(form.fase),
|
||||
};
|
||||
if (avanzado) {
|
||||
if (form.orden !== "") payload.orden = Number(form.orden);
|
||||
payload.activo = form.activo;
|
||||
}
|
||||
const res = await fetch(editando ? `/api/catalogo/${servicio!.id}` : "/api/catalogo", {
|
||||
method: editando ? "PATCH" : "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
setError(data.error || "No se pudo guardar el servicio");
|
||||
return;
|
||||
}
|
||||
onSaved(data as ServicioCatalogoDatos);
|
||||
} catch {
|
||||
setError("No se pudo conectar con el servidor");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onClick={() => !saving && onClose()}>
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="servicio-modal-titulo"
|
||||
className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[85vh] flex flex-col"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="px-5 py-4 border-b border-border flex items-center justify-between">
|
||||
<h3 id="servicio-modal-titulo" className="font-semibold">
|
||||
{editando ? "Editar servicio" : "Nuevo servicio"}
|
||||
</h3>
|
||||
<button onClick={onClose} aria-label="Cerrar">
|
||||
<X className="w-5 h-5 text-muted" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="overflow-y-auto flex-1 p-5 space-y-4">
|
||||
{aviso && (
|
||||
<div className="flex gap-2 text-xs text-muted bg-primary-light/30 border border-primary/20 rounded-lg px-3 py-2">
|
||||
<Info className="w-4 h-4 text-primary shrink-0 mt-0.5" />
|
||||
<span>{aviso}</span>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label htmlFor="sf-nombre" className="block text-sm font-medium mb-1">Nombre *</label>
|
||||
<input id="sf-nombre"
|
||||
type="text"
|
||||
value={form.nombre}
|
||||
onChange={(e) => update("nombre", e.target.value)}
|
||||
className={INPUT}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sf-descripcion" className="block text-sm font-medium mb-1">Descripcion</label>
|
||||
<textarea id="sf-descripcion"
|
||||
value={form.descripcion}
|
||||
onChange={(e) => update("descripcion", e.target.value)}
|
||||
rows={2}
|
||||
className={`${INPUT} resize-none`}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label htmlFor="sf-categoria" className="block text-sm font-medium mb-1">Categoria</label>
|
||||
<select id="sf-categoria" value={form.categoriaId} onChange={(e) => update("categoriaId", e.target.value)} className={`${INPUT} bg-white`}>
|
||||
<option value="">Sin categoria</option>
|
||||
{categorias.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.nombre}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sf-tipo-pago" className="block text-sm font-medium mb-1">Tipo de pago</label>
|
||||
<select id="sf-tipo-pago" value={form.tipoPago} onChange={(e) => update("tipoPago", e.target.value)} className={`${INPUT} bg-white`}>
|
||||
<option value="unico">Pago unico</option>
|
||||
<option value="mensual">Mensual</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label htmlFor="sf-precio" className="block text-sm font-medium mb-1">Precio base</label>
|
||||
<input id="sf-precio"
|
||||
type="number"
|
||||
value={form.precioBase}
|
||||
onChange={(e) => update("precioBase", e.target.value === "" ? "" : Number(e.target.value))}
|
||||
min={0}
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sf-fase" className="block text-sm font-medium mb-1">Fase</label>
|
||||
<select id="sf-fase" value={form.fase} onChange={(e) => update("fase", Number(e.target.value))} className={`${INPUT} bg-white`}>
|
||||
{Object.entries(FASES).map(([k, v]) => (
|
||||
<option key={k} value={k}>
|
||||
{v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sf-tiempo" className="block text-sm font-medium mb-1">Tiempo de entrega</label>
|
||||
<input id="sf-tiempo" type="text" value={form.tiempoEntrega} onChange={(e) => update("tiempoEntrega", e.target.value)} className={INPUT} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sf-entregables" className="block text-sm font-medium mb-1">Entregables (uno por linea)</label>
|
||||
<textarea id="sf-entregables"
|
||||
value={form.entregablesDefault}
|
||||
onChange={(e) => update("entregablesDefault", e.target.value)}
|
||||
rows={4}
|
||||
placeholder={"Entregable 1\nEntregable 2"}
|
||||
className={`${INPUT} resize-none font-mono text-xs`}
|
||||
/>
|
||||
</div>
|
||||
<div className={`grid grid-cols-1 gap-4 ${avanzado ? "sm:grid-cols-3" : "sm:grid-cols-2"}`}>
|
||||
<div>
|
||||
<label htmlFor="sf-nivel" className="block text-sm font-medium mb-1">Nivel</label>
|
||||
<select id="sf-nivel" value={form.nivel} onChange={(e) => update("nivel", e.target.value)} className={`${INPUT} bg-white`}>
|
||||
<option value="">Sin nivel</option>
|
||||
{NIVELES.map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sf-variante" className="block text-sm font-medium mb-1">Variante</label>
|
||||
<input id="sf-variante"
|
||||
type="text"
|
||||
value={form.variante}
|
||||
onChange={(e) => update("variante", e.target.value)}
|
||||
placeholder="Ej: WooCommerce, Shopify..."
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
{avanzado && (
|
||||
<div>
|
||||
<label htmlFor="sf-orden" className="block text-sm font-medium mb-1">Orden</label>
|
||||
<input id="sf-orden"
|
||||
type="number"
|
||||
value={form.orden}
|
||||
onChange={(e) => update("orden", e.target.value === "" ? "" : Number(e.target.value))}
|
||||
min={0}
|
||||
placeholder="Al final"
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{avanzado && (
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.activo}
|
||||
onChange={(e) => update("activo", e.target.checked)}
|
||||
className="rounded border-border"
|
||||
/>
|
||||
Activo (visible al cotizar)
|
||||
</label>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-danger bg-danger/10 border border-danger/30 rounded-lg px-3 py-2">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="px-5 py-4 border-t border-border flex justify-end gap-3">
|
||||
<button onClick={onClose} disabled={saving} className="px-4 py-2 border border-border rounded-lg text-sm hover:bg-gray-50">
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving || !form.nombre.trim()}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium disabled:opacity-50 hover:bg-primary-dark"
|
||||
>
|
||||
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
{editando ? "Guardar cambios" : textoCrear}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { ZodError } from "zod";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
// Catalogo de servicios: lo que comparten /api/catalogo, /api/catalogo/[id] y
|
||||
// las paginas que los pintan. Solo servidor (arrastra Prisma).
|
||||
|
||||
export const servicioCatalogoInclude = {
|
||||
categoriaRel: { select: { nombre: true, color: true } },
|
||||
_count: { select: { servicios: true } },
|
||||
} as const;
|
||||
|
||||
type ServicioConCategoria = {
|
||||
id: string;
|
||||
nombre: string;
|
||||
descripcion: string | null;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precioBase: number;
|
||||
tiempoEntrega: string;
|
||||
entregablesDefault: unknown;
|
||||
categoriaId: string | null;
|
||||
variante: string | null;
|
||||
nivel: string | null;
|
||||
activo: boolean;
|
||||
orden: number;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
categoriaRel?: { nombre: string; color: string } | null;
|
||||
_count?: { servicios: number };
|
||||
};
|
||||
|
||||
// Forma publica de un servicio: plana y estable, para la UI, el CLI y las LLM.
|
||||
// `enCotizaciones` dice cuantas partidas lo usan (si es > 0, borrarlo lo archiva).
|
||||
export function serializarServicio(s: ServicioConCategoria) {
|
||||
return {
|
||||
id: s.id,
|
||||
nombre: s.nombre,
|
||||
descripcion: s.descripcion,
|
||||
fase: s.fase,
|
||||
tipoPago: s.tipoPago,
|
||||
precioBase: s.precioBase,
|
||||
tiempoEntrega: s.tiempoEntrega,
|
||||
entregablesDefault: Array.isArray(s.entregablesDefault) ? (s.entregablesDefault as string[]) : [],
|
||||
categoriaId: s.categoriaId,
|
||||
categoriaNombre: s.categoriaRel?.nombre ?? "Sin categoria",
|
||||
categoriaColor: s.categoriaRel?.color ?? "#6b7280",
|
||||
variante: s.variante,
|
||||
nivel: s.nivel,
|
||||
activo: s.activo,
|
||||
orden: s.orden,
|
||||
enCotizaciones: s._count?.servicios ?? 0,
|
||||
createdAt: s.createdAt,
|
||||
updatedAt: s.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export type ServicioCatalogoPublico = ReturnType<typeof serializarServicio>;
|
||||
|
||||
// Campos que la API devuelve pero no se editan. Se quitan del cuerpo antes de
|
||||
// validar, para poder reenviar un servicio tal como lo devolvio un GET.
|
||||
const CAMPOS_SOLO_LECTURA = ["id", "categoriaNombre", "categoriaColor", "enCotizaciones", "createdAt", "updatedAt"];
|
||||
|
||||
export function sinCamposDeSoloLectura(body: unknown): unknown {
|
||||
if (!body || typeof body !== "object" || Array.isArray(body)) return body;
|
||||
const copia = { ...(body as Record<string, unknown>) };
|
||||
for (const k of CAMPOS_SOLO_LECTURA) delete copia[k];
|
||||
return copia;
|
||||
}
|
||||
|
||||
// Siguiente `orden` libre dentro de una fase: el servicio nuevo queda al final.
|
||||
export async function siguienteOrden(fase: number): Promise<number> {
|
||||
const r = await prisma.servicioCatalogo.aggregate({
|
||||
where: { fase },
|
||||
_max: { orden: true },
|
||||
});
|
||||
return (r._max.orden ?? -1) + 1;
|
||||
}
|
||||
|
||||
export async function categoriaExiste(id: string): Promise<boolean> {
|
||||
const c = await prisma.categoria.findUnique({ where: { id }, select: { id: true } });
|
||||
return !!c;
|
||||
}
|
||||
|
||||
// Respuesta 400 uniforme: `error` legible para humanos y `detalles` por campo
|
||||
// para que un cliente (o una LLM) sepa exactamente que corregir.
|
||||
export function errorValidacion(error: ZodError): NextResponse {
|
||||
return NextResponse.json(
|
||||
{
|
||||
// Se antepone el campo solo si el mensaje no lo nombra ya.
|
||||
error: error.issues
|
||||
.map((i) => {
|
||||
const campo = i.path.join(".");
|
||||
return campo && !i.message.includes(String(i.path[i.path.length - 1])) ? `${campo}: ${i.message}` : i.message;
|
||||
})
|
||||
.join("; "),
|
||||
detalles: error.issues.map((i) => ({ campo: i.path.join(".") || null, mensaje: i.message })),
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
export function errorInterno(error: unknown): NextResponse {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { generarNumeroCotizacion } from "@/lib/calculators";
|
||||
|
||||
// Utilidades de servidor para cotizaciones (arrastra Prisma: no importar desde
|
||||
// componentes "use client").
|
||||
|
||||
// Siguiente numero de cotizacion con la misma regla que el formulario web:
|
||||
// UJ{YY}{MM}{2 primeras letras del asesor}{secuencia global de 3 digitos}.
|
||||
// Si el numero ya existe (unico en BD) avanza la secuencia hasta uno libre.
|
||||
export async function siguienteNumeroCotizacion(asesorNombre: string): Promise<string> {
|
||||
const iniciales = (asesorNombre || "XX").substring(0, 2).toUpperCase();
|
||||
const ultima = await prisma.cotizacion.findFirst({
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: { numero: true },
|
||||
});
|
||||
const match = ultima?.numero.match(/(\d+)$/);
|
||||
let seq = match ? parseInt(match[1], 10) + 1 : 1;
|
||||
for (let intento = 0; intento < 100; intento++, seq++) {
|
||||
const numero = generarNumeroCotizacion(iniciales, seq);
|
||||
const existe = await prisma.cotizacion.findUnique({ where: { numero }, select: { id: true } });
|
||||
if (!existe) return numero;
|
||||
}
|
||||
throw new Error("No se pudo generar un numero de cotizacion libre");
|
||||
}
|
||||
|
||||
// Campos del asesor que pueden salir en una respuesta JSON. Nunca `asesor: true`:
|
||||
// eso incluye el hash de la contrasena.
|
||||
export const asesorPublicoSelect = { id: true, name: true, email: true, role: true } as const;
|
||||
+103
-30
@@ -29,36 +29,46 @@ const opcionesSchema = z
|
||||
.object({ "1": metaOpcionSchema.optional(), "2": metaOpcionSchema.optional() })
|
||||
.optional();
|
||||
|
||||
// Alta de cotizacion. El formulario web manda todo; para la API/CLI casi todo
|
||||
// es opcional y el servidor completa: `numero` (UJ{YY}{MM}{iniciales}{seq}),
|
||||
// `asesorId` (el usuario de la sesion), `fecha` (hoy) y `vigencia` (15 dias
|
||||
// habiles), ademas de los defaults de moneda, esquema y textos.
|
||||
export const cotizacionPostSchema = z.object({
|
||||
numero: z.string().min(1),
|
||||
fecha: z.coerce.date(),
|
||||
vigencia: z.coerce.date(),
|
||||
moneda: z.enum(["MXN", "USD"]),
|
||||
tipoCambio: z.string(),
|
||||
proyecto: z.string(),
|
||||
esquemaPago: z.enum(["Pago Unico", "Mensual", "Pago Unico/Mensual", "Por hora (postpago)"]),
|
||||
incluirBonos: z.boolean(),
|
||||
incluirFinanciamiento: z.boolean(),
|
||||
numero: z.string().min(1).optional(),
|
||||
fecha: z.coerce.date().optional(),
|
||||
vigencia: z.coerce.date().optional(),
|
||||
moneda: z.enum(["MXN", "USD"]).default("MXN"),
|
||||
tipoCambio: z.string().default("NA"),
|
||||
proyecto: z.string().default("MKT Digital"),
|
||||
esquemaPago: z
|
||||
.enum(["Pago Unico", "Mensual", "Pago Unico/Mensual", "Por hora (postpago)"])
|
||||
.default("Pago Unico/Mensual"),
|
||||
incluirBonos: z.boolean().default(false),
|
||||
incluirFinanciamiento: z.boolean().default(false),
|
||||
incluirIva: z.boolean().optional(),
|
||||
esDoble: z.boolean().optional(),
|
||||
opciones: opcionesSchema,
|
||||
observaciones: z.string(),
|
||||
observaciones: z.string().default(""),
|
||||
observacionesInternas: z.string().optional(),
|
||||
asesorId: z.string().min(1),
|
||||
asesorId: z.string().min(1).optional(),
|
||||
cliente: z.object({
|
||||
nombre: z.string().min(1, "Cliente nombre es requerido"),
|
||||
empresa: z.string(),
|
||||
email: z.string().email().or(z.literal("")),
|
||||
telefono: z.string(),
|
||||
empresa: z.string().default(""),
|
||||
email: z.string().email().or(z.literal("")).default(""),
|
||||
telefono: z.string().default(""),
|
||||
rfc: z.string().optional(),
|
||||
}),
|
||||
servicios: z.array(servicioSchema),
|
||||
// Sin `precio`, el servidor usa el precio de lista del plan (calculators.ts).
|
||||
planBucefalo: z
|
||||
.object({
|
||||
nivel: z.string(),
|
||||
precio: z.number().min(0),
|
||||
nivel: z.enum(["basico", "estandar", "premium", "empresarial"], {
|
||||
message: "planBucefalo.nivel debe ser basico, estandar, premium o empresarial",
|
||||
}),
|
||||
precio: z.number().min(0).optional(),
|
||||
})
|
||||
.nullable(),
|
||||
.nullable()
|
||||
.default(null),
|
||||
});
|
||||
|
||||
export const cotizacionPutSchema = z.object({
|
||||
@@ -115,19 +125,82 @@ export const loginSchema = z.object({
|
||||
password: z.string().min(1, "Password es requerido"),
|
||||
});
|
||||
|
||||
export const servicioCatalogoSchema = z.object({
|
||||
nombre: z.string().min(1, "Nombre es requerido"),
|
||||
descripcion: z.string().nullable(),
|
||||
fase: z.number().int().min(0).max(3),
|
||||
tipoPago: z.enum(["unico", "mensual"]),
|
||||
precioBase: z.number().min(0, "Precio debe ser positivo"),
|
||||
tiempoEntrega: z.string().min(1),
|
||||
entregablesDefault: z.array(z.string()),
|
||||
categoriaId: z.string().min(1, "Categoria es requerida"),
|
||||
variante: z.string().nullable(),
|
||||
nivel: z.string().nullable().optional(),
|
||||
orden: z.number().int().min(0),
|
||||
});
|
||||
// Texto opcional del catalogo: "" y espacios cuentan como "sin valor" (null).
|
||||
// El `.optional()` va POR FUERA del transform: asi una clave ausente sigue
|
||||
// ausente (undefined) en vez de convertirse en null y borrar el dato en un PATCH.
|
||||
const textoCatalogo = z
|
||||
.string()
|
||||
.trim()
|
||||
.nullable()
|
||||
.transform((v) => (v ? v : null))
|
||||
.optional();
|
||||
|
||||
export const NIVELES_SERVICIO = ["Emprendedor", "PYME", "Empresario", "Corporativo"] as const;
|
||||
|
||||
const nivelServicio = z
|
||||
.preprocess(
|
||||
(v) => (v === "" ? null : v),
|
||||
z
|
||||
.enum(NIVELES_SERVICIO, { message: `nivel debe ser uno de: ${NIVELES_SERVICIO.join(", ")}` })
|
||||
.nullable()
|
||||
)
|
||||
.optional();
|
||||
|
||||
const camposServicio = {
|
||||
nombre: z.string().trim().min(1, "Nombre es requerido"),
|
||||
descripcion: textoCatalogo,
|
||||
fase: z.number().int().min(0, "fase debe ser 0, 1, 2 o 3").max(3, "fase debe ser 0, 1, 2 o 3"),
|
||||
tipoPago: z.enum(["unico", "mensual"], { message: "tipoPago debe ser 'unico' o 'mensual'" }),
|
||||
precioBase: z.number().min(0, "precioBase debe ser 0 o mayor"),
|
||||
categoriaId: textoCatalogo,
|
||||
variante: textoCatalogo,
|
||||
nivel: nivelServicio,
|
||||
activo: z.boolean().optional(),
|
||||
};
|
||||
|
||||
// Campos que no existen en el catalogo se rechazan con su nombre (en vez de
|
||||
// descartarse en silencio), para que quien llame sepa que se equivoco.
|
||||
const soloCamposConocidos = {
|
||||
error: (iss: { code?: string; keys?: string[] }) =>
|
||||
iss.code === "unrecognized_keys" ? `Campo no reconocido: ${(iss.keys ?? []).join(", ")}` : undefined,
|
||||
};
|
||||
|
||||
// Alta de un servicio del catalogo. Solo `nombre`, `fase`, `tipoPago` y
|
||||
// `precioBase` son obligatorios; el resto tiene un default razonable para que
|
||||
// un alta desde el CLI o desde una LLM no tenga que adivinar campos.
|
||||
export const servicioCatalogoSchema = z.strictObject(
|
||||
{
|
||||
...camposServicio,
|
||||
tiempoEntrega: z.string().trim().min(1).default("4 - 10 dias"),
|
||||
entregablesDefault: z.array(z.string().trim().min(1)).default([]),
|
||||
// Sin `orden`, el servidor lo coloca al final de su fase.
|
||||
orden: z.number().int().min(0).optional(),
|
||||
},
|
||||
soloCamposConocidos
|
||||
);
|
||||
|
||||
// Edicion parcial: solo se tocan los campos enviados. Sin defaults, para que un
|
||||
// PATCH con { precioBase } no reinicie tiempoEntrega ni entregables.
|
||||
export const servicioCatalogoPatchSchema = z
|
||||
.strictObject(
|
||||
{
|
||||
...camposServicio,
|
||||
nombre: camposServicio.nombre.optional(),
|
||||
fase: camposServicio.fase.optional(),
|
||||
tipoPago: camposServicio.tipoPago.optional(),
|
||||
precioBase: camposServicio.precioBase.optional(),
|
||||
tiempoEntrega: z.string().trim().min(1).optional(),
|
||||
entregablesDefault: z.array(z.string().trim().min(1)).optional(),
|
||||
orden: z.number().int().min(0).optional(),
|
||||
},
|
||||
soloCamposConocidos
|
||||
)
|
||||
.refine((d) => Object.values(d).some((v) => v !== undefined), {
|
||||
message: "No se envio ningun campo para actualizar",
|
||||
});
|
||||
|
||||
export type ServicioCatalogoInput = z.infer<typeof servicioCatalogoSchema>;
|
||||
export type ServicioCatalogoPatch = z.infer<typeof servicioCatalogoPatchSchema>;
|
||||
|
||||
export function validateOrError<T>(
|
||||
schema: z.ZodType<T>,
|
||||
|
||||
Reference in New Issue
Block a user