Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/.env.development
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions app/src/lib/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
],
);

Expand Down
54 changes: 54 additions & 0 deletions app/src/routes/api/cronjobs/generarcuatrimestre/+server.ts
Original file line number Diff line number Diff line change
@@ -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,
});
};
12 changes: 11 additions & 1 deletion app/vercel.json
Original file line number Diff line number Diff line change
@@ -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 *"
}
]
}