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: sync plans between devices #103

Merged
merged 20 commits into from
Dec 10, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
566 changes: 386 additions & 180 deletions frontend/package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,14 @@
"lucide-react": "^0.426.0",
"next": "^15.0.3",
"next-sitemap": "^4.2.3",
"next-themes": "^0.4.3",
"node-fetch": "^3.3.2",
"oauth-1.0a": "^2.2.6",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-icons": "^5.3.0",
"sharp": "^0.33.5",
"sonner": "^1.7.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.2",
Expand Down
1 change: 1 addition & 0 deletions frontend/src/actions/logout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const signOutFunction = async () => {
name: "access_token_secret",
path: "/",
});
await fetch("/api/v1/user", { method: "DELETE" });

return true;
};
81 changes: 81 additions & 0 deletions frontend/src/actions/plans.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"use server";

import { revalidatePath } from "next/cache";

import { auth, fetchToAdonis } from "@/lib/auth";

interface CreatePlanResponseType {
message: string;
schedule: {
name: string;
userId: number;
createdAt: string;
updatedAt: string;
id: number;
};
}

export const createNewPlan = async ({ name }: { name: string }) => {
const isLogged = await auth({});
qamarq marked this conversation as resolved.
Show resolved Hide resolved
if (!isLogged) {
return false;
}

const data = await fetchToAdonis<CreatePlanResponseType>({
url: "/user/schedules",
method: "POST",
body: JSON.stringify({ name }),
});
if (!data) {
return false;
}
return data;
};

export const updatePlan = async ({
id,
name,
courses,
registrations,
groups,
}: {
id: number;
name: string;
courses: Array<{ id: string }>;
registrations: Array<{ id: string }>;
groups: Array<{ id: number }>;
}) => {
const isLogged = await auth({});
if (!isLogged) {
return false;
}

const data = await fetchToAdonis<CreatePlanResponseType>({
url: `/user/schedules/${id}`,
method: "PATCH",
body: JSON.stringify({ name, courses, registrations, groups }),
});
if (!data) {
return false;
}
qamarq marked this conversation as resolved.
Show resolved Hide resolved
return data;
};

export const deletePlan = async ({ id }: { id: number }) => {
console.log(id);
const isLogged = await auth({});
if (!isLogged) {
return false;
}

const data = await fetchToAdonis<CreatePlanResponseType>({
url: `/user/schedules/${id}`,
method: "DELETE",
});
console.log(data);
if (!data) {
return false;
}
revalidatePath("/plans");
return data;
};
2 changes: 2 additions & 0 deletions frontend/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Script from "next/script";
import type React from "react";

import ClientProviders from "@/components/Providers";
import { Toaster } from "@/components/ui/sonner";
import { env } from "@/env.mjs";
import { cn } from "@/lib/utils";
import type { UmamiTracker } from "@/types/umami";
Expand Down Expand Up @@ -105,6 +106,7 @@ export default function RootLayout({
data-website-id="ab126a0c-c0ab-401b-bf9d-da652aab69ec"
data-domains="planer.solvro.pl"
/>
<Toaster richColors={true} />
</body>
</ClientProviders>
</html>
Expand Down
121 changes: 121 additions & 0 deletions frontend/src/app/plans/_components/PlansPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"use client";

import { atom, useAtom } from "jotai";
import { PlusIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useRef } from "react";

import type { ExtendedCourse } from "@/atoms/planFamily";
import { planFamily } from "@/atoms/planFamily";
import { plansIds } from "@/atoms/plansIds";
import { PlanItem } from "@/components/PlanItem";
import type { Registration } from "@/lib/types";

import type { PlanResponseDataType } from "../page";

const plansAtom = atom(
(get) => get(plansIds).map((id) => get(planFamily(id))),
(get, set, values: Array<{ id: string }>) => {
set(plansIds, values);
},
);
export function PlansPage({
plans: onlinePlans,
}: {
plans: PlanResponseDataType[];
}) {
const [plans, setPlans] = useAtom(plansAtom);
const router = useRouter();
const firstTime = useRef(true);
Copy link
Member

Choose a reason for hiding this comment

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

fu

Copy link
Member Author

Choose a reason for hiding this comment

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

?


const addNewPlan = () => {
const uuid = crypto.randomUUID();
const newPlan = {
id: uuid,
};

void window.umami?.track("Create plan", {
numberOfPlans: plans.length,
});

router.push(`/plans/edit/${newPlan.id}`);
setPlans([...plans, newPlan]);
};

const handleCreateOfflinePlansIfNotExists = () => {
if (firstTime.current) {
firstTime.current = false;
const tmpPlans: Array<{
id: string;
name: string;
synced: boolean;
onlineId: string;
courses: ExtendedCourse[];
registrations: Registration[];
createdAt: Date;
updatedAt: Date;
}> = [];
onlinePlans.forEach((onlinePlan) => {
if (plans.some((plan) => plan.onlineId === onlinePlan.id.toString())) {
return;
}

const uuid = crypto.randomUUID();
const newPlan = {
id: uuid,
name: onlinePlan.name,
synced: true,
onlineId: onlinePlan.id.toString(),
courses: onlinePlan.courses,
registrations: onlinePlan.registrations,
createdAt: new Date(onlinePlan.createdAt),
updatedAt: new Date(onlinePlan.updatedAt),
};

tmpPlans.push(newPlan);
});
setPlans([...plans, ...tmpPlans]);
}
};

// useEffect(() => {
// handleCreateOfflinePlansIfNotExists();
// }, []);

return (
<div className="container mx-auto max-h-full flex-1 flex-grow overflow-y-auto p-4">
<div className="grid grid-cols-2 gap-4 sm:justify-start md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6">
<button
onClick={addNewPlan}
className="group flex aspect-square items-center justify-center rounded-lg border-2 border-dashed border-gray-400 p-4 shadow-md transition-all hover:border-primary hover:bg-primary/5 hover:shadow-xl"
>
<PlusIcon className="h-24 w-24 text-gray-400 transition-colors group-hover:text-primary" />
</button>
{plans.map((plan) => (
<PlanItem
key={plan.id}
id={plan.id}
name={plan.name}
synced={false}
onlineId={plan.onlineId}
/>
))}
{onlinePlans.map((plan) => {
if (plans.some((p) => p.onlineId === plan.id.toString())) {
return null;
}
return (
<PlanItem
key={plan.id}
id={plan.id.toString()}
name={plan.name}
synced={true}
onlineId={plan.id.toString()}
onlineOnly={true}
/>
);
})}
</div>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

import { useMutation, useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { MdArrowBack } from "react-icons/md";
import { toast } from "sonner";

import { createNewPlan, updatePlan } from "@/actions/plans";
import type { ExtendedCourse, ExtendedGroup } from "@/atoms/planFamily";
import { ClassSchedule } from "@/components/ClassSchedule";
import { GroupsAccordionItem } from "@/components/GroupsAccordion";
Expand All @@ -27,6 +29,8 @@ import { registrationReplacer } from "@/lib/utils";
import type { LessonType } from "@/services/usos/types";
import { Day } from "@/services/usos/types";

import { SyncedButton } from "./SyncedButton";

type CourseType = Array<{
id: string;
name: string;
Expand Down Expand Up @@ -57,10 +61,61 @@ export function CreateNewPlanPage({
planId: string;
faculties: Array<{ name: string; value: string }>;
}) {
const [syncing, setSyncing] = useState(false);
const firstTime = useRef(true);

const plan = usePlan({
planId,
});

const handleCreateOnlinePlan = async () => {
firstTime.current = false;
const res = await createNewPlan({ name: plan.name });
if (res === false) {
return toast.error("Nie udało się utworzyć planu");
}
plan.setOnlineId(res.schedule.id.toString());
toast.success("Utworzono plan");
return true;
};

const handleSyncPlan = async () => {
setSyncing(true);
try {
const res = await updatePlan({
id: Number(plan.onlineId),
name: plan.name,
courses: plan.courses
.filter((c) => c.isChecked)
.map((c) => ({ id: c.id })),
registrations: plan.registrations.map((r) => ({ id: r.id })),
groups: plan.allGroups
.filter((g) => g.isChecked)
.map((g) => ({ id: g.groupOnlineId })),
});
if (res === false) {
return toast.error("Nie udało się zaktualizować planu");
}
toast.success("Zaktualizowano plan");
plan.setSynced(true);
return true;
} finally {
setSyncing(false);
}
};

useEffect(() => {
if (plan.onlineId === null && firstTime.current) {
void handleCreateOnlinePlan();
}
}, [plan]);
Comment on lines +149 to +153
Copy link
Member

Choose a reason for hiding this comment

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

ohydne


// useEffect(() => {
// if (!plan.synced && plan.onlineId !== null && !firstTime.current) {
// void handleUpdatePlan();
// }
// }, [plan.onlineId, plan.synced, firstTime]);

const inputRef = useRef<HTMLInputElement>(null);

const [faculty, setFaculty] = useState<string | null>(null);
Expand Down Expand Up @@ -99,8 +154,8 @@ export function CreateNewPlanPage({
<div className="flex w-full flex-1 flex-col items-center justify-center gap-5 py-3 md:flex-row md:items-start">
<div className="flex max-h-screen w-full flex-none flex-col items-center justify-center gap-2 px-2 md:ml-4 md:w-[350px] md:flex-col">
<div className="flex flex-col justify-start gap-3 md:w-full">
<div className="flex w-full items-end gap-2">
<div className="flex items-end gap-2">
<div className="flex w-full items-end gap-1">
<div className="flex items-end gap-1">
<Button
variant="outline"
className="aspect-square"
Expand Down Expand Up @@ -138,6 +193,12 @@ export function CreateNewPlanPage({
</div>
</form>
</div>
<SyncedButton
synced={plan.synced}
onlineId={plan.onlineId}
syncing={syncing}
onClick={handleSyncPlan}
/>
<PlanDisplayLink id={plan.id} />
</div>
</div>
Expand Down Expand Up @@ -207,6 +268,7 @@ export function CreateNewPlanPage({
({
groupId: g.group + c.id + g.type,
groupNumber: g.group.toString(),
groupOnlineId: g.id,
courseId: c.id,
courseName: c.name,
isChecked: false,
Expand Down
Loading
Loading