diff --git a/app/.env.development b/app/.env.development index 42a6ada..614b9f6 100644 --- a/app/.env.development +++ b/app/.env.development @@ -4,3 +4,4 @@ POSTGRES_HOST=0.0.0.0 POSTGRES_PORT=5432 POSTGRES_DB=postgres DATABASE_URL=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB} +CRON_SECRET=secret \ No newline at end of file diff --git a/app/src/lib/db/schema.ts b/app/src/lib/db/schema.ts index 3824ccb..2de5871 100644 --- a/app/src/lib/db/schema.ts +++ b/app/src/lib/db/schema.ts @@ -32,6 +32,7 @@ export const cuatrimestre = pgTable( using: sql`true`, }), check("cuatrimestre_numero_check", sql`numero = ANY (ARRAY[1, 2])`), + unique("cuatrimestre_natural_key").on(table.anio, table.numero), ], ); diff --git a/app/src/routes/api/cronjobs/generarcuatrimestre/+server.ts b/app/src/routes/api/cronjobs/generarcuatrimestre/+server.ts new file mode 100644 index 0000000..8a84990 --- /dev/null +++ b/app/src/routes/api/cronjobs/generarcuatrimestre/+server.ts @@ -0,0 +1,54 @@ +import { CRON_SECRET } from "$env/static/private"; +import db from "$lib/db"; +import { cuatrimestre } from "$lib/db/schema"; +import type { RequestHandler } from "@sveltejs/kit"; + +interface Cuatrimestre { + anio: number; + numero: number; +} + +function calcularCuatrimestreAnterior(fechaActual: Date): Cuatrimestre { + const mesActual = fechaActual.getUTCMonth() + 1; + // 1er Cuatri Diciembre-Junio, 2do Cuatri Julio-Noviembre. + const cuatrimestreActual = mesActual <= 6 || mesActual == 12 ? 1 : 2; + const cuatrimestrePasado = { + anio: fechaActual.getUTCFullYear(), + numero: cuatrimestreActual - 1, + }; + + if (cuatrimestrePasado.numero === 0) { + cuatrimestrePasado.anio--; + cuatrimestrePasado.numero = 2; + } + + return cuatrimestrePasado; +} + +export const GET: RequestHandler = async ({ request }) => { + const authHeader = request.headers.get("Authorization"); + if (authHeader !== `Bearer ${CRON_SECRET}`) { + return new Response("Unauthorized", { + status: 401, + }); + } + + const fechaActual = new Date(); + const cuatrimestreAnterior = calcularCuatrimestreAnterior(fechaActual); + let registro; + try { + registro = await db + .insert(cuatrimestre) + .values(cuatrimestreAnterior) + .returning(); + } catch (err: any) { + const UNIQUE_VIOLATION = "23505"; + if (err?.code == UNIQUE_VIOLATION) + return new Response("Cuatrimestre duplicado", { status: 400 }); + else throw err; + } + + return new Response(JSON.stringify(registro), { + status: 201, + }); +}; diff --git a/app/vercel.json b/app/vercel.json index c8833c8..216d967 100644 --- a/app/vercel.json +++ b/app/vercel.json @@ -1,4 +1,14 @@ { "framework": "sveltekit-1", - "regions": ["gru1"] + "regions": ["gru1"], + "crons": [ + { + "path": "/api/cronjobs/generarcuatrimestre", + "schedule": "0 0 1 7 *" + }, + { + "path": "/api/cronjobs/generarcuatrimestre", + "schedule": "0 0 1 12 *" + } + ] }