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

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"@radix-ui/react-collapsible": "^1.1.1",
"@radix-ui/react-dialog": "^1.1.2",
"@radix-ui/react-dropdown-menu": "^2.1.2",
"@radix-ui/react-select": "^2.1.2",
"@radix-ui/react-separator": "^1.1.0",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.1",
Expand Down
65 changes: 65 additions & 0 deletions pnpm-lock.yaml

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

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

import { db } from "@/db";
import {
availabilities,
AvailabilityInsertSchema,
meetingDates,
MeetingDateSelectSchema,
membersInMeeting,
} from "@/db/schema";
import { getExistingMeeting } from "@/lib/db/databaseUtils";
import { ZotDate } from "@/lib/zotdate";
import { eq, 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 _getMeetingDates(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",
},
};
}
}

export async function _getMeetingDates(
Copy link
Member

Choose a reason for hiding this comment

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

move this function outside of the server action file, as this will otherwise also be exposed to be callable by the client

meetingId: string
): Promise<MeetingDateSelectSchema[]> {
const dbMeeting = await getExistingMeeting(meetingId);
const dbMeetingDates = await db
.select()
.from(meetingDates)
.where(eq(meetingDates.meeting_id, dbMeeting.id));

return dbMeetingDates.sort((a, b) => (a.date < b.date ? -1 : 1));
}
71 changes: 71 additions & 0 deletions src/actions/creation/createMeeting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"use server";

import { getUserIdFromSession, insertMeeting } from "@/lib/db/databaseUtils";
import { CreateMeetingPostParams } from "@/lib/types/meetings";

export async function createMeeting(newMeeting: CreateMeetingPostParams) {
try {
const {
title,
description,
fromTime,
toTime,
meetingDates,
sessionId,
} = newMeeting;

console.log(
"Creating meeting:",
title,
description,
fromTime,
toTime,
meetingDates
);

// Validate the input data
if (fromTime >= toTime) {
return { error: "From time must be before to time" };
}

if (!meetingDates || meetingDates.length === 0) {
return { error: "At least one date must be provided" };
}

// Limit the number of dates to prevent abuse
if (meetingDates.length > 100) {
return { error: "Too many dates provided" };
}

// Sort the dates in UTC order
const sortedDates = meetingDates
.map((dateString) => new Date(dateString))
.sort((a, b) => a.getTime() - b.getTime());

// Retrieve the host ID if the session ID is provided
const host_id = sessionId
? await getUserIdFromSession(sessionId)
: undefined;

// Prepare the meeting data
const meeting = {
title,
description: description || "",
from_time: fromTime,
to_time: toTime,
host_id,
};

// Insert the meeting into the database
const meetingId = await insertMeeting(meeting, sortedDates);

// Return the created meeting ID
return { meetingId };
} catch (err) {
const error = err as Error;
console.error("Error creating meeting:", error.message);

// Return a 500 error response
return { error: `Error creating meeting: ${error.message}` };
}
}
7 changes: 5 additions & 2 deletions src/app/availability/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,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) {
redirect("/error");
Expand All @@ -38,7 +37,11 @@ export default async function Page({ params }: PageProps) {
}

const meetingDates = await getMeetingDates(slug);
const availability = user ? await getAvailability(user, 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
4 changes: 3 additions & 1 deletion src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Creation } from "@/components/creation/creation";

export default function Home() {
return <div className="p-4">ZotMeet</div>;
return <Creation />;
}
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
Loading