Se crea funcionalidad de exportar pdf desde front y generar historial de version de cambios se agrego una libreri jspdf
This commit is contained in:
67
src/hooks/useSupabaseUpdateWithHistory.ts
Normal file
67
src/hooks/useSupabaseUpdateWithHistory.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
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 };
|
||||
}
|
||||
Reference in New Issue
Block a user