Compare commits
11 Commits
dev
...
cb9e1bd266
| Author | SHA1 | Date | |
|---|---|---|---|
| cb9e1bd266 | |||
| 1f289e8545 | |||
| ce694f0be8 | |||
| 852ac9ad0d | |||
| 9ab2a1cb08 | |||
| 19a6d435b2 | |||
| 5b5082df38 | |||
| 2c11c3b21a | |||
| f510c8c415 | |||
| a2c1fd16c9 | |||
| 0055e09806 |
@@ -4,8 +4,22 @@ import { FunctionComponent, h } from "preact";
|
||||
import { useLocation } from "preact-iso";
|
||||
import { tv } from "tailwind-variants";
|
||||
import classes from "./menu.module.scss";
|
||||
import { calculatePoints, getCurrentStatus } from "@/utils/status-system";
|
||||
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 {
|
||||
title: string;
|
||||
@@ -36,32 +50,27 @@ const MenuItem: FunctionComponent<MenuItemProps> = ({ title, link, icon }: MenuI
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
const Avatar: FunctionComponent = () => {
|
||||
const [status, setStatus] = useState("");
|
||||
const [username, setUsername] = useState("");
|
||||
const { route, path } = useLocation();
|
||||
const { isLoggedIn } = useAppContext();
|
||||
|
||||
useEffect(() => {
|
||||
const updateStatus = () => {
|
||||
const tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
|
||||
const completedTasks = tasks.filter((task: { checked: boolean }) => task.checked).length;
|
||||
const points = calculatePoints(completedTasks);
|
||||
setStatus(getCurrentStatus(points));
|
||||
};
|
||||
|
||||
// Initial update
|
||||
updateStatus();
|
||||
|
||||
// Update when tasks change
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === "tasks") {
|
||||
updateStatus();
|
||||
const fetchUserData = async () => {
|
||||
try {
|
||||
const response = await apiClient<UserSettings>("/api/settings/view_settings/", { method: "GET" }, isLoggedIn);
|
||||
setUsername(response.profile.username);
|
||||
setStatus(response.profile.status);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch user data:", error);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('storage', handleStorage);
|
||||
return () => window.removeEventListener('storage', handleStorage);
|
||||
}, []);
|
||||
|
||||
if (isLoggedIn.value) {
|
||||
fetchUserData();
|
||||
}
|
||||
}, [isLoggedIn.value]);
|
||||
|
||||
return (
|
||||
<button
|
||||
@@ -77,7 +86,7 @@ const Avatar: FunctionComponent = () => {
|
||||
>
|
||||
<div class="my-5 aspect-square h-full rounded-full bg-white"></div>
|
||||
<div class="flex flex-col items-center justify-center">
|
||||
<p class="text-3xl font-semibold">никнейм</p>
|
||||
<p class="text-3xl font-semibold">{username}</p>
|
||||
<div class="rounded-[1rem] bg-white px-5 leading-5 font-light italic">{status}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,7 @@ import Input from "@/components/ui/Input";
|
||||
import { withTitle } from "@/constructors/Component";
|
||||
import { UrlsTitle } from "@/enums/urls";
|
||||
import { useAppContext } from "@/providers/AuthProvider";
|
||||
import apiClient from "@/services/api";
|
||||
import { FunctionComponent } from "preact";
|
||||
import { useLocation } from "preact-iso";
|
||||
import "preact/debug";
|
||||
@@ -10,10 +11,6 @@ import { Controller, SubmitHandler, useForm } from "react-hook-form";
|
||||
import { ILoginForm } from "./login.dto";
|
||||
import classes from "./login.module.scss";
|
||||
|
||||
const testUser = {
|
||||
login: "test",
|
||||
password: "test",
|
||||
};
|
||||
const LoginPage: FunctionComponent = () => {
|
||||
const { isLoggedIn } = useAppContext();
|
||||
const { route } = useLocation();
|
||||
@@ -25,15 +22,35 @@ const LoginPage: FunctionComponent = () => {
|
||||
mode: "onChange",
|
||||
});
|
||||
const login: SubmitHandler<ILoginForm> = async (data) => {
|
||||
console.log(data);
|
||||
if (data.login !== testUser.login || data.password !== testUser.password) {
|
||||
setError("login", { message: "Неверный логин или пароль" });
|
||||
setError("password", { message: "Неверный логин или пароль" });
|
||||
return;
|
||||
try {
|
||||
const response = await apiClient<{ success: boolean; user?: any; error?: string }>(
|
||||
"/api/login/",
|
||||
{
|
||||
method: "POST",
|
||||
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);
|
||||
return !isLoggedIn.value ? (
|
||||
|
||||
@@ -6,8 +6,16 @@ import ids from "./profile.module.scss";
|
||||
|
||||
const ProfilePage: FunctionComponent = () => {
|
||||
const { route } = useLocation();
|
||||
const { isLoggedIn } = useAppContext();
|
||||
if (!isLoggedIn.value) route("/login", true);
|
||||
const { isLoggedIn, isCheckingAuth } = useAppContext(); // Получаем новый сигнал
|
||||
|
||||
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 ? (
|
||||
<div id={ids.main_container}>
|
||||
<div id={ids.router_container}>
|
||||
|
||||
@@ -2,57 +2,88 @@ import Button from "@/components/ui/Button";
|
||||
import { withTitle } from "@/constructors/Component";
|
||||
import { UrlsTitle } from "@/enums/urls";
|
||||
import { useAppContext } from "@/providers/AuthProvider";
|
||||
import apiClient from "@/services/api";
|
||||
import { cn } from "@/utils/class-merge";
|
||||
import { calculatePoints, getCurrentStatus } from "@/utils/status-system";
|
||||
import { ArrowRightStartOnRectangleIcon, Cog8ToothIcon } from "@heroicons/react/24/outline";
|
||||
import { FunctionComponent } from "preact";
|
||||
import { useLocation } from "preact-iso";
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
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 { isLoggedIn } = useAppContext();
|
||||
const { route } = useLocation();
|
||||
const [status, setStatus] = useState(0);
|
||||
const [userData, setUserData] = useState<UserProfile>({
|
||||
username: "",
|
||||
email: "",
|
||||
status: "",
|
||||
avatar_url: null,
|
||||
telegram_notifications: false,
|
||||
telegram_chat_id: "",
|
||||
});
|
||||
const maxStatus = 100;
|
||||
|
||||
useEffect(() => {
|
||||
const updateStatus = () => {
|
||||
const tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
|
||||
const completedTasks = tasks.filter((task: { checked: boolean }) => task.checked).length;
|
||||
const points = calculatePoints(completedTasks);
|
||||
setStatus(points);
|
||||
};
|
||||
|
||||
// Initial update
|
||||
updateStatus();
|
||||
|
||||
// Update when tasks change
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === "tasks") {
|
||||
updateStatus();
|
||||
const fetchUserData = async () => {
|
||||
try {
|
||||
const response = await apiClient<UserSettings>("/api/settings/view_settings/", { method: "GET" }, isLoggedIn);
|
||||
setUserData(response.profile);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch user data:", error);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("storage", handleStorage);
|
||||
return () => window.removeEventListener("storage", handleStorage);
|
||||
}, []);
|
||||
if (isLoggedIn.value) {
|
||||
fetchUserData();
|
||||
}
|
||||
}, [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 (
|
||||
<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 id={classes.avatar}>Аватар</div>
|
||||
<div id={classes.avatar}>
|
||||
{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}>
|
||||
<p class="text-4xl font-semibold">Никнейм</p>
|
||||
<p class="text-2xl font-light">{getCurrentStatus(status)}</p>
|
||||
<p class="text-4xl font-semibold">{userData.username}</p>
|
||||
<p class="text-2xl font-light">{userData.status}</p>
|
||||
<div class="h-1.5 w-full overflow-hidden rounded-2xl bg-white">
|
||||
<div
|
||||
class={cn("relative top-0 left-0 h-2 bg-black")}
|
||||
style={{ width: `${(status / maxStatus) * 100}%` }}
|
||||
style={{ width: `${userData.telegram_chat_id ? 100 : 0}%` }}
|
||||
></div>
|
||||
</div>
|
||||
<div class="-mt-3 self-end text-sm font-light">
|
||||
{status}/{maxStatus}
|
||||
{userData.telegram_chat_id ? "100" : "0"}/{maxStatus}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -64,11 +95,7 @@ const ProfileSettings: FunctionComponent = () => {
|
||||
</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%)]"
|
||||
onClick={() => {
|
||||
isLoggedIn.value = false;
|
||||
localStorage.setItem("loggedIn", "false");
|
||||
route("/login", true);
|
||||
}}
|
||||
onClick={handleLogout}
|
||||
>
|
||||
<ArrowRightStartOnRectangleIcon class="size-8" /> Выйти
|
||||
</Button>
|
||||
|
||||
@@ -11,3 +11,83 @@ export interface ITask {
|
||||
export interface ITaskForm extends Omit<ITask, "date"> {
|
||||
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;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import Dialog from "@/components/ui/Dialog";
|
||||
import ModalWindow from "@/components/ui/Modal";
|
||||
import { withTitle } from "@/constructors/Component";
|
||||
import { UrlsTitle } from "@/enums/urls";
|
||||
import apiClient from "@/services/api";
|
||||
import { cn } from "@/utils/class-merge";
|
||||
import { PlusIcon } from "@heroicons/react/20/solid";
|
||||
import {
|
||||
@@ -28,14 +29,17 @@ import { Checkbox, CheckboxPassThroughMethodOptions } from "primereact/checkbox"
|
||||
import { Nullable } from "primereact/ts-helpers";
|
||||
import { SubmitHandler, useForm } from "react-hook-form";
|
||||
import { v4 as uuid } from "uuid";
|
||||
import { ITask, ITaskForm } from "./profile_tasks.dto";
|
||||
import {
|
||||
IApiResponse,
|
||||
ICreateTaskResponse,
|
||||
IDeleteTaskResponse,
|
||||
IEditTaskResponse,
|
||||
ITask,
|
||||
ITaskDetails,
|
||||
ITaskForm,
|
||||
} from "./profile_tasks.dto";
|
||||
import classes from "./profile_tasks.module.scss";
|
||||
|
||||
const example_tags: { first: string[]; second: string[] } = {
|
||||
first: ["Программирование", "Информатика", "Физика", "Математика"],
|
||||
second: ["Лабораторная работа", "Практическая работа", "Домашнее задание", "Экзамен"],
|
||||
};
|
||||
|
||||
const ProfileTasks: FunctionComponent = () => {
|
||||
const [openModal, setIsOpen] = useState(false); // Открыта модалка
|
||||
const [openModalCalendar, setOpenModalCalendar] = useState(false); // Открыта модалка календаря
|
||||
@@ -58,17 +62,42 @@ const ProfileTasks: FunctionComponent = () => {
|
||||
const formatter = new Intl.DateTimeFormat("ru-RU", { month: "long", day: "numeric" });
|
||||
return formatter.format(date);
|
||||
}, []);
|
||||
const init_tasks: ITask[] = localStorage.getItem("tasks") ? JSON.parse(localStorage.getItem("tasks") as string) : [];
|
||||
let clear = false;
|
||||
init_tasks.forEach((task) => {
|
||||
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);
|
||||
const [tasks, setTasks] = useState<ITask[]>([]);
|
||||
const [subjectChoices, setSubjectChoices] = useState<Record<string, string>>({});
|
||||
const [taskTypeChoices, setTaskTypeChoices] = useState<Record<string, string>>({});
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem("tasks", JSON.stringify(tasks));
|
||||
}, [tasks]);
|
||||
fetchTasks();
|
||||
}, []);
|
||||
|
||||
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 {
|
||||
handleSubmit,
|
||||
@@ -81,27 +110,81 @@ const ProfileTasks: FunctionComponent = () => {
|
||||
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) {
|
||||
setError("date", { message: "Выберите дату" });
|
||||
return;
|
||||
}
|
||||
console.log(tags);
|
||||
if ((!editContent?.tags[0] || !editContent.tags[1]) && (!tags.first || !tags.second)) {
|
||||
setError("tags", { message: "Выберите теги" });
|
||||
return;
|
||||
}
|
||||
const eTask: ITask = {
|
||||
...data,
|
||||
date: calendarDate,
|
||||
tags: editContent?.tags.length ? editContent.tags : [tags.first, tags.second],
|
||||
new: true,
|
||||
};
|
||||
if (isCreating) setTasks([...tasks, eTask]);
|
||||
else setTasks(tasks.map((task) => (task.id === eTask.id ? eTask : task)));
|
||||
if (isCreating) setIsOpen(false);
|
||||
setTags({ first: "", second: "", overdue: false });
|
||||
|
||||
try {
|
||||
const selectedSubject = editContent?.tags[0] || tags.first;
|
||||
const selectedTaskType = editContent?.tags[1] || tags.second;
|
||||
|
||||
// Format date to DD-MM-YYYYTHH:MM
|
||||
const formattedDate = calendarDate
|
||||
.toLocaleString("en-GB", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
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(() => {
|
||||
if (editContent) reset({ ...editContent, date: editContent.date.toISOString().slice(0, 16) });
|
||||
else reset();
|
||||
@@ -174,17 +257,44 @@ const ProfileTasks: FunctionComponent = () => {
|
||||
}).format(date);
|
||||
};
|
||||
|
||||
const handleDeleteTask = () => {
|
||||
const handleDeleteTask = async () => {
|
||||
if (!editContent) return;
|
||||
setTasks(tasks.filter((task) => task.id !== editContent.id));
|
||||
setIsOpen(false);
|
||||
setShowDeleteDialog(false);
|
||||
|
||||
try {
|
||||
const response = await apiClient<IDeleteTaskResponse>(`/api/tasks/delete_task/${editContent.id}/`, {
|
||||
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) => {
|
||||
try {
|
||||
await apiClient(`/api/tasks/toggle_complete_task/${taskId}/`, {
|
||||
method: "PATCH",
|
||||
});
|
||||
|
||||
setTasks((prevTasks) =>
|
||||
prevTasks.map((task) => (task.id === taskId ? { ...task, checked: !task.checked } : task))
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Failed to mark task:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredTasks = useMemo(() => {
|
||||
let filtered = tasks;
|
||||
|
||||
// Фильтрация по поиску
|
||||
if (searchQuery) {
|
||||
filtered = filtered.filter(
|
||||
(task) =>
|
||||
@@ -193,7 +303,6 @@ const ProfileTasks: FunctionComponent = () => {
|
||||
);
|
||||
}
|
||||
|
||||
// Фильтрация по тегам
|
||||
if (filterTags.first || filterTags.second) {
|
||||
filtered = filtered.filter(
|
||||
(task) =>
|
||||
@@ -211,19 +320,50 @@ const ProfileTasks: FunctionComponent = () => {
|
||||
useEffect(() => {
|
||||
if (searchInputRef.current && openSearchModal) searchInputRef.current.focus();
|
||||
}, [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 (
|
||||
<div class={classes.container}>
|
||||
<ModalTags
|
||||
zIndex={70}
|
||||
isOpen={openModalTags}
|
||||
setIsOpen={setOpenModalTags}
|
||||
tagsList={example_tags}
|
||||
value={tags}
|
||||
onClose={() => {
|
||||
if (!isCreating) setTags({ first: "", second: "", overdue: false });
|
||||
}}
|
||||
onChange={setTags}
|
||||
/>
|
||||
{isLoading ? (
|
||||
<div class="flex w-full flex-1 items-center justify-center">
|
||||
<div class="text-2xl">Загрузка...</div>
|
||||
</div>
|
||||
) : (
|
||||
<ModalTags
|
||||
zIndex={70}
|
||||
isOpen={openModalTags}
|
||||
setIsOpen={setOpenModalTags}
|
||||
tagsList={example_tags}
|
||||
value={tags}
|
||||
onClose={() => {
|
||||
if (!isCreating) setTags({ first: "", second: "", overdue: false });
|
||||
}}
|
||||
onChange={setTags}
|
||||
/>
|
||||
)}
|
||||
<ModalCalendar
|
||||
zIndex={80}
|
||||
isOpen={openModalCalendar}
|
||||
@@ -474,15 +614,8 @@ const ProfileTasks: FunctionComponent = () => {
|
||||
key={task.id}
|
||||
checked={task.checked}
|
||||
overdue={task.date < new Date()}
|
||||
onClick={() => {
|
||||
setIsOpen(true);
|
||||
setIsEdit(true);
|
||||
setEditContent(task);
|
||||
setCalendarDate(task.date);
|
||||
}}
|
||||
onMarkClick={() => {
|
||||
setTasks(tasks.map((t) => (t.id === task.id ? { ...t, checked: !t.checked } : t)));
|
||||
}}
|
||||
onClick={() => handleViewTask(task.id)}
|
||||
onMarkClick={() => handleMarkTask(task.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -497,15 +630,8 @@ const ProfileTasks: FunctionComponent = () => {
|
||||
name={task.name}
|
||||
key={task.id}
|
||||
checked={task.checked}
|
||||
onClick={() => {
|
||||
setIsOpen(true);
|
||||
setIsEdit(true);
|
||||
setEditContent(task);
|
||||
setCalendarDate(task.date);
|
||||
}}
|
||||
onMarkClick={() => {
|
||||
setTasks(tasks.map((t) => (t.id === task.id ? { ...t, checked: !t.checked } : t)));
|
||||
}}
|
||||
onClick={() => handleViewTask(task.id)}
|
||||
onMarkClick={() => handleMarkTask(task.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -518,15 +644,8 @@ const ProfileTasks: FunctionComponent = () => {
|
||||
name={task.name}
|
||||
key={task.id}
|
||||
checked={task.checked}
|
||||
onClick={() => {
|
||||
setIsOpen(true);
|
||||
setIsEdit(true);
|
||||
setEditContent(task);
|
||||
setCalendarDate(task.date);
|
||||
}}
|
||||
onMarkClick={() => {
|
||||
setTasks(tasks.map((t) => (t.id === task.id ? { ...t, checked: !t.checked } : t)));
|
||||
}}
|
||||
onClick={() => handleViewTask(task.id)}
|
||||
onMarkClick={() => handleMarkTask(task.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -572,15 +691,8 @@ const ProfileTasks: FunctionComponent = () => {
|
||||
key={task.id}
|
||||
checked={task.checked}
|
||||
overdue={task.date < new Date()}
|
||||
onClick={() => {
|
||||
setIsOpen(true);
|
||||
setIsEdit(true);
|
||||
setEditContent(task);
|
||||
setCalendarDate(task.date);
|
||||
}}
|
||||
onMarkClick={() => {
|
||||
setTasks(tasks.map((t) => (t.id === task.id ? { ...t, checked: !t.checked } : t)));
|
||||
}}
|
||||
onClick={() => handleViewTask(task.id)}
|
||||
onMarkClick={() => handleMarkTask(task.id)}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
|
||||
@@ -1,20 +1,75 @@
|
||||
import { stringToBoolean } from "@/utils/converter";
|
||||
import apiClient from "@/services/api";
|
||||
import { signal, Signal } from "@preact/signals";
|
||||
import { createContext, JSX } from "preact";
|
||||
import { useContext } from "preact/hooks";
|
||||
import { useContext, useEffect } from "preact/hooks";
|
||||
|
||||
interface UserData {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
interface AuthStatusResponse {
|
||||
isAuthenticated: boolean;
|
||||
user?: UserData;
|
||||
}
|
||||
|
||||
interface AppContextValue {
|
||||
isLoggedIn: Signal<boolean>;
|
||||
isCheckingAuth: Signal<boolean>;
|
||||
currentUser: Signal<UserData | null>;
|
||||
checkAuth: () => Promise<void>;
|
||||
}
|
||||
const ininitialValue = stringToBoolean(localStorage.getItem("loggedIn"));
|
||||
|
||||
const AppContext = createContext<AppContextValue>({
|
||||
isLoggedIn: signal(ininitialValue),
|
||||
});
|
||||
const initialLoggedIn = localStorage.getItem("loggedIn") === "true";
|
||||
|
||||
const AppContext = createContext<AppContextValue | null>(null);
|
||||
|
||||
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 = {
|
||||
isLoggedIn: signal(ininitialValue),
|
||||
isLoggedIn,
|
||||
isCheckingAuth,
|
||||
currentUser,
|
||||
checkAuth,
|
||||
};
|
||||
|
||||
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
|
||||
@@ -29,3 +84,4 @@ const useAppContext = () => {
|
||||
};
|
||||
|
||||
export { AppProvider, useAppContext };
|
||||
export type { UserData };
|
||||
|
||||
99
src/services/api.ts
Normal file
99
src/services/api.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
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