Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Select Coaching Session Component #37

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
Draft
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"react": "^18",
"react-day-picker": "^8.10.0",
"react-dom": "^18",
"swr": "^2.2.5",
"tailwind-merge": "^2.2.0",
"tailwindcss-animate": "^1.0.7",
"ts-luxon": "^4.5.2",
Expand Down
4 changes: 2 additions & 2 deletions src/app/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import Image from "next/image";

import { cn } from "@/lib/utils";

import { SelectCoachingSession } from "@/components/ui/dashboard/select-coaching-session";
import { JoinCoachingSession } from "@/components/ui/dashboard/join-coaching-session";
import { useAuthStore } from "@/lib/providers/auth-store-provider";

// export const metadata: Metadata = {
Expand Down Expand Up @@ -54,7 +54,7 @@ export default function DashboardPage() {
</div>
<div className="hidden items-start justify-center gap-6 rounded-lg p-8 md:grid lg:grid-cols-2 xl:grid-cols-3">
<DashboardContainer>
<SelectCoachingSession userId={userId} />
<JoinCoachingSession userId={userId} />
</DashboardContainer>
</div>
</>
Expand Down
150 changes: 150 additions & 0 deletions src/components/ui/dashboard/dynamic-api-select.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import React, { useState } from "react";
import { useApiData } from "@/hooks/use-api-data";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
CoachingSession,
isCoachingSession,
sortCoachingSessionArray,
} from "@/types/coaching-session";
import { DateTime } from "ts-luxon";
import { SortOrder } from "@/types/general";

interface DynamicApiSelectProps<T> {
url: string;
method?: "GET" | "POST";
params?: Record<string, any>;
onChange: (value: string) => void;
placeholder?: string;
getOptionLabel: (item: T) => string;
getOptionValue: (item: T) => string; // TODO: return generic type
elementId: string;
groupByDate?: boolean;
}

interface ApiResponse<T> {
status_code: number;
data: T[];
}

export function DynamicApiSelect<T>({
url,
method = "GET",
params = {},
onChange,
placeholder = "Select an option",
getOptionLabel,
getOptionValue,
elementId,
groupByDate = false,
}: DynamicApiSelectProps<T>) {
const {
data: response,
isLoading,
error,
} = useApiData<ApiResponse<T>>(url, { method, params });
const [value, setValue] = useState<string>(""); // use AppStateStore

const handleValueChange = (newValue: string) => { // TODO: update state store
setValue(newValue);
onChange(newValue);
};

if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
if (!response || response.status_code !== 200)
return <p>Error: Invalid response</p>;

const items = response.data;

const renderSessions = (
sessions: CoachingSession[],
label: string,
filterFn: (session: CoachingSession) => boolean,
sortOrder: SortOrder
) => {
const filteredSessions = sessions.filter(filterFn);
const sortedSessions = sortCoachingSessionArray(
filteredSessions,
sortOrder
);

return (
sortedSessions.length > 0 && (
<SelectGroup>
<SelectLabel>{label}</SelectLabel>
{sortedSessions.map((session) => (
<SelectItem value={session.id} key={session.id}>
{DateTime.fromISO(session.date).toLocaleString(
DateTime.DATETIME_FULL
)}
</SelectItem>
))}
</SelectGroup>
)
);
};

const renderCoachingSessions = (sessions: CoachingSession[]) => (
<SelectContent>
{sessions.length === 0 ? (
<SelectItem disabled value="none">
None found
</SelectItem>
) : (
<>
{renderSessions(
sessions,
"Previous Sessions",
(session) => DateTime.fromISO(session.date) < DateTime.now(),
SortOrder.Descending
)}
{renderSessions(
sessions,
"Upcoming Sessions",
(session) => DateTime.fromISO(session.date) >= DateTime.now(),
SortOrder.Ascending
)}
</>
)}
</SelectContent>
);

const renderOtherItems = (items: T[]) => (
<SelectContent>
{items.length === 0 ? (
<SelectItem disabled value="none">
None found
</SelectItem>
) : (
items.map((item, index) => (
<SelectItem key={index} value={getOptionValue(item)}>
{getOptionLabel(item)}
</SelectItem>
))
)}
</SelectContent>
);

const coachingSessions = groupByDate
? (items.filter(isCoachingSession) as CoachingSession[])
: [];

return (
<Select value={value} onValueChange={handleValueChange}>
<SelectTrigger id={elementId}>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
{groupByDate && coachingSessions.length > 0
? renderCoachingSessions(coachingSessions)
: renderOtherItems(items)}
</Select>
);
}
133 changes: 133 additions & 0 deletions src/components/ui/dashboard/join-coaching-session.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import React from "react";
import { useAppStateStore } from "@/lib/providers/app-state-store-provider";
import { Id } from "@/types/general";
import { DynamicApiSelect } from "./dynamic-api-select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Organization } from "@/types/organization";
import { CoachingRelationshipWithUserNames } from "@/types/coaching_relationship_with_user_names";
import {
CoachingSession,
} from "@/types/coaching-session";
import { DateTime } from "ts-luxon";
import { Label } from "@/components/ui/label";
import { Button } from "../button";
import Link from "next/link";

export interface CoachingSessionCardProps {
userId: Id;
}

export function JoinCoachingSession({
userId: userId,
}: CoachingSessionCardProps) {

const FROM_DATE = DateTime.now().minus({ month: 1 }).toISODate();
const TO_DATE = DateTime.now().plus({ month: 1 }).toISODate();

const {
organization,
organizationId,
relationship,
relationshipId,
coachingSession,
coachingSessionId,
setOrganizationId,
setRelationshipId,
setCoachingSessionId
} = useAppStateStore(state => ({
organization: state.setOrganization,
organizationId: state.organizationId,
relationship: state.setCoachingRelationship,
relationshipId: state.relationshipId,
coachingSession: state.setCoachingSession,
coachingSessionId: state.coachingSessionId,
setOrganizationId: state.setOrganizationId,
setRelationshipId: state.setRelationshipId,
setCoachingSessionId: state.setCoachingSessionId
}));

// TODO: pass Organization type
const handleOrganizationSelection = (value: string) => {
setOrganizationId(value);
}

// TODO: pass Relationship type
const handleRelationshipSelection = (value: string) => {
setRelationshipId(value);
setCoachingSessionId;
}

// TODO: pass CoachingSession type
const handleSessionSelection = (value: string) => {
setCoachingSessionId(value);
}

return (
<Card className="w-[300px]">
<CardHeader>
<CardTitle>Join a Coaching Session</CardTitle>
</CardHeader>
<CardContent className="grid gap-6">
<div className="grid gap-2">
<Label htmlFor="organization-selector">Organization</Label>

<DynamicApiSelect<Organization>
url="/organizations"
params={{ userId }}
onChange={handleOrganizationSelection}
placeholder="Select an organization"
getOptionLabel={(org) => org.name}
getOptionValue={(org) => org.id}
elementId="organization-selector"
/>
</div>
{organizationId.length > 0 && (
<div className="grid gap-2">
<Label htmlFor="relationship-selector">Relationship</Label>

<DynamicApiSelect<CoachingRelationshipWithUserNames>
url={`/organizations/${organizationId}/coaching_relationships`}
params={{ organizationId: organizationId }}
onChange={handleRelationshipSelection}
placeholder="Select coaching relationship"
getOptionLabel={(relationship) =>
`${relationship.coach_first_name} ${relationship.coach_last_name} -> ${relationship.coachee_first_name} ${relationship.coach_last_name}`
}
getOptionValue={(relationship) => relationship.id}
elementId="relationship-selector"
/>
</div>
)}
{relationshipId.length > 0 && (
<div className="grid gap-2">
<Label htmlFor="session-selector">Coaching Session</Label>

<DynamicApiSelect<CoachingSession>
url="/coaching_sessions"
params={{
coaching_relationship_id: relationshipId,
from_date: FROM_DATE,
to_Date: TO_DATE,
}}
onChange={handleSessionSelection}
placeholder="Select coaching session"
getOptionLabel={(session) => session.date}
getOptionValue={(session) => session.id}
elementId="session-selector"
groupByDate={true}
/>
</div>
)}
{coachingSessionId.length > 0 && (
<div className="grid gap-2">
<Button variant="outline" className="w-full">
<Link href={`/coaching-sessions/${coachingSessionId}`}>
Join Session
</Link>
</Button>
</div>
)}
</CardContent>
</Card>
);
}
Loading
Loading