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 #34

Closed
wants to merge 14 commits into from
32 changes: 24 additions & 8 deletions package-lock.json

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

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,11 @@
"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",
"zustand": "^4.5.2"
"zustand": "^4.5.5"
},
"devDependencies": {
"@types/node": "^20",
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
144 changes: 144 additions & 0 deletions src/components/ui/dashboard/dynamic-api-select.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import React from "react";
import { useApiData } from "@/hooks/use-api-data";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { CoachingSession, isCoachingSession } from "@/types/coaching-session";
import { DateTime } from "ts-luxon";
import { getRefactorType, Id } from "@/types/general";
import { useAppStateStore } from "@/lib/providers/app-state-store-provider";

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;
elementId: string;
groupByDate?: boolean;
}

export 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 [value, setValue] = React.useState<string>("");
const setRefactorDataType = useAppStateStore(
(state) => state.setRefactorDataType
);

const {
data: response,
isLoading,
error,
} = useApiData<ApiResponse<T>>(url, { method, params });

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 = getRefactorType(response.data);

const handleValueChange = (newValue: string) => {
setValue(newValue);
};

const renderSessions = (
sessions: CoachingSession[],
label: string,
filterFn: (session: CoachingSession) => boolean
) => {
const filteredSessions = sessions.filter(filterFn);
return (
filteredSessions.length > 0 && (
<SelectGroup>
<SelectLabel>{label}</SelectLabel>
{filteredSessions.map((session) => (
<SelectItem value={session.id} key={session.id}>
{DateTime.fromISO(session.date.toString()).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.toString()) < DateTime.now()
)}
{renderSessions(
sessions,
"Upcoming Sessions",
(session) =>
DateTime.fromISO(session.date.toString()) >= DateTime.now()
)}
</>
)}
</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.value.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.value)}
</Select>
);
}
115 changes: 115 additions & 0 deletions src/components/ui/dashboard/join-coaching-session.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import React, { useState } 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 setOrganizationId = useAppStateStore(
(state) => state.setOrganizationId
);
const setRelationshipId = useAppStateStore(
(state) => state.setRelationshipId
);
const setCoachingSessionId = useAppStateStore(
(state) => state.setCoachingSessionId
);
const [organizationId, setOrganization] = useState<string | null>(null);
const [relationshipId, setRelationship] = useState<string | null>(null);
const [sessionId, setSessions] = useState<string | null>(null);
const FROM_DATE = DateTime.now().minus({ month: 1 }).toISODate();
const TO_DATE = DateTime.now().plus({ month: 1 }).toISODate();

const handleOrganizationSelection = (value: string) => {
setOrganizationId(value);
};

const handleRelationshipSelection = (value: string) => {
setRelationshipId(value);
};

const handleSessionSelection = (value: string) => {
setSessions(value);
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="setOrganization">Organization</Label>

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

<DynamicApiSelect<CoachingRelationshipWithUserNames>
url={`/organizations/${organizationId}/coaching_relationships`}
params={{ 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.toString()}
elementId="setCoachingRelationships"
/>
</div>
)}
{relationshipId && (
<div className="grid gap-2">
<Label htmlFor="setCoachingSessions">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.toString()}
getOptionValue={(session) => session.id.toString()}
elementId="setCoachingSessions"
groupByDate={true}
/>
</div>
)}
{sessionId && (
<div className="grid gap-2">
<Button variant="outline" className="w-full">
<Link href={`/coaching-sessions/${sessionId}`}>Join Session</Link>
</Button>
</div>
)}
</CardContent>
</Card>
);
}
Loading
Loading