feat(frontend): migrate dashboard projects flow off Supabase to V2 Studio

User-saved projects now read/write through the gateway /v1/saved-projects
(studio schema) using the Identity access-token cookie, replacing the
Supabase `projects` table. Adds src/lib/api/saved-projects.ts client that
maps studio snake_case DTOs into the existing DashboardProject shape.

- DashboardProjectsContent: lists via studio service, degrades gracefully
- /api/projects GET: studio list; POST: copy-from-template create
  (studio requires original_project_id; falls back to scene_data.templateId)
- /api/projects/[projectId] GET/PATCH: proxy to studio with JWT

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
soroush.asadi
2026-05-30 05:56:25 +03:30
parent f366d73697
commit 14cdb772b4
4 changed files with 298 additions and 198 deletions
+196
View File
@@ -0,0 +1,196 @@
/**
* Server-side client for the FlatRender V2 Studio service's saved-projects API.
*
* Replaces the legacy Supabase `projects` table. User-saved projects now live in
* the `studio` schema and are reached through the gateway at `/v1/saved-projects`,
* authenticated with the caller's Identity access JWT (read from the httpOnly
* `fr_access` cookie).
*
* Studio JSON bodies are snake_case (responses + request bodies), but query-string
* params bind by C# property name (camelCase) — see project memory. This module
* maps the studio DTOs into the camelCase `DashboardProject` the UI consumes, so
* dashboard call sites are unchanged.
*/
import { gatewayUrl } from "@/lib/api/gateway";
import { getAccessToken } from "@/lib/auth/session";
import type { DashboardProject, ProjectType } from "@/lib/projects";
// ── V2 studio response shapes (snake_case JSON) ──────────────────────────────
export interface V2SavedProjectSummary {
id: string;
user_id: string;
original_project_id: string;
original_project_name: string;
original_container_slug?: string | null;
name: string;
image?: string | null;
type: string;
resolution: string;
choose_mode: string;
project_duration_sec: number;
last_edit_date: string;
created_at: string;
}
export interface V2SavedProjectFull extends V2SavedProjectSummary {
frame_rate: number;
edit_state: string;
last_edit_step?: string | null;
// The studio full payload carries the normalized scene graph; the dashboard
// does not need it, so we keep it loosely typed for pass-through.
scenes?: unknown[];
shared_colors?: unknown[];
shared_color_presets?: unknown[];
shared_layers?: unknown[];
[key: string]: unknown;
}
interface V2Paged<T> {
items: T[];
meta: { page: number; page_size: number; total: number; total_pages: number };
}
// ── Mappers (V2 → UI shapes) ─────────────────────────────────────────────────
/** Studio stores `type` as a free string; coerce to the UI's ProjectType. */
function normalizeType(type: string | null | undefined): ProjectType {
switch ((type ?? "").toLowerCase()) {
case "image":
return "image";
case "trimmer":
return "trimmer";
default:
return "video";
}
}
function thumbnailSeed(id: string): string {
return id.replace(/-/g, "").slice(0, 12);
}
export function savedProjectToDashboard(
p: V2SavedProjectSummary
): DashboardProject {
return {
id: p.id,
name: p.name,
type: normalizeType(p.type),
// Studio has no draft/rendering/ready lifecycle on the summary; treat saved
// projects as editable drafts until the render service reports otherwise.
status: "draft",
renderUrl: null,
thumbnailSeed: thumbnailSeed(p.id),
lastEditedAt: p.last_edit_date ?? p.created_at ?? new Date().toISOString(),
};
}
// ── Fetch helper (authenticated) ─────────────────────────────────────────────
interface StudioResult<T> {
ok: boolean;
status: number;
data: T | null;
error?: string;
}
async function studioFetch<T>(
path: string,
init?: RequestInit
): Promise<StudioResult<T>> {
const token = await getAccessToken();
if (!token) return { ok: false, status: 401, data: null, error: "Unauthorized" };
try {
const res = await fetch(gatewayUrl(path), {
...init,
cache: "no-store",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
...(init?.headers ?? {}),
},
});
if (res.status === 204) return { ok: true, status: 204, data: null };
const json = (await res.json().catch(() => null)) as T | null;
if (!res.ok) {
const err =
(json as { message?: string } | null)?.message ??
`Studio service error (${res.status})`;
return { ok: false, status: res.status, data: null, error: err };
}
return { ok: true, status: res.status, data: json };
} catch {
return { ok: false, status: 502, data: null, error: "Studio service unreachable" };
}
}
// ── Public API ───────────────────────────────────────────────────────────────
/**
* List the current user's saved projects (newest first per the studio service's
* own ordering). Returns an empty array when signed out or the service is down,
* so the dashboard degrades gracefully instead of throwing.
*/
export async function listSavedProjects(opts?: {
page?: number;
pageSize?: number;
q?: string;
type?: ProjectType;
}): Promise<DashboardProject[]> {
const params = new URLSearchParams();
if (opts?.page) params.set("page", String(opts.page));
params.set("pageSize", String(opts?.pageSize ?? 100));
if (opts?.q) params.set("q", opts.q);
if (opts?.type) params.set("type", opts.type);
const qs = params.toString() ? `?${params}` : "";
const res = await studioFetch<V2Paged<V2SavedProjectSummary>>(
`/v1/saved-projects${qs}`
);
if (!res.ok || !res.data) return [];
return (res.data.items ?? []).map(savedProjectToDashboard);
}
export async function getSavedProject(
id: string
): Promise<StudioResult<V2SavedProjectFull>> {
return studioFetch<V2SavedProjectFull>(
`/v1/saved-projects/${encodeURIComponent(id)}`
);
}
/**
* Create a saved project by copying a content template container.
* The studio service requires `original_project_id` (the content template
* project GUID) — there is no blank-project concept in V2.
*/
export async function createSavedProject(body: {
original_project_id: string;
name?: string;
preset_story_id?: string;
copy_default_values?: boolean;
}): Promise<StudioResult<V2SavedProjectFull>> {
return studioFetch<V2SavedProjectFull>("/v1/saved-projects", {
method: "POST",
body: JSON.stringify(body),
});
}
export async function updateSavedProject(
id: string,
body: Record<string, unknown>
): Promise<StudioResult<V2SavedProjectFull>> {
return studioFetch<V2SavedProjectFull>(
`/v1/saved-projects/${encodeURIComponent(id)}`,
{ method: "PATCH", body: JSON.stringify(body) }
);
}
export async function deleteSavedProject(id: string): Promise<StudioResult<null>> {
return studioFetch<null>(`/v1/saved-projects/${encodeURIComponent(id)}`, {
method: "DELETE",
});
}