diff --git a/actions/supabase/queries/sessions.ts b/actions/supabase/queries/sessions.ts index 624073cd..9367e29e 100644 --- a/actions/supabase/queries/sessions.ts +++ b/actions/supabase/queries/sessions.ts @@ -304,7 +304,7 @@ export async function advancePhaseForSingleUser( roleId: UUID, sessionId: UUID, ): Promise { - changePhaseForSingleUser(userId, roleId, sessionId, 1); + return changePhaseForSingleUser(userId, roleId, sessionId, 1); } export async function backPhaseForSingleUser( @@ -312,7 +312,7 @@ export async function backPhaseForSingleUser( roleId: UUID, sessionId: UUID, ): Promise { - changePhaseForSingleUser(userId, roleId, sessionId, -1); + return changePhaseForSingleUser(userId, roleId, sessionId, -1); } export async function changePhaseForSingleUser( @@ -546,21 +546,23 @@ export async function isSessionFinished(sessionId: string): Promise { return data[0].is_finished; } -export async function fetchRole( +export async function fetchRoleForParticipant( userId: UUID, sessionId: UUID, -): Promise { +): Promise { const supabase = await getSupabaseServerClient(); const { data, error } = await supabase .from("participant_session") - .select("role_id") + .select("role(*)") .eq("session_id", sessionId) .eq("user_id", userId) - .single(); + .single<{ role: Role | null }>(); + if (error) { throw error; } - return data.role_id; + + return data.role; } export async function createPromptAnswer( @@ -679,22 +681,6 @@ export async function fetchPromptResponses( return data ?? []; } -export async function fetchRoleName(roleId: UUID): Promise { - const supabase = await getSupabaseServerClient(); - const { data, error } = await supabase - .from("role") - .select("*") - .eq("role_id", roleId) - .single(); - - if (error) { - console.error("Error fetching role name:", error); - throw error; - } - - return data; -} - export type ParticipantDetailBundle = { participant: ParticipantSessionWithProfile; email: string; diff --git a/actions/supabase/queries/templates.ts b/actions/supabase/queries/templates.ts index 30d3ff69..0b9ab10c 100644 --- a/actions/supabase/queries/templates.ts +++ b/actions/supabase/queries/templates.ts @@ -194,7 +194,8 @@ export const fetchTemplatesExercise = async (userGroup: string) => { const { data, error } = await supabase .from("template") .select("*") - .or(`user_group_id.eq.${userGroup},accessible_to_all.eq.true`); + .or(`user_group_id.eq.${userGroup},accessible_to_all.eq.true`) + .eq("archived", false); if (error) { console.error("Error fetching templates:", error); @@ -203,6 +204,50 @@ export const fetchTemplatesExercise = async (userGroup: string) => { return data; }; +// archive or delete a template +// can only do if from the right user_group (or if admin) +// no data is deleted (for PDFs and sessions) +export async function setTemplateArchived( + template_id: UUID, + archived: boolean, + requester_group_id: UUID, + is_admin: boolean, +): Promise { + const supabase = await getSupabaseServerClient(); + + const { data: tmpl, error: fetchErr } = await supabase + .from("template") + .select("user_group_id, accessible_to_all") + .eq("template_id", template_id) + .single(); + + if (fetchErr || !tmpl) { + console.error("Error loading template for archive:", fetchErr); + return false; + } + + const ownsTemplate = tmpl.user_group_id === requester_group_id; + const canArchive = + ownsTemplate || (is_admin && Boolean(tmpl.accessible_to_all)); + + if (!canArchive) { + console.error("Not authorized to archive template:", template_id); + return false; + } + + const { error } = await supabase + .from("template") + .update({ archived }) + .eq("template_id", template_id); + + if (error) { + console.error("Error archiving template:", error); + return false; + } + + return true; +} + export async function fetchFullTemplate(template_id: string) { const supabase = await getSupabaseServerClient(); diff --git a/app/facilitator/exercises/start/page.tsx b/app/facilitator/exercises/start/page.tsx index b22c3cf6..6c740372 100644 --- a/app/facilitator/exercises/start/page.tsx +++ b/app/facilitator/exercises/start/page.tsx @@ -10,7 +10,10 @@ import { createSession, fetchRoles, } from "@/actions/supabase/queries/sessions"; -import { fetchTemplatesExercise } from "@/actions/supabase/queries/templates"; +import { + fetchTemplate, + fetchTemplatesExercise, +} from "@/actions/supabase/queries/templates"; import { fetchUserGroupMembers } from "@/actions/supabase/queries/user-groups"; import Play from "@/assets/images/play.svg"; import AccessError from "@/components/AccessError/AccessError"; @@ -81,13 +84,22 @@ export default function Page() { setTemplatesLoading(true); try { const data = await fetchTemplatesExercise(profile.user_group_id as UUID); - setTemplates(data || []); + let list = data || []; if (preselectedTemplateId) { + // The list is decluttered (archived templates dropped), but if we were + // sent here with a specific template, make sure it's an option so the + // dropdown populates instead of showing blank. + if (!list.some(t => t.template_id === preselectedTemplateId)) { + const preselected = await fetchTemplate(preselectedTemplateId); + if (preselected) list = [preselected, ...list]; + } setSelectedTemplateId(preselectedTemplateId); const rolesData = await fetchRoles(preselectedTemplateId); setRoles((rolesData as Role[]) || []); } + + setTemplates(list); } finally { setTemplatesLoading(false); } diff --git a/app/participants/scenario-overview/[sessionId]/[userId]/components/PromptsRightPanel.tsx b/app/participants/scenario-overview/[sessionId]/[userId]/components/PromptsRightPanel.tsx index 26afdf57..ce994071 100644 --- a/app/participants/scenario-overview/[sessionId]/[userId]/components/PromptsRightPanel.tsx +++ b/app/participants/scenario-overview/[sessionId]/[userId]/components/PromptsRightPanel.tsx @@ -70,7 +70,6 @@ export default function PromptsRightPanel({ backButton, nextButton, }: PromptsRightPanelProps) { - console.log(prompts); const totalPrompts = prompts.length; const completedCount = Math.min(completedPrompts.size, totalPrompts); const progressPercentage = diff --git a/app/participants/scenario-overview/[sessionId]/[userId]/components/ScenarioLeftPanel.tsx b/app/participants/scenario-overview/[sessionId]/[userId]/components/ScenarioLeftPanel.tsx index f8b2be28..c74a062d 100644 --- a/app/participants/scenario-overview/[sessionId]/[userId]/components/ScenarioLeftPanel.tsx +++ b/app/participants/scenario-overview/[sessionId]/[userId]/components/ScenarioLeftPanel.tsx @@ -1,9 +1,7 @@ "use client"; -import type { Phase, RolePhase, Template, UUID } from "@/types/schema"; -import { useEffect, useState } from "react"; +import type { Phase, Role, RolePhase, Template } from "@/types/schema"; import CircularProgress from "@mui/material/CircularProgress"; -import { fetchRoleName } from "@/actions/supabase/queries/sessions"; import LinkedText from "@/components/Linki/Linkify"; import { ContentBody, @@ -26,7 +24,8 @@ interface ScenarioLeftPanelProps { rolePhase: RolePhase | null; onContinue: () => void; isOverview: boolean; - roleId: UUID; + role: Role | null; + isRoleLoading: boolean; isLoading: boolean; } @@ -37,28 +36,11 @@ export default function ScenarioLeftPanel({ rolePhase, onContinue, isOverview, - roleId, + role, + isRoleLoading = false, isLoading = false, }: ScenarioLeftPanelProps) { const currentPhase = phases[phaseInd] ?? null; - const [roleDescription, setRoleDescription] = useState(null); - const [roleName, setRoleName] = useState(null); - - useEffect(() => { - if (!roleId) return; - - async function loadRoleName() { - try { - const name = await fetchRoleName(roleId); - setRoleDescription(name.role_description); - setRoleName(name.role_name); - } catch (err) { - console.error("Failed to load role name:", err); - } - } - - loadRoleName(); - }, [roleId]); return ( @@ -122,12 +104,20 @@ export default function ScenarioLeftPanel({ Your Role - - - - - - + {isRoleLoading ? ( + + + + ) : ( + <> + + + + + + + + )} )} diff --git a/app/participants/scenario-overview/[sessionId]/[userId]/page.tsx b/app/participants/scenario-overview/[sessionId]/[userId]/page.tsx index 448b31f0..fffcdd2c 100644 --- a/app/participants/scenario-overview/[sessionId]/[userId]/page.tsx +++ b/app/participants/scenario-overview/[sessionId]/[userId]/page.tsx @@ -4,6 +4,7 @@ import type { Phase, Prompt, PromptAnswer, + Role, RolePhase, Template, UUID, @@ -19,7 +20,7 @@ import { fetchPhases, fetchPromptResponses, fetchPrompts, - fetchRole, + fetchRoleForParticipant, fetchRolePhases, fetchSessionGlobalPhaseIndex, fetchTemplateId, @@ -61,6 +62,8 @@ export default function SessionFlowPage() { const [sessionFinished, setSessionFinished] = useState(null); const [roleId, setRoleId] = useState(""); + const [role, setRole] = useState(null); + const [isOverviewLoading, setIsOverviewLoading] = useState(true); const [rolePhase, setRolePhase] = useState(null); const [prompts, setPrompts] = useState([]); const [promptsLoading, setPromptsLoading] = useState(false); @@ -72,6 +75,7 @@ export default function SessionFlowPage() { new Set(), ); const [isForceAdvance, setIsForceAdvance] = useState(false); + const [isAdvancing, setIsAdvancing] = useState(false); const [dbPhaseIndex, setDbPhaseIndex] = useState(0); // 1-indexed in supabase (start at 0 for overview) @@ -89,34 +93,29 @@ export default function SessionFlowPage() { setSessionFinished(true); return; } + setIsOverviewLoading(true); try { - const templateId = await fetchTemplateId(sessionIdStr); - const template = await fetchTemplate( - templateId.template_id as unknown as UUID, - ); - setTemplateInfo(template); + const [template, phaseData, participantRole, isForce, phaseIndex] = + await Promise.all([ + fetchTemplateId(sessionIdStr).then(templateId => + fetchTemplate(templateId.template_id as unknown as UUID), + ), + fetchPhases(sessionIdStr), + fetchRoleForParticipant(userId, sessionIdStr), + isSessionForceAdvance(sessionIdStr), + fetchParticipantPhaseIndex(userId, sessionIdStr).catch(() => -1), + ]); - const phaseData = await fetchPhases(sessionIdStr); + setTemplateInfo(template); setPhases(phaseData); - - const fetchedRoleId = await fetchRole(userId, sessionIdStr); - setRoleId(fetchedRoleId as string); - - const isForce = await isSessionForceAdvance(sessionIdStr); + setRole(participantRole); + setRoleId((participantRole?.role_id as string) ?? ""); setIsForceAdvance(isForce); - - let mostRecentPhaseIndex: number; - try { - mostRecentPhaseIndex = await fetchParticipantPhaseIndex( - userId, - sessionIdStr, - ); - } catch { - mostRecentPhaseIndex = -1; - } - setDbPhaseIndex(mostRecentPhaseIndex); + setDbPhaseIndex(phaseIndex); } catch (err) { console.error("Error loading session data:", err); + } finally { + setIsOverviewLoading(false); } }, [userId, sessionIdStr]); @@ -274,6 +273,24 @@ export default function SessionFlowPage() { }; }, [userId, sessionIdStr]); + const handleContinue = useCallback(async () => { + if (!userId || !roleId || !sessionIdStr || isAdvancing) return; + + const prevPhaseIndex = dbPhaseIndex; + setIsAdvancing(true); + // move the UI forward immediately; the realtime update will confirm it + setDbPhaseIndex(prevPhaseIndex + 1); + + try { + await advancePhaseForSingleUser(userId, roleId as UUID, sessionIdStr); + } catch (err) { + console.error("Failed to advance phase:", err); + setDbPhaseIndex(prevPhaseIndex); + } finally { + setIsAdvancing(false); + } + }, [userId, roleId, sessionIdStr, dbPhaseIndex, isAdvancing]); + function sortResponsesByPromptOrder( prompts: Prompt[], responses: PromptAnswer[], @@ -399,11 +416,10 @@ export default function SessionFlowPage() { phases={phases} phaseInd={arrayIdx} // used to get the actual phaseId from phase[] rolePhase={rolePhase} - onContinue={() => - advancePhaseForSingleUser(userId, roleId as UUID, sessionIdStr) - } + onContinue={handleContinue} isOverview={isOverview} - roleId={roleId} + role={role} + isRoleLoading={isOverviewLoading} isLoading={promptsLoading} /> diff --git a/app/templates/page.tsx b/app/templates/page.tsx index 622c3218..a70ca43a 100644 --- a/app/templates/page.tsx +++ b/app/templates/page.tsx @@ -83,6 +83,7 @@ const createInitialStore = (): LocalStore => { template_id: templateID, template_name: "New Template", accessible_to_all: null, + archived: false, user_group_id: null, summary: "", setting: "", diff --git a/components/TemplateList/TemplateList.tsx b/components/TemplateList/TemplateList.tsx index 7508648d..ea045788 100644 --- a/components/TemplateList/TemplateList.tsx +++ b/components/TemplateList/TemplateList.tsx @@ -4,7 +4,13 @@ import type { Template, UUID } from "@/types/schema"; import { useEffect, useMemo, useState } from "react"; import { useRouter } from "next/navigation"; import { CircularProgress } from "@mui/material"; -import { ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react"; +import { + Archive, + ArchiveRestore, + ArrowDown, + ArrowUp, + ArrowUpDown, +} from "lucide-react"; import { assignTagToTemplate, createTag, @@ -15,6 +21,7 @@ import { import { copyTemplate, fetchTemplatesWithTags, + setTemplateArchived, } from "@/actions/supabase/queries/templates"; import TopNavBar from "@/components/FacilitatorNavBar/FacilitatorNavBar"; import { Tag } from "@/components/Tag/TagCreator"; @@ -35,6 +42,7 @@ import { SortButton, } from "../../app/facilitator/styles"; import { + ArchivedToggle, AssociatedTags, ContentWrapper, DateColumn, @@ -62,10 +70,11 @@ export default function TemplateListPage({ const router = useRouter(); const { profile } = useProfile(); const user_group_id = profile?.user_group_id as UUID; + const adminAccess = profile?.user_type === "Admin"; const loading = !user_group_id; - const [filterMode, setFilterMode] = useState<"All" | "Your" | "Browse">( - "All", - ); + const [filterMode, setFilterMode] = useState< + "All" | "Your" | "Browse" | "Archived" + >("All"); const [searchInput, setSearchInput] = useState(""); const [templates, setTemplates] = useState([]); const [templatesLoading, setTemplatesLoading] = useState(true); @@ -81,6 +90,11 @@ export default function TemplateListPage({ const [copyConfirm, setCopyConfirm] = useState(null); const [copying, setCopying] = useState(false); + const [archiveConfirm, setArchiveConfirm] = useState( + null, + ); + const [archiving, setArchiving] = useState(false); + useEffect(() => { if (!user_group_id) return; @@ -104,14 +118,25 @@ export default function TemplateListPage({ const filteredTemplates = useMemo(() => { let updated = [...templates]; - if (filterMode === "All") { + if (filterMode === "Archived") { updated = updated.filter( - t => t.accessible_to_all || t.user_group_id === user_group_id, + t => + t.archived && + (t.user_group_id === user_group_id || + (adminAccess && Boolean(t.accessible_to_all))), ); - } else if (filterMode === "Your") { - updated = updated.filter(t => t.user_group_id === user_group_id); } else { - updated = updated.filter(t => t.accessible_to_all); + updated = updated.filter(t => !t.archived); + + if (filterMode === "All") { + updated = updated.filter( + t => t.accessible_to_all || t.user_group_id === user_group_id, + ); + } else if (filterMode === "Your") { + updated = updated.filter(t => t.user_group_id === user_group_id); + } else { + updated = updated.filter(t => t.accessible_to_all); + } } if (selectedTagIds) { @@ -147,6 +172,7 @@ export default function TemplateListPage({ sortKey, sortOrder, user_group_id, + adminAccess, ]); const toggleSort = (key: "name" | "date") => { @@ -160,9 +186,25 @@ export default function TemplateListPage({ const isAdminTemplate = (t: TemplateWithTags) => Boolean(t.accessible_to_all); + // You manage a template if your group owns it, or you're an admin + const canManageTemplate = (t: TemplateWithTags) => + t.user_group_id === user_group_id || + (adminAccess && Boolean(t.accessible_to_all)); + + // A shared template you don't manage stays copy-to-edit only + const isLockedTemplate = (t: TemplateWithTags) => + isAdminTemplate(t) && !canManageTemplate(t); + const handleOpenTemplate = (t: TemplateWithTags) => { - if (isAdminTemplate(t)) return; - router.push(`/templates?templateId=${t.template_id}&fromTemplateList=true`); + if (isLockedTemplate(t)) return; + + const params = new URLSearchParams({ + templateId: t.template_id, + fromTemplateList: "true", + }); + if (t.accessible_to_all) params.set("isAdmin", "true"); + + router.push(`/templates?${params.toString()}`); }; const handleCopyConfirm = async (action: WarningAction) => { @@ -185,6 +227,40 @@ export default function TemplateListPage({ } }; + const handleArchiveConfirm = async (action: WarningAction) => { + if (action === "cancel" || !archiveConfirm) { + setArchiveConfirm(null); + return; + } + + const target = archiveConfirm; + const nextArchived = !target.archived; + + setArchiving(true); + try { + const ok = await setTemplateArchived( + target.template_id, + nextArchived, + user_group_id, + adminAccess, + ); + if (ok) { + setTemplates(prev => + prev.map(t => + t.template_id === target.template_id + ? { ...t, archived: nextArchived } + : t, + ), + ); + } + } catch (err) { + console.error("Archive failed", err); + } finally { + setArchiving(false); + setArchiveConfirm(null); + } + }; + async function deleteTagComponent(tag_id: UUID, template_id?: UUID) { if (template_id) { const success = await removeTagFromTemplate(template_id, tag_id); @@ -363,6 +439,21 @@ export default function TemplateListPage({ } showBorder={true} /> + + {!showSidebar && ( + + setFilterMode(prev => + prev === "Archived" ? "All" : "Archived", + ) + } + > + {filterMode === "Archived" + ? "Active templates" + : "Archived"} + + )} {templatesLoading ? ( @@ -406,15 +497,15 @@ export default function TemplateListPage({ )} {filteredTemplates.map(t => { - const isAdmin = isAdminTemplate(t); + const isLocked = isLockedTemplate(t); return ( - + handleOpenTemplate(t)} title={ - isAdmin - ? "Shared template — make a copy to edit" + isLocked + ? "You cannot edit this template. View content through downloading the PDF." : undefined } > @@ -536,6 +627,22 @@ export default function TemplateListPage({ + + {canManageTemplate(t) && ( + { + e.stopPropagation(); + setArchiveConfirm(t); + }} + title={t.archived ? "Unarchive" : "Archive"} + > + {t.archived ? ( + + ) : ( + + )} + + )} ); @@ -554,6 +661,22 @@ export default function TemplateListPage({ confirmLabel="Make a copy" loading={copying} /> + +