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;
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>("");

const handleValueChange = (newValue: string) => {
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>
);
}
153 changes: 153 additions & 0 deletions src/components/ui/dashboard/join-coaching-session.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
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,
getCoachingSessionById,
} from "@/types/coaching-session";
import { DateTime } from "ts-luxon";
import { Label } from "@/components/ui/label";
import { Button } from "../button";
import Link from "next/link";
import { fetchOrganization } from "@/lib/api/organizations";
import { fetchCoachingRelationshipWithUserNames } from "@/lib/api/coaching-relationships";
import { fetchCoachingSessions } from "@/lib/api/coaching-sessions";

export interface CoachingSessionCardProps {
userId: Id;
}

export function JoinCoachingSession({
userId: userId,
}: CoachingSessionCardProps) {
const { setOrganizationId } = useAppStateStore((state) => ({
setOrganizationId: state.setOrganizationId,
}));
const { setRelationshipId } = useAppStateStore((state) => ({
setRelationshipId: state.setRelationshipId,
}));
const { setCoachingSessionId } = useAppStateStore((state) => ({
setCoachingSessionId: state.setCoachingSessionId,
}));
const { organization, setOrganization } = useAppStateStore((state) => ({
organization: state.organization,
setOrganization: state.setOrganization,
}));
const { relationship, setRelationship } = useAppStateStore((state) => ({
relationship: state.coachingRelationship,
setRelationship: state.setCoachingRelationship,
}));
const { coachingSession, setCoachingSession } = useAppStateStore((state) => ({
coachingSession: state.coachingSession,
setCoachingSession: state.setCoachingSession,
}));
const FROM_DATE = DateTime.now().minus({ month: 1 }).toISODate();
const TO_DATE = DateTime.now().plus({ month: 1 }).toISODate();

const handleOrganizationSelection = (id: Id) => {
fetchOrganization(id)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@qafui This is what I'm referring to, can we/should we rework fetchOrganization to use your use-api-data in this PR, or do that across the board in a second fast-follower PR? I'm open to either option.

.then((organization) => {
setOrganizationId(organization.id);
setOrganization(organization);
})
.catch((err) => {
console.error("Failed to retrieve and set organization: " + err);
});
};

const handleRelationshipSelection = (id: Id) => {
fetchCoachingRelationshipWithUserNames(organization.id, id)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@qafui Same thing here...

.then((relationship) => {
setRelationshipId(relationship.id);
setRelationship(relationship);
})
.catch((err) => {
console.error("Failed to retrieve and set relationship: " + err);
});
};

const handleSessionSelection = (id: Id) => {
fetchCoachingSessions(relationship.id)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@qafui and here again...

.then((sessions) => {
const session = getCoachingSessionById(id, sessions);
setCoachingSessionId(session.id);
setCoachingSession(session);
})
.catch((err) => {
console.error("Failed to retrieve and set relationship: " + err);
});
};

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} // FIXME: this doesn't seem to display the currently selected organization when the page loads and the org.id is set
elementId="organization-selector"
/>
</div>
{organization.id.length > 0 && (
<div className="grid gap-2">
<Label htmlFor="relationship-selector">Relationship</Label>

<DynamicApiSelect<CoachingRelationshipWithUserNames>
url={`/organizations/${organization.id}/coaching_relationships`}
params={{ organizationId: organization.id }}
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>
)}
{relationship.id.length > 0 && (
<div className="grid gap-2">
<Label htmlFor="session-selector">Coaching Session</Label>

<DynamicApiSelect<CoachingSession>
url="/coaching_sessions"
params={{
coaching_relationship_id: relationship.id,
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>
)}
{coachingSession.id.length > 0 && (
<div className="grid gap-2">
<Button variant="outline" className="w-full">
<Link href={`/coaching-sessions/${coachingSession.id}`}>
Join Session
</Link>
</Button>
</div>
)}
</CardContent>
</Card>
);
}
Loading
Loading