Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 9 additions & 23 deletions actions/supabase/queries/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,15 +304,15 @@ export async function advancePhaseForSingleUser(
roleId: UUID,
sessionId: UUID,
): Promise<void> {
changePhaseForSingleUser(userId, roleId, sessionId, 1);
return changePhaseForSingleUser(userId, roleId, sessionId, 1);
}

export async function backPhaseForSingleUser(
userId: UUID,
roleId: UUID,
sessionId: UUID,
): Promise<void> {
changePhaseForSingleUser(userId, roleId, sessionId, -1);
return changePhaseForSingleUser(userId, roleId, sessionId, -1);
}

export async function changePhaseForSingleUser(
Expand Down Expand Up @@ -546,21 +546,23 @@ export async function isSessionFinished(sessionId: string): Promise<boolean> {
return data[0].is_finished;
}

export async function fetchRole(
export async function fetchRoleForParticipant(
userId: UUID,
sessionId: UUID,
): Promise<string | null> {
): Promise<Role | null> {
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(
Expand Down Expand Up @@ -679,22 +681,6 @@ export async function fetchPromptResponses(
return data ?? [];
}

export async function fetchRoleName(roleId: UUID): Promise<Role> {
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;
Expand Down
47 changes: 46 additions & 1 deletion actions/supabase/queries/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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<boolean> {
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();

Expand Down
16 changes: 14 additions & 2 deletions app/facilitator/exercises/start/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -26,7 +24,8 @@ interface ScenarioLeftPanelProps {
rolePhase: RolePhase | null;
onContinue: () => void;
isOverview: boolean;
roleId: UUID;
role: Role | null;
isRoleLoading: boolean;
isLoading: boolean;
}

Expand All @@ -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<string | null>(null);
const [roleName, setRoleName] = useState<string | null>(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 (
<ContentDiv $isOverview={isOverview}>
Expand Down Expand Up @@ -122,12 +104,20 @@ export default function ScenarioLeftPanel({

<ContentBubble>
<ContentHeader>Your Role</ContentHeader>
<ContentBody>
<LinkedText text={roleName} />
</ContentBody>
<ContentBody>
<LinkedText text={roleDescription} />
</ContentBody>
{isRoleLoading ? (
<LoadingScreen>
<CircularProgress color="inherit" aria-label="Loading…" />
</LoadingScreen>
) : (
<>
<ContentBody>
<LinkedText text={role?.role_name ?? null} />
</ContentBody>
<ContentBody>
<LinkedText text={role?.role_description ?? null} />
</ContentBody>
</>
)}
</ContentBubble>
</>
)}
Expand Down
70 changes: 43 additions & 27 deletions app/participants/scenario-overview/[sessionId]/[userId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
Phase,
Prompt,
PromptAnswer,
Role,
RolePhase,
Template,
UUID,
Expand All @@ -19,7 +20,7 @@ import {
fetchPhases,
fetchPromptResponses,
fetchPrompts,
fetchRole,
fetchRoleForParticipant,
fetchRolePhases,
fetchSessionGlobalPhaseIndex,
fetchTemplateId,
Expand Down Expand Up @@ -61,6 +62,8 @@ export default function SessionFlowPage() {
const [sessionFinished, setSessionFinished] = useState<boolean | null>(null);

const [roleId, setRoleId] = useState<string>("");
const [role, setRole] = useState<Role | null>(null);
const [isOverviewLoading, setIsOverviewLoading] = useState(true);
const [rolePhase, setRolePhase] = useState<RolePhase | null>(null);
const [prompts, setPrompts] = useState<Prompt[]>([]);
const [promptsLoading, setPromptsLoading] = useState(false);
Expand All @@ -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)

Expand All @@ -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]);

Expand Down Expand Up @@ -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[],
Expand Down Expand Up @@ -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}
/>

Expand Down
1 change: 1 addition & 0 deletions app/templates/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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: "",
Expand Down
Loading
Loading