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

feat: hook up actions #127

Merged
merged 20 commits into from
Jan 12, 2025
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
209 changes: 131 additions & 78 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

99 changes: 99 additions & 0 deletions src/actions/availability/saveAvailability.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"use server";

import { db } from "@/db";
import {
availabilities,
AvailabilityInsertSchema,
MeetingDateSelectSchema,
membersInMeeting,
} from "@/db/schema";
import { getExistingMeetingDates } from "@/lib/db/databaseUtils";
import { ZotDate } from "@/lib/zotdate";
import { sql } from "drizzle-orm";

interface saveAvailabilityProps {
meetingId: string;
availabilityDates: Pick<ZotDate, "day" | "availability">[];
}

export async function saveAvailability({
meetingId,
availabilityDates,
}: saveAvailabilityProps) {
// const user: User | null = locals.user;

let dbMeetingDates: MeetingDateSelectSchema[] = [];

try {
dbMeetingDates = await getExistingMeetingDates(meetingId);
} catch (e) {
console.log("Error getting meeting dates:", e);
}

if (!dbMeetingDates || dbMeetingDates.length === 0) {
return;
}

try {
// const memberId =
// user?.id ??
// (
// await getExistingGuest(
// formData.get("username") as string,
// await getExistingMeeting(meetingId)
// )
// ).id;

const memberId = "123";

const insertDates: AvailabilityInsertSchema[] = availabilityDates.map(
(date, index) => ({
day: new Date(date.day).toISOString(),
member_id: memberId,
meeting_day: dbMeetingDates[index].id as string, // Type-cast since id is guaranteed if a meetingDate exists
availability_string: date.availability
.map((bool) => (bool ? "1" : "0"))
.join(""),
})
);

await db.transaction(async (tx) => {
await Promise.all([
tx
.insert(availabilities)
.values(insertDates)
.onConflictDoUpdate({
target: [
availabilities.member_id,
availabilities.meeting_day,
],
set: {
// `excluded` refers to the row currently in conflict
availability_string: sql.raw(
`excluded.availability_string`
),
},
}),
tx
.insert(membersInMeeting)
.values({ memberId, meetingId, attending: "maybe" })
.onConflictDoNothing(),
]);
});

return {
status: 200,
body: {
message: "Saved successfully",
},
};
} catch (error) {
console.log("Error saving availabilities:", error);
return {
status: 500,
body: {
error: "Failed to save",
},
};
}
}
16 changes: 11 additions & 5 deletions src/app/availability/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ import {
getTimeFromHourMinuteString,
SAMPLE_MEMBERS,
} from "@/lib/availability/utils";
import { getExistingMeeting } from "@/lib/db/databaseUtils";
import { getAvailability, getMeetingDates } from "@/lib/db/utils";
import {
getAvailability,
getExistingMeeting,
getExistingMeetingDates,
} from "@/lib/db/databaseUtils";
import { HourMinuteString } from "@/lib/types/chrono";
import { cn } from "@/lib/utils";

Expand All @@ -25,7 +28,6 @@ interface PageProps {

export default async function Page({ params }: PageProps) {
const { slug } = params;
const user = { id: "123" }; // TODO (#auth): replace with actual user from session

if (!slug) {
notFound();
Expand All @@ -42,8 +44,12 @@ export default async function Page({ params }: PageProps) {
notFound();
}

const meetingDates = await getMeetingDates(slug);
const availability = user ? await getAvailability(user, slug) : [];
const meetingDates = await getExistingMeetingDates(slug);
// const availability = user ? await getAvailability(user, slug) : [];
const availability = await getAvailability({
userId: "123", // TODO (#auth): replace with actual user from session
meetingId: meetingData.id,
});

const availabilityTimeBlocks = generateTimeBlocks(
getTimeFromHourMinuteString(meetingData.from_time as HourMinuteString),
Expand Down
16 changes: 15 additions & 1 deletion src/components/availability/availability-header.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client";

import { saveAvailability } from "@/actions/availability/saveAvailability";
import { useAvailabilityContext } from "@/components/availability/context/availability-context";
import { Button } from "@/components/ui/button";
import { MeetingSelectSchema } from "@/db/schema";
Expand Down Expand Up @@ -27,9 +28,21 @@ export function AvailabilityHeader({ meetingData }: AvailabilityHeaderProps) {
setIsStateUnsaved(false);
};

const handleSave = async () => {
const availability = {
meetingId: meetingData.id,
availabilityDates: availabilityDates.map((date) => ({
day: date.day,
availability: date.availability,
})),
};

await saveAvailability(availability);
};

return (
<div className="flex-between px-2 pt-8 md:px-4 md:pt-10 lg:px-[60px]">
<h1 className="font-montserrat line-clamp-1 h-8 pr-2 text-xl font-medium md:h-fit md:text-3xl">
<h1 className="line-clamp-1 h-8 pr-2 font-montserrat text-xl font-medium md:h-fit md:text-3xl">
{meetingData.title}
</h1>

Expand Down Expand Up @@ -87,6 +100,7 @@ export function AvailabilityHeader({ meetingData }: AvailabilityHeaderProps) {
"group hover:border-green-500 hover:bg-green-500"
)}
type="submit"
onClick={handleSave}
>
<span className="hidden text-green-500 group-hover:text-white md:flex">
Save
Expand Down
43 changes: 18 additions & 25 deletions src/components/availability/personal-availability.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -179,31 +179,24 @@ export function PersonalAvailability({
}, [isStateUnsaved]);

useEffect(() => {
const init = async () => {
// const generalAvailability = await getGeneralAvailability(
// meetingData,
// guestSession
// );

const generalAvailability: Array<unknown> | null = null;

const defaultMeetingDates = meetingDates.map(
(item) => new ZotDate(item.date, false, [])
);

ZotDate.initializeAvailabilities(defaultMeetingDates);

setAvailabilityDates(
// ! fix this
// @ts-expect-error trust me bro
generalAvailability && generalAvailability.length > 0
? generalAvailability
: defaultMeetingDates
);
};
if (!availability) {
setAvailabilityDates([]);
return;
}

init();
}, [meetingData, meetingDates, setAvailabilityDates]);
setAvailabilityDates(
availability?.map(
(availability) =>
new ZotDate(
new Date(availability.meeting_dates.date),
false,
Array.from(
availability.availabilities.availability_string
).map((char) => char === "1")
)
)
);
}, [availability, setAvailabilityDates]);

const handlePrevPage = () => {
if (currentPage > 0) {
Expand All @@ -219,7 +212,7 @@ export function PersonalAvailability({

return (
<div>
<div className="font-dm-sans flex items-center justify-between overflow-x-auto">
<div className="flex items-center justify-between overflow-x-auto font-dm-sans">
<AvailabilityNavButton
direction="left"
handleClick={handlePrevPage}
Expand Down
39 changes: 39 additions & 0 deletions src/components/creation/calendar/calendar-body-day-cell.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React from "react";
import { cn } from "@/lib/utils";
import { ZotDate } from "@/lib/zotdate";

interface CalendarBodyDayCellProps {
isHighlighted: boolean;
calendarDay: ZotDate;
isCurrentMonth: boolean;
}

export function CalendarBodyDayCell({
isHighlighted,
calendarDay,
isCurrentMonth,
}: CalendarBodyDayCellProps) {
const isSelected = calendarDay.isSelected;

return (
<p
className={cn(
"flex-center relative aspect-square h-8 w-8 rounded-lg text-base font-medium text-gray-dark md:h-12 md:w-12 md:rounded-xl md:text-xl",
isSelected && "bg-primary text-gray-50",
isHighlighted && "bg-slate-base text-gray-dark",
!isCurrentMonth &&
cn(
"text-gray-base",
isHighlighted && "bg-opacity-30",
isSelected && "bg-opacity-50 text-gray-100"
)
)}
data-day={calendarDay.getDay()}
data-month={calendarDay.getMonth()}
data-year={calendarDay.getYear()}
data-selected={isSelected}
>
{calendarDay.getDay()}
</p>
);
}
4 changes: 2 additions & 2 deletions src/components/creation/calendar/calendar-body-day.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Dispatch, SetStateAction } from "react";
import { CalendarBodyDaySquare } from "@/components/creation/calendar/calendar-body-day-square";
import { CalendarBodyDayCell } from "@/components/creation/calendar/calendar-body-day-cell";
import { ZotDate } from "@/lib/zotdate";

interface CalendarBodyDayProps {
Expand Down Expand Up @@ -111,7 +111,7 @@ export function CalendarBodyDay({
onMouseDown={handleMouseDown}
className="relative flex w-full cursor-pointer select-none justify-center py-2"
>
<CalendarBodyDaySquare
<CalendarBodyDayCell
isHighlighted={!!isHighlighted}
calendarDay={calendarDay}
isCurrentMonth={isCurrentMonth}
Expand Down
32 changes: 8 additions & 24 deletions src/components/nav/app-nav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,36 +15,20 @@ import {
SidebarMenuItem,
} from "@/components/ui/sidebar";
import { UserProfile } from "@/lib/auth/user";
import {
BookOpen,
Bot,
Command,
Settings2,
SquareTerminal,
} from "lucide-react";
import { CalendarSearchIcon, Command, SquarePlusIcon } from "lucide-react";

const data = {
navMain: [
{
title: "Playground",
url: "#",
icon: SquareTerminal,
title: "New Meeting",
url: "/",
icon: SquarePlusIcon,
isActive: true,
},
{
title: "Models",
url: "#",
icon: Bot,
},
{
title: "Documentation",
url: "#",
icon: BookOpen,
},
{
title: "Settings",
url: "#",
icon: Settings2,
title: "Summary",
url: "/summary",
icon: CalendarSearchIcon,
},
],
};
Expand Down Expand Up @@ -88,7 +72,7 @@ export function SidebarComponent({ user, ...props }: SidebarComponentProps) {
className="hover:bg-inherit active:bg-inherit"
>
<a
href="#"
href="/"
className="space-gray-800 space-x-2"
>
<div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
Expand Down
31 changes: 30 additions & 1 deletion src/lib/db/databaseUtils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { db } from "@/db";
import {
availabilities,
AvailabilityMeetingDateJoinSchema,
GuestInsertSchema,
guests,
MeetingDateInsertSchema,
Expand Down Expand Up @@ -164,5 +166,32 @@ export const getExistingMeetingDates = async (meetingId: string) => {
.from(meetingDates)
.where(eq(meetingDates.meeting_id, meetingId));

return dbMeetingDates;
return dbMeetingDates.sort((a, b) => (a.date < b.date ? -1 : 1));
};

// TODO (#auth): Replace `user` with User type
export const getAvailability = async ({
userId,
meetingId,
}: {
userId: string;
meetingId: string;
}): Promise<AvailabilityMeetingDateJoinSchema[]> => {
const availability = await db
.select()
.from(availabilities)
.innerJoin(
meetingDates,
eq(availabilities.meeting_day, meetingDates.id)
)
.where(
and(
eq(availabilities.member_id, userId),
eq(meetingDates.meeting_id, meetingId || "")
)
);

return availability.sort((a, b) =>
a.meeting_dates.date > b.meeting_dates.date ? 1 : -1
);
};
Loading