This repository has been archived on 2026-01-21. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
Acad-IA/src/hooks/useSupabaseUpdateWithHistory.ts

68 lines
1.8 KiB
TypeScript

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/auth/supabase";
/**
* Hook genérico para actualizar una tabla y guardar respaldo en historico_cambios
*
* @param tableName Nombre de la tabla a actualizar
* @param idKey Campo que se usa para hacer eq (por defecto 'id')
*/
export function useSupabaseUpdateWithHistory<T extends Record<string, any>>(
tableName: string,
idKey: keyof T = "id" as keyof T
) {
const qc = useQueryClient();
// Generar diferencias tipo JSON Patch
function generateDiff(oldData: T, newData: Partial<T>) {
const changes: any[] = [];
for (const key of Object.keys(newData)) {
const oldValue = (oldData as any)[key];
const newValue = (newData as any)[key];
if (newValue !== undefined && newValue !== oldValue) {
changes.push({
op: "replace",
path: `/${key}`,
from: oldValue,
value: newValue,
});
}
}
return changes;
}
const mutation = useMutation({
mutationFn: async ({
oldData,
newData,
}: {
oldData: T;
newData: Partial<T>;
}) => {
const diff = generateDiff(oldData, newData);
if (diff.length > 0) {
const { error: backupError } = await supabase
.from("historico_cambios")
.insert({
id_plan_estudios: oldData.id ?? null, // ajusta si es otra tabla
tabla_afectada: tableName,
json_cambios: diff,
created_at: new Date().toISOString(),
});
if (backupError) throw backupError;
}
const { error } = await supabase
.from(tableName)
.update(newData)
.eq(idKey as string, oldData[idKey]);
if (error) throw error;
},
});
return { mutation };
}