Files
confidence-engine/lib/storage/server-investigation-persistence.js
T

76 lines
2.4 KiB
JavaScript

import {
createServerSupabaseClient,
getAuthenticatedUser,
} from "@/lib/supabase/server.js";
import { restartSnapshot } from "./restart-investigation.js";
const SCHEMA = "confidence_engine";
const TABLE = "investigations";
async function getAuthenticatedPersistenceContext() {
const user = await getAuthenticatedUser();
if (!user) return null;
return { user, supabase: createServerSupabaseClient() };
}
function throwIfDatabaseError(error) {
if (error) throw new Error("Investigation persistence request failed");
}
export async function saveInvestigation(snapshot, id = snapshot?.id) {
if (!snapshot || typeof snapshot !== "object" || !id) {
throw new Error("Investigation snapshot and id are required");
}
const context = await getAuthenticatedPersistenceContext();
if (!context) return null;
const { data, error } = await context.supabase
.schema(SCHEMA)
.from(TABLE)
.upsert({ id, user_id: context.user.id, snapshot }, { onConflict: "id" })
.select("id, snapshot, created_at, updated_at")
.single();
throwIfDatabaseError(error);
return data?.snapshot ?? null;
}
export async function loadInvestigation(id) {
if (!id) return null;
const context = await getAuthenticatedPersistenceContext();
if (!context) return null;
const { data, error } = await context.supabase
.schema(SCHEMA)
.from(TABLE)
.select("snapshot")
.eq("id", id)
.maybeSingle();
throwIfDatabaseError(error);
return data?.snapshot ?? null;
}
export async function listInvestigations() {
const context = await getAuthenticatedPersistenceContext();
if (!context) return [];
const { data, error } = await context.supabase
.schema(SCHEMA)
.from(TABLE)
.select("id, snapshot, created_at, updated_at")
.order("updated_at", { ascending: false });
throwIfDatabaseError(error);
return (data ?? []).map((record) => ({
id: record.id,
scenario: record.snapshot?.scenario ?? null,
updatedAt: record.snapshot?.updatedAt ?? record.updated_at,
investigationRevision: record.snapshot?.investigationRevision ?? 0,
reportExists: !!record.snapshot?.investigationReport,
reportGeneratedFromRevision: record.snapshot?.investigationReport?.generatedFromRevision ?? null,
}));
}
export async function restartInvestigation(id) {
const snapshot = await loadInvestigation(id);
if (!snapshot) return null;
return saveInvestigation(restartSnapshot(snapshot), id);
}