Compare commits
6 Commits
1f289e8545
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| ec81492d49 | |||
| 562302b5a0 | |||
| df36c180af | |||
| a53687d0f8 | |||
| 4d1264417e | |||
| 9e3c9ba016 |
@@ -4,22 +4,8 @@ import { FunctionComponent, h } from "preact";
|
|||||||
import { useLocation } from "preact-iso";
|
import { useLocation } from "preact-iso";
|
||||||
import { tv } from "tailwind-variants";
|
import { tv } from "tailwind-variants";
|
||||||
import classes from "./menu.module.scss";
|
import classes from "./menu.module.scss";
|
||||||
|
import { calculatePoints, getCurrentStatus } from "@/utils/status-system";
|
||||||
import { useEffect, useState } from "preact/hooks";
|
import { useEffect, useState } from "preact/hooks";
|
||||||
import apiClient from "@/services/api";
|
|
||||||
import { useAppContext } from "@/providers/AuthProvider";
|
|
||||||
|
|
||||||
interface UserProfile {
|
|
||||||
username: string;
|
|
||||||
email: string;
|
|
||||||
status: string;
|
|
||||||
avatar_url: string | null;
|
|
||||||
telegram_notifications: boolean;
|
|
||||||
telegram_chat_id: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface UserSettings {
|
|
||||||
profile: UserProfile;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MenuItemProps {
|
interface MenuItemProps {
|
||||||
title: string;
|
title: string;
|
||||||
@@ -50,27 +36,32 @@ const MenuItem: FunctionComponent<MenuItemProps> = ({ title, link, icon }: MenuI
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const Avatar: FunctionComponent = () => {
|
const Avatar: FunctionComponent = () => {
|
||||||
const [status, setStatus] = useState("");
|
const [status, setStatus] = useState("");
|
||||||
const [username, setUsername] = useState("");
|
|
||||||
const { route, path } = useLocation();
|
const { route, path } = useLocation();
|
||||||
const { isLoggedIn } = useAppContext();
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchUserData = async () => {
|
const updateStatus = () => {
|
||||||
try {
|
const tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
|
||||||
const response = await apiClient<UserSettings>("/api/settings/view_settings/", { method: "GET" }, isLoggedIn);
|
const completedTasks = tasks.filter((task: { checked: boolean }) => task.checked).length;
|
||||||
setUsername(response.profile.username);
|
const points = calculatePoints(completedTasks);
|
||||||
setStatus(response.profile.status);
|
setStatus(getCurrentStatus(points));
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to fetch user data:", error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (isLoggedIn.value) {
|
// Initial update
|
||||||
fetchUserData();
|
updateStatus();
|
||||||
}
|
|
||||||
}, [isLoggedIn.value]);
|
// Update when tasks change
|
||||||
|
const handleStorage = (e: StorageEvent) => {
|
||||||
|
if (e.key === "tasks") {
|
||||||
|
updateStatus();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('storage', handleStorage);
|
||||||
|
return () => window.removeEventListener('storage', handleStorage);
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
@@ -86,7 +77,7 @@ const Avatar: FunctionComponent = () => {
|
|||||||
>
|
>
|
||||||
<div class="my-5 aspect-square h-full rounded-full bg-white"></div>
|
<div class="my-5 aspect-square h-full rounded-full bg-white"></div>
|
||||||
<div class="flex flex-col items-center justify-center">
|
<div class="flex flex-col items-center justify-center">
|
||||||
<p class="text-3xl font-semibold">{username}</p>
|
<p class="text-3xl font-semibold">никнейм</p>
|
||||||
<div class="rounded-[1rem] bg-white px-5 leading-5 font-light italic">{status}</div>
|
<div class="rounded-[1rem] bg-white px-5 leading-5 font-light italic">{status}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import Input from "@/components/ui/Input";
|
|||||||
import { withTitle } from "@/constructors/Component";
|
import { withTitle } from "@/constructors/Component";
|
||||||
import { UrlsTitle } from "@/enums/urls";
|
import { UrlsTitle } from "@/enums/urls";
|
||||||
import { useAppContext } from "@/providers/AuthProvider";
|
import { useAppContext } from "@/providers/AuthProvider";
|
||||||
import apiClient from "@/services/api";
|
|
||||||
import { FunctionComponent } from "preact";
|
import { FunctionComponent } from "preact";
|
||||||
import { useLocation } from "preact-iso";
|
import { useLocation } from "preact-iso";
|
||||||
import "preact/debug";
|
import "preact/debug";
|
||||||
@@ -11,6 +10,10 @@ import { Controller, SubmitHandler, useForm } from "react-hook-form";
|
|||||||
import { ILoginForm } from "./login.dto";
|
import { ILoginForm } from "./login.dto";
|
||||||
import classes from "./login.module.scss";
|
import classes from "./login.module.scss";
|
||||||
|
|
||||||
|
const testUser = {
|
||||||
|
login: "test",
|
||||||
|
password: "test",
|
||||||
|
};
|
||||||
const LoginPage: FunctionComponent = () => {
|
const LoginPage: FunctionComponent = () => {
|
||||||
const { isLoggedIn } = useAppContext();
|
const { isLoggedIn } = useAppContext();
|
||||||
const { route } = useLocation();
|
const { route } = useLocation();
|
||||||
@@ -22,35 +25,15 @@ const LoginPage: FunctionComponent = () => {
|
|||||||
mode: "onChange",
|
mode: "onChange",
|
||||||
});
|
});
|
||||||
const login: SubmitHandler<ILoginForm> = async (data) => {
|
const login: SubmitHandler<ILoginForm> = async (data) => {
|
||||||
try {
|
console.log(data);
|
||||||
const response = await apiClient<{ success: boolean; user?: any; error?: string }>(
|
if (data.login !== testUser.login || data.password !== testUser.password) {
|
||||||
"/api/login/",
|
setError("login", { message: "Неверный логин или пароль" });
|
||||||
{
|
setError("password", { message: "Неверный логин или пароль" });
|
||||||
method: "POST",
|
return;
|
||||||
body: JSON.stringify({ username: data.login, password: data.password }),
|
|
||||||
needsCsrf: true,
|
|
||||||
},
|
|
||||||
isLoggedIn
|
|
||||||
);
|
|
||||||
|
|
||||||
if (response.success) {
|
|
||||||
isLoggedIn.value = true;
|
|
||||||
localStorage.setItem("loggedIn", "true");
|
|
||||||
route("/profile/tasks", true);
|
|
||||||
} else {
|
|
||||||
const errorMessage = response.error || "Неверный логин или пароль";
|
|
||||||
setError("login", { message: errorMessage });
|
|
||||||
setError("password", { message: " " });
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error("Login failed:", error);
|
|
||||||
const errorMessage =
|
|
||||||
error.message.includes("Authentication failed") || error.message.includes("Invalid credentials")
|
|
||||||
? "Неверный логин или пароль"
|
|
||||||
: "Ошибка входа. Попробуйте позже.";
|
|
||||||
setError("login", { message: errorMessage });
|
|
||||||
setError("password", { message: " " });
|
|
||||||
}
|
}
|
||||||
|
isLoggedIn.value = true;
|
||||||
|
localStorage.setItem("loggedIn", "true");
|
||||||
|
route("/profile/tasks", true);
|
||||||
};
|
};
|
||||||
if (isLoggedIn.value) route("/profile/tasks", true);
|
if (isLoggedIn.value) route("/profile/tasks", true);
|
||||||
return !isLoggedIn.value ? (
|
return !isLoggedIn.value ? (
|
||||||
|
|||||||
@@ -6,16 +6,8 @@ import ids from "./profile.module.scss";
|
|||||||
|
|
||||||
const ProfilePage: FunctionComponent = () => {
|
const ProfilePage: FunctionComponent = () => {
|
||||||
const { route } = useLocation();
|
const { route } = useLocation();
|
||||||
const { isLoggedIn, isCheckingAuth } = useAppContext(); // Получаем новый сигнал
|
const { isLoggedIn } = useAppContext();
|
||||||
|
if (!isLoggedIn.value) route("/login", true);
|
||||||
if (isCheckingAuth.value) {
|
|
||||||
return <div class="flex h-screen items-center justify-center">Проверка авторизации...</div>;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isLoggedIn.value) {
|
|
||||||
route("/login", true);
|
|
||||||
return <p>Redirecting...</p>; // Заглушка на время редиректа
|
|
||||||
}
|
|
||||||
return isLoggedIn.value ? (
|
return isLoggedIn.value ? (
|
||||||
<div id={ids.main_container}>
|
<div id={ids.main_container}>
|
||||||
<div id={ids.router_container}>
|
<div id={ids.router_container}>
|
||||||
|
|||||||
@@ -2,88 +2,57 @@ import Button from "@/components/ui/Button";
|
|||||||
import { withTitle } from "@/constructors/Component";
|
import { withTitle } from "@/constructors/Component";
|
||||||
import { UrlsTitle } from "@/enums/urls";
|
import { UrlsTitle } from "@/enums/urls";
|
||||||
import { useAppContext } from "@/providers/AuthProvider";
|
import { useAppContext } from "@/providers/AuthProvider";
|
||||||
import apiClient from "@/services/api";
|
|
||||||
import { cn } from "@/utils/class-merge";
|
import { cn } from "@/utils/class-merge";
|
||||||
|
import { calculatePoints, getCurrentStatus } from "@/utils/status-system";
|
||||||
import { ArrowRightStartOnRectangleIcon, Cog8ToothIcon } from "@heroicons/react/24/outline";
|
import { ArrowRightStartOnRectangleIcon, Cog8ToothIcon } from "@heroicons/react/24/outline";
|
||||||
import { FunctionComponent } from "preact";
|
import { FunctionComponent } from "preact";
|
||||||
import { useLocation } from "preact-iso";
|
import { useLocation } from "preact-iso";
|
||||||
import { useEffect, useState } from "preact/hooks";
|
import { useEffect, useState } from "preact/hooks";
|
||||||
import classes from "./profile_settings.module.scss";
|
import classes from "./profile_settings.module.scss";
|
||||||
|
|
||||||
interface UserProfile {
|
|
||||||
username: string;
|
|
||||||
email: string;
|
|
||||||
status: string;
|
|
||||||
avatar_url: string | null;
|
|
||||||
telegram_notifications: boolean;
|
|
||||||
telegram_chat_id: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface UserSettings {
|
|
||||||
profile: UserProfile;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ProfileSettings: FunctionComponent = () => {
|
const ProfileSettings: FunctionComponent = () => {
|
||||||
const { isLoggedIn } = useAppContext();
|
const { isLoggedIn } = useAppContext();
|
||||||
const { route } = useLocation();
|
const { route } = useLocation();
|
||||||
const [userData, setUserData] = useState<UserProfile>({
|
const [status, setStatus] = useState(0);
|
||||||
username: "",
|
|
||||||
email: "",
|
|
||||||
status: "",
|
|
||||||
avatar_url: null,
|
|
||||||
telegram_notifications: false,
|
|
||||||
telegram_chat_id: "",
|
|
||||||
});
|
|
||||||
const maxStatus = 100;
|
const maxStatus = 100;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchUserData = async () => {
|
const updateStatus = () => {
|
||||||
try {
|
const tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
|
||||||
const response = await apiClient<UserSettings>("/api/settings/view_settings/", { method: "GET" }, isLoggedIn);
|
const completedTasks = tasks.filter((task: { checked: boolean }) => task.checked).length;
|
||||||
setUserData(response.profile);
|
const points = calculatePoints(completedTasks);
|
||||||
} catch (error) {
|
setStatus(points);
|
||||||
console.error("Failed to fetch user data:", error);
|
};
|
||||||
|
|
||||||
|
// Initial update
|
||||||
|
updateStatus();
|
||||||
|
|
||||||
|
// Update when tasks change
|
||||||
|
const handleStorage = (e: StorageEvent) => {
|
||||||
|
if (e.key === "tasks") {
|
||||||
|
updateStatus();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (isLoggedIn.value) {
|
window.addEventListener("storage", handleStorage);
|
||||||
fetchUserData();
|
return () => window.removeEventListener("storage", handleStorage);
|
||||||
}
|
}, []);
|
||||||
}, [isLoggedIn.value]);
|
|
||||||
|
|
||||||
const handleLogout = async () => {
|
|
||||||
try {
|
|
||||||
await apiClient("/api/settings/logout/", { method: "POST", needsCsrf: true }, isLoggedIn);
|
|
||||||
isLoggedIn.value = false;
|
|
||||||
localStorage.removeItem("loggedIn");
|
|
||||||
localStorage.removeItem("user");
|
|
||||||
route("/login", true);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Logout failed:", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div class={classes.container}>
|
<div class={classes.container}>
|
||||||
<div class="flex w-full flex-col items-center rounded-[4rem] bg-[linear-gradient(180.00deg,rgb(251,194,199),rgba(206,232,251,0.72)_100%)] px-7 py-5 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] md:flex-row">
|
<div class="flex w-full flex-col items-center rounded-[4rem] bg-[linear-gradient(180.00deg,rgb(251,194,199),rgba(206,232,251,0.72)_100%)] px-7 py-5 shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] md:flex-row">
|
||||||
<div id={classes.avatar}>
|
<div id={classes.avatar}>Аватар</div>
|
||||||
{userData.avatar_url ? (
|
|
||||||
<img src={userData.avatar_url} alt="User avatar" class="h-full w-full rounded-full object-cover" />
|
|
||||||
) : (
|
|
||||||
"Аватар"
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div class={classes.header_block__name}>
|
<div class={classes.header_block__name}>
|
||||||
<p class="text-4xl font-semibold">{userData.username}</p>
|
<p class="text-4xl font-semibold">Никнейм</p>
|
||||||
<p class="text-2xl font-light">{userData.status}</p>
|
<p class="text-2xl font-light">{getCurrentStatus(status)}</p>
|
||||||
<div class="h-1.5 w-full overflow-hidden rounded-2xl bg-white">
|
<div class="h-1.5 w-full overflow-hidden rounded-2xl bg-white">
|
||||||
<div
|
<div
|
||||||
class={cn("relative top-0 left-0 h-2 bg-black")}
|
class={cn("relative top-0 left-0 h-2 bg-black")}
|
||||||
style={{ width: `${userData.telegram_chat_id ? 100 : 0}%` }}
|
style={{ width: `${(status / maxStatus) * 100}%` }}
|
||||||
></div>
|
></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="-mt-3 self-end text-sm font-light">
|
<div class="-mt-3 self-end text-sm font-light">
|
||||||
{userData.telegram_chat_id ? "100" : "0"}/{maxStatus}
|
{status}/{maxStatus}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -95,7 +64,11 @@ const ProfileSettings: FunctionComponent = () => {
|
|||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
className="flex flex-row items-center justify-center gap-2 bg-[linear-gradient(180.00deg,rgba(246,255,211,0.7),rgba(195,229,253,0.7)_100%)]"
|
className="flex flex-row items-center justify-center gap-2 bg-[linear-gradient(180.00deg,rgba(246,255,211,0.7),rgba(195,229,253,0.7)_100%)]"
|
||||||
onClick={handleLogout}
|
onClick={() => {
|
||||||
|
isLoggedIn.value = false;
|
||||||
|
localStorage.setItem("loggedIn", "false");
|
||||||
|
route("/login", true);
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<ArrowRightStartOnRectangleIcon class="size-8" /> Выйти
|
<ArrowRightStartOnRectangleIcon class="size-8" /> Выйти
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -11,83 +11,3 @@ export interface ITask {
|
|||||||
export interface ITaskForm extends Omit<ITask, "date"> {
|
export interface ITaskForm extends Omit<ITask, "date"> {
|
||||||
date: string;
|
date: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IApiTask {
|
|
||||||
id: number;
|
|
||||||
title: string;
|
|
||||||
description: string;
|
|
||||||
isCompleted: boolean;
|
|
||||||
due_date: string;
|
|
||||||
subject: string;
|
|
||||||
task_type: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IApiDay {
|
|
||||||
date: string;
|
|
||||||
name: string;
|
|
||||||
tasks: IApiTask[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IApiResponse {
|
|
||||||
profile: string;
|
|
||||||
days: IApiDay[];
|
|
||||||
subject_choices: Record<string, string>;
|
|
||||||
task_type_choices: Record<string, string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ICreateTaskResponse {
|
|
||||||
success: boolean;
|
|
||||||
message: string;
|
|
||||||
profile: string;
|
|
||||||
task: {
|
|
||||||
id: number;
|
|
||||||
title: string;
|
|
||||||
description: string;
|
|
||||||
subject: string;
|
|
||||||
taskType: string;
|
|
||||||
dateTime_due: string;
|
|
||||||
isCompleted: boolean;
|
|
||||||
reminder?: {
|
|
||||||
remind_before_days: number;
|
|
||||||
repeat_interval: number;
|
|
||||||
reminder_time: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ITaskDetails {
|
|
||||||
profile: string;
|
|
||||||
title: string;
|
|
||||||
description: string;
|
|
||||||
subject: string;
|
|
||||||
taskType: string;
|
|
||||||
dateTime_due: string;
|
|
||||||
remind_before_days: number;
|
|
||||||
repeat_reminder: number;
|
|
||||||
reminder_time: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IDeleteTaskResponse {
|
|
||||||
success: boolean;
|
|
||||||
message: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IEditTaskResponse {
|
|
||||||
success: boolean;
|
|
||||||
message: string;
|
|
||||||
profile: string;
|
|
||||||
task: {
|
|
||||||
id: number;
|
|
||||||
title: string;
|
|
||||||
description: string;
|
|
||||||
subject: string;
|
|
||||||
taskType: string;
|
|
||||||
dateTime_due: string;
|
|
||||||
isCompleted: boolean;
|
|
||||||
reminder?: {
|
|
||||||
remind_before_days: number;
|
|
||||||
repeat_interval: number;
|
|
||||||
reminder_time: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -28,17 +28,13 @@ import { Checkbox, CheckboxPassThroughMethodOptions } from "primereact/checkbox"
|
|||||||
import { Nullable } from "primereact/ts-helpers";
|
import { Nullable } from "primereact/ts-helpers";
|
||||||
import { SubmitHandler, useForm } from "react-hook-form";
|
import { SubmitHandler, useForm } from "react-hook-form";
|
||||||
import { v4 as uuid } from "uuid";
|
import { v4 as uuid } from "uuid";
|
||||||
import {
|
import { ITask, ITaskForm } from "./profile_tasks.dto";
|
||||||
ITask,
|
|
||||||
ITaskForm,
|
|
||||||
IApiResponse,
|
|
||||||
ICreateTaskResponse,
|
|
||||||
ITaskDetails,
|
|
||||||
IDeleteTaskResponse,
|
|
||||||
IEditTaskResponse,
|
|
||||||
} from "./profile_tasks.dto";
|
|
||||||
import classes from "./profile_tasks.module.scss";
|
import classes from "./profile_tasks.module.scss";
|
||||||
import apiClient from "@/services/api";
|
|
||||||
|
const example_tags: { first: string[]; second: string[] } = {
|
||||||
|
first: ["Программирование", "Информатика", "Физика", "Математика"],
|
||||||
|
second: ["Лабораторная работа", "Практическая работа", "Домашнее задание", "Экзамен"],
|
||||||
|
};
|
||||||
|
|
||||||
const ProfileTasks: FunctionComponent = () => {
|
const ProfileTasks: FunctionComponent = () => {
|
||||||
const [openModal, setIsOpen] = useState(false); // Открыта модалка
|
const [openModal, setIsOpen] = useState(false); // Открыта модалка
|
||||||
@@ -62,42 +58,17 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
const formatter = new Intl.DateTimeFormat("ru-RU", { month: "long", day: "numeric" });
|
const formatter = new Intl.DateTimeFormat("ru-RU", { month: "long", day: "numeric" });
|
||||||
return formatter.format(date);
|
return formatter.format(date);
|
||||||
}, []);
|
}, []);
|
||||||
const [tasks, setTasks] = useState<ITask[]>([]);
|
const init_tasks: ITask[] = localStorage.getItem("tasks") ? JSON.parse(localStorage.getItem("tasks") as string) : [];
|
||||||
const [subjectChoices, setSubjectChoices] = useState<Record<string, string>>({});
|
let clear = false;
|
||||||
const [taskTypeChoices, setTaskTypeChoices] = useState<Record<string, string>>({});
|
init_tasks.forEach((task) => {
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
clear = clear || (task.new == undefined ? true : false);
|
||||||
|
if (!clear) task.new = true;
|
||||||
|
task.date = new Date(task.date);
|
||||||
|
});
|
||||||
|
const [tasks, setTasks] = useState<ITask[]>(clear ? [] : init_tasks);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchTasks();
|
localStorage.setItem("tasks", JSON.stringify(tasks));
|
||||||
}, []);
|
}, [tasks]);
|
||||||
|
|
||||||
const fetchTasks = async () => {
|
|
||||||
try {
|
|
||||||
setIsLoading(true);
|
|
||||||
const response = await apiClient<IApiResponse>("/api/tasks/view_tasks/");
|
|
||||||
|
|
||||||
setSubjectChoices(response.subject_choices);
|
|
||||||
setTaskTypeChoices(response.task_type_choices);
|
|
||||||
|
|
||||||
const convertedTasks: ITask[] = response.days.flatMap((day) =>
|
|
||||||
day.tasks.map((apiTask) => ({
|
|
||||||
id: apiTask.id.toString(),
|
|
||||||
name: apiTask.title,
|
|
||||||
checked: apiTask.isCompleted,
|
|
||||||
date: new Date(apiTask.due_date),
|
|
||||||
description: apiTask.description,
|
|
||||||
tags: [apiTask.subject, apiTask.task_type],
|
|
||||||
new: false,
|
|
||||||
}))
|
|
||||||
);
|
|
||||||
|
|
||||||
setTasks(convertedTasks);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to fetch tasks:", error);
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
@@ -110,81 +81,27 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
tags: [],
|
tags: [],
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
const saveTask: SubmitHandler<ITaskForm> = (data) => {
|
||||||
const example_tags = useMemo(
|
|
||||||
() => ({
|
|
||||||
first: Object.keys(subjectChoices),
|
|
||||||
second: Object.keys(taskTypeChoices),
|
|
||||||
}),
|
|
||||||
[subjectChoices, taskTypeChoices]
|
|
||||||
);
|
|
||||||
|
|
||||||
const saveTask: SubmitHandler<ITaskForm> = async (data) => {
|
|
||||||
if (!calendarDate) {
|
if (!calendarDate) {
|
||||||
setError("date", { message: "Выберите дату" });
|
setError("date", { message: "Выберите дату" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
console.log(tags);
|
||||||
if ((!editContent?.tags[0] || !editContent.tags[1]) && (!tags.first || !tags.second)) {
|
if ((!editContent?.tags[0] || !editContent.tags[1]) && (!tags.first || !tags.second)) {
|
||||||
setError("tags", { message: "Выберите теги" });
|
setError("tags", { message: "Выберите теги" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const eTask: ITask = {
|
||||||
try {
|
...data,
|
||||||
const selectedSubject = editContent?.tags[0] || tags.first;
|
date: calendarDate,
|
||||||
const selectedTaskType = editContent?.tags[1] || tags.second;
|
tags: editContent?.tags.length ? editContent.tags : [tags.first, tags.second],
|
||||||
|
new: true,
|
||||||
// Format date to DD-MM-YYYYTHH:MM
|
};
|
||||||
const formattedDate = calendarDate
|
if (isCreating) setTasks([...tasks, eTask]);
|
||||||
.toLocaleString("en-GB", {
|
else setTasks(tasks.map((task) => (task.id === eTask.id ? eTask : task)));
|
||||||
day: "2-digit",
|
if (isCreating) setIsOpen(false);
|
||||||
month: "2-digit",
|
setTags({ first: "", second: "", overdue: false });
|
||||||
year: "numeric",
|
|
||||||
hour: "2-digit",
|
|
||||||
minute: "2-digit",
|
|
||||||
hour12: false,
|
|
||||||
})
|
|
||||||
.replace(",", "T")
|
|
||||||
.replace(/\//g, "-")
|
|
||||||
.replace("T ", "T");
|
|
||||||
|
|
||||||
const taskData = {
|
|
||||||
title: data.name,
|
|
||||||
description: data.description || "",
|
|
||||||
subject: selectedSubject,
|
|
||||||
taskType: selectedTaskType,
|
|
||||||
dateTime_due: formattedDate,
|
|
||||||
telegram_notifications: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (isCreating) {
|
|
||||||
const response = await apiClient<ICreateTaskResponse>("/api/tasks/create_task/", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify(taskData),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.success) {
|
|
||||||
throw new Error(response.message);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const response = await apiClient<IEditTaskResponse>(`/api/tasks/edit_task/${editContent?.id}/`, {
|
|
||||||
method: "PUT",
|
|
||||||
body: JSON.stringify(taskData),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.success) {
|
|
||||||
throw new Error(response.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await fetchTasks();
|
|
||||||
|
|
||||||
if (isCreating) setIsOpen(false);
|
|
||||||
setTags({ first: "", second: "", overdue: false });
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to save task:", error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (editContent) reset({ ...editContent, date: editContent.date.toISOString().slice(0, 16) });
|
if (editContent) reset({ ...editContent, date: editContent.date.toISOString().slice(0, 16) });
|
||||||
else reset();
|
else reset();
|
||||||
@@ -257,43 +174,17 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
}).format(date);
|
}).format(date);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteTask = async () => {
|
const handleDeleteTask = () => {
|
||||||
if (!editContent) return;
|
if (!editContent) return;
|
||||||
|
setTasks(tasks.filter((task) => task.id !== editContent.id));
|
||||||
try {
|
setIsOpen(false);
|
||||||
const response = await apiClient<IDeleteTaskResponse>(`/api/tasks/delete_task/${editContent.id}/`, {
|
setShowDeleteDialog(false);
|
||||||
method: "DELETE",
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.success) {
|
|
||||||
throw new Error(response.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
await fetchTasks();
|
|
||||||
|
|
||||||
setIsOpen(false);
|
|
||||||
setShowDeleteDialog(false);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to delete task:", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleMarkTask = async (taskId: string, isCompleted: boolean) => {
|
|
||||||
try {
|
|
||||||
await apiClient(`/api/update_task/${taskId}/`, {
|
|
||||||
method: "PATCH",
|
|
||||||
body: JSON.stringify({ isCompleted }),
|
|
||||||
});
|
|
||||||
|
|
||||||
await fetchTasks();
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to mark task:", error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const filteredTasks = useMemo(() => {
|
const filteredTasks = useMemo(() => {
|
||||||
let filtered = tasks;
|
let filtered = tasks;
|
||||||
|
|
||||||
|
// Фильтрация по поиску
|
||||||
if (searchQuery) {
|
if (searchQuery) {
|
||||||
filtered = filtered.filter(
|
filtered = filtered.filter(
|
||||||
(task) =>
|
(task) =>
|
||||||
@@ -302,6 +193,7 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Фильтрация по тегам
|
||||||
if (filterTags.first || filterTags.second) {
|
if (filterTags.first || filterTags.second) {
|
||||||
filtered = filtered.filter(
|
filtered = filtered.filter(
|
||||||
(task) =>
|
(task) =>
|
||||||
@@ -319,50 +211,19 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (searchInputRef.current && openSearchModal) searchInputRef.current.focus();
|
if (searchInputRef.current && openSearchModal) searchInputRef.current.focus();
|
||||||
}, [searchInputRef, openSearchModal]);
|
}, [searchInputRef, openSearchModal]);
|
||||||
|
|
||||||
const handleViewTask = async (taskId: string) => {
|
|
||||||
try {
|
|
||||||
const taskDetails = await apiClient<ITaskDetails>(`/api/tasks/view_task/${taskId}/`);
|
|
||||||
|
|
||||||
const task: ITask = {
|
|
||||||
id: taskId,
|
|
||||||
name: taskDetails.title,
|
|
||||||
checked: false,
|
|
||||||
date: new Date(taskDetails.dateTime_due),
|
|
||||||
description: taskDetails.description,
|
|
||||||
tags: [taskDetails.subject, taskDetails.taskType],
|
|
||||||
new: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
setIsOpen(true);
|
|
||||||
setIsEdit(true);
|
|
||||||
setEditContent(task);
|
|
||||||
setCalendarDate(task.date);
|
|
||||||
setIsEditModal(false);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to fetch task details:", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div class={classes.container}>
|
<div class={classes.container}>
|
||||||
{isLoading ? (
|
<ModalTags
|
||||||
<div class="flex w-full flex-1 items-center justify-center">
|
zIndex={70}
|
||||||
<div class="text-2xl">Загрузка...</div>
|
isOpen={openModalTags}
|
||||||
</div>
|
setIsOpen={setOpenModalTags}
|
||||||
) : (
|
tagsList={example_tags}
|
||||||
<ModalTags
|
value={tags}
|
||||||
zIndex={70}
|
onClose={() => {
|
||||||
isOpen={openModalTags}
|
if (!isCreating) setTags({ first: "", second: "", overdue: false });
|
||||||
setIsOpen={setOpenModalTags}
|
}}
|
||||||
tagsList={example_tags}
|
onChange={setTags}
|
||||||
value={tags}
|
/>
|
||||||
onClose={() => {
|
|
||||||
if (!isCreating) setTags({ first: "", second: "", overdue: false });
|
|
||||||
}}
|
|
||||||
onChange={setTags}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<ModalCalendar
|
<ModalCalendar
|
||||||
zIndex={80}
|
zIndex={80}
|
||||||
isOpen={openModalCalendar}
|
isOpen={openModalCalendar}
|
||||||
@@ -613,8 +474,15 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
key={task.id}
|
key={task.id}
|
||||||
checked={task.checked}
|
checked={task.checked}
|
||||||
overdue={task.date < new Date()}
|
overdue={task.date < new Date()}
|
||||||
onClick={() => handleViewTask(task.id)}
|
onClick={() => {
|
||||||
onMarkClick={() => handleMarkTask(task.id, !task.checked)}
|
setIsOpen(true);
|
||||||
|
setIsEdit(true);
|
||||||
|
setEditContent(task);
|
||||||
|
setCalendarDate(task.date);
|
||||||
|
}}
|
||||||
|
onMarkClick={() => {
|
||||||
|
setTasks(tasks.map((t) => (t.id === task.id ? { ...t, checked: !t.checked } : t)));
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -629,8 +497,15 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
name={task.name}
|
name={task.name}
|
||||||
key={task.id}
|
key={task.id}
|
||||||
checked={task.checked}
|
checked={task.checked}
|
||||||
onClick={() => handleViewTask(task.id)}
|
onClick={() => {
|
||||||
onMarkClick={() => handleMarkTask(task.id, !task.checked)}
|
setIsOpen(true);
|
||||||
|
setIsEdit(true);
|
||||||
|
setEditContent(task);
|
||||||
|
setCalendarDate(task.date);
|
||||||
|
}}
|
||||||
|
onMarkClick={() => {
|
||||||
|
setTasks(tasks.map((t) => (t.id === task.id ? { ...t, checked: !t.checked } : t)));
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -643,8 +518,15 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
name={task.name}
|
name={task.name}
|
||||||
key={task.id}
|
key={task.id}
|
||||||
checked={task.checked}
|
checked={task.checked}
|
||||||
onClick={() => handleViewTask(task.id)}
|
onClick={() => {
|
||||||
onMarkClick={() => handleMarkTask(task.id, !task.checked)}
|
setIsOpen(true);
|
||||||
|
setIsEdit(true);
|
||||||
|
setEditContent(task);
|
||||||
|
setCalendarDate(task.date);
|
||||||
|
}}
|
||||||
|
onMarkClick={() => {
|
||||||
|
setTasks(tasks.map((t) => (t.id === task.id ? { ...t, checked: !t.checked } : t)));
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -690,8 +572,15 @@ const ProfileTasks: FunctionComponent = () => {
|
|||||||
key={task.id}
|
key={task.id}
|
||||||
checked={task.checked}
|
checked={task.checked}
|
||||||
overdue={task.date < new Date()}
|
overdue={task.date < new Date()}
|
||||||
onClick={() => handleViewTask(task.id)}
|
onClick={() => {
|
||||||
onMarkClick={() => handleMarkTask(task.id, !task.checked)}
|
setIsOpen(true);
|
||||||
|
setIsEdit(true);
|
||||||
|
setEditContent(task);
|
||||||
|
setCalendarDate(task.date);
|
||||||
|
}}
|
||||||
|
onMarkClick={() => {
|
||||||
|
setTasks(tasks.map((t) => (t.id === task.id ? { ...t, checked: !t.checked } : t)));
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
))
|
))
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -1,75 +1,20 @@
|
|||||||
import apiClient from "@/services/api";
|
import { stringToBoolean } from "@/utils/converter";
|
||||||
import { signal, Signal } from "@preact/signals";
|
import { signal, Signal } from "@preact/signals";
|
||||||
import { createContext, JSX } from "preact";
|
import { createContext, JSX } from "preact";
|
||||||
import { useContext, useEffect } from "preact/hooks";
|
import { useContext } from "preact/hooks";
|
||||||
|
|
||||||
interface UserData {
|
|
||||||
id: number;
|
|
||||||
username: string;
|
|
||||||
email: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AuthStatusResponse {
|
|
||||||
isAuthenticated: boolean;
|
|
||||||
user?: UserData;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AppContextValue {
|
interface AppContextValue {
|
||||||
isLoggedIn: Signal<boolean>;
|
isLoggedIn: Signal<boolean>;
|
||||||
isCheckingAuth: Signal<boolean>;
|
|
||||||
currentUser: Signal<UserData | null>;
|
|
||||||
checkAuth: () => Promise<void>;
|
|
||||||
}
|
}
|
||||||
|
const ininitialValue = stringToBoolean(localStorage.getItem("loggedIn"));
|
||||||
|
|
||||||
const initialLoggedIn = localStorage.getItem("loggedIn") === "true";
|
const AppContext = createContext<AppContextValue>({
|
||||||
|
isLoggedIn: signal(ininitialValue),
|
||||||
const AppContext = createContext<AppContextValue | null>(null);
|
});
|
||||||
|
|
||||||
const AppProvider = ({ children }: { children: JSX.Element }) => {
|
const AppProvider = ({ children }: { children: JSX.Element }) => {
|
||||||
const isLoggedIn = signal(initialLoggedIn);
|
|
||||||
const isCheckingAuth = signal(true);
|
|
||||||
const currentUser = signal<UserData | null>(null);
|
|
||||||
|
|
||||||
const checkAuth = async () => {
|
|
||||||
console.log("Checking auth status...");
|
|
||||||
isCheckingAuth.value = true;
|
|
||||||
try {
|
|
||||||
const response = await apiClient<AuthStatusResponse>("/api/auth/status/", {
|
|
||||||
method: "GET",
|
|
||||||
needsCsrf: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.isAuthenticated && response.user) {
|
|
||||||
console.log("User is authenticated:", response.user.username);
|
|
||||||
isLoggedIn.value = true;
|
|
||||||
currentUser.value = response.user;
|
|
||||||
localStorage.setItem("loggedIn", "true");
|
|
||||||
} else {
|
|
||||||
console.log("User is not authenticated.");
|
|
||||||
isLoggedIn.value = false;
|
|
||||||
currentUser.value = null;
|
|
||||||
localStorage.removeItem("loggedIn");
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error("Auth check failed:", error.message);
|
|
||||||
isLoggedIn.value = false;
|
|
||||||
currentUser.value = null;
|
|
||||||
localStorage.removeItem("loggedIn");
|
|
||||||
} finally {
|
|
||||||
isCheckingAuth.value = false;
|
|
||||||
console.log("Auth check finished. isLoggedIn:", isLoggedIn.value);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
checkAuth();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const value: AppContextValue = {
|
const value: AppContextValue = {
|
||||||
isLoggedIn,
|
isLoggedIn: signal(ininitialValue),
|
||||||
isCheckingAuth,
|
|
||||||
currentUser,
|
|
||||||
checkAuth,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
|
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
|
||||||
@@ -84,4 +29,3 @@ const useAppContext = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export { AppProvider, useAppContext };
|
export { AppProvider, useAppContext };
|
||||||
export type { UserData };
|
|
||||||
|
|||||||
@@ -1,99 +0,0 @@
|
|||||||
import { Signal } from "@preact/signals";
|
|
||||||
|
|
||||||
function getCookie(name: string): string | null {
|
|
||||||
let cookieValue = null;
|
|
||||||
if (document.cookie && document.cookie !== "") {
|
|
||||||
const cookies = document.cookie.split(";");
|
|
||||||
for (let i = 0; i < cookies.length; i++) {
|
|
||||||
const cookie = cookies[i].trim();
|
|
||||||
if (cookie.substring(0, name.length + 1) === name + "=") {
|
|
||||||
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return cookieValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "http://localhost:8000";
|
|
||||||
|
|
||||||
interface RequestOptions extends RequestInit {
|
|
||||||
needsCsrf?: boolean;
|
|
||||||
isFormData?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function apiClient<T>(
|
|
||||||
endpoint: string,
|
|
||||||
options: RequestOptions = {},
|
|
||||||
isLoggedInSignal?: Signal<boolean>
|
|
||||||
): Promise<T> {
|
|
||||||
const url = `${API_BASE_URL}${endpoint}`;
|
|
||||||
const { needsCsrf = true, isFormData = false, ...fetchOptions } = options;
|
|
||||||
|
|
||||||
const headers: HeadersInit = {
|
|
||||||
...(isFormData ? {} : { "Content-Type": "application/json" }),
|
|
||||||
Accept: "application/json",
|
|
||||||
...fetchOptions.headers,
|
|
||||||
};
|
|
||||||
|
|
||||||
const method = options.method?.toUpperCase() || "GET";
|
|
||||||
if (needsCsrf && ["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
|
|
||||||
const csrfToken = getCookie("csrftoken");
|
|
||||||
if (csrfToken) {
|
|
||||||
(headers as Record<string, string>)["X-CSRFToken"] = csrfToken;
|
|
||||||
} else {
|
|
||||||
console.warn("CSRF token not found in cookies.");
|
|
||||||
await fetchCsrfToken(); // Implement this function if needed
|
|
||||||
const newCsrfToken = getCookie("csrftoken");
|
|
||||||
if (newCsrfToken) {
|
|
||||||
(headers as Record<string, string>)["X-CSRFToken"] = newCsrfToken;
|
|
||||||
} else {
|
|
||||||
throw new Error("CSRF token is missing");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const config: RequestInit = {
|
|
||||||
...fetchOptions,
|
|
||||||
headers,
|
|
||||||
credentials: "include",
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch(url, config);
|
|
||||||
|
|
||||||
if (response.status === 401 || response.status === 403) {
|
|
||||||
console.error("Authentication error:", response.status);
|
|
||||||
if (isLoggedInSignal) {
|
|
||||||
isLoggedInSignal.value = false;
|
|
||||||
localStorage.setItem("loggedIn", "false");
|
|
||||||
}
|
|
||||||
throw new Error(`Authentication failed: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => ({}));
|
|
||||||
console.error("API Error:", response.status, errorData);
|
|
||||||
throw new Error(`HTTP error ${response.status}: ${JSON.stringify(errorData) || response.statusText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (response.status === 204) {
|
|
||||||
return {} as T;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (await response.json()) as T;
|
|
||||||
} catch (error) {
|
|
||||||
console.error("API Client Fetch Error:", error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchCsrfToken() {
|
|
||||||
try {
|
|
||||||
await apiClient("/api/get-csrf/", { method: "GET", needsCsrf: false });
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to fetch CSRF token:", error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default apiClient;
|
|
||||||
Reference in New Issue
Block a user