feat: opcion de update a asignaturas ya creadas para ponerles la información generada con IA
- Created a new enum type "estado_asignatura" with values 'borrador', 'revisada', 'aprobada', and 'generando'. - Added a new column "estado" to the "asignaturas" table, defaulting to 'generando'. - Implemented a trigger function to log changes in the "planes_estudio" table, capturing inserts, updates, and deletes. - Updated the logging mechanism to track changes in various fields, including JSONB data. - Removed the "asignaturas" table from the supabase_realtime publication. - Added a script for generating TypeScript types from the local Supabase database.
This commit is contained in:
@@ -4,14 +4,9 @@
|
||||
| boolean
|
||||
| null
|
||||
| { [key: string]: Json | undefined }
|
||||
| Array<Json>;
|
||||
| Json[];
|
||||
|
||||
export type Database = {
|
||||
// Allows to automatically instantiate createClient with right options
|
||||
// instead of createClient<Database, { PostgrestVersion: 'XX' }>(URL, KEY)
|
||||
__InternalSupabase: {
|
||||
PostgrestVersion: "12.2.3 (519615d)";
|
||||
};
|
||||
graphql_public: {
|
||||
Tables: {
|
||||
[_ in never]: never;
|
||||
@@ -98,6 +93,7 @@ export type Database = {
|
||||
creado_por: string | null;
|
||||
creditos: number;
|
||||
datos: Json;
|
||||
estado: Database["public"]["Enums"]["estado_asignatura"];
|
||||
estructura_id: string | null;
|
||||
horas_academicas: number | null;
|
||||
horas_independientes: number | null;
|
||||
@@ -124,6 +120,7 @@ export type Database = {
|
||||
creado_por?: string | null;
|
||||
creditos: number;
|
||||
datos?: Json;
|
||||
estado?: Database["public"]["Enums"]["estado_asignatura"];
|
||||
estructura_id?: string | null;
|
||||
horas_academicas?: number | null;
|
||||
horas_independientes?: number | null;
|
||||
@@ -150,6 +147,7 @@ export type Database = {
|
||||
creado_por?: string | null;
|
||||
creditos?: number;
|
||||
datos?: Json;
|
||||
estado?: Database["public"]["Enums"]["estado_asignatura"];
|
||||
estructura_id?: string | null;
|
||||
horas_academicas?: number | null;
|
||||
horas_independientes?: number | null;
|
||||
@@ -815,20 +813,18 @@ export type Database = {
|
||||
asignatura_id: string;
|
||||
creado_en?: string;
|
||||
id?: string;
|
||||
rol?:
|
||||
Database["public"]["Enums"][
|
||||
"rol_responsable_asignatura"
|
||||
];
|
||||
rol?: Database["public"]["Enums"][
|
||||
"rol_responsable_asignatura"
|
||||
];
|
||||
usuario_id: string;
|
||||
};
|
||||
Update: {
|
||||
asignatura_id?: string;
|
||||
creado_en?: string;
|
||||
id?: string;
|
||||
rol?:
|
||||
Database["public"]["Enums"][
|
||||
"rol_responsable_asignatura"
|
||||
];
|
||||
rol?: Database["public"]["Enums"][
|
||||
"rol_responsable_asignatura"
|
||||
];
|
||||
usuario_id?: string;
|
||||
};
|
||||
Relationships: [
|
||||
@@ -1126,6 +1122,11 @@ export type Database = {
|
||||
unaccent_immutable: { Args: { "": string }; Returns: string };
|
||||
};
|
||||
Enums: {
|
||||
estado_asignatura:
|
||||
| "borrador"
|
||||
| "revisada"
|
||||
| "aprobada"
|
||||
| "generando";
|
||||
estado_tarea_revision: "PENDIENTE" | "COMPLETADA" | "OMITIDA";
|
||||
fuente_cambio: "HUMANO" | "IA";
|
||||
nivel_plan_estudio:
|
||||
@@ -1233,15 +1234,13 @@ export type TablesInsert<
|
||||
| { schema: keyof DatabaseWithoutInternals },
|
||||
TableName extends DefaultSchemaTableNameOrOptions extends {
|
||||
schema: keyof DatabaseWithoutInternals;
|
||||
}
|
||||
? keyof DatabaseWithoutInternals[
|
||||
} ? keyof DatabaseWithoutInternals[
|
||||
DefaultSchemaTableNameOrOptions["schema"]
|
||||
]["Tables"]
|
||||
: never = never,
|
||||
> = DefaultSchemaTableNameOrOptions extends {
|
||||
schema: keyof DatabaseWithoutInternals;
|
||||
}
|
||||
? DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]][
|
||||
} ? DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]][
|
||||
"Tables"
|
||||
][TableName] extends {
|
||||
Insert: infer I;
|
||||
@@ -1260,15 +1259,13 @@ export type TablesUpdate<
|
||||
| { schema: keyof DatabaseWithoutInternals },
|
||||
TableName extends DefaultSchemaTableNameOrOptions extends {
|
||||
schema: keyof DatabaseWithoutInternals;
|
||||
}
|
||||
? keyof DatabaseWithoutInternals[
|
||||
} ? keyof DatabaseWithoutInternals[
|
||||
DefaultSchemaTableNameOrOptions["schema"]
|
||||
]["Tables"]
|
||||
: never = never,
|
||||
> = DefaultSchemaTableNameOrOptions extends {
|
||||
schema: keyof DatabaseWithoutInternals;
|
||||
}
|
||||
? DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]][
|
||||
} ? DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]][
|
||||
"Tables"
|
||||
][TableName] extends {
|
||||
Update: infer U;
|
||||
@@ -1287,15 +1284,13 @@ export type Enums<
|
||||
| { schema: keyof DatabaseWithoutInternals },
|
||||
EnumName extends DefaultSchemaEnumNameOrOptions extends {
|
||||
schema: keyof DatabaseWithoutInternals;
|
||||
}
|
||||
? keyof DatabaseWithoutInternals[
|
||||
} ? keyof DatabaseWithoutInternals[
|
||||
DefaultSchemaEnumNameOrOptions["schema"]
|
||||
]["Enums"]
|
||||
: never = never,
|
||||
> = DefaultSchemaEnumNameOrOptions extends {
|
||||
schema: keyof DatabaseWithoutInternals;
|
||||
}
|
||||
? DatabaseWithoutInternals[DefaultSchemaEnumNameOrOptions["schema"]][
|
||||
} ? DatabaseWithoutInternals[DefaultSchemaEnumNameOrOptions["schema"]][
|
||||
"Enums"
|
||||
][EnumName]
|
||||
: DefaultSchemaEnumNameOrOptions extends keyof DefaultSchema["Enums"]
|
||||
@@ -1308,15 +1303,13 @@ export type CompositeTypes<
|
||||
| { schema: keyof DatabaseWithoutInternals },
|
||||
CompositeTypeName extends PublicCompositeTypeNameOrOptions extends {
|
||||
schema: keyof DatabaseWithoutInternals;
|
||||
}
|
||||
? keyof DatabaseWithoutInternals[
|
||||
} ? keyof DatabaseWithoutInternals[
|
||||
PublicCompositeTypeNameOrOptions["schema"]
|
||||
]["CompositeTypes"]
|
||||
: never = never,
|
||||
> = PublicCompositeTypeNameOrOptions extends {
|
||||
schema: keyof DatabaseWithoutInternals;
|
||||
}
|
||||
? DatabaseWithoutInternals[PublicCompositeTypeNameOrOptions["schema"]][
|
||||
} ? DatabaseWithoutInternals[PublicCompositeTypeNameOrOptions["schema"]][
|
||||
"CompositeTypes"
|
||||
][CompositeTypeName]
|
||||
: PublicCompositeTypeNameOrOptions extends
|
||||
@@ -1330,6 +1323,12 @@ export const Constants = {
|
||||
},
|
||||
public: {
|
||||
Enums: {
|
||||
estado_asignatura: [
|
||||
"borrador",
|
||||
"revisada",
|
||||
"aprobada",
|
||||
"generando",
|
||||
],
|
||||
estado_tarea_revision: ["PENDIENTE", "COMPLETADA", "OMITIDA"],
|
||||
fuente_cambio: ["HUMANO", "IA"],
|
||||
nivel_plan_estudio: [
|
||||
|
||||
@@ -9,6 +9,66 @@ import {
|
||||
type StructuredResponseOptions,
|
||||
} from "../_shared/openai-service.ts";
|
||||
|
||||
/**
|
||||
* JSON input signature (when `Content-Type: application/json`)
|
||||
*
|
||||
* Required:
|
||||
* - `id` (uuid) - corresponde a la columna `id` de `asignaturas`
|
||||
*
|
||||
* Optional patch fields (any subset is allowed):
|
||||
* - `nombre` (string)
|
||||
* - `codigo` (string | null)
|
||||
* - `tipo` (string | null) // must match DB enum values
|
||||
* - `creditos` (number)
|
||||
* - `horas_academicas` (number | null)
|
||||
* - `horas_independientes` (number | null)
|
||||
* - `numero_ciclo` (number | null)
|
||||
* - `estructura_id` (uuid | null)
|
||||
* - `plan_estudio_id` (uuid)
|
||||
* - `linea_plan_id` (uuid | null)
|
||||
* - `orden_celda` (number | null)
|
||||
*
|
||||
* IA config (optional):
|
||||
* - `descripcionEnfoqueAcademico` (string)
|
||||
*
|
||||
* Notes:
|
||||
* - This JSON flow does NOT accept `instruccionesAdicionalesIA`.
|
||||
* - Missing optional fields are ignored (the existing DB values remain).
|
||||
*/
|
||||
|
||||
const JsonUpdateSchema = z
|
||||
.object({
|
||||
id: z.string().uuid("id debe ser un UUID"),
|
||||
|
||||
// patch fields (all optional) — nombres coinciden con columnas DB
|
||||
nombre: z.string().min(1).optional(),
|
||||
codigo: z.union([z.string().min(1), z.null()]).optional(),
|
||||
tipo: z.union([z.string().min(1), z.null()]).optional(),
|
||||
creditos: z.number().positive().optional(),
|
||||
horas_academicas: z.number().int().nonnegative().nullable().optional(),
|
||||
horas_independientes: z.number().int().nonnegative().nullable().optional(),
|
||||
numero_ciclo: z.number().int().positive().nullable().optional(),
|
||||
estructura_id: z.string().uuid().nullable().optional(),
|
||||
plan_estudio_id: z.string().uuid().optional(),
|
||||
linea_plan_id: z.string().uuid().nullable().optional(),
|
||||
orden_celda: z.number().int().nonnegative().nullable().optional(),
|
||||
|
||||
// IA config (no instruccionesAdicionalesIA)
|
||||
descripcionEnfoqueAcademico: z.string().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
type EdgeAIGenerateSubjectJsonUpdateInput = z.infer<typeof JsonUpdateSchema>;
|
||||
|
||||
function formatZodIssues(issues: z.ZodIssue[]): string {
|
||||
return issues
|
||||
.map((issue, i) => {
|
||||
const path = issue.path.length ? issue.path.join(".") : "(root)";
|
||||
return `${i + 1}. ${path}: ${issue.message}`;
|
||||
})
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
Deno.serve(async (req: Request): Promise<Response> => {
|
||||
const url = new URL(req.url);
|
||||
const functionName = url.pathname.split("/").pop();
|
||||
@@ -53,7 +113,9 @@ Deno.serve(async (req: Request): Promise<Response> => {
|
||||
}
|
||||
|
||||
const contentType = (req.headers.get("content-type") || "").toLowerCase();
|
||||
if (!contentType.startsWith("multipart/form-data")) {
|
||||
const isMultipart = contentType.startsWith("multipart/form-data");
|
||||
const isJson = contentType.includes("application/json");
|
||||
if (!isMultipart && !isJson) {
|
||||
console.error(
|
||||
`[${
|
||||
new Date().toISOString()
|
||||
@@ -108,6 +170,299 @@ Deno.serve(async (req: Request): Promise<Response> => {
|
||||
SERVICE_ROLE_KEY,
|
||||
);
|
||||
|
||||
// -----------------------------
|
||||
// JSON update flow
|
||||
// -----------------------------
|
||||
if (isJson) {
|
||||
let rawBody: unknown;
|
||||
try {
|
||||
rawBody = await req.json();
|
||||
} catch (e) {
|
||||
throw new HttpError(
|
||||
400,
|
||||
"Body JSON inválido.",
|
||||
"INVALID_JSON",
|
||||
{ cause: e },
|
||||
);
|
||||
}
|
||||
|
||||
const parsedBody = JsonUpdateSchema.safeParse(rawBody);
|
||||
if (!parsedBody.success) {
|
||||
throw new HttpError(
|
||||
422,
|
||||
formatZodIssues(parsedBody.error.issues),
|
||||
"VALIDATION_ERROR",
|
||||
parsedBody.error,
|
||||
);
|
||||
}
|
||||
|
||||
const payload: EdgeAIGenerateSubjectJsonUpdateInput = parsedBody.data;
|
||||
|
||||
const { data: existingAsignatura, error: existingAsignaturaError } =
|
||||
await supabaseService
|
||||
.from("asignaturas")
|
||||
.select(
|
||||
"id,plan_estudio_id,estructura_id,nombre,codigo,tipo,creditos,horas_academicas,horas_independientes,numero_ciclo,linea_plan_id,orden_celda",
|
||||
)
|
||||
.eq("id", payload.id)
|
||||
.single();
|
||||
|
||||
if (existingAsignaturaError) {
|
||||
const maybeCode = (existingAsignaturaError as { code?: string }).code;
|
||||
if (maybeCode === "PGRST116") {
|
||||
throw new HttpError(
|
||||
404,
|
||||
"No se encontró la asignatura.",
|
||||
"NOT_FOUND",
|
||||
{ table: "asignaturas", id: payload.id },
|
||||
);
|
||||
}
|
||||
throw new HttpError(
|
||||
500,
|
||||
"No se pudo obtener la asignatura.",
|
||||
"SUPABASE_QUERY_FAILED",
|
||||
existingAsignaturaError,
|
||||
);
|
||||
}
|
||||
|
||||
const resolved = {
|
||||
plan_estudio_id: payload.plan_estudio_id ??
|
||||
existingAsignatura.plan_estudio_id,
|
||||
estructura_id: payload.estructura_id ??
|
||||
existingAsignatura.estructura_id,
|
||||
nombre: payload.nombre ?? existingAsignatura.nombre,
|
||||
codigo: payload.codigo ?? existingAsignatura.codigo,
|
||||
tipo: payload.tipo ?? existingAsignatura.tipo,
|
||||
creditos: payload.creditos ?? existingAsignatura.creditos,
|
||||
horas_academicas: payload.horas_academicas ??
|
||||
existingAsignatura.horas_academicas,
|
||||
horas_independientes: payload.horas_independientes ??
|
||||
existingAsignatura.horas_independientes,
|
||||
numero_ciclo: payload.numero_ciclo ?? existingAsignatura.numero_ciclo,
|
||||
linea_plan_id: payload.linea_plan_id ??
|
||||
existingAsignatura.linea_plan_id,
|
||||
orden_celda: payload.orden_celda ?? existingAsignatura.orden_celda,
|
||||
};
|
||||
|
||||
if (!resolved.estructura_id) {
|
||||
throw new HttpError(
|
||||
422,
|
||||
"estructura_id es requerido (no está presente ni en el JSON ni en la asignatura existente).",
|
||||
"VALIDATION_ERROR",
|
||||
{
|
||||
id: payload.id,
|
||||
existing_estructura_id: existingAsignatura.estructura_id,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const { data: estructura, error: estructuraError } = await supabaseService
|
||||
.from("estructuras_asignatura")
|
||||
.select("id,nombre,definicion,version")
|
||||
.eq("id", resolved.estructura_id)
|
||||
.single();
|
||||
if (estructuraError) {
|
||||
const maybeCode = (estructuraError as { code?: string }).code;
|
||||
if (maybeCode === "PGRST116") {
|
||||
throw new HttpError(
|
||||
404,
|
||||
"No se encontró la estructura de la asignatura.",
|
||||
"NOT_FOUND",
|
||||
{ table: "estructuras_asignatura", id: resolved.estructura_id },
|
||||
);
|
||||
}
|
||||
throw new HttpError(
|
||||
500,
|
||||
"No se pudo obtener la estructura de la asignatura.",
|
||||
"SUPABASE_QUERY_FAILED",
|
||||
estructuraError,
|
||||
);
|
||||
}
|
||||
|
||||
const systemPrompt =
|
||||
"Eres un asistente experto en diseño curricular. Responde únicamente con JSON válido que cumpla estrictamente el JSON Schema proporcionado.";
|
||||
|
||||
const userPrompt =
|
||||
`Genera un borrador completo completo de una ASIGNATURA con base en lo siguiente:\n` +
|
||||
`- Nombre de la asignatura: ${resolved.nombre}\n` +
|
||||
`- Código (clave de la asignatura): ${
|
||||
resolved.codigo ?? "(no especificado)"
|
||||
}\n` +
|
||||
`- Tipo: ${resolved.tipo ?? "(no especificado)"}\n` +
|
||||
`- Número de créditos: ${resolved.creditos}\n` +
|
||||
`- Horas académicas: ${
|
||||
resolved.horas_academicas ?? "(no especificado)"
|
||||
}\n` +
|
||||
`- Horas independientes: ${
|
||||
resolved.horas_independientes ?? "(no especificado)"
|
||||
}\n` +
|
||||
`- Descripción del enfoque académico (sobre el contenido de la respuesta generada): ${
|
||||
payload.descripcionEnfoqueAcademico ?? "(ninguna)"
|
||||
}`;
|
||||
|
||||
const schemaDef: Record<string, unknown> =
|
||||
typeof estructura?.definicion === "object" &&
|
||||
estructura?.definicion !== null
|
||||
? (estructura.definicion as Record<string, unknown>)
|
||||
: {};
|
||||
|
||||
const aiStructuredPayload: StructuredResponseOptions = {
|
||||
model: "gpt-5-nano",
|
||||
input: [
|
||||
{ role: "system", content: systemPrompt },
|
||||
{ role: "user", content: userPrompt },
|
||||
],
|
||||
text: {
|
||||
format: {
|
||||
type: "json_schema",
|
||||
name: "asignatura_contenido_tematico",
|
||||
schema: schemaDef,
|
||||
strict: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const svc = OpenAIService.fromEnv();
|
||||
if (!(svc instanceof OpenAIService)) {
|
||||
throw new HttpError(
|
||||
500,
|
||||
"Configuración del servidor incompleta.",
|
||||
"OPENAI_MISCONFIGURED",
|
||||
svc,
|
||||
);
|
||||
}
|
||||
|
||||
const aiResult = await svc.createStructuredResponse(aiStructuredPayload);
|
||||
if (!aiResult.ok) {
|
||||
const status = aiResult.code === "MissingEnv" ? 500 : 502;
|
||||
throw new HttpError(
|
||||
status,
|
||||
"No se pudo generar la asignatura con IA.",
|
||||
"OPENAI_REQUEST_FAILED",
|
||||
aiResult,
|
||||
);
|
||||
}
|
||||
|
||||
let aiOutput = aiResult.output ?? null;
|
||||
if (aiOutput == null && aiResult.outputText) {
|
||||
try {
|
||||
aiOutput = JSON.parse(aiResult.outputText);
|
||||
} catch {
|
||||
throw new HttpError(
|
||||
502,
|
||||
"La respuesta de la IA no es JSON válido.",
|
||||
"OPENAI_INVALID_JSON",
|
||||
{ outputText: aiResult.outputText },
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!aiOutput) {
|
||||
throw new HttpError(
|
||||
502,
|
||||
"La respuesta de la IA no contiene salida estructurada.",
|
||||
"OPENAI_MISSING_STRUCTURED_OUTPUT",
|
||||
{ outputText: aiResult.outputText ?? null },
|
||||
);
|
||||
}
|
||||
|
||||
const aiOutputJson: Json = aiOutput as unknown as Json;
|
||||
|
||||
const updatePatch: Database["public"]["Tables"]["asignaturas"]["Update"] =
|
||||
{
|
||||
datos: aiOutputJson,
|
||||
tipo_origen: "IA",
|
||||
estado: "borrador",
|
||||
};
|
||||
|
||||
// Apply only provided JSON fields (do not overwrite if missing)
|
||||
if (payload.plan_estudio_id !== undefined) {
|
||||
updatePatch.plan_estudio_id = payload.plan_estudio_id;
|
||||
}
|
||||
if (payload.estructura_id !== undefined) {
|
||||
updatePatch.estructura_id = payload.estructura_id;
|
||||
}
|
||||
if (payload.nombre !== undefined) {
|
||||
updatePatch.nombre = payload.nombre;
|
||||
}
|
||||
if (payload.codigo !== undefined) {
|
||||
updatePatch.codigo = payload.codigo;
|
||||
}
|
||||
if (payload.tipo !== undefined) {
|
||||
updatePatch.tipo = payload.tipo as Database["public"]["Tables"][
|
||||
"asignaturas"
|
||||
]["Update"]["tipo"];
|
||||
}
|
||||
if (payload.creditos !== undefined) {
|
||||
updatePatch.creditos = payload.creditos;
|
||||
}
|
||||
if (payload.horas_academicas !== undefined) {
|
||||
updatePatch.horas_academicas = payload.horas_academicas;
|
||||
}
|
||||
if (payload.horas_independientes !== undefined) {
|
||||
updatePatch.horas_independientes = payload.horas_independientes;
|
||||
}
|
||||
if (payload.numero_ciclo !== undefined) {
|
||||
updatePatch.numero_ciclo = payload.numero_ciclo;
|
||||
}
|
||||
if (payload.linea_plan_id !== undefined) {
|
||||
updatePatch.linea_plan_id = payload.linea_plan_id;
|
||||
}
|
||||
if (payload.orden_celda !== undefined) {
|
||||
updatePatch.orden_celda = payload.orden_celda;
|
||||
}
|
||||
|
||||
updatePatch.meta_origen = {
|
||||
generado_por: "ai_generate_subject_update_json",
|
||||
ai: {
|
||||
responseId: aiResult.responseId ?? null,
|
||||
conversationId: aiResult.conversationId ?? null,
|
||||
model: aiResult.model,
|
||||
usage: aiResult.usage ?? null,
|
||||
},
|
||||
iaConfig: {
|
||||
descripcionEnfoqueAcademico: payload.descripcionEnfoqueAcademico ??
|
||||
null,
|
||||
},
|
||||
} as unknown as Json;
|
||||
|
||||
const { data: asignatura, error: asignaturaError } = await supabaseService
|
||||
.from("asignaturas")
|
||||
.update(updatePatch)
|
||||
.eq("id", payload.id)
|
||||
.select(
|
||||
"id,nombre,codigo,tipo,creditos,horas_academicas,horas_independientes,estructura_id,plan_estudio_id,contenido_tematico,meta_origen,datos,creado_en,actualizado_en,numero_ciclo,linea_plan_id,orden_celda",
|
||||
)
|
||||
.single();
|
||||
|
||||
if (asignaturaError) {
|
||||
const maybeCode = (asignaturaError as { code?: string }).code;
|
||||
if (maybeCode === "PGRST116") {
|
||||
throw new HttpError(
|
||||
404,
|
||||
"No se encontró la asignatura.",
|
||||
"NOT_FOUND",
|
||||
{ table: "asignaturas", id: payload.id },
|
||||
);
|
||||
}
|
||||
throw new HttpError(
|
||||
500,
|
||||
"No se pudo actualizar la asignatura.",
|
||||
"SUPABASE_UPDATE_FAILED",
|
||||
asignaturaError,
|
||||
);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[${
|
||||
new Date().toISOString()
|
||||
}][${functionName}]: JSON update processed successfully`,
|
||||
);
|
||||
return sendSuccess(asignatura);
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Multipart create flow (existing)
|
||||
// -----------------------------
|
||||
const formData = await req.formData();
|
||||
const validation = parseAndValidate(formData);
|
||||
if (!validation.success) {
|
||||
|
||||
Reference in New Issue
Block a user