Compare commits
48 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
1effb62498 | |
|
|
47ef376564 | |
|
|
3351fb3330 | |
|
|
54a65d8ac9 | |
|
|
1fbe4cb931 | |
|
|
a5d736a30d | |
|
|
b12ff93b6c | |
|
|
cd78defda1 | |
|
|
497f49e85d | |
|
|
36e9474801 | |
|
|
6e7c22cc9c | |
|
|
f1258b8e8e | |
|
|
d30e57f006 | |
|
|
3fd64368a2 | |
|
|
a9ca3f59f3 | |
|
|
144ce428f0 | |
|
|
653e5b4fd2 | |
|
|
68d5e1a205 | |
|
|
371c5ec31c | |
|
|
b756830559 | |
|
|
470f0f389c | |
|
|
acf723ac7d | |
|
|
b4078b41d6 | |
|
|
7e7e13c313 | |
|
|
de451ca234 | |
|
|
fac45d6346 | |
|
|
f5cb6f794d | |
|
|
5757d20b3b | |
|
|
7362f1a8d0 | |
|
|
75449c9b4f | |
|
|
83f0631e43 | |
|
|
e1dc916b57 | |
|
|
6ecf7b98cd | |
|
|
361a39f8a3 | |
|
|
74e7e6c085 | |
|
|
e1fb8b6f1d | |
|
|
cfedd443c2 | |
|
|
0901d4eae8 | |
|
|
04cc1c28d2 | |
|
|
3fb5a411c3 | |
|
|
d90b129924 | |
|
|
a4ba8095f5 | |
|
|
affbc47bfd | |
|
|
fe365801e9 | |
|
|
ceaa96dd1c | |
|
|
4348aab5b1 | |
|
|
b4826543de | |
|
|
92532f538f |
19
.env
19
.env
|
|
@ -18,8 +18,6 @@ EMAIL_API_KEY=9UShpS8oh5Iun92TJSfevElI3Lp99TCv
|
||||||
# server with the prisma dev CLI command, when not choosing any non-default ports or settings. The API key, unlike the
|
# server with the prisma dev CLI command, when not choosing any non-default ports or settings. The API key, unlike the
|
||||||
# one found in a remote Prisma Postgres URL, does not contain any sensitive information.
|
# one found in a remote Prisma Postgres URL, does not contain any sensitive information.
|
||||||
|
|
||||||
DATABASE_URL="file:./dev.db"
|
|
||||||
|
|
||||||
N8N_WEBHOOK_URL="https://flows2.carpa.com/webhook/news-summary"
|
N8N_WEBHOOK_URL="https://flows2.carpa.com/webhook/news-summary"
|
||||||
N8N_API_KEY="sk_live_JwjpTdZrLVvijCKuWylWZbUuhBm6zPDH"
|
N8N_API_KEY="sk_live_JwjpTdZrLVvijCKuWylWZbUuhBm6zPDH"
|
||||||
|
|
||||||
|
|
@ -33,3 +31,20 @@ TURNSTILE_SITE_KEY=0x4AAAAAAD9IYWC6HPflpneO
|
||||||
# Cloudflare Turnstile — secret key (server-side, keep safe!)
|
# Cloudflare Turnstile — secret key (server-side, keep safe!)
|
||||||
# In production, set this as a Gitea Actions secret named TURNSTILE_SECRET_KEY
|
# In production, set this as a Gitea Actions secret named TURNSTILE_SECRET_KEY
|
||||||
TURNSTILE_SECRET_KEY=0x4AAAAAAD9IYXASjQSpmo2iS902SDoXnT4
|
TURNSTILE_SECRET_KEY=0x4AAAAAAD9IYXASjQSpmo2iS902SDoXnT4
|
||||||
|
|
||||||
|
# Supabase PostgreSQL
|
||||||
|
# <<<<<<< Updated upstream
|
||||||
|
# DATABASE_URL="postgresql://postgres:postgres@localhost:5432/postgres?schema=public"
|
||||||
|
# DIRECT_URL="postgresql://postgres:postgres@localhost:5432/postgres?schema=public"
|
||||||
|
# SUPABASE_URL="http://localhost:8000"
|
||||||
|
# SUPABASE_ANON_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJhbm9uIiwKICAgICJpc3MiOiAic3VwYWJhc2UtZGVtbyIsCiAgICAiaWF0IjogMTY0MTc2OTIwMCwKICAgICJleHAiOiAxNzk5NTM1NjAwCn0.dc_X5iR_VP_qT0zsiyj_I_OZ2T9FtRU2BBNWN8Bu4GE"
|
||||||
|
# SUPABASE_SERVICE_ROLE_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJzZXJ2aWNlX3JvbGUiLAogICAgImlzcyI6ICJzdXBhYmFzZS1kZW1vIiwKICAgICJpYXQiOiAxNjQxNzY5MjAwLAogICAgImV4cCI6IDE3OTk1MzU2MDAKfQ.DaYlNEoUrrEn2Ig7tqibS-PHK5vgusbcbo7X36XVt4Q"
|
||||||
|
# POSTGRES_PASSWORD=postgres
|
||||||
|
# =======
|
||||||
|
DATABASE_URL="postgresql://postgres:13730fbbdb2e76c904b228bd93bedd7f@vps1.carpa.com:5432/postgres?schema=public"
|
||||||
|
DIRECT_URL="postgresql://postgres:13730fbbdb2e76c904b228bd93bedd7f@vps1.carpa.com:5432/postgres?schema=public"
|
||||||
|
SUPABASE_URL="http://vps1.carpa.com"
|
||||||
|
SUPABASE_ANON_KEY="eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjNhMWFiMzE3LWJhOWQtNGVlMy1hY2Y4LTgzNjVmNmE5ZTBiNyJ9.eyJyb2xlIjoiYW5vbiIsImlzcyI6InN1cGFiYXNlIiwiaWF0IjoxNzgyODU4MjA4LCJleHAiOjE5NDA1MzgyMDh9.53Jkizte60-Hos40tOz0Ld7ffHe6DAG6Nt033XDZHPCnanjYOpgaLfC2QlbY4mFWw9Z2hCd8bUgxWsGpwFNcPg"
|
||||||
|
SUPABASE_SERVICE_ROLE_KEY="eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjNhMWFiMzE3LWJhOWQtNGVlMy1hY2Y4LTgzNjVmNmE5ZTBiNyJ9.eyJyb2xlIjoic2VydmljZV9yb2xlIiwiaXNzIjoic3VwYWJhc2UiLCJpYXQiOjE3ODI4NTgyMDgsImV4cCI6MTk0MDUzODIwOH0.f4ZWyQj0fGpEAKXWvL97b1w_4eaBfXRC13b5Mtac9UhJNbMFKIJJn1x_-8Kds-1PfIv590xlumN4sp_3X_tZeg"
|
||||||
|
POSTGRES_PASSWORD=13730fbbdb2e76c904b228bd93bedd7f
|
||||||
|
# >>>>>>> Stashed changes
|
||||||
|
|
|
||||||
|
|
@ -31,5 +31,12 @@ data/
|
||||||
opencode/
|
opencode/
|
||||||
.opencode/
|
.opencode/
|
||||||
docs/
|
docs/
|
||||||
|
|
||||||
|
# guía técnica local
|
||||||
|
docs/GUIA-TECNICA.md
|
||||||
|
|
||||||
|
# scripts de migración (locales, no en producción)
|
||||||
|
scripts/migrate-sheets-to-db.ts
|
||||||
|
scripts/seed-form-config.ts
|
||||||
scripts/
|
scripts/
|
||||||
.env.example
|
.env.example
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,10 @@
|
||||||
"build": "astro build",
|
"build": "astro build",
|
||||||
"postbuild": "node scripts/send-to-n8n.js",
|
"postbuild": "node scripts/send-to-n8n.js",
|
||||||
"preview": "astro preview",
|
"preview": "astro preview",
|
||||||
"astro": "astro"
|
"astro": "astro",
|
||||||
|
"db:migrate-sheets": "npx tsx scripts/migrate-sheets-to-db.ts",
|
||||||
|
"db:seed-form-config": "npx tsx scripts/seed-form-config.ts",
|
||||||
|
"db:setup": "npx tsx scripts/seed-form-config.ts && npx tsx scripts/migrate-sheets-to-db.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@astrojs/markdoc": "^2.0.3",
|
"@astrojs/markdoc": "^2.0.3",
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,6 @@ export default defineConfig({
|
||||||
},
|
},
|
||||||
engine: "classic",
|
engine: "classic",
|
||||||
datasource: {
|
datasource: {
|
||||||
url: env("DATABASE_URL"),
|
url: env("DIRECT_URL") || env("DATABASE_URL"),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,3 @@
|
||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "sqlite"
|
||||||
|
|
@ -0,0 +1,17 @@
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Contact" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"nombre" TEXT NOT NULL,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"mensaje" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "Contact_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "Contact_email_key" ON "Contact"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "Contact_email_createdAt_idx" ON "Contact"("email", "createdAt");
|
||||||
|
|
@ -0,0 +1,174 @@
|
||||||
|
/*
|
||||||
|
Warnings:
|
||||||
|
|
||||||
|
- You are about to drop the `Contact` table. If the table is not empty, all the data it contains will be lost.
|
||||||
|
|
||||||
|
*/
|
||||||
|
-- DropTable
|
||||||
|
DROP TABLE "Contact";
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "contact" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"nombre" TEXT NOT NULL,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"mensaje" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "contact_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "formularios" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"numero_voluntario" SERIAL NOT NULL,
|
||||||
|
"nombre" TEXT NOT NULL,
|
||||||
|
"segundo_nombre" TEXT,
|
||||||
|
"apellido" TEXT NOT NULL,
|
||||||
|
"documento_nro" TEXT,
|
||||||
|
"documento_tipo" TEXT,
|
||||||
|
"correo" TEXT NOT NULL,
|
||||||
|
"fecha_nacimiento" DATE,
|
||||||
|
"nacionalidad" TEXT,
|
||||||
|
"sexo" TEXT,
|
||||||
|
"direccion" TEXT,
|
||||||
|
"ciudad" TEXT,
|
||||||
|
"estado" TEXT,
|
||||||
|
"pais" TEXT,
|
||||||
|
"codigo_postal" TEXT,
|
||||||
|
"telefono" TEXT,
|
||||||
|
"whatsapp" TEXT,
|
||||||
|
"profesion" TEXT,
|
||||||
|
"lugar_trabajo" TEXT,
|
||||||
|
"nivel_academico" TEXT,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'pendiente',
|
||||||
|
"form_version" TEXT,
|
||||||
|
"email_sent_at" TIMESTAMPTZ,
|
||||||
|
"submitted_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMPTZ NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "formularios_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "respuestas" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"formulario_id" UUID NOT NULL,
|
||||||
|
"key" TEXT NOT NULL,
|
||||||
|
"value" TEXT NOT NULL,
|
||||||
|
"seccion" TEXT NOT NULL DEFAULT '',
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "respuestas_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "secciones" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"title_key" TEXT NOT NULL,
|
||||||
|
"title" TEXT,
|
||||||
|
"orden" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"columns" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "secciones_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "campos" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"key" TEXT NOT NULL,
|
||||||
|
"label_key" TEXT NOT NULL,
|
||||||
|
"tipo" TEXT NOT NULL,
|
||||||
|
"seccion_id" UUID,
|
||||||
|
"required" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"orden" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"options" JSONB,
|
||||||
|
"source" TEXT,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "campos_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "form_versions" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"version" TEXT NOT NULL,
|
||||||
|
"config" JSONB NOT NULL,
|
||||||
|
"active" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "form_versions_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "admins" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"auth_user_id" UUID NOT NULL,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"nombre" TEXT NOT NULL,
|
||||||
|
"rol" TEXT NOT NULL DEFAULT 'coordinador',
|
||||||
|
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"ultimo_acceso" TIMESTAMPTZ,
|
||||||
|
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "admins_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "contact_email_key" ON "contact"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "contact_email_createdAt_idx" ON "contact"("email", "createdAt");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "formularios_numero_voluntario_key" ON "formularios"("numero_voluntario");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_correo_idx" ON "formularios"("correo");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_status_idx" ON "formularios"("status");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_pais_idx" ON "formularios"("pais");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_submitted_at_idx" ON "formularios"("submitted_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "respuestas_formulario_id_idx" ON "respuestas"("formulario_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "respuestas_key_idx" ON "respuestas"("key");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "respuestas_seccion_idx" ON "respuestas"("seccion");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "secciones_orden_idx" ON "secciones"("orden");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "campos_key_key" ON "campos"("key");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "campos_seccion_id_idx" ON "campos"("seccion_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "campos_tipo_idx" ON "campos"("tipo");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "admins_auth_user_id_key" ON "admins"("auth_user_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "admins_email_key" ON "admins"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "admins_email_idx" ON "admins"("email");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "respuestas" ADD CONSTRAINT "respuestas_formulario_id_fkey" FOREIGN KEY ("formulario_id") REFERENCES "formularios"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "campos" ADD CONSTRAINT "campos_seccion_id_fkey" FOREIGN KEY ("seccion_id") REFERENCES "secciones"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
@ -0,0 +1,23 @@
|
||||||
|
-- Enable pg_trgm for trigram-based GIN indexes
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_nombre_trgm_idx" ON "formularios" USING GIN ("nombre" gin_trgm_ops);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_apellido_trgm_idx" ON "formularios" USING GIN ("apellido" gin_trgm_ops);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_correo_trgm_idx" ON "formularios" USING GIN ("correo" gin_trgm_ops);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_telefono_trgm_idx" ON "formularios" USING GIN ("telefono" gin_trgm_ops);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_whatsapp_trgm_idx" ON "formularios" USING GIN ("whatsapp" gin_trgm_ops);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_documento_nro_trgm_idx" ON "formularios" USING GIN ("documento_nro" gin_trgm_ops);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "respuestas_value_trgm_idx" ON "respuestas" USING GIN ("value" gin_trgm_ops);
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_ciudad_trgm_idx" ON "formularios" USING GIN ("ciudad" gin_trgm_ops);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_estado_trgm_idx" ON "formularios" USING GIN ("estado" gin_trgm_ops);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_profesion_trgm_idx" ON "formularios" USING GIN ("profesion" gin_trgm_ops);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_nivel_academico_trgm_idx" ON "formularios" USING GIN ("nivel_academico" gin_trgm_ops);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "formularios_nacionalidad_trgm_idx" ON "formularios" USING GIN ("nacionalidad" gin_trgm_ops);
|
||||||
|
|
@ -1,3 +1,3 @@
|
||||||
# Please do not edit this file manually
|
# Please do not edit this file manually
|
||||||
# It should be added in your version-control system (e.g., Git)
|
# It should be added in your version-control system (e.g., Git)
|
||||||
provider = "sqlite"
|
provider = "postgresql"
|
||||||
|
|
|
||||||
|
|
@ -3,8 +3,9 @@ generator client {
|
||||||
}
|
}
|
||||||
|
|
||||||
datasource db {
|
datasource db {
|
||||||
provider = "sqlite"
|
provider = "postgresql"
|
||||||
url = env("DATABASE_URL")
|
url = env("DATABASE_URL")
|
||||||
|
directUrl = env("DIRECT_URL")
|
||||||
}
|
}
|
||||||
|
|
||||||
model Contact {
|
model Contact {
|
||||||
|
|
@ -16,4 +17,127 @@ model Contact {
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
@@index([email, createdAt])
|
@@index([email, createdAt])
|
||||||
|
@@map("contact")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Formulario {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
numero_voluntario Int @unique @default(autoincrement())
|
||||||
|
nombre String
|
||||||
|
segundo_nombre String?
|
||||||
|
apellido String
|
||||||
|
documento_nro String?
|
||||||
|
documento_tipo String?
|
||||||
|
correo String
|
||||||
|
fecha_nacimiento DateTime? @db.Date
|
||||||
|
nacionalidad String?
|
||||||
|
sexo String?
|
||||||
|
direccion String?
|
||||||
|
ciudad String?
|
||||||
|
estado String?
|
||||||
|
pais String?
|
||||||
|
codigo_postal String?
|
||||||
|
telefono String?
|
||||||
|
whatsapp String?
|
||||||
|
profesion String?
|
||||||
|
lugar_trabajo String?
|
||||||
|
nivel_academico String?
|
||||||
|
status String @default("pendiente")
|
||||||
|
form_version String?
|
||||||
|
email_sent_at DateTime? @db.Timestamptz
|
||||||
|
submitted_at DateTime @default(now()) @db.Timestamptz
|
||||||
|
updated_at DateTime @updatedAt @db.Timestamptz
|
||||||
|
|
||||||
|
respuestas Respuesta[]
|
||||||
|
|
||||||
|
@@index([correo])
|
||||||
|
@@index([status])
|
||||||
|
@@index([pais])
|
||||||
|
@@index([submitted_at])
|
||||||
|
@@index([nombre(ops: raw("gin_trgm_ops"))], type: Gin, map: "formularios_nombre_trgm_idx")
|
||||||
|
@@index([apellido(ops: raw("gin_trgm_ops"))], type: Gin, map: "formularios_apellido_trgm_idx")
|
||||||
|
@@index([correo(ops: raw("gin_trgm_ops"))], type: Gin, map: "formularios_correo_trgm_idx")
|
||||||
|
@@index([telefono(ops: raw("gin_trgm_ops"))], type: Gin, map: "formularios_telefono_trgm_idx")
|
||||||
|
@@index([whatsapp(ops: raw("gin_trgm_ops"))], type: Gin, map: "formularios_whatsapp_trgm_idx")
|
||||||
|
@@index([documento_nro(ops: raw("gin_trgm_ops"))], type: Gin, map: "formularios_documento_nro_trgm_idx")
|
||||||
|
@@index([ciudad(ops: raw("gin_trgm_ops"))], type: Gin, map: "formularios_ciudad_trgm_idx")
|
||||||
|
@@index([estado(ops: raw("gin_trgm_ops"))], type: Gin, map: "formularios_estado_trgm_idx")
|
||||||
|
@@index([profesion(ops: raw("gin_trgm_ops"))], type: Gin, map: "formularios_profesion_trgm_idx")
|
||||||
|
@@index([nivel_academico(ops: raw("gin_trgm_ops"))], type: Gin, map: "formularios_nivel_academico_trgm_idx")
|
||||||
|
@@index([nacionalidad(ops: raw("gin_trgm_ops"))], type: Gin, map: "formularios_nacionalidad_trgm_idx")
|
||||||
|
@@map("formularios")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Respuesta {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
formulario_id String @db.Uuid
|
||||||
|
key String
|
||||||
|
value String
|
||||||
|
seccion String @default("")
|
||||||
|
created_at DateTime @default(now()) @db.Timestamptz
|
||||||
|
|
||||||
|
formulario Formulario @relation(fields: [formulario_id], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([formulario_id])
|
||||||
|
@@index([key])
|
||||||
|
@@index([seccion])
|
||||||
|
@@index([value(ops: raw("gin_trgm_ops"))], type: Gin, map: "respuestas_value_trgm_idx")
|
||||||
|
@@map("respuestas")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Seccion {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
title_key String
|
||||||
|
title String?
|
||||||
|
orden Int @default(0)
|
||||||
|
columns Int @default(1)
|
||||||
|
created_at DateTime @default(now()) @db.Timestamptz
|
||||||
|
|
||||||
|
campos Campo[]
|
||||||
|
|
||||||
|
@@index([orden])
|
||||||
|
@@map("secciones")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Campo {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
key String @unique
|
||||||
|
label_key String
|
||||||
|
tipo String
|
||||||
|
seccion_id String? @db.Uuid
|
||||||
|
required Boolean @default(false)
|
||||||
|
orden Int @default(0)
|
||||||
|
options Json? @db.JsonB
|
||||||
|
source String?
|
||||||
|
created_at DateTime @default(now()) @db.Timestamptz
|
||||||
|
|
||||||
|
seccion Seccion? @relation(fields: [seccion_id], references: [id], onDelete: SetNull)
|
||||||
|
|
||||||
|
@@index([seccion_id])
|
||||||
|
@@index([tipo])
|
||||||
|
@@map("campos")
|
||||||
|
}
|
||||||
|
|
||||||
|
model FormVersion {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
version String
|
||||||
|
config Json @db.JsonB
|
||||||
|
active Boolean @default(false)
|
||||||
|
created_at DateTime @default(now()) @db.Timestamptz
|
||||||
|
|
||||||
|
@@map("form_versions")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Admin {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
auth_user_id String @unique @db.Uuid
|
||||||
|
email String @unique
|
||||||
|
nombre String
|
||||||
|
rol String @default("coordinador")
|
||||||
|
activo Boolean @default(true)
|
||||||
|
ultimo_acceso DateTime? @db.Timestamptz
|
||||||
|
created_at DateTime @default(now()) @db.Timestamptz
|
||||||
|
|
||||||
|
@@index([email])
|
||||||
|
@@map("admins")
|
||||||
}
|
}
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
||||||
<title>TinaCMS</title>
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<!-- if development -->
|
|
||||||
<script type="module">
|
|
||||||
import RefreshRuntime from 'http://localhost:4001/@react-refresh'
|
|
||||||
RefreshRuntime.injectIntoGlobalHook(window)
|
|
||||||
window.$RefreshReg$ = () => {}
|
|
||||||
window.$RefreshSig$ = () => (type) => type
|
|
||||||
window.__vite_plugin_react_preamble_installed__ = true
|
|
||||||
</script>
|
|
||||||
<script type="module" src="http://localhost:4001/@vite/client"></script>
|
|
||||||
<script>
|
|
||||||
function handleLoadError() {
|
|
||||||
// Assets have failed to load
|
|
||||||
document.getElementById('root').innerHTML = '<style type="text/css"> #no-assets-placeholder body { font-family: sans-serif; font-size: 16px; line-height: 1.4; color: #333; background-color: #f5f5f5; } #no-assets-placeholder { max-width: 600px; margin: 0 auto; padding: 40px; text-align: center; background-color: #fff; box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.1); } #no-assets-placeholder h1 { font-size: 24px; margin-bottom: 20px; } #no-assets-placeholder p { margin-bottom: 10px; } #no-assets-placeholder a { color: #0077cc; text-decoration: none; } #no-assets-placeholder a:hover { text-decoration: underline; } </style> <div id="no-assets-placeholder"> <h1>Failed loading TinaCMS assets</h1> <p> Your TinaCMS configuration may be misconfigured, and we could not load the assets for this page. </p> <p> Please visit <a href="https://tina.io/docs/r/FAQ/#13-how-do-i-resolve-failed-loading-tinacms-assets-error">this doc</a> for help. </p> </div> </div>';
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
<script
|
|
||||||
type="module"
|
|
||||||
src="http://localhost:4001/src/main.tsx"
|
|
||||||
onerror="handleLoadError()"
|
|
||||||
></script>
|
|
||||||
<body class="tina-tailwind">
|
|
||||||
<div id="root"></div>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
|
|
@ -12,6 +12,7 @@ const tl = createTranslator(Astro.currentLocale);
|
||||||
const currentLocale = Astro.currentLocale;
|
const currentLocale = Astro.currentLocale;
|
||||||
const currentPath = Astro.url.pathname;
|
const currentPath = Astro.url.pathname;
|
||||||
const { locale } = Astro.params;
|
const { locale } = Astro.params;
|
||||||
|
const isAdmin = currentPath.split("/").includes("admin");
|
||||||
|
|
||||||
const languages = [
|
const languages = [
|
||||||
{ code: "es", icon: "icon_flag_es", label: "Español" },
|
{ code: "es", icon: "icon_flag_es", label: "Español" },
|
||||||
|
|
@ -156,6 +157,16 @@ function translatePath(newLocale: string) {
|
||||||
</li>
|
</li>
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
{isAdmin && (
|
||||||
|
<li>
|
||||||
|
<a
|
||||||
|
class="hover:text-colorPrimary transition"
|
||||||
|
href="#"
|
||||||
|
>
|
||||||
|
Acceder
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
)}
|
||||||
</ul>
|
</ul>
|
||||||
<div class="w-50">
|
<div class="w-50">
|
||||||
<Button
|
<Button
|
||||||
|
|
@ -202,6 +213,16 @@ function translatePath(newLocale: string) {
|
||||||
variant="primary"
|
variant="primary"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
{isAdmin && (
|
||||||
|
<div class="hidden md:block">
|
||||||
|
<Button
|
||||||
|
class="px-4 py-2 uppercase"
|
||||||
|
title="Acceder"
|
||||||
|
url="#"
|
||||||
|
variant="secondary"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div class="dropdown dropdown-end md:block hidden">
|
<div class="dropdown dropdown-end md:block hidden">
|
||||||
<div
|
<div
|
||||||
tabindex="0"
|
tabindex="0"
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,209 @@
|
||||||
|
<template>
|
||||||
|
<div class="space-y-8">
|
||||||
|
<div v-if="loading" class="flex justify-center py-16">
|
||||||
|
<span class="loading loading-spinner loading-lg text-primary"></span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="error" class="text-center py-10 text-error">{{ error }}</div>
|
||||||
|
|
||||||
|
<template v-else-if="stats">
|
||||||
|
<!-- Resumen -->
|
||||||
|
<section>
|
||||||
|
<h3 class="text-xs font-bold text-tertiary uppercase tracking-wide flex items-center gap-2 mb-3">
|
||||||
|
<span class="inline-block w-1 h-3.5 bg-colorSecondary"></span>Resumen
|
||||||
|
</h3>
|
||||||
|
<div class="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||||
|
<div class="stat bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box p-4">
|
||||||
|
<div class="stat-title text-tertiary/70 text-xs font-medium">Total voluntarios</div>
|
||||||
|
<div class="stat-value text-tertiary font-primary">{{ fmt(stats.total) }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box p-4">
|
||||||
|
<div class="stat-title text-tertiary/70 text-xs font-medium">Edad promedio</div>
|
||||||
|
<div class="stat-value text-tertiary font-primary">{{ stats.edad.promedio ?? "—" }} años</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box p-4">
|
||||||
|
<div class="stat-title text-tertiary/70 text-xs font-medium">Femenino</div>
|
||||||
|
<div class="stat-value text-tertiary font-primary">{{ fmt(sexo.f) }}</div>
|
||||||
|
<div class="stat-desc text-tertiary/60">{{ pct(sexo.f, sexo.total) }}% del total</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box p-4">
|
||||||
|
<div class="stat-title text-tertiary/70 text-xs font-medium">Masculino</div>
|
||||||
|
<div class="stat-value text-tertiary font-primary">{{ fmt(sexo.m) }}</div>
|
||||||
|
<div class="stat-desc text-tertiary/60">{{ pct(sexo.m, sexo.total) }}% del total</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Idiomas -->
|
||||||
|
<section>
|
||||||
|
<h3 class="text-xs font-bold text-tertiary uppercase tracking-wide flex items-center gap-2 mb-3">
|
||||||
|
<span class="inline-block w-1 h-3.5 bg-colorSecondary"></span>Idiomas
|
||||||
|
</h3>
|
||||||
|
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
|
||||||
|
<div
|
||||||
|
v-for="lang in stats.idiomas"
|
||||||
|
:key="lang.value"
|
||||||
|
class="stat bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box p-4"
|
||||||
|
>
|
||||||
|
<div class="stat-title text-tertiary/70 text-xs font-medium">{{ lang.label }}</div>
|
||||||
|
<div class="stat-value text-tertiary font-primary text-2xl">{{ fmt(lang.count) }}</div>
|
||||||
|
<div class="stat-desc text-tertiary/60">{{ pct(lang.count, stats.total) }}% del total</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Distribuciones -->
|
||||||
|
<section>
|
||||||
|
<h3 class="text-xs font-bold text-tertiary uppercase tracking-wide flex items-center gap-2 mb-3">
|
||||||
|
<span class="inline-block w-1 h-3.5 bg-colorSecondary"></span>Distribuciones
|
||||||
|
</h3>
|
||||||
|
<div class="grid md:grid-cols-2 gap-4">
|
||||||
|
<div class="card bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box">
|
||||||
|
<div class="card-body p-4 sm:p-5">
|
||||||
|
<h4 class="card-title text-tertiary text-sm font-bold">Áreas de colaboración</h4>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<div v-for="item in topAreas" :key="item.value" class="flex items-center gap-3">
|
||||||
|
<span class="w-32 sm:w-44 shrink-0 text-sm text-tertiary truncate" :title="item.label">{{ item.label }}</span>
|
||||||
|
<progress class="progress progress-secondary flex-1" :value="item.count" :max="areasMax"></progress>
|
||||||
|
<span class="w-12 shrink-0 text-right text-sm font-semibold text-tertiary">{{ fmt(item.count) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box">
|
||||||
|
<div class="card-body p-4 sm:p-5">
|
||||||
|
<h4 class="card-title text-tertiary text-sm font-bold">Días disponibles</h4>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<div v-for="item in stats.dias" :key="item.value" class="flex items-center gap-3">
|
||||||
|
<span class="w-32 sm:w-44 shrink-0 text-sm text-tertiary truncate" :title="item.label">{{ item.label }}</span>
|
||||||
|
<progress class="progress progress-secondary flex-1" :value="item.count" :max="diasMax"></progress>
|
||||||
|
<span class="w-12 shrink-0 text-right text-sm font-semibold text-tertiary">{{ fmt(item.count) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box">
|
||||||
|
<div class="card-body p-4 sm:p-5">
|
||||||
|
<h4 class="card-title text-tertiary text-sm font-bold">Horario preferido</h4>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<div v-for="item in stats.horarios" :key="item.value" class="flex items-center gap-3">
|
||||||
|
<span class="w-32 sm:w-44 shrink-0 text-sm text-tertiary truncate" :title="item.label">{{ item.label }}</span>
|
||||||
|
<progress class="progress progress-secondary flex-1" :value="item.count" :max="horariosMax"></progress>
|
||||||
|
<span class="w-12 shrink-0 text-right text-sm font-semibold text-tertiary">{{ fmt(item.count) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box">
|
||||||
|
<div class="card-body p-4 sm:p-5">
|
||||||
|
<h4 class="card-title text-tertiary text-sm font-bold">Países</h4>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<div v-for="item in stats.paises" :key="item.value" class="flex items-center gap-3">
|
||||||
|
<span class="w-32 sm:w-44 shrink-0 text-sm text-tertiary truncate" :title="item.value">{{ item.value }}</span>
|
||||||
|
<progress class="progress progress-secondary flex-1" :value="item.count" :max="paisesMax"></progress>
|
||||||
|
<span class="w-12 shrink-0 text-right text-sm font-semibold text-tertiary">{{ fmt(item.count) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Disponibilidad y salud -->
|
||||||
|
<section>
|
||||||
|
<h3 class="text-xs font-bold text-tertiary uppercase tracking-wide flex items-center gap-2 mb-3">
|
||||||
|
<span class="inline-block w-1 h-3.5 bg-colorSecondary"></span>Disponibilidad y salud
|
||||||
|
</h3>
|
||||||
|
<div class="card bg-colorPrimary ring-1 ring-colorSecondary/40 rounded-box">
|
||||||
|
<div class="card-body p-4 sm:p-6 grid md:grid-cols-2 gap-x-8 gap-y-5">
|
||||||
|
<div v-for="m in condMetrics" :key="m.title" class="space-y-1.5">
|
||||||
|
<div class="flex justify-between text-sm text-tertiary">
|
||||||
|
<span class="font-medium">{{ m.title }}</span>
|
||||||
|
<span>Sí {{ m.pct }}% · No {{ 100 - m.pct }}%</span>
|
||||||
|
</div>
|
||||||
|
<progress class="progress progress-secondary w-full" :value="m.si" :max="m.total"></progress>
|
||||||
|
<p class="text-xs text-tertiary/60">
|
||||||
|
Sí: {{ fmt(m.si) }} · No: {{ fmt(m.no) }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<div class="flex justify-between text-sm text-tertiary">
|
||||||
|
<span class="font-medium">Sexo</span>
|
||||||
|
<span>F {{ pct(sexo.f, sexo.total) }}% · M {{ pct(sexo.m, sexo.total) }}%</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex w-full h-3 rounded-none overflow-hidden bg-tertiary/15">
|
||||||
|
<div class="bg-tertiary h-full" :style="{ width: pct(sexo.f, sexo.total) + '%' }"></div>
|
||||||
|
<div class="bg-colorSecondary h-full" :style="{ width: pct(sexo.m, sexo.total) + '%' }"></div>
|
||||||
|
</div>
|
||||||
|
<p class="text-xs text-tertiary/60">
|
||||||
|
F: {{ fmt(sexo.f) }} · M: {{ fmt(sexo.m) }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, computed, onMounted } from "vue";
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const error = ref("");
|
||||||
|
const stats = ref(null);
|
||||||
|
|
||||||
|
const fmt = (n) => Number(n || 0).toLocaleString("es");
|
||||||
|
const pct = (n, total) => (total ? Math.round(((n || 0) / total) * 100) : 0);
|
||||||
|
|
||||||
|
const sexo = computed(() => {
|
||||||
|
const s = stats.value?.sexo || [];
|
||||||
|
const f = s.find((x) => x.value === "F")?.count || 0;
|
||||||
|
const m = s.find((x) => x.value === "M")?.count || 0;
|
||||||
|
return { f, m, total: f + m };
|
||||||
|
});
|
||||||
|
|
||||||
|
const topAreas = computed(() => (stats.value?.areas || []).slice(0, 8));
|
||||||
|
const areasMax = computed(() => topAreas.value[0]?.count || 1);
|
||||||
|
const diasMax = computed(() => stats.value?.dias[0]?.count || 1);
|
||||||
|
const horariosMax = computed(() => stats.value?.horarios[0]?.count || 1);
|
||||||
|
const paisesMax = computed(() => stats.value?.paises[0]?.count || 1);
|
||||||
|
|
||||||
|
const condMetrics = computed(() => {
|
||||||
|
const c = stats.value?.condiciones;
|
||||||
|
if (!c) return [];
|
||||||
|
const mk = (title, key) => {
|
||||||
|
const si = c[key].si || 0;
|
||||||
|
const no = c[key].no || 0;
|
||||||
|
const total = si + no;
|
||||||
|
return { title, si, no, total, pct: total ? Math.round((si / total) * 100) : 0 };
|
||||||
|
};
|
||||||
|
return [
|
||||||
|
mk("Disponible fuera de ciudad", "fuera_ciudad"),
|
||||||
|
mk("Misiones internacionales", "misiones_internacionales"),
|
||||||
|
mk("Condición médica", "condicion_medica"),
|
||||||
|
mk("Voluntariado anterior", "voluntariado_anterior"),
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
|
async function fetchStats() {
|
||||||
|
loading.value = true;
|
||||||
|
error.value = "";
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/admin/voluntarios/stats");
|
||||||
|
const json = await res.json();
|
||||||
|
if (!json.success) throw new Error(json.message || "Error al cargar estadísticas");
|
||||||
|
stats.value = json;
|
||||||
|
} catch (e) {
|
||||||
|
error.value = e.message;
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(fetchStats);
|
||||||
|
</script>
|
||||||
|
|
@ -0,0 +1,178 @@
|
||||||
|
<template>
|
||||||
|
<div ref="rootEl" class="relative">
|
||||||
|
<div
|
||||||
|
class="combobox-input input input-sm flex flex-wrap items-center gap-1 w-full cursor-text"
|
||||||
|
@click="focusInput"
|
||||||
|
>
|
||||||
|
<template v-if="multiple">
|
||||||
|
<span
|
||||||
|
v-for="item in currentValue"
|
||||||
|
:key="item"
|
||||||
|
class="badge badge-sm badge-neutral gap-1"
|
||||||
|
>
|
||||||
|
{{ item }}
|
||||||
|
<button type="button" class="btn btn-ghost btn-xs btn-circle" @click.stop="toggle(item)">✕</button>
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
<input
|
||||||
|
ref="inputEl"
|
||||||
|
v-model="query"
|
||||||
|
type="text"
|
||||||
|
:placeholder="placeholder"
|
||||||
|
class="flex-1 min-w-[4rem]"
|
||||||
|
@input="onInput"
|
||||||
|
@focus="open = true"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ul
|
||||||
|
v-if="open"
|
||||||
|
class="absolute z-30 mt-1 w-full max-h-64 overflow-y-auto bg-base-100 rounded-box shadow ring-1 ring-base-300"
|
||||||
|
@mousedown.prevent
|
||||||
|
>
|
||||||
|
<li v-if="loading" class="px-3 py-2 text-sm text-base-content/50 flex items-center gap-2">
|
||||||
|
<span class="loading loading-spinner loading-xs"></span> Cargando…
|
||||||
|
</li>
|
||||||
|
<li v-else-if="options.length === 0" class="px-3 py-2 text-sm text-base-content/50">
|
||||||
|
{{ multiple ? "Sin opciones" : "Sin sugerencias — sigue escribiendo" }}
|
||||||
|
</li>
|
||||||
|
<li v-for="opt in options" :key="opt.value">
|
||||||
|
<label
|
||||||
|
v-if="multiple"
|
||||||
|
class="flex items-center gap-2 px-3 py-1.5 hover:bg-base-200 cursor-pointer"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
class="checkbox checkbox-xs"
|
||||||
|
:checked="isSelected(opt.value)"
|
||||||
|
@change="toggle(opt.value)"
|
||||||
|
/>
|
||||||
|
<span class="flex-1 text-sm">
|
||||||
|
{{ opt.value }}
|
||||||
|
<span class="text-xs text-base-content/50">({{ opt.count }})</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
v-else
|
||||||
|
type="button"
|
||||||
|
class="flex w-full items-center justify-between gap-2 px-3 py-1.5 text-left text-sm hover:bg-base-200"
|
||||||
|
@click="pick(opt.value)"
|
||||||
|
>
|
||||||
|
<span class="truncate">{{ opt.value }}</span>
|
||||||
|
<span class="text-xs text-base-content/50 shrink-0">({{ opt.count }})</span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, watch, onMounted, onBeforeUnmount } from "vue";
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
field: { type: String, required: true },
|
||||||
|
placeholder: { type: String, default: "Escribir…" },
|
||||||
|
multiple: { type: Boolean, default: false },
|
||||||
|
limit: { type: Number, default: 25 },
|
||||||
|
});
|
||||||
|
|
||||||
|
const modelValue = defineModel({ type: [String, Array], default: "" });
|
||||||
|
|
||||||
|
const rootEl = ref(null);
|
||||||
|
const inputEl = ref(null);
|
||||||
|
const query = ref("");
|
||||||
|
const open = ref(false);
|
||||||
|
const loading = ref(false);
|
||||||
|
const options = ref([]);
|
||||||
|
|
||||||
|
let fetchTimer = null;
|
||||||
|
let fetchVersion = 0;
|
||||||
|
|
||||||
|
const currentValue = () => {
|
||||||
|
const v = modelValue.value;
|
||||||
|
return Array.isArray(v) ? v : typeof v === "string" ? v : "";
|
||||||
|
};
|
||||||
|
|
||||||
|
function focusInput() {
|
||||||
|
inputEl.value?.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSelected(v) {
|
||||||
|
return currentValue().includes(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle(v) {
|
||||||
|
const arr = [...currentValue()];
|
||||||
|
const i = arr.indexOf(v);
|
||||||
|
if (i >= 0) arr.splice(i, 1);
|
||||||
|
else arr.push(v);
|
||||||
|
modelValue.value = arr;
|
||||||
|
query.value = "";
|
||||||
|
scheduleFetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
function pick(v) {
|
||||||
|
modelValue.value = v;
|
||||||
|
query.value = v;
|
||||||
|
open.value = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onInput() {
|
||||||
|
if (!props.multiple) modelValue.value = query.value;
|
||||||
|
scheduleFetch();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchOptions() {
|
||||||
|
loading.value = true;
|
||||||
|
const version = ++fetchVersion;
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
params.set("field", props.field);
|
||||||
|
params.set("limit", String(props.limit));
|
||||||
|
if (query.value.trim().length >= 2) params.set("q", query.value.trim());
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/admin/voluntarios/distinct?${params.toString()}`);
|
||||||
|
const json = await res.json();
|
||||||
|
if (version !== fetchVersion) return;
|
||||||
|
options.value = json.success ? json.data : [];
|
||||||
|
} catch {
|
||||||
|
if (version === fetchVersion) options.value = [];
|
||||||
|
} finally {
|
||||||
|
if (version === fetchVersion) loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleFetch() {
|
||||||
|
clearTimeout(fetchTimer);
|
||||||
|
fetchTimer = setTimeout(fetchOptions, 250);
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => modelValue.value,
|
||||||
|
(val) => {
|
||||||
|
if (!props.multiple && query.value !== val) query.value = typeof val === "string" ? val : "";
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
function onDocClick(e) {
|
||||||
|
if (rootEl.value && !rootEl.value.contains(e.target)) open.value = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
document.addEventListener("mousedown", onDocClick);
|
||||||
|
scheduleFetch();
|
||||||
|
});
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
document.removeEventListener("mousedown", onDocClick);
|
||||||
|
clearTimeout(fetchTimer);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.combobox-input {
|
||||||
|
height: auto;
|
||||||
|
min-height: 2rem;
|
||||||
|
padding-top: 0.125rem;
|
||||||
|
padding-bottom: 0.125rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
@ -0,0 +1,284 @@
|
||||||
|
<template>
|
||||||
|
<div class="space-y-4">
|
||||||
|
<div v-if="loading" class="flex justify-center py-16">
|
||||||
|
<span class="loading loading-spinner loading-lg text-primary"></span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="error" class="text-center py-10 text-error">{{ error }}</div>
|
||||||
|
|
||||||
|
<div v-else-if="data" class="space-y-6">
|
||||||
|
<div class="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||||
|
<h3 class="text-lg sm:text-xl font-bold">
|
||||||
|
{{ data.nombre }} {{ data.segundo_nombre }} {{ data.apellido }}
|
||||||
|
</h3>
|
||||||
|
<span class="font-mono text-sm opacity-70">#{{ data.numero_voluntario }}</span>
|
||||||
|
<span class="badge badge-sm" :class="badgeClass(data.status)">{{ data.status }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section
|
||||||
|
v-for="sec in sectionsWithData"
|
||||||
|
:key="sec.key"
|
||||||
|
class="rounded-box ring-1 ring-base-300 bg-base-100/60 overflow-hidden"
|
||||||
|
>
|
||||||
|
<h4 class="font-medium text-sm uppercase tracking-wide px-4 py-3 border-b border-base-200">
|
||||||
|
{{ sec.title }}
|
||||||
|
</h4>
|
||||||
|
<dl class="divide-y divide-base-200/70 text-sm">
|
||||||
|
<div
|
||||||
|
v-for="f in sec.fields"
|
||||||
|
:key="f.key"
|
||||||
|
class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1"
|
||||||
|
>
|
||||||
|
<dt class="text-base-content/60">{{ f.label }}</dt>
|
||||||
|
<dd class="min-w-0 break-words">
|
||||||
|
<div v-if="f.isList" :class="f.isLongList ? 'space-y-1.5' : 'flex flex-wrap gap-1.5'">
|
||||||
|
<div
|
||||||
|
v-if="f.isLongList"
|
||||||
|
v-for="(item, i) in f.displayValues"
|
||||||
|
:key="'list-' + i"
|
||||||
|
class="text-sm border-l-2 border-base-300 pl-2"
|
||||||
|
>
|
||||||
|
{{ item }}
|
||||||
|
</div>
|
||||||
|
<span
|
||||||
|
v-else
|
||||||
|
v-for="(item, i) in f.displayValues"
|
||||||
|
:key="'chip-' + i"
|
||||||
|
class="badge badge-sm badge-ghost border border-base-300 whitespace-normal text-left"
|
||||||
|
>
|
||||||
|
{{ item }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span v-else>{{ f.displayText }}</span>
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section
|
||||||
|
v-if="extraRows.length"
|
||||||
|
class="rounded-box ring-1 ring-base-300 bg-base-100/60 overflow-hidden"
|
||||||
|
>
|
||||||
|
<h4 class="font-medium text-sm uppercase tracking-wide px-4 py-3 border-b border-base-200">
|
||||||
|
Otros datos
|
||||||
|
</h4>
|
||||||
|
<dl class="divide-y divide-base-200/70 text-sm">
|
||||||
|
<div
|
||||||
|
v-for="r in extraRows"
|
||||||
|
:key="r.rawKey"
|
||||||
|
class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1"
|
||||||
|
>
|
||||||
|
<dt class="text-base-content/60">{{ r.key }}</dt>
|
||||||
|
<dd class="min-w-0 break-words">{{ r.value }}</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="rounded-box ring-1 ring-base-300 bg-base-100/60 overflow-hidden">
|
||||||
|
<h4 class="font-medium text-sm uppercase tracking-wide px-4 py-3 border-b border-base-200">
|
||||||
|
Sistema
|
||||||
|
</h4>
|
||||||
|
<dl class="divide-y divide-base-200/70 text-sm">
|
||||||
|
<div class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1">
|
||||||
|
<dt class="text-base-content/60">ID</dt>
|
||||||
|
<dd class="font-mono break-all">{{ data.id }}</dd>
|
||||||
|
</div>
|
||||||
|
<div class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1">
|
||||||
|
<dt class="text-base-content/60">Versión de formulario</dt>
|
||||||
|
<dd>{{ data.form_version || "—" }}</dd>
|
||||||
|
</div>
|
||||||
|
<div class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1">
|
||||||
|
<dt class="text-base-content/60">Correo enviado</dt>
|
||||||
|
<dd>{{ formatDateTime(data.email_sent_at) }}</dd>
|
||||||
|
</div>
|
||||||
|
<div class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1">
|
||||||
|
<dt class="text-base-content/60">Registrado</dt>
|
||||||
|
<dd>{{ formatDateTime(data.submitted_at) }}</dd>
|
||||||
|
</div>
|
||||||
|
<div class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1">
|
||||||
|
<dt class="text-base-content/60">Actualizado</dt>
|
||||||
|
<dd>{{ formatDateTime(data.updated_at) }}</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, computed, watch, onMounted } from "vue";
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
numero: { type: [Number, String], required: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const CORE_COLUMN_MAP = {
|
||||||
|
nombre: "nombre",
|
||||||
|
segundo_nombre: "segundo_nombre",
|
||||||
|
apellido: "apellido",
|
||||||
|
correo: "correo",
|
||||||
|
fecha_nacimiento: "fecha_nacimiento",
|
||||||
|
nacionalidad: "nacionalidad",
|
||||||
|
sexo: "sexo",
|
||||||
|
direccion_completa: "direccion",
|
||||||
|
ciudad: "ciudad",
|
||||||
|
estado: "estado",
|
||||||
|
pais: "pais",
|
||||||
|
postal: "codigo_postal",
|
||||||
|
telefono: "telefono",
|
||||||
|
whatsapp: "whatsapp",
|
||||||
|
profesion: "profesion",
|
||||||
|
lugar_trabajo_actual: "lugar_trabajo",
|
||||||
|
nivel_academico: "nivel_academico",
|
||||||
|
};
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const error = ref("");
|
||||||
|
const data = ref(null);
|
||||||
|
const sections = ref([]);
|
||||||
|
|
||||||
|
function pretty(v) {
|
||||||
|
if (v === "si") return "Sí";
|
||||||
|
if (v === "no") return "No";
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fallbackLabel(key) {
|
||||||
|
if (key.startsWith("idioma_nivel_")) return `Nivel de ${key.slice("idioma_nivel_".length)}`;
|
||||||
|
if (key === "locale") return "Idioma de la solicitud";
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
const respuestasByKey = computed(() => {
|
||||||
|
const map = {};
|
||||||
|
for (const r of data.value?.respuestas || []) {
|
||||||
|
(map[r.key] ||= []).push(r.value);
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
});
|
||||||
|
|
||||||
|
function fieldTokens(field) {
|
||||||
|
let values;
|
||||||
|
if (field.key === "documentos") {
|
||||||
|
const s = [data.value.documento_tipo, data.value.documento_nro].filter(Boolean).join(" ");
|
||||||
|
values = s ? [s] : [];
|
||||||
|
} else if (CORE_COLUMN_MAP[field.key]) {
|
||||||
|
const v = data.value[CORE_COLUMN_MAP[field.key]];
|
||||||
|
values = v === null || v === undefined || v === "" ? [] : [String(v)];
|
||||||
|
} else {
|
||||||
|
values = respuestasByKey.value[field.key] || [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokens = [];
|
||||||
|
for (const raw of values) {
|
||||||
|
for (const part of String(raw).split(",")) {
|
||||||
|
const tok = part.trim();
|
||||||
|
if (!tok) continue;
|
||||||
|
const opt = (field.options || []).find((o) => o.value === tok);
|
||||||
|
let display = (opt ? opt.label : pretty(tok)).replace(/<[^>]*>/g, "");
|
||||||
|
if (field.tipo === "date" || field.key === "fecha_nacimiento") {
|
||||||
|
const d = new Date(display);
|
||||||
|
if (!isNaN(d)) {
|
||||||
|
display = d.toLocaleDateString("es", { year: "numeric", month: "2-digit", day: "2-digit" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokens.push(display);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sectionsWithData = computed(() => {
|
||||||
|
if (!data.value) return [];
|
||||||
|
return sections.value
|
||||||
|
.map((sec) => ({
|
||||||
|
...sec,
|
||||||
|
fields: sec.fields
|
||||||
|
.map((f) => {
|
||||||
|
const tokens = fieldTokens(f);
|
||||||
|
if (!tokens.length) return null;
|
||||||
|
return {
|
||||||
|
...f,
|
||||||
|
isList: f.tipo === "checkbox" && tokens.length > 1,
|
||||||
|
isLongList: f.tipo === "checkbox" && tokens.length > 1 && tokens.some((t) => t.length > 40),
|
||||||
|
displayValues: tokens,
|
||||||
|
displayText: tokens.join(", "),
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.filter(Boolean),
|
||||||
|
}))
|
||||||
|
.filter((sec) => sec.fields.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
const extraRows = computed(() => {
|
||||||
|
if (!data.value) return [];
|
||||||
|
const known = new Set();
|
||||||
|
for (const sec of sections.value) for (const f of sec.fields) known.add(f.key);
|
||||||
|
const rows = [];
|
||||||
|
for (const [key, vals] of Object.entries(respuestasByKey.value)) {
|
||||||
|
if (known.has(key)) continue;
|
||||||
|
const tokens = [];
|
||||||
|
for (const raw of vals) {
|
||||||
|
for (const part of String(raw).split(",")) {
|
||||||
|
const t = part.trim();
|
||||||
|
if (t) tokens.push(pretty(t));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!tokens.length) continue;
|
||||||
|
rows.push({ key: fallbackLabel(key), rawKey: key, value: tokens.join(", ") });
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
});
|
||||||
|
|
||||||
|
async function fetchData() {
|
||||||
|
loading.value = true;
|
||||||
|
error.value = "";
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/admin/voluntarios/${props.numero}`);
|
||||||
|
const json = await res.json();
|
||||||
|
if (!json.success) throw new Error(json.message || "Voluntario no encontrado");
|
||||||
|
data.value = json.data;
|
||||||
|
sections.value = json.form.sections;
|
||||||
|
} catch (e) {
|
||||||
|
error.value = e.message;
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.numero,
|
||||||
|
() => {
|
||||||
|
data.value = null;
|
||||||
|
fetchData();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
function formatDateTime(iso) {
|
||||||
|
if (!iso) return "—";
|
||||||
|
const d = new Date(iso);
|
||||||
|
if (isNaN(d)) return "—";
|
||||||
|
return d.toLocaleString("es", {
|
||||||
|
year: "numeric",
|
||||||
|
month: "2-digit",
|
||||||
|
day: "2-digit",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function badgeClass(s) {
|
||||||
|
switch (s) {
|
||||||
|
case "aprobado":
|
||||||
|
return "badge-success";
|
||||||
|
case "rechazado":
|
||||||
|
return "badge-error";
|
||||||
|
case "legacy":
|
||||||
|
return "badge-warning";
|
||||||
|
default:
|
||||||
|
return "badge-neutral";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(fetchData);
|
||||||
|
</script>
|
||||||
|
|
@ -0,0 +1,604 @@
|
||||||
|
<template>
|
||||||
|
<div class="space-y-4">
|
||||||
|
<!-- Filtros -->
|
||||||
|
<div class="bg-colorPrimary border-l-4 border-colorSecondary p-4 rounded-box space-y-3 shadow-lg shadow-tertiary/20">
|
||||||
|
<div class="flex flex-col md:flex-row gap-3 items-end">
|
||||||
|
<div class="flex-1 w-full">
|
||||||
|
<label class="label py-0 text-xs font-medium">Buscar</label>
|
||||||
|
<input
|
||||||
|
v-model="search"
|
||||||
|
type="text"
|
||||||
|
placeholder="Nombre, correo, teléfono, documento…"
|
||||||
|
class="input input-bordered input-sm w-full"
|
||||||
|
@input="onSearch"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="w-full md:w-52">
|
||||||
|
<label class="label py-0 text-xs font-medium">Status</label>
|
||||||
|
<details class="dropdown w-full">
|
||||||
|
<summary class="btn btn-sm btn-outline w-full justify-between">
|
||||||
|
<span class="truncate">{{ statusLabel }}</span>
|
||||||
|
<span class="opacity-60">▾</span>
|
||||||
|
</summary>
|
||||||
|
<ul class="menu dropdown-content bg-base-100 rounded-box shadow ring-1 ring-base-300 z-20 w-56 max-h-64 overflow-y-auto">
|
||||||
|
<li v-for="s in statuses" :key="s">
|
||||||
|
<label class="flex items-center gap-2 py-1.5">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
:value="s"
|
||||||
|
v-model="selectedStatuses"
|
||||||
|
class="checkbox checkbox-xs"
|
||||||
|
@change="applyFilters"
|
||||||
|
/>
|
||||||
|
<span>{{ s }}</span>
|
||||||
|
</label>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<button class="btn btn-ghost btn-sm text-tertiary" @click="clearFilters">Limpiar</button>
|
||||||
|
<button class="btn btn-primary btn-sm" @click="showFilters = !showFilters">
|
||||||
|
{{ showFilters ? "Ocultar filtros" : "Filtros" }}
|
||||||
|
<span v-if="activeFilterCount" class="badge badge-sm bg-tertiary text-colorPrimary border-0">{{ activeFilterCount }}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Chips de filtros activos -->
|
||||||
|
<div v-if="activeChips.length" class="flex flex-wrap gap-1.5">
|
||||||
|
<span
|
||||||
|
v-for="chip in activeChips"
|
||||||
|
:key="chip.key"
|
||||||
|
class="badge badge-sm bg-white gap-1 border border-colorSecondary/60 text-tertiary"
|
||||||
|
>
|
||||||
|
{{ chip.label }}
|
||||||
|
<button type="button" class="opacity-60 hover:opacity-100" @click="chip.remove()">✕</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Panel de filtros -->
|
||||||
|
<div v-if="showFilters" class="border-t border-colorSecondary/40 pt-3 space-y-4">
|
||||||
|
<div>
|
||||||
|
<p class="text-xs font-bold text-tertiary mb-2 uppercase tracking-wide flex items-center gap-2">
|
||||||
|
<span class="inline-block w-1 h-3.5 bg-colorSecondary"></span>Fecha y edad
|
||||||
|
</p>
|
||||||
|
<div class="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">Desde</label>
|
||||||
|
<input v-model="desde" type="date" class="input input-bordered input-sm w-full" @change="applyFilters" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">Hasta</label>
|
||||||
|
<input v-model="hasta" type="date" class="input input-bordered input-sm w-full" @change="applyFilters" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">Edad mín</label>
|
||||||
|
<input v-model="edadMin" type="number" min="0" max="120" class="input input-bordered input-sm w-full" @change="applyFilters" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">Edad máx</label>
|
||||||
|
<input v-model="edadMax" type="number" min="0" max="120" class="input input-bordered input-sm w-full" @change="applyFilters" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p class="text-xs font-bold text-tertiary mb-2 uppercase tracking-wide flex items-center gap-2">
|
||||||
|
<span class="inline-block w-1 h-3.5 bg-colorSecondary"></span>Ubicación
|
||||||
|
</p>
|
||||||
|
<div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">País</label>
|
||||||
|
<SearchableCombobox
|
||||||
|
v-model="selectedPaises"
|
||||||
|
field="pais"
|
||||||
|
multiple
|
||||||
|
placeholder="Buscar país…"
|
||||||
|
@update:modelValue="applyFilters"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">Nacionalidad</label>
|
||||||
|
<SearchableCombobox
|
||||||
|
v-model="nacionalidad"
|
||||||
|
field="nacionalidad"
|
||||||
|
placeholder="Buscar…"
|
||||||
|
@update:modelValue="onSearch"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">Sexo</label>
|
||||||
|
<select v-model="sexo" class="select select-bordered select-sm w-full" @change="applyFilters">
|
||||||
|
<option value="">Todos</option>
|
||||||
|
<option value="M">M</option>
|
||||||
|
<option value="F">F</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">Ciudad</label>
|
||||||
|
<SearchableCombobox
|
||||||
|
v-model="coreText.ciudad"
|
||||||
|
field="ciudad"
|
||||||
|
placeholder="Buscar…"
|
||||||
|
@update:modelValue="onSearch"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">Estado</label>
|
||||||
|
<SearchableCombobox
|
||||||
|
v-model="coreText.estado"
|
||||||
|
field="estado"
|
||||||
|
placeholder="Buscar…"
|
||||||
|
@update:modelValue="onSearch"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p class="text-xs font-bold text-tertiary mb-2 uppercase tracking-wide flex items-center gap-2">
|
||||||
|
<span class="inline-block w-1 h-3.5 bg-colorSecondary"></span>Perfil
|
||||||
|
</p>
|
||||||
|
<div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">Profesión</label>
|
||||||
|
<SearchableCombobox
|
||||||
|
v-model="coreText.profesion"
|
||||||
|
field="profesion"
|
||||||
|
placeholder="Buscar…"
|
||||||
|
@update:modelValue="onSearch"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">Nivel académico</label>
|
||||||
|
<SearchableCombobox
|
||||||
|
v-model="coreText.nivel_academico"
|
||||||
|
field="nivel_academico"
|
||||||
|
placeholder="Buscar…"
|
||||||
|
@update:modelValue="onSearch"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">Documento</label>
|
||||||
|
<input v-model="coreText.documento_nro" type="text" class="input input-bordered input-sm w-full" @input="onSearch" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="label py-0 text-xs font-medium">Versión de formulario</label>
|
||||||
|
<select v-model="formVersion" class="select select-bordered select-sm w-full" @change="applyFilters">
|
||||||
|
<option value="">Todas</option>
|
||||||
|
<option v-for="f in formVersions" :key="f" :value="f">{{ f }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p class="text-xs font-bold text-tertiary mb-2 uppercase tracking-wide flex items-center gap-2">
|
||||||
|
<span class="inline-block w-1 h-3.5 bg-colorSecondary"></span>Preferencias y condiciones
|
||||||
|
</p>
|
||||||
|
<div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
|
||||||
|
<div v-for="f in responseFields" :key="f">
|
||||||
|
<label class="label py-0 text-xs font-medium">{{ respLabels[f] }}</label>
|
||||||
|
<select v-model="respFilters[f]" class="select select-bordered select-sm w-full" @change="applyFilters">
|
||||||
|
<option value="">Todos</option>
|
||||||
|
<option v-for="o in respFilterOptions[f]" :key="o" :value="o">{{ o }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tabla -->
|
||||||
|
<div class="overflow-x-auto bg-base-100 rounded-box shadow ring-1 ring-base-300">
|
||||||
|
<table class="table table-sm">
|
||||||
|
<thead>
|
||||||
|
<tr class="text-xs uppercase">
|
||||||
|
<th class="cursor-pointer select-none" @click="toggleSort('numero_voluntario')">#</th>
|
||||||
|
<th class="cursor-pointer select-none" @click="toggleSort('nombre')">Nombre completo</th>
|
||||||
|
<th>Correo</th>
|
||||||
|
<th>Teléfono</th>
|
||||||
|
<th class="cursor-pointer select-none" @click="toggleSort('pais')">País</th>
|
||||||
|
<th>Ciudad</th>
|
||||||
|
<th>Idiomas</th>
|
||||||
|
<th>Áreas</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th class="cursor-pointer select-none" @click="toggleSort('submitted_at')">Fecha</th>
|
||||||
|
<th class="w-20 text-right">Acción</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-if="loading">
|
||||||
|
<td colspan="11" class="text-center py-10">
|
||||||
|
<span class="loading loading-spinner loading-md text-primary"></span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-else-if="error">
|
||||||
|
<td colspan="11" class="text-center py-10 text-error">{{ error }}</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-else-if="rows.length === 0">
|
||||||
|
<td colspan="11" class="text-center py-10 text-base-content/40">Sin resultados</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-for="row in rows" :key="row.id" class="hover:bg-base-200/50 cursor-pointer" @click="openDetail(row)">
|
||||||
|
<td class="font-mono">{{ row.numero_voluntario }}</td>
|
||||||
|
<td class="font-medium whitespace-nowrap">{{ row.nombre_completo }}</td>
|
||||||
|
<td class="max-w-[220px] truncate">{{ row.correo }}</td>
|
||||||
|
<td class="whitespace-nowrap">{{ row.telefono || "—" }}</td>
|
||||||
|
<td class="whitespace-nowrap">{{ row.pais || "—" }}</td>
|
||||||
|
<td class="whitespace-nowrap">{{ row.ciudad || "—" }}</td>
|
||||||
|
<td class="max-w-[200px] truncate" :title="row.idioma">{{ row.idioma || "—" }}</td>
|
||||||
|
<td class="max-w-[200px] truncate" :title="row.areas_colaborar">{{ row.areas_colaborar || "—" }}</td>
|
||||||
|
<td>
|
||||||
|
<span class="badge badge-sm" :class="badgeClass(row.status)">{{ row.status || "pendiente" }}</span>
|
||||||
|
</td>
|
||||||
|
<td class="whitespace-nowrap">{{ formatDate(row.submitted_at) }}</td>
|
||||||
|
<td class="text-right">
|
||||||
|
<button class="btn btn-ghost btn-xs" title="Ver detalle" @click.stop="openDetail(row)">Ver</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Paginación -->
|
||||||
|
<div class="flex items-center justify-between flex-wrap gap-3">
|
||||||
|
<p class="text-sm text-amber-200">
|
||||||
|
{{ total }} registros · página {{ page }} de {{ totalPages || 1 }}
|
||||||
|
</p>
|
||||||
|
<div class="join">
|
||||||
|
<button class="join-item btn btn-sm" :disabled="page <= 1" @click="goPage(page - 1)">«</button>
|
||||||
|
<button
|
||||||
|
v-for="p in pageNumbers"
|
||||||
|
:key="p"
|
||||||
|
class="join-item btn btn-sm"
|
||||||
|
:class="p === page ? 'btn-primary' : ''"
|
||||||
|
@click="goPage(p)"
|
||||||
|
>
|
||||||
|
{{ p }}
|
||||||
|
</button>
|
||||||
|
<button class="join-item btn btn-sm" :disabled="page >= totalPages" @click="goPage(page + 1)">»</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Modal de detalle -->
|
||||||
|
<Teleport v-if="detailNumero !== null" to="body">
|
||||||
|
<div class="fixed inset-0 z-[60] overflow-y-auto">
|
||||||
|
<div class="fixed inset-0 bg-black/60" @click="closeDetail"></div>
|
||||||
|
<div class="relative min-h-full flex items-center justify-center p-4 sm:p-6">
|
||||||
|
<div class="w-full max-w-3xl max-h-[85vh] overflow-y-auto rounded-box bg-base-100 shadow-2xl ring-1 ring-base-300">
|
||||||
|
<div class="sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-base-100 border-b border-base-200">
|
||||||
|
<span class="text-sm font-semibold">Detalle del voluntario</span>
|
||||||
|
<button class="btn btn-ghost btn-sm" @click="closeDetail">✕</button>
|
||||||
|
</div>
|
||||||
|
<div class="p-4">
|
||||||
|
<VoluntarioDetail :numero="detailNumero" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, reactive, computed, watch, onMounted, onUnmounted } from "vue";
|
||||||
|
import SearchableCombobox from "./SearchableCombobox.vue";
|
||||||
|
import VoluntarioDetail from "./VoluntarioDetail.vue";
|
||||||
|
|
||||||
|
const rows = ref([]);
|
||||||
|
const total = ref(0);
|
||||||
|
const page = ref(1);
|
||||||
|
const totalPages = ref(1);
|
||||||
|
const limit = 25;
|
||||||
|
const loading = ref(false);
|
||||||
|
const error = ref("");
|
||||||
|
|
||||||
|
const detailNumero = ref(null);
|
||||||
|
let returnPath = "";
|
||||||
|
|
||||||
|
function slugUrl(numero) {
|
||||||
|
const m = window.location.pathname.match(/^\/([a-z]{2})\/admin/);
|
||||||
|
const locale = m ? m[1] : "es";
|
||||||
|
return `/${locale}/admin/voluntario/${numero}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function openDetail(row) {
|
||||||
|
returnPath = window.location.pathname;
|
||||||
|
detailNumero.value = row.numero_voluntario;
|
||||||
|
history.pushState({ voluntario: true }, "", slugUrl(row.numero_voluntario));
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeDetail() {
|
||||||
|
detailNumero.value = null;
|
||||||
|
history.replaceState(null, "", returnPath || window.location.pathname);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onPopstate() {
|
||||||
|
if (detailNumero.value !== null) detailNumero.value = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onKeydown(e) {
|
||||||
|
if (e.key === "Escape" && detailNumero.value !== null) closeDetail();
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(detailNumero, (v) => {
|
||||||
|
document.body.style.overflow = v === null ? "" : "hidden";
|
||||||
|
});
|
||||||
|
|
||||||
|
const search = ref("");
|
||||||
|
const selectedStatuses = ref([]);
|
||||||
|
const selectedPaises = ref([]);
|
||||||
|
const sort = ref("submitted_at");
|
||||||
|
const order = ref("desc");
|
||||||
|
const showFilters = ref(false);
|
||||||
|
|
||||||
|
const desde = ref("");
|
||||||
|
const hasta = ref("");
|
||||||
|
const edadMin = ref("");
|
||||||
|
const edadMax = ref("");
|
||||||
|
|
||||||
|
const coreText = reactive({
|
||||||
|
ciudad: "",
|
||||||
|
estado: "",
|
||||||
|
profesion: "",
|
||||||
|
nivel_academico: "",
|
||||||
|
documento_nro: "",
|
||||||
|
});
|
||||||
|
const sexo = ref("");
|
||||||
|
const nacionalidad = ref("");
|
||||||
|
const formVersion = ref("");
|
||||||
|
|
||||||
|
const responseFields = [
|
||||||
|
"idioma",
|
||||||
|
"areas_colaborar",
|
||||||
|
"dias_disponibles",
|
||||||
|
"horario_preferido",
|
||||||
|
"fuera_ciudad",
|
||||||
|
"misiones_internacionales",
|
||||||
|
"condicion_medica",
|
||||||
|
"voluntariado_anterior",
|
||||||
|
];
|
||||||
|
const respFilters = reactive(Object.fromEntries(responseFields.map((f) => [f, ""])));
|
||||||
|
|
||||||
|
const respLabels = {
|
||||||
|
idioma: "Idioma",
|
||||||
|
areas_colaborar: "Áreas de colaboración",
|
||||||
|
dias_disponibles: "Días disponibles",
|
||||||
|
horario_preferido: "Horario preferido",
|
||||||
|
fuera_ciudad: "Disponible fuera de ciudad",
|
||||||
|
misiones_internacionales: "Misiones internacionales",
|
||||||
|
condicion_medica: "Condición médica",
|
||||||
|
voluntariado_anterior: "Voluntariado anterior",
|
||||||
|
};
|
||||||
|
|
||||||
|
const respFilterOptions = {
|
||||||
|
idioma: ["Espanol", "Ingles", "Hebreo", "Portugues", "Frances", "Otro"],
|
||||||
|
areas_colaborar: [
|
||||||
|
"Ayuda Humanitaria", "Educacion", "Desarrollo Comunitario", "Liderazgo",
|
||||||
|
"Logistica", "Organizacion de Eventos", "Comunicacion Institucional",
|
||||||
|
"Fotografia y Medios", "Recaudacion de Fondos", "Gestion de Proyectos",
|
||||||
|
"Traduccion e Interpretacion", "Asesoria Juridica", "Servicios Medicos",
|
||||||
|
"Diplomacia Publica", "Administracion", "Tecnologia e Innovacion", "Otra",
|
||||||
|
],
|
||||||
|
dias_disponibles: ["Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo"],
|
||||||
|
horario_preferido: ["Manana", "Tarde", "Noche", "Segun necesidades"],
|
||||||
|
fuera_ciudad: ["si", "no"],
|
||||||
|
misiones_internacionales: ["si", "no"],
|
||||||
|
condicion_medica: ["si", "no"],
|
||||||
|
voluntariado_anterior: ["si", "no"],
|
||||||
|
};
|
||||||
|
|
||||||
|
const statuses = ref([]);
|
||||||
|
const formVersions = ref([]);
|
||||||
|
|
||||||
|
let searchTimer = null;
|
||||||
|
|
||||||
|
const statusLabel = computed(() =>
|
||||||
|
selectedStatuses.value.length ? selectedStatuses.value.join(", ") : "Todos"
|
||||||
|
);
|
||||||
|
|
||||||
|
const activeFilterCount = computed(() => activeChips.value.length);
|
||||||
|
|
||||||
|
const activeChips = computed(() => {
|
||||||
|
const chips = [];
|
||||||
|
const add = (key, label, remove) => chips.push({ key, label, remove });
|
||||||
|
|
||||||
|
if (search.value.trim()) add("q", `Búsqueda: ${search.value.trim()}`, () => {
|
||||||
|
search.value = "";
|
||||||
|
onSearch();
|
||||||
|
});
|
||||||
|
for (const s of selectedStatuses.value) add(`status-${s}`, `Status: ${s}`, () => {
|
||||||
|
selectedStatuses.value = selectedStatuses.value.filter((x) => x !== s);
|
||||||
|
applyFilters();
|
||||||
|
});
|
||||||
|
for (const p of selectedPaises.value) add(`pais-${p}`, `País: ${p}`, () => {
|
||||||
|
selectedPaises.value = selectedPaises.value.filter((x) => x !== p);
|
||||||
|
applyFilters();
|
||||||
|
});
|
||||||
|
if (desde.value) add("desde", `Desde: ${desde.value}`, () => {
|
||||||
|
desde.value = "";
|
||||||
|
applyFilters();
|
||||||
|
});
|
||||||
|
if (hasta.value) add("hasta", `Hasta: ${hasta.value}`, () => {
|
||||||
|
hasta.value = "";
|
||||||
|
applyFilters();
|
||||||
|
});
|
||||||
|
if (edadMin.value) add("edad_min", `Edad mín: ${edadMin.value}`, () => {
|
||||||
|
edadMin.value = "";
|
||||||
|
applyFilters();
|
||||||
|
});
|
||||||
|
if (edadMax.value) add("edad_max", `Edad máx: ${edadMax.value}`, () => {
|
||||||
|
edadMax.value = "";
|
||||||
|
applyFilters();
|
||||||
|
});
|
||||||
|
for (const [k, v] of Object.entries(coreText)) {
|
||||||
|
if (v) {
|
||||||
|
const label = { ciudad: "Ciudad", estado: "Estado", profesion: "Profesión", nivel_academico: "Nivel académico", documento_nro: "Documento" }[k];
|
||||||
|
add(`core-${k}`, `${label}: ${v}`, () => {
|
||||||
|
coreText[k] = "";
|
||||||
|
applyFilters();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sexo.value) add("sexo", `Sexo: ${sexo.value}`, () => {
|
||||||
|
sexo.value = "";
|
||||||
|
applyFilters();
|
||||||
|
});
|
||||||
|
if (nacionalidad.value) add("nacionalidad", `Nacionalidad: ${nacionalidad.value}`, () => {
|
||||||
|
nacionalidad.value = "";
|
||||||
|
applyFilters();
|
||||||
|
});
|
||||||
|
if (formVersion.value) add("form_version", `Versión: ${formVersion.value}`, () => {
|
||||||
|
formVersion.value = "";
|
||||||
|
applyFilters();
|
||||||
|
});
|
||||||
|
for (const f of responseFields) {
|
||||||
|
if (respFilters[f]) add(`resp-${f}`, `${respLabels[f]}: ${respFilters[f]}`, () => {
|
||||||
|
respFilters[f] = "";
|
||||||
|
applyFilters();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return chips;
|
||||||
|
});
|
||||||
|
|
||||||
|
async function fetchData() {
|
||||||
|
loading.value = true;
|
||||||
|
error.value = "";
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
params.set("page", String(page.value));
|
||||||
|
params.set("limit", String(limit));
|
||||||
|
params.set("sort", sort.value);
|
||||||
|
params.set("order", order.value);
|
||||||
|
if (search.value.trim()) params.set("q", search.value.trim());
|
||||||
|
if (selectedStatuses.value.length) params.set("status", selectedStatuses.value.join(","));
|
||||||
|
if (selectedPaises.value.length) params.set("pais", selectedPaises.value.join(","));
|
||||||
|
if (desde.value) params.set("desde", desde.value);
|
||||||
|
if (hasta.value) params.set("hasta", hasta.value);
|
||||||
|
if (edadMin.value) params.set("edad_min", edadMin.value);
|
||||||
|
if (edadMax.value) params.set("edad_max", edadMax.value);
|
||||||
|
for (const [f, v] of Object.entries(coreText)) if (v) params.set(f, v);
|
||||||
|
if (sexo.value) params.set("sexo", sexo.value);
|
||||||
|
if (nacionalidad.value) params.set("nacionalidad", nacionalidad.value);
|
||||||
|
if (formVersion.value) params.set("form_version", formVersion.value);
|
||||||
|
for (const f of responseFields) if (respFilters[f]) params.set(f, respFilters[f]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/admin/voluntarios?${params.toString()}`);
|
||||||
|
const json = await res.json();
|
||||||
|
if (!json.success) throw new Error(json.message || "Error al cargar");
|
||||||
|
rows.value = json.data;
|
||||||
|
total.value = json.total;
|
||||||
|
totalPages.value = json.totalPages;
|
||||||
|
page.value = json.page;
|
||||||
|
} catch (e) {
|
||||||
|
error.value = e.message;
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchOptions() {
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/admin/voluntarios/options");
|
||||||
|
const json = await res.json();
|
||||||
|
if (json.success) {
|
||||||
|
statuses.value = json.statuses;
|
||||||
|
formVersions.value = json.form_versions;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// opciones no críticas
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSearch() {
|
||||||
|
clearTimeout(searchTimer);
|
||||||
|
searchTimer = setTimeout(() => {
|
||||||
|
page.value = 1;
|
||||||
|
fetchData();
|
||||||
|
}, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyFilters() {
|
||||||
|
page.value = 1;
|
||||||
|
fetchData();
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearFilters() {
|
||||||
|
search.value = "";
|
||||||
|
selectedStatuses.value = [];
|
||||||
|
selectedPaises.value = [];
|
||||||
|
desde.value = "";
|
||||||
|
hasta.value = "";
|
||||||
|
edadMin.value = "";
|
||||||
|
edadMax.value = "";
|
||||||
|
Object.keys(coreText).forEach((k) => (coreText[k] = ""));
|
||||||
|
sexo.value = "";
|
||||||
|
nacionalidad.value = "";
|
||||||
|
formVersion.value = "";
|
||||||
|
Object.keys(respFilters).forEach((k) => (respFilters[k] = ""));
|
||||||
|
page.value = 1;
|
||||||
|
fetchData();
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleSort(field) {
|
||||||
|
if (sort.value === field) {
|
||||||
|
order.value = order.value === "asc" ? "desc" : "asc";
|
||||||
|
} else {
|
||||||
|
sort.value = field;
|
||||||
|
order.value = "asc";
|
||||||
|
}
|
||||||
|
page.value = 1;
|
||||||
|
fetchData();
|
||||||
|
}
|
||||||
|
|
||||||
|
function goPage(p) {
|
||||||
|
if (p < 1 || p > totalPages.value || p === page.value) return;
|
||||||
|
page.value = p;
|
||||||
|
fetchData();
|
||||||
|
}
|
||||||
|
|
||||||
|
const pageNumbers = computed(() => {
|
||||||
|
const total = totalPages.value;
|
||||||
|
const current = page.value;
|
||||||
|
const start = Math.max(1, current - 2);
|
||||||
|
const end = Math.min(total, current + 2);
|
||||||
|
const pages = [];
|
||||||
|
for (let i = start; i <= end; i++) pages.push(i);
|
||||||
|
return pages;
|
||||||
|
});
|
||||||
|
|
||||||
|
function formatDate(iso) {
|
||||||
|
if (!iso) return "—";
|
||||||
|
return new Date(iso).toLocaleDateString("es", {
|
||||||
|
year: "numeric",
|
||||||
|
month: "2-digit",
|
||||||
|
day: "2-digit",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function badgeClass(s) {
|
||||||
|
switch (s) {
|
||||||
|
case "aprobado":
|
||||||
|
return "badge-success";
|
||||||
|
case "rechazado":
|
||||||
|
return "badge-error";
|
||||||
|
case "legacy":
|
||||||
|
return "badge-warning";
|
||||||
|
default:
|
||||||
|
return "badge-neutral";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
fetchOptions();
|
||||||
|
fetchData();
|
||||||
|
window.addEventListener("popstate", onPopstate);
|
||||||
|
window.addEventListener("keydown", onKeydown);
|
||||||
|
});
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
window.removeEventListener("popstate", onPopstate);
|
||||||
|
window.removeEventListener("keydown", onKeydown);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
---
|
---
|
||||||
locale: en
|
locale: es
|
||||||
title: 'Señales de una transformación global: advertencias sobre Israel y el clima en el Medio Oriente'
|
title: 'Señales de una transformación global: advertencias sobre Israel y el clima en el Medio Oriente'
|
||||||
date: 2023-07-27
|
date: 2023-07-27
|
||||||
slug: 2023-07-27-senales-de-una-transformacion-global-advertencias-sobre-israel-y-el-clima-en-el-medio-oriente
|
slug: 2023-07-27-senales-de-una-transformacion-global-advertencias-sobre-israel-y-el-clima-en-el-medio-oriente
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ import "@fontsource/poppins/700.css";
|
||||||
import "@fontsource-variable/kameron";
|
import "@fontsource-variable/kameron";
|
||||||
import ShareSticky from "../components/ShareSticky.vue";
|
import ShareSticky from "../components/ShareSticky.vue";
|
||||||
import { routeTranslations } from "../i18n";
|
import { routeTranslations } from "../i18n";
|
||||||
const { title, description, image, url, date, noindex } = Astro.props;
|
const { title, description, image, url, date, noindex, theme } = Astro.props;
|
||||||
|
|
||||||
const currentLocale = Astro.currentLocale ?? "es";
|
const currentLocale = Astro.currentLocale ?? "es";
|
||||||
const direction = currentLocale === "he" ? "rtl" : "ltr";
|
const direction = currentLocale === "he" ? "rtl" : "ltr";
|
||||||
|
|
@ -21,7 +21,7 @@ const isNewsPage = contentSegments.some((segment) =>
|
||||||
);
|
);
|
||||||
---
|
---
|
||||||
|
|
||||||
<html lang={currentLocale} dir={direction} class="scroll-smooth">
|
<html lang={currentLocale} dir={direction} data-theme={theme ?? undefined} class="scroll-smooth">
|
||||||
<BaseHead
|
<BaseHead
|
||||||
title={title}
|
title={title}
|
||||||
description={description}
|
description={description}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
import { defineMiddleware } from "astro:middleware";
|
||||||
|
|
||||||
|
export const onRequest = defineMiddleware((context, next) => {
|
||||||
|
const { url, redirect } = context;
|
||||||
|
const { pathname } = url;
|
||||||
|
|
||||||
|
if (pathname === "/admin" || pathname === "/admin/") {
|
||||||
|
return redirect("/es/admin", 302);
|
||||||
|
}
|
||||||
|
|
||||||
|
return next();
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
---
|
||||||
|
import MainLayout from "@/layouts/MainLayout.astro";
|
||||||
|
import Header from "@/components/Header.astro";
|
||||||
|
import AdminDashboard from "@/components/admin/AdminDashboard.vue";
|
||||||
|
|
||||||
|
const { locale } = Astro.params;
|
||||||
|
---
|
||||||
|
|
||||||
|
<MainLayout theme="cdrpj" title="Dashboard de Voluntarios" noindex>
|
||||||
|
<div class="top-16 relative mb container mx-auto">
|
||||||
|
<Header />
|
||||||
|
</div>
|
||||||
|
<main class="container mx-auto px-4 py-10 mt-8">
|
||||||
|
<div class="flex flex-col lg:w-1/2 items-center mx-auto mb-6">
|
||||||
|
<h1 class="text-white text-2xl uppercase font-bold text-center mb-3 font-primary">
|
||||||
|
Admin
|
||||||
|
</h1>
|
||||||
|
<h2 class="text-colorPrimary text-3xl lg:text-5xl font-bold text-center font-secondary">
|
||||||
|
Dashboard de Voluntarios
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<nav class="flex justify-center gap-2 mb-10">
|
||||||
|
<a href={`/${locale}/admin/dashboard`} class="btn btn-primary btn-sm">Dashboard</a>
|
||||||
|
<a href={`/${locale}/admin`} class="btn btn-ghost btn-sm text-colorPrimary">Voluntarios</a>
|
||||||
|
</nav>
|
||||||
|
<div class="max-w-5xl mx-auto">
|
||||||
|
<AdminDashboard client:load />
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</MainLayout>
|
||||||
|
|
@ -0,0 +1,28 @@
|
||||||
|
---
|
||||||
|
import MainLayout from "@/layouts/MainLayout.astro";
|
||||||
|
import Header from "@/components/Header.astro";
|
||||||
|
import VoluntariosTable from "../../../components/admin/VoluntariosTable.vue";
|
||||||
|
|
||||||
|
const { locale } = Astro.params;
|
||||||
|
---
|
||||||
|
|
||||||
|
<MainLayout theme="cdrpj" title="Dashboard de Voluntarios" noindex>
|
||||||
|
<div class="top-16 relative mb container mx-auto">
|
||||||
|
<Header />
|
||||||
|
</div>
|
||||||
|
<main class="container mx-auto px-4 py-10 mt-8">
|
||||||
|
<div class="flex flex-col lg:w-1/2 items-center mx-auto mb-6">
|
||||||
|
<h1 class="text-white text-2xl uppercase font-bold text-center mb-3 font-primary">
|
||||||
|
Admin
|
||||||
|
</h1>
|
||||||
|
<h2 class="text-colorPrimary text-3xl lg:text-5xl font-bold text-center font-secondary">
|
||||||
|
Dashboard de Voluntarios
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<nav class="flex justify-center gap-2 mb-10">
|
||||||
|
<a href={`/${locale}/admin/dashboard`} class="btn btn-ghost btn-sm text-colorPrimary">Dashboard</a>
|
||||||
|
<a href={`/${locale}/admin`} class="btn btn-primary btn-sm">Voluntarios</a>
|
||||||
|
</nav>
|
||||||
|
<VoluntariosTable client:load />
|
||||||
|
</main>
|
||||||
|
</MainLayout>
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
---
|
||||||
|
import MainLayout from "@/layouts/MainLayout.astro";
|
||||||
|
import Header from "@/components/Header.astro";
|
||||||
|
import VoluntarioDetail from "@/components/admin/VoluntarioDetail.vue";
|
||||||
|
|
||||||
|
const { numero } = Astro.params;
|
||||||
|
---
|
||||||
|
|
||||||
|
<MainLayout theme="cdrpj" title="Detalle de Voluntario" noindex>
|
||||||
|
<div class="top-16 relative mb container mx-auto">
|
||||||
|
<Header />
|
||||||
|
</div>
|
||||||
|
<main class="container mx-auto px-4 py-10 mt-8">
|
||||||
|
<div class="flex flex-col lg:w-1/2 items-center mx-auto mb-10">
|
||||||
|
<h1 class="text-white text-2xl uppercase font-bold text-center mb-3 font-primary">
|
||||||
|
Admin
|
||||||
|
</h1>
|
||||||
|
<h2 class="text-colorPrimary text-3xl lg:text-5xl font-bold text-center font-secondary">
|
||||||
|
Detalle de Voluntario
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<div class="max-w-3xl mx-auto">
|
||||||
|
<VoluntarioDetail numero={numero} client:load />
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</MainLayout>
|
||||||
|
|
@ -0,0 +1,248 @@
|
||||||
|
import type { APIRoute } from "astro";
|
||||||
|
import { prisma } from "../lib/prisma";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
|
|
||||||
|
export const prerender = false;
|
||||||
|
|
||||||
|
const SORT_FIELDS = new Set([
|
||||||
|
"numero_voluntario",
|
||||||
|
"submitted_at",
|
||||||
|
"nombre",
|
||||||
|
"apellido",
|
||||||
|
"correo",
|
||||||
|
"status",
|
||||||
|
"pais",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const SEARCHABLE_FIELDS = [
|
||||||
|
"nombre",
|
||||||
|
"segundo_nombre",
|
||||||
|
"apellido",
|
||||||
|
"correo",
|
||||||
|
"telefono",
|
||||||
|
"whatsapp",
|
||||||
|
"documento_nro",
|
||||||
|
"ciudad",
|
||||||
|
"profesion",
|
||||||
|
"nivel_academico",
|
||||||
|
"nacionalidad",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const CORE_TEXT_FILTERS = ["documento_nro"] as const;
|
||||||
|
|
||||||
|
const FUZZY_TEXT_FILTERS = [
|
||||||
|
"ciudad",
|
||||||
|
"estado",
|
||||||
|
"profesion",
|
||||||
|
"nivel_academico",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const FUZZY_THRESHOLD = 0.35;
|
||||||
|
|
||||||
|
const CORE_EXACT_FILTERS = [
|
||||||
|
"sexo",
|
||||||
|
"nacionalidad",
|
||||||
|
"form_version",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const RESPONSE_FILTERS = [
|
||||||
|
"idioma",
|
||||||
|
"areas_colaborar",
|
||||||
|
"dias_disponibles",
|
||||||
|
"horario_preferido",
|
||||||
|
"fuera_ciudad",
|
||||||
|
"misiones_internacionales",
|
||||||
|
"condicion_medica",
|
||||||
|
"voluntariado_anterior",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
function splitList(v: string): string[] {
|
||||||
|
return v
|
||||||
|
.split(",")
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenToOr(token: string): Prisma.FormularioWhereInput {
|
||||||
|
const or: Prisma.FormularioWhereInput[] = SEARCHABLE_FIELDS.map((field) => ({
|
||||||
|
[field]: { contains: token, mode: "insensitive" },
|
||||||
|
}));
|
||||||
|
or.push({
|
||||||
|
respuestas: {
|
||||||
|
some: { value: { contains: token, mode: "insensitive" } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (/^\d+$/.test(token)) {
|
||||||
|
or.push({ numero_voluntario: { equals: Number(token) } });
|
||||||
|
}
|
||||||
|
return { OR: or };
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildSearchWhere(q: string): Prisma.FormularioWhereInput {
|
||||||
|
const tokens = q.split(/\s+/).filter(Boolean);
|
||||||
|
if (tokens.length === 1) return tokenToOr(tokens[0]);
|
||||||
|
return { AND: tokens.map(tokenToOr) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildDateRange(desde: string, hasta: string): Prisma.FormularioWhereInput | null {
|
||||||
|
const filter: Prisma.DateTimeFilter = {};
|
||||||
|
if (desde) filter.gte = new Date(desde);
|
||||||
|
if (hasta) {
|
||||||
|
const h = new Date(hasta);
|
||||||
|
h.setHours(23, 59, 59, 999);
|
||||||
|
filter.lte = h;
|
||||||
|
}
|
||||||
|
if (Object.keys(filter).length === 0) return null;
|
||||||
|
return { submitted_at: filter };
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildAgeRange(min: string, max: string): Prisma.FormularioWhereInput | null {
|
||||||
|
const filter: Prisma.DateTimeFilter = {};
|
||||||
|
const now = new Date();
|
||||||
|
if (min) {
|
||||||
|
const maxBirth = new Date(now);
|
||||||
|
maxBirth.setFullYear(now.getFullYear() - Number(min));
|
||||||
|
filter.lte = maxBirth;
|
||||||
|
}
|
||||||
|
if (max) {
|
||||||
|
const minBirth = new Date(now);
|
||||||
|
minBirth.setFullYear(now.getFullYear() - Number(max) - 1);
|
||||||
|
minBirth.setDate(minBirth.getDate() + 1);
|
||||||
|
filter.gte = minBirth;
|
||||||
|
}
|
||||||
|
if (Object.keys(filter).length === 0) return null;
|
||||||
|
return { fecha_nacimiento: filter };
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildResponseFilter(key: string, values: string[]): Prisma.FormularioWhereInput {
|
||||||
|
const or: Prisma.FormularioWhereInput[] = values.map((v) => ({
|
||||||
|
respuestas: {
|
||||||
|
some: { key, value: { contains: v, mode: "insensitive" } },
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
return or.length === 1 ? or[0] : { OR: or };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fuzzyIds(field: string, value: string): Promise<string[]> {
|
||||||
|
const col = Prisma.raw(field);
|
||||||
|
const rows = await prisma.$queryRaw<{ id: string }[]>`
|
||||||
|
SELECT id::text AS id
|
||||||
|
FROM formularios
|
||||||
|
WHERE ${col} IS NOT NULL
|
||||||
|
AND ${col} <> ''
|
||||||
|
AND length(${col}) >= 2
|
||||||
|
AND (
|
||||||
|
similarity(lower(${col}), lower(${value})) > ${FUZZY_THRESHOLD}
|
||||||
|
OR ${col} ILIKE ${`%${value}%`}
|
||||||
|
)
|
||||||
|
LIMIT 5000
|
||||||
|
`;
|
||||||
|
return rows.map((r) => r.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GET: APIRoute = async ({ url }) => {
|
||||||
|
try {
|
||||||
|
const sp = url.searchParams;
|
||||||
|
const page = Math.max(1, parseInt(sp.get("page") || "1", 10));
|
||||||
|
const limit = Math.min(100, Math.max(1, parseInt(sp.get("limit") || "25", 10)));
|
||||||
|
const q = (sp.get("q") || "").trim();
|
||||||
|
const status = (sp.get("status") || "").trim();
|
||||||
|
const pais = (sp.get("pais") || "").trim();
|
||||||
|
const sort = SORT_FIELDS.has(sp.get("sort") || "") ? sp.get("sort")! : "submitted_at";
|
||||||
|
const order = sp.get("order") === "asc" ? "asc" : "desc";
|
||||||
|
|
||||||
|
const conditions: Prisma.FormularioWhereInput[] = [];
|
||||||
|
|
||||||
|
if (q) conditions.push(buildSearchWhere(q));
|
||||||
|
|
||||||
|
const dateRange = buildDateRange((sp.get("desde") || "").trim(), (sp.get("hasta") || "").trim());
|
||||||
|
if (dateRange) conditions.push(dateRange);
|
||||||
|
|
||||||
|
const ageRange = buildAgeRange((sp.get("edad_min") || "").trim(), (sp.get("edad_max") || "").trim());
|
||||||
|
if (ageRange) conditions.push(ageRange);
|
||||||
|
|
||||||
|
if (status) conditions.push({ status: { in: splitList(status) } });
|
||||||
|
if (pais) conditions.push({ pais: { in: splitList(pais) } });
|
||||||
|
|
||||||
|
for (const field of CORE_TEXT_FILTERS) {
|
||||||
|
const v = (sp.get(field) || "").trim();
|
||||||
|
if (v) conditions.push({ [field]: { contains: v, mode: "insensitive" } });
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const field of FUZZY_TEXT_FILTERS) {
|
||||||
|
const v = (sp.get(field) || "").trim();
|
||||||
|
if (v) {
|
||||||
|
const ids = await fuzzyIds(field, v);
|
||||||
|
conditions.push(ids.length ? { id: { in: ids } } : { id: { in: [] } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const field of CORE_EXACT_FILTERS) {
|
||||||
|
const v = (sp.get(field) || "").trim();
|
||||||
|
if (v) conditions.push({ [field]: { in: splitList(v) } });
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const key of RESPONSE_FILTERS) {
|
||||||
|
const v = (sp.get(key) || "").trim();
|
||||||
|
if (v) conditions.push(buildResponseFilter(key, splitList(v)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const where: Prisma.FormularioWhereInput = conditions.length ? { AND: conditions } : {};
|
||||||
|
|
||||||
|
const [total, rows] = await Promise.all([
|
||||||
|
prisma.formulario.count({ where }),
|
||||||
|
prisma.formulario.findMany({
|
||||||
|
where,
|
||||||
|
include: { respuestas: { select: { key: true, value: true } } },
|
||||||
|
orderBy: { [sort]: order },
|
||||||
|
skip: (page - 1) * limit,
|
||||||
|
take: limit,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const data = rows.map((f) => {
|
||||||
|
const respuestas: Record<string, string> = {};
|
||||||
|
for (const r of f.respuestas) {
|
||||||
|
respuestas[r.key] = respuestas[r.key]
|
||||||
|
? `${respuestas[r.key]}, ${r.value}`
|
||||||
|
: r.value;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: f.id,
|
||||||
|
numero_voluntario: f.numero_voluntario,
|
||||||
|
nombre_completo: [f.nombre, f.segundo_nombre, f.apellido]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" "),
|
||||||
|
nombre: f.nombre,
|
||||||
|
segundo_nombre: f.segundo_nombre,
|
||||||
|
apellido: f.apellido,
|
||||||
|
correo: f.correo,
|
||||||
|
telefono: f.telefono,
|
||||||
|
whatsapp: f.whatsapp,
|
||||||
|
pais: f.pais,
|
||||||
|
ciudad: f.ciudad,
|
||||||
|
estado: f.estado,
|
||||||
|
profesion: f.profesion,
|
||||||
|
nivel_academico: f.nivel_academico,
|
||||||
|
status: f.status,
|
||||||
|
submitted_at: f.submitted_at,
|
||||||
|
...respuestas,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return Response.json({
|
||||||
|
success: true,
|
||||||
|
data,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
totalPages: Math.ceil(total / limit),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error en /api/admin/voluntarios:", error);
|
||||||
|
return Response.json(
|
||||||
|
{ success: false, message: "Error al obtener voluntarios" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -0,0 +1,97 @@
|
||||||
|
import type { APIRoute } from "astro";
|
||||||
|
import { prisma } from "../../lib/prisma";
|
||||||
|
import { t, type I18nKey } from "../../../../i18n";
|
||||||
|
|
||||||
|
export const prerender = false;
|
||||||
|
|
||||||
|
export const GET: APIRoute = async ({ params }) => {
|
||||||
|
try {
|
||||||
|
const numero = Number(params.numero);
|
||||||
|
if (!Number.isInteger(numero) || numero <= 0) {
|
||||||
|
return Response.json(
|
||||||
|
{ success: false, message: "Número de voluntario inválido" },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const [voluntario, secciones] = await Promise.all([
|
||||||
|
prisma.formulario.findUnique({
|
||||||
|
where: { numero_voluntario: numero },
|
||||||
|
include: { respuestas: { orderBy: { created_at: "asc" } } },
|
||||||
|
}),
|
||||||
|
prisma.seccion.findMany({
|
||||||
|
orderBy: { orden: "asc" },
|
||||||
|
include: { campos: { orderBy: { orden: "asc" } } },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!voluntario) {
|
||||||
|
return Response.json(
|
||||||
|
{ success: false, message: "Voluntario no encontrado" },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sections = secciones.map((s) => ({
|
||||||
|
key: s.title_key.replace(/^form\./, ""),
|
||||||
|
title: t("es", s.title_key as I18nKey),
|
||||||
|
fields: s.campos.map((c) => ({
|
||||||
|
key: c.key,
|
||||||
|
label: t("es", c.label_key as I18nKey),
|
||||||
|
tipo: c.tipo,
|
||||||
|
options: Array.isArray(c.options)
|
||||||
|
? (c.options as { value?: string; label?: string }[])
|
||||||
|
.filter((o) => o && typeof o === "object")
|
||||||
|
.map((o) => ({
|
||||||
|
value: o.value ?? "",
|
||||||
|
label: o.label ? t("es", o.label as I18nKey) : o.value ?? "",
|
||||||
|
}))
|
||||||
|
: [],
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
|
return Response.json({
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
id: voluntario.id,
|
||||||
|
numero_voluntario: voluntario.numero_voluntario,
|
||||||
|
nombre: voluntario.nombre,
|
||||||
|
segundo_nombre: voluntario.segundo_nombre,
|
||||||
|
apellido: voluntario.apellido,
|
||||||
|
documento_nro: voluntario.documento_nro,
|
||||||
|
documento_tipo: voluntario.documento_tipo,
|
||||||
|
correo: voluntario.correo,
|
||||||
|
fecha_nacimiento: voluntario.fecha_nacimiento,
|
||||||
|
nacionalidad: voluntario.nacionalidad,
|
||||||
|
sexo: voluntario.sexo,
|
||||||
|
direccion: voluntario.direccion,
|
||||||
|
ciudad: voluntario.ciudad,
|
||||||
|
estado: voluntario.estado,
|
||||||
|
pais: voluntario.pais,
|
||||||
|
codigo_postal: voluntario.codigo_postal,
|
||||||
|
telefono: voluntario.telefono,
|
||||||
|
whatsapp: voluntario.whatsapp,
|
||||||
|
profesion: voluntario.profesion,
|
||||||
|
lugar_trabajo: voluntario.lugar_trabajo,
|
||||||
|
nivel_academico: voluntario.nivel_academico,
|
||||||
|
status: voluntario.status,
|
||||||
|
form_version: voluntario.form_version,
|
||||||
|
email_sent_at: voluntario.email_sent_at,
|
||||||
|
submitted_at: voluntario.submitted_at,
|
||||||
|
updated_at: voluntario.updated_at,
|
||||||
|
respuestas: voluntario.respuestas.map((r) => ({
|
||||||
|
seccion: r.seccion,
|
||||||
|
key: r.key,
|
||||||
|
value: r.value,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
form: { sections },
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error en /api/admin/voluntarios/[numero]:", error);
|
||||||
|
return Response.json(
|
||||||
|
{ success: false, message: "Error al obtener el voluntario" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
import type { APIRoute } from "astro";
|
||||||
|
import { prisma } from "../../lib/prisma";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
|
|
||||||
|
export const prerender = false;
|
||||||
|
|
||||||
|
const DISTINCT_FIELDS = new Set([
|
||||||
|
"ciudad",
|
||||||
|
"estado",
|
||||||
|
"profesion",
|
||||||
|
"nivel_academico",
|
||||||
|
"nacionalidad",
|
||||||
|
"pais",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const SIMILARITY_THRESHOLD = 0.35;
|
||||||
|
|
||||||
|
export const GET: APIRoute = async ({ url }) => {
|
||||||
|
try {
|
||||||
|
const sp = url.searchParams;
|
||||||
|
const field = (sp.get("field") || "").trim();
|
||||||
|
const q = (sp.get("q") || "").trim();
|
||||||
|
const limit = Math.min(100, Math.max(1, parseInt(sp.get("limit") || "25", 10)));
|
||||||
|
|
||||||
|
if (!DISTINCT_FIELDS.has(field)) {
|
||||||
|
return Response.json(
|
||||||
|
{ success: false, message: "Campo no permitido" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const col = Prisma.raw(field);
|
||||||
|
|
||||||
|
const rows = await prisma.$queryRaw<{ value: string; count: number }[]>`
|
||||||
|
SELECT ${col} AS value, COUNT(*)::int AS count
|
||||||
|
FROM formularios
|
||||||
|
WHERE ${col} IS NOT NULL AND ${col} <> ''
|
||||||
|
${q.length >= 2 ? Prisma.sql`AND (similarity(lower(${col}), lower(${q})) > ${SIMILARITY_THRESHOLD} OR ${col} ILIKE ${`%${q}%`})` : Prisma.empty}
|
||||||
|
GROUP BY ${col}
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT ${limit}
|
||||||
|
`;
|
||||||
|
|
||||||
|
return Response.json({
|
||||||
|
success: true,
|
||||||
|
field,
|
||||||
|
data: rows.map((r) => ({ value: r.value, count: r.count })),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error en /api/admin/voluntarios/distinct:", error);
|
||||||
|
return Response.json(
|
||||||
|
{ success: false, message: "Error al obtener valores" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
import type { APIRoute } from "astro";
|
||||||
|
import { prisma } from "../../lib/prisma";
|
||||||
|
|
||||||
|
export const prerender = false;
|
||||||
|
|
||||||
|
export const GET: APIRoute = async () => {
|
||||||
|
try {
|
||||||
|
const [paises, statuses, nacionalidades, form_versions] = await Promise.all([
|
||||||
|
prisma.formulario.findMany({
|
||||||
|
distinct: ["pais"],
|
||||||
|
select: { pais: true },
|
||||||
|
where: { pais: { not: null } },
|
||||||
|
}),
|
||||||
|
prisma.formulario.findMany({
|
||||||
|
distinct: ["status"],
|
||||||
|
select: { status: true },
|
||||||
|
}),
|
||||||
|
prisma.formulario.findMany({
|
||||||
|
distinct: ["nacionalidad"],
|
||||||
|
select: { nacionalidad: true },
|
||||||
|
where: { nacionalidad: { not: null } },
|
||||||
|
}),
|
||||||
|
prisma.formulario.findMany({
|
||||||
|
distinct: ["form_version"],
|
||||||
|
select: { form_version: true },
|
||||||
|
where: { form_version: { not: null } },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return Response.json({
|
||||||
|
success: true,
|
||||||
|
paises: paises
|
||||||
|
.map((p) => p.pais)
|
||||||
|
.filter((p): p is string => Boolean(p))
|
||||||
|
.sort((a, b) => a.localeCompare(b, "es")),
|
||||||
|
statuses: statuses
|
||||||
|
.map((s) => s.status)
|
||||||
|
.filter((s): s is string => Boolean(s))
|
||||||
|
.sort(),
|
||||||
|
nacionalidades: nacionalidades
|
||||||
|
.map((n) => n.nacionalidad)
|
||||||
|
.filter((n): n is string => Boolean(n))
|
||||||
|
.sort((a, b) => a.localeCompare(b, "es")),
|
||||||
|
form_versions: form_versions
|
||||||
|
.map((f) => f.form_version)
|
||||||
|
.filter((f): f is string => Boolean(f))
|
||||||
|
.sort(),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error en /api/admin/voluntarios/options:", error);
|
||||||
|
return Response.json(
|
||||||
|
{ success: false, message: "Error al obtener opciones" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -0,0 +1,138 @@
|
||||||
|
import type { APIRoute } from "astro";
|
||||||
|
import { prisma } from "../../lib/prisma";
|
||||||
|
import { t, type I18nKey } from "../../../../i18n";
|
||||||
|
|
||||||
|
export const prerender = false;
|
||||||
|
|
||||||
|
const OPTION_FIELDS = [
|
||||||
|
"idioma",
|
||||||
|
"areas_colaborar",
|
||||||
|
"dias_disponibles",
|
||||||
|
"horario_preferido",
|
||||||
|
"sexo",
|
||||||
|
"fuera_ciudad",
|
||||||
|
"misiones_internacionales",
|
||||||
|
"condicion_medica",
|
||||||
|
"voluntariado_anterior",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
async function multiValueDist(key: string): Promise<{ value: string; count: number }[]> {
|
||||||
|
const rows = await prisma.$queryRaw<{ v: string; cnt: number }[]>`
|
||||||
|
SELECT trim(unnest(string_to_array(value, ','))) AS v, count(DISTINCT formulario_id)::int AS cnt
|
||||||
|
FROM respuestas
|
||||||
|
WHERE key = ${key} AND btrim(value) <> ''
|
||||||
|
GROUP BY v
|
||||||
|
ORDER BY cnt DESC
|
||||||
|
`;
|
||||||
|
return rows.map((r) => ({ value: r.v, count: r.cnt }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function valueDist(key: string): Promise<{ value: string; count: number }[]> {
|
||||||
|
const rows = await prisma.respuesta.groupBy({
|
||||||
|
by: ["value"],
|
||||||
|
where: { key, value: { not: "" } },
|
||||||
|
_count: { _all: true },
|
||||||
|
});
|
||||||
|
return rows
|
||||||
|
.filter((r) => r.value !== null)
|
||||||
|
.map((r) => ({ value: r.value!, count: r._count._all }))
|
||||||
|
.sort((a, b) => b.count - a.count);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GET: APIRoute = async () => {
|
||||||
|
try {
|
||||||
|
const campos = await prisma.campo.findMany({
|
||||||
|
where: { key: { in: OPTION_FIELDS as unknown as string[] } },
|
||||||
|
});
|
||||||
|
|
||||||
|
const optionMaps: Record<string, Record<string, string>> = {};
|
||||||
|
for (const c of campos) {
|
||||||
|
optionMaps[c.key] = {};
|
||||||
|
if (Array.isArray(c.options)) {
|
||||||
|
for (const o of c.options as { value?: string; label?: string }[]) {
|
||||||
|
if (o && o.value) {
|
||||||
|
optionMaps[c.key][o.value] = o.label ? t("es", o.label as I18nKey) : o.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const withLabels = (
|
||||||
|
dist: { value: string; count: number }[],
|
||||||
|
key: string
|
||||||
|
): { value: string; label: string; count: number }[] =>
|
||||||
|
dist.map((d) => ({
|
||||||
|
value: d.value,
|
||||||
|
label: optionMaps[key]?.[d.value] || d.value,
|
||||||
|
count: d.count,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const [total, statuses, sexo, paises, [idiomas, areas, dias, horarios], condiciones, edad] =
|
||||||
|
await Promise.all([
|
||||||
|
prisma.formulario.count(),
|
||||||
|
prisma.formulario.groupBy({ by: ["status"], _count: { _all: true } }),
|
||||||
|
prisma.formulario.groupBy({ by: ["sexo"], _count: { _all: true } }),
|
||||||
|
prisma.formulario.groupBy({
|
||||||
|
by: ["pais"],
|
||||||
|
_count: { _all: true },
|
||||||
|
where: { pais: { not: null } },
|
||||||
|
orderBy: { _count: { pais: "desc" } },
|
||||||
|
take: 12,
|
||||||
|
}),
|
||||||
|
Promise.all([
|
||||||
|
multiValueDist("idioma"),
|
||||||
|
multiValueDist("areas_colaborar"),
|
||||||
|
multiValueDist("dias_disponibles"),
|
||||||
|
multiValueDist("horario_preferido"),
|
||||||
|
]),
|
||||||
|
Promise.all(
|
||||||
|
["fuera_ciudad", "misiones_internacionales", "condicion_medica", "voluntariado_anterior"].map(
|
||||||
|
(k) => valueDist(k)
|
||||||
|
)
|
||||||
|
),
|
||||||
|
prisma.$queryRaw<{ promedio: number | null }[]>`
|
||||||
|
SELECT round(avg(extract(epoch from (now() - fecha_nacimiento)) / 31557600), 1) AS promedio
|
||||||
|
FROM formularios
|
||||||
|
WHERE fecha_nacimiento IS NOT NULL
|
||||||
|
`,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const condKeys = [
|
||||||
|
"fuera_ciudad",
|
||||||
|
"misiones_internacionales",
|
||||||
|
"condicion_medica",
|
||||||
|
"voluntariado_anterior",
|
||||||
|
] as const;
|
||||||
|
const condicionesObj: Record<string, Record<string, number>> = {};
|
||||||
|
condKeys.forEach((k, i) => {
|
||||||
|
condicionesObj[k] = Object.fromEntries(condiciones[i].map((c) => [c.value, c.count]));
|
||||||
|
});
|
||||||
|
|
||||||
|
const formatPais = paises
|
||||||
|
.filter((p) => p.pais !== null)
|
||||||
|
.map((p) => ({ value: p.pais!, count: p._count._all }));
|
||||||
|
|
||||||
|
return Response.json({
|
||||||
|
success: true,
|
||||||
|
total,
|
||||||
|
edad: { promedio: edad[0]?.promedio ?? null },
|
||||||
|
idiomas: withLabels(idiomas, "idioma"),
|
||||||
|
areas: withLabels(areas, "areas_colaborar"),
|
||||||
|
dias: withLabels(dias, "dias_disponibles"),
|
||||||
|
horarios: withLabels(horarios, "horario_preferido"),
|
||||||
|
sexo: withLabels(
|
||||||
|
sexo.filter((s) => s.sexo !== null).map((s) => ({ value: s.sexo!, count: s._count._all })),
|
||||||
|
"sexo"
|
||||||
|
),
|
||||||
|
paises: formatPais,
|
||||||
|
statuses: statuses.map((s) => ({ value: s.status, count: s._count._all })),
|
||||||
|
condiciones: condicionesObj,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error en /api/admin/voluntarios/stats:", error);
|
||||||
|
return Response.json(
|
||||||
|
{ success: false, message: "Error al obtener estadísticas" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
import type { APIRoute } from "astro";
|
import type { APIRoute } from "astro";
|
||||||
import { appendToSheet, emailExists } from "../lib/googleSheets";
|
import { appendToSheet } from "../lib/googleSheets";
|
||||||
import { sendEmailCf } from "../lib/email";
|
import { sendEmailCf } from "../lib/email";
|
||||||
|
import { prisma } from "../lib/prisma";
|
||||||
|
import { emailExistsInDb } from "../lib/formularioDb";
|
||||||
export const prerender = false;
|
export const prerender = false;
|
||||||
|
|
||||||
export const POST: APIRoute = async ({ request }) => {
|
export const POST: APIRoute = async ({ request }) => {
|
||||||
|
|
@ -22,7 +24,7 @@ export const POST: APIRoute = async ({ request }) => {
|
||||||
return Response.redirect("/?error=datos", 303);
|
return Response.redirect("/?error=datos", 303);
|
||||||
}
|
}
|
||||||
|
|
||||||
const exists = await emailExists(email);
|
const exists = await emailExistsInDb(email);
|
||||||
if (exists) {
|
if (exists) {
|
||||||
return Response.json({
|
return Response.json({
|
||||||
success: false,
|
success: false,
|
||||||
|
|
@ -41,10 +43,22 @@ export const POST: APIRoute = async ({ request }) => {
|
||||||
new Date().toLocaleString()
|
new Date().toLocaleString()
|
||||||
];
|
];
|
||||||
|
|
||||||
// 🔹 Enviar correo (Cloudflare) y guardar en Google Sheets
|
// 🔹 Enviar correo (Cloudflare), guardar en Google Sheets y en PostgreSQL
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
sendEmailCf({ nombres, apellidos }, email, "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION"),
|
sendEmailCf({ nombres, apellidos }, email, "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION"),
|
||||||
appendToSheet(valuesForSheets)
|
appendToSheet(valuesForSheets),
|
||||||
|
prisma.formulario.create({
|
||||||
|
data: {
|
||||||
|
nombre: nombres!,
|
||||||
|
apellido: apellidos!,
|
||||||
|
pais: pais || null,
|
||||||
|
ciudad: lugar || null,
|
||||||
|
direccion: direccion || null,
|
||||||
|
telefono: telefono || null,
|
||||||
|
correo: email!,
|
||||||
|
status: "legacy",
|
||||||
|
},
|
||||||
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// 🔹 Redirección elegante después de enviar
|
// 🔹 Redirección elegante después de enviar
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import type { APIRoute } from "astro";
|
import type { APIRoute } from "astro";
|
||||||
import { appendRegistrationToSheet } from "../lib/googleSheets";
|
import { appendRegistrationToSheet } from "../lib/googleSheets";
|
||||||
import { sendEmailCf } from "../lib/email";
|
import { sendEmailCf } from "../lib/email";
|
||||||
import { emailExistsInRegistry, addEmailToRegistry } from "../lib/emailsRegistry";
|
import { saveFormularioToSupabase, emailExistsInDb } from "../lib/formularioDb";
|
||||||
export const prerender = false;
|
export const prerender = false;
|
||||||
|
|
||||||
const COLUMNS = [
|
const COLUMNS = [
|
||||||
|
|
@ -102,13 +102,19 @@ export const POST: APIRoute = async ({ request }) => {
|
||||||
timeZone: "America/Puerto_Rico",
|
timeZone: "America/Puerto_Rico",
|
||||||
});
|
});
|
||||||
|
|
||||||
if (emailExistsInRegistry(formData.correo)) {
|
const exists = await emailExistsInDb(formData.correo);
|
||||||
|
if (exists) {
|
||||||
return Response.json(
|
return Response.json(
|
||||||
{ success: false, message: "Este correo ya está registrado. No se permiten 2 registros." },
|
{ success: false, message: "Este correo ya está registrado. No se permiten 2 registros." },
|
||||||
{ status: 409 }
|
{ status: 409 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const form = await saveFormularioToSupabase(
|
||||||
|
formData,
|
||||||
|
body.responses || []
|
||||||
|
);
|
||||||
|
|
||||||
const row = COLUMNS.map((key) => flattenValue(formData[key]));
|
const row = COLUMNS.map((key) => flattenValue(formData[key]));
|
||||||
row.push(timestamp);
|
row.push(timestamp);
|
||||||
|
|
||||||
|
|
@ -119,9 +125,10 @@ export const POST: APIRoute = async ({ request }) => {
|
||||||
apellidos: formData.apellido,
|
apellidos: formData.apellido,
|
||||||
}, formData.correo, "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION");
|
}, formData.correo, "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION");
|
||||||
|
|
||||||
addEmailToRegistry(formData.correo);
|
return Response.json({
|
||||||
|
...result,
|
||||||
return Response.json(result);
|
numero_voluntario: form.numero_voluntario,
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error en /api/formulario/send:", error);
|
console.error("Error en /api/formulario/send:", error);
|
||||||
return Response.json(
|
return Response.json(
|
||||||
|
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
|
|
||||||
const REGISTRY_PATH = path.resolve(process.cwd(), "data", "emails.txt");
|
|
||||||
|
|
||||||
export function emailExistsInRegistry(email: string): boolean {
|
|
||||||
try {
|
|
||||||
if (!fs.existsSync(REGISTRY_PATH)) return false;
|
|
||||||
const content = fs.readFileSync(REGISTRY_PATH, "utf-8");
|
|
||||||
return content.split("\n").some((line) => line.trim().toLowerCase() === email.trim().toLowerCase());
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function addEmailToRegistry(email: string): void {
|
|
||||||
const dir = path.dirname(REGISTRY_PATH);
|
|
||||||
if (!fs.existsSync(dir)) {
|
|
||||||
fs.mkdirSync(dir, { recursive: true });
|
|
||||||
}
|
|
||||||
fs.appendFileSync(REGISTRY_PATH, email.trim().toLowerCase() + "\n");
|
|
||||||
}
|
|
||||||
|
|
@ -0,0 +1,113 @@
|
||||||
|
import { prisma } from "./prisma";
|
||||||
|
|
||||||
|
type FormData = Record<string, unknown>;
|
||||||
|
type RespuestaPayload = {
|
||||||
|
key: string;
|
||||||
|
value: unknown;
|
||||||
|
section_id?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CORE_KEYS = new Set([
|
||||||
|
"nombre",
|
||||||
|
"segundo_nombre",
|
||||||
|
"apellido",
|
||||||
|
"documentos",
|
||||||
|
"correo",
|
||||||
|
"fecha_nacimiento",
|
||||||
|
"nacionalidad",
|
||||||
|
"sexo",
|
||||||
|
"direccion_completa",
|
||||||
|
"ciudad",
|
||||||
|
"estado",
|
||||||
|
"pais",
|
||||||
|
"postal",
|
||||||
|
"telefono",
|
||||||
|
"whatsapp",
|
||||||
|
"profesion",
|
||||||
|
"lugar_trabajo_actual",
|
||||||
|
"nivel_academico",
|
||||||
|
"nombre_completo",
|
||||||
|
"confirmar_nombre",
|
||||||
|
"confirmar_firma",
|
||||||
|
]);
|
||||||
|
|
||||||
|
function isBlank(v: unknown): boolean {
|
||||||
|
return v === undefined || v === null || v === "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function emailExistsInDb(email: string): Promise<boolean> {
|
||||||
|
const normalized = (email || "").trim().toLowerCase();
|
||||||
|
if (!normalized) return false;
|
||||||
|
const found = await prisma.formulario.findFirst({
|
||||||
|
where: { correo: { equals: normalized, mode: "insensitive" } },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
return Boolean(found);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveFormularioToSupabase(
|
||||||
|
formData: FormData,
|
||||||
|
responses: RespuestaPayload[]
|
||||||
|
) {
|
||||||
|
const core = {
|
||||||
|
nombre: (formData.nombre as string) ?? "",
|
||||||
|
segundo_nombre: (formData.segundo_nombre as string) || null,
|
||||||
|
apellido: (formData.apellido as string) ?? "",
|
||||||
|
documento_nro: (formData.documentos as string) || null,
|
||||||
|
correo: (formData.correo as string) ?? "",
|
||||||
|
fecha_nacimiento: formData.fecha_nacimiento
|
||||||
|
? new Date(formData.fecha_nacimiento as string)
|
||||||
|
: null,
|
||||||
|
nacionalidad: (formData.nacionalidad as string) || null,
|
||||||
|
sexo: (formData.sexo as string) || null,
|
||||||
|
direccion: (formData.direccion_completa as string) || null,
|
||||||
|
ciudad: (formData.ciudad as string) || null,
|
||||||
|
estado: (formData.estado as string) || null,
|
||||||
|
pais: (formData.pais as string) || null,
|
||||||
|
codigo_postal: (formData.postal as string) || null,
|
||||||
|
telefono: (formData.telefono as string) || null,
|
||||||
|
whatsapp: (formData.whatsapp as string) || null,
|
||||||
|
profesion: (formData.profesion as string) || null,
|
||||||
|
lugar_trabajo: (formData.lugar_trabajo_actual as string) || null,
|
||||||
|
nivel_academico: (formData.nivel_academico as string) || null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const respRows: {
|
||||||
|
key: string;
|
||||||
|
value: string;
|
||||||
|
seccion: string;
|
||||||
|
}[] = [];
|
||||||
|
|
||||||
|
for (const r of responses || []) {
|
||||||
|
if (CORE_KEYS.has(r.key)) continue;
|
||||||
|
if (isBlank(r.value)) continue;
|
||||||
|
|
||||||
|
if (Array.isArray(r.value)) {
|
||||||
|
for (const v of r.value) {
|
||||||
|
if (!isBlank(v)) {
|
||||||
|
respRows.push({
|
||||||
|
key: r.key,
|
||||||
|
value: String(v),
|
||||||
|
seccion: r.section_id ?? "",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
respRows.push({
|
||||||
|
key: r.key,
|
||||||
|
value: String(r.value),
|
||||||
|
seccion: r.section_id ?? "",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return prisma.$transaction(async (tx) => {
|
||||||
|
const form = await tx.formulario.create({ data: core });
|
||||||
|
if (respRows.length) {
|
||||||
|
await tx.respuesta.createMany({
|
||||||
|
data: respRows.map((r) => ({ ...r, formulario_id: form.id })),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return form;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
@ -7,4 +7,4 @@ const globalForPrisma = globalThis as unknown as {
|
||||||
export const prisma =
|
export const prisma =
|
||||||
globalForPrisma.prisma ?? new PrismaClient();
|
globalForPrisma.prisma ?? new PrismaClient();
|
||||||
|
|
||||||
if (import.meta.env.DEV) globalForPrisma.prisma = prisma;
|
if (import.meta.env?.DEV) globalForPrisma.prisma = prisma;
|
||||||
|
|
@ -1,11 +1,11 @@
|
||||||
import type { APIRoute } from "astro";
|
import type { APIRoute } from "astro";
|
||||||
import { getVolunteerCount } from "../lib/googleSheets";
|
import { prisma } from "../lib/prisma";
|
||||||
|
|
||||||
export const prerender = false;
|
export const prerender = false;
|
||||||
|
|
||||||
export const GET: APIRoute = async () => {
|
export const GET: APIRoute = async () => {
|
||||||
try {
|
try {
|
||||||
const count = await getVolunteerCount();
|
const count = await prisma.formulario.count();
|
||||||
|
|
||||||
return Response.json(
|
return Response.json(
|
||||||
{ success: true, count },
|
{ success: true, count },
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,40 @@
|
||||||
@plugin '@tailwindcss/typography';
|
@plugin '@tailwindcss/typography';
|
||||||
@plugin "daisyui";
|
@plugin "daisyui";
|
||||||
|
|
||||||
|
@plugin "daisyui/theme" {
|
||||||
|
name: "cdrpj";
|
||||||
|
default: false;
|
||||||
|
color-scheme: light;
|
||||||
|
--color-base-100: #ffffff;
|
||||||
|
--color-base-200: #ebe6d2;
|
||||||
|
--color-base-300: #d8d1b9;
|
||||||
|
--color-base-content: #003421;
|
||||||
|
--color-primary: #cba16a;
|
||||||
|
--color-primary-content: #003421;
|
||||||
|
--color-secondary: #003421;
|
||||||
|
--color-secondary-content: #ebe6d2;
|
||||||
|
--color-accent: #22523f;
|
||||||
|
--color-accent-content: #ebe6d2;
|
||||||
|
--color-neutral: #22523f;
|
||||||
|
--color-neutral-content: #ebe6d2;
|
||||||
|
--color-info: #22523f;
|
||||||
|
--color-info-content: #ebe6d2;
|
||||||
|
--color-success: #4a8c6f;
|
||||||
|
--color-success-content: #ffffff;
|
||||||
|
--color-warning: #cba16a;
|
||||||
|
--color-warning-content: #003421;
|
||||||
|
--color-error: #b03a2e;
|
||||||
|
--color-error-content: #ffffff;
|
||||||
|
--radius-selector: 0rem;
|
||||||
|
--radius-field: 0rem;
|
||||||
|
--radius-box: 0rem;
|
||||||
|
--size-selector: .25rem;
|
||||||
|
--size-field: .25rem;
|
||||||
|
--border: 1px;
|
||||||
|
--depth: 1;
|
||||||
|
--noise: 0;
|
||||||
|
}
|
||||||
|
|
||||||
@theme {
|
@theme {
|
||||||
--font-primary: "Poppins", sans-serif;
|
--font-primary: "Poppins", sans-serif;
|
||||||
--font-secondary: "Kameron Variable", sans-serif;
|
--font-secondary: "Kameron Variable", sans-serif;
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue