Compare commits
4 Commits
back_conne
...
df36c180af
| Author | SHA1 | Date | |
|---|---|---|---|
| df36c180af | |||
| a53687d0f8 | |||
| 4d1264417e | |||
| 9e3c9ba016 |
3
.vscode/settings.json
vendored
3
.vscode/settings.json
vendored
@@ -9,6 +9,5 @@
|
|||||||
"[\"'`]([^\"'`]*).*?[\"'`]"
|
"[\"'`]([^\"'`]*).*?[\"'`]"
|
||||||
]
|
]
|
||||||
],
|
],
|
||||||
"editor.formatOnSave": true,
|
"editor.formatOnSave": true
|
||||||
"editor.tabSize": 2
|
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
<html lang="ru">
|
<html lang="ru">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Антихвост</title>
|
<title>Антихвост</title>
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { addLocale, locale, PrimeReactProvider } from "primereact/api";
|
|||||||
import { useMountEffect } from "primereact/hooks";
|
import { useMountEffect } from "primereact/hooks";
|
||||||
import Page404 from "./pages/404";
|
import Page404 from "./pages/404";
|
||||||
import LoginPage from "./pages/login";
|
import LoginPage from "./pages/login";
|
||||||
import RegisterPage from "./pages/register";
|
|
||||||
import { AppProvider, useAppContext } from "./providers/AuthProvider";
|
import { AppProvider, useAppContext } from "./providers/AuthProvider";
|
||||||
|
|
||||||
const HomePage: FunctionComponent = () => {
|
const HomePage: FunctionComponent = () => {
|
||||||
@@ -33,7 +32,6 @@ export function App() {
|
|||||||
<Router>
|
<Router>
|
||||||
<Route path="/" component={HomePage} />
|
<Route path="/" component={HomePage} />
|
||||||
<Route path="/login" component={LoginPage} />
|
<Route path="/login" component={LoginPage} />
|
||||||
<Route path="/register" component={RegisterPage} />
|
|
||||||
<Route path="/profile/*" component={lazy(() => import("./pages/profile"))} />
|
<Route path="/profile/*" component={lazy(() => import("./pages/profile"))} />
|
||||||
<Route default component={() => <Page404 />} />
|
<Route default component={() => <Page404 />} />
|
||||||
</Router>
|
</Router>
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 2.3 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1012 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.5 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 970 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 2.0 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 973 KiB |
@@ -1,208 +0,0 @@
|
|||||||
import apiClient from "@/services/api";
|
|
||||||
import { cn } from "@/utils/class-merge";
|
|
||||||
import { EyeIcon, EyeSlashIcon, XCircleIcon } from "@heroicons/react/24/outline";
|
|
||||||
import { FunctionComponent } from "preact";
|
|
||||||
import { useEffect, useState } from "preact/hooks";
|
|
||||||
import {
|
|
||||||
InputSwitch,
|
|
||||||
InputSwitchPassThroughMethodOptions,
|
|
||||||
InputSwitchPassThroughOptions,
|
|
||||||
} from "primereact/inputswitch";
|
|
||||||
import { SubmitHandler, useForm } from "react-hook-form";
|
|
||||||
import Button from "./ui/Button";
|
|
||||||
import ModalWindow, { ModalWindowProps } from "./ui/Modal";
|
|
||||||
|
|
||||||
interface ISettings {
|
|
||||||
login: string;
|
|
||||||
oldPassword: string;
|
|
||||||
newPassword: string;
|
|
||||||
tgId: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IAPIResponse {
|
|
||||||
profile: IAPIProfile;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IAPIProfile {
|
|
||||||
username: string;
|
|
||||||
email: string;
|
|
||||||
status: string;
|
|
||||||
avatar_url: string;
|
|
||||||
telegram_notifications: boolean;
|
|
||||||
telegram_chat_id: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IAPIUpdateSettingsResponse {
|
|
||||||
success: boolean;
|
|
||||||
username: string;
|
|
||||||
email: string;
|
|
||||||
avatar_url: string;
|
|
||||||
password_changed: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
const SwitchStyles: InputSwitchPassThroughOptions = {
|
|
||||||
root: ({ props }: InputSwitchPassThroughMethodOptions) => ({
|
|
||||||
className: cn("inline-block relative", "w-12 h-7", {
|
|
||||||
"opacity-60 select-none pointer-events-none cursor-default": props.disabled,
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
input: {
|
|
||||||
className: cn("absolute appearance-none top-0 left-0 size-full p-0 m-0 opacity-0 z-10 outline-none cursor-pointer"),
|
|
||||||
},
|
|
||||||
slider: ({ props }: InputSwitchPassThroughMethodOptions) => ({
|
|
||||||
className: cn(
|
|
||||||
"absolute cursor-pointer top-0 left-0 right-0 bottom-0 border border-transparent",
|
|
||||||
"transition-colors duration-200 rounded-2xl",
|
|
||||||
"focus:outline-none focus:outline-offset-0 focus:shadow-[0_0_0_0.2rem_rgba(191,219,254,1)] ",
|
|
||||||
"before:absolute before:content-'' before:top-1/2 before:bg-white before:w-5 before:h-5 before:left-1 before:-mt-2.5 before:rounded-full before:transition-duration-200",
|
|
||||||
{
|
|
||||||
"bg-gray-200 hover:bg-gray-300": !props.checked,
|
|
||||||
"bg-[rgba(251,194,199,0.53)] before:transform before:translate-x-5": props.checked,
|
|
||||||
}
|
|
||||||
),
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
|
|
||||||
const ModalSettings: FunctionComponent<ModalWindowProps> = ({ isOpen, setIsOpen, onClose, ...rest }) => {
|
|
||||||
const { handleSubmit, register, setValue, reset } = useForm<ISettings>({
|
|
||||||
defaultValues: {
|
|
||||||
login: "",
|
|
||||||
oldPassword: "",
|
|
||||||
newPassword: "",
|
|
||||||
},
|
|
||||||
mode: "onChange",
|
|
||||||
});
|
|
||||||
|
|
||||||
const changeSettings: SubmitHandler<ISettings> = async (data: ISettings) => {
|
|
||||||
interface IReq {
|
|
||||||
username?: string;
|
|
||||||
current_password?: string;
|
|
||||||
password?: string;
|
|
||||||
}
|
|
||||||
const req: IReq = {
|
|
||||||
username: data.login || undefined,
|
|
||||||
current_password: data.oldPassword || undefined,
|
|
||||||
password: data.newPassword || undefined,
|
|
||||||
};
|
|
||||||
|
|
||||||
const response = await apiClient<IAPIUpdateSettingsResponse>("/api/settings/edit_profile/", {
|
|
||||||
method: "PATCH",
|
|
||||||
body: JSON.stringify(req),
|
|
||||||
});
|
|
||||||
if (!response.success) console.error("Error changing settings");
|
|
||||||
|
|
||||||
if (enableNotification && data.tgId) {
|
|
||||||
await apiClient("/api/settings/save_chat_id/", {
|
|
||||||
method: "PATCH",
|
|
||||||
body: JSON.stringify({ telegram_chat_id: data.tgId }),
|
|
||||||
});
|
|
||||||
if (oldEnabledNotif !== enableNotification) {
|
|
||||||
await apiClient("/api/settings/toggle_telegram_notifications/", { method: "PATCH" });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
handleClose();
|
|
||||||
};
|
|
||||||
|
|
||||||
const [enableNotification, setEnableNotification] = useState(false);
|
|
||||||
const [login, setLogin] = useState("");
|
|
||||||
const [showOldPassword, setShowOldPassword] = useState(false);
|
|
||||||
const [showNewPassword, setShowNewPassword] = useState(false);
|
|
||||||
const [oldEnabledNotif, setOldEnabledNotif] = useState(false);
|
|
||||||
const [tgId, setTgId] = useState("");
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const getSettings = async () => {
|
|
||||||
const response = await apiClient<IAPIResponse>("/api/settings/view_settings/", { method: "GET" });
|
|
||||||
setEnableNotification(response.profile.telegram_notifications);
|
|
||||||
setOldEnabledNotif(response.profile.telegram_notifications);
|
|
||||||
setLogin(response.profile.username);
|
|
||||||
setTgId(response.profile.telegram_chat_id);
|
|
||||||
};
|
|
||||||
if (isOpen) getSettings();
|
|
||||||
}, [isOpen]);
|
|
||||||
|
|
||||||
const handleClose = () => {
|
|
||||||
setIsOpen!(false);
|
|
||||||
setEnableNotification(false);
|
|
||||||
reset();
|
|
||||||
if (onClose) onClose();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ModalWindow setIsOpen={setIsOpen} isOpen={isOpen} onClose={handleClose} {...rest} className="h-fit! md:w-[40%]!">
|
|
||||||
<form onSubmit={handleSubmit(changeSettings)} class="flex w-full flex-col gap-4">
|
|
||||||
<div class="flex flex-col items-start gap-2">
|
|
||||||
<span class="ms-5 text-sm">Имя</span>
|
|
||||||
<div class="flex w-full flex-row items-center rounded-[4rem] bg-[rgba(251,194,199,0.53)] px-5 py-3 leading-8">
|
|
||||||
<input class="flex-1 outline-0" {...register("login")} placeholder={login} />
|
|
||||||
<XCircleIcon class="size-6 cursor-pointer" onClick={() => setValue("login", "")} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="flex flex-col items-start gap-2">
|
|
||||||
<span class="ms-5 text-sm">Старый пароль</span>
|
|
||||||
<div class="flex w-full flex-row items-center gap-1 rounded-[4rem] bg-[rgba(251,194,199,0.53)] px-5 py-3 leading-8">
|
|
||||||
<input
|
|
||||||
class="flex-1 outline-0"
|
|
||||||
{...register("oldPassword")}
|
|
||||||
placeholder="Старый пароль"
|
|
||||||
type={showOldPassword ? "text" : "password"}
|
|
||||||
/>
|
|
||||||
{showOldPassword ? (
|
|
||||||
<EyeIcon class="size-6 cursor-pointer" onClick={() => setShowOldPassword(false)} />
|
|
||||||
) : (
|
|
||||||
<EyeSlashIcon class="size-6 cursor-pointer" onClick={() => setShowOldPassword(true)} />
|
|
||||||
)}
|
|
||||||
<XCircleIcon class="size-6 cursor-pointer" onClick={() => setValue("oldPassword", "")} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="flex flex-col items-start gap-2">
|
|
||||||
<span class="ms-5 text-sm">Новый пароль</span>
|
|
||||||
<div class="flex w-full flex-row items-center gap-1 rounded-[4rem] bg-[rgba(251,194,199,0.53)] px-5 py-3 leading-8">
|
|
||||||
<input
|
|
||||||
class="flex-1 outline-0"
|
|
||||||
{...register("newPassword", {
|
|
||||||
minLength: { value: 8, message: "Пароль должен быть не менее 8 символов" },
|
|
||||||
})}
|
|
||||||
placeholder="Новый пароль"
|
|
||||||
type={showNewPassword ? "text" : "password"}
|
|
||||||
/>
|
|
||||||
{showNewPassword ? (
|
|
||||||
<EyeIcon class="size-6 cursor-pointer" onClick={() => setShowNewPassword(false)} />
|
|
||||||
) : (
|
|
||||||
<EyeSlashIcon class="size-6 cursor-pointer" onClick={() => setShowNewPassword(true)} />
|
|
||||||
)}
|
|
||||||
<XCircleIcon class="size-6 cursor-pointer" onClick={() => setValue("newPassword", "")} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="flex flex-row items-center justify-between rounded-[4rem] px-5 py-4 ring-3 ring-[rgba(251,194,199,0.53)]">
|
|
||||||
<span>Уведомления</span>
|
|
||||||
<InputSwitch
|
|
||||||
pt={SwitchStyles}
|
|
||||||
checked={enableNotification}
|
|
||||||
onChange={(e) => setEnableNotification(e.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div class={cn({ hidden: !enableNotification })}>
|
|
||||||
<div class="flex flex-col items-start gap-2">
|
|
||||||
<span class="ms-5 text-sm">
|
|
||||||
Telegram ID. Для работы перейдите в бота{" "}
|
|
||||||
<a href="https://t.me/antihvost_notif_bot" class="font-medium text-blue-600 hover:underline">
|
|
||||||
@antihvost_notif_bot
|
|
||||||
</a>
|
|
||||||
</span>
|
|
||||||
<div class="flex w-full flex-row items-center rounded-[4rem] px-5 py-3 leading-8 ring-2 ring-[rgba(206,232,251,0.7)]">
|
|
||||||
<input class="flex-1 outline-0" {...register("tgId")} placeholder={tgId} />
|
|
||||||
<XCircleIcon class="size-6 cursor-pointer" onClick={() => setValue("tgId", "")} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Button type="submit">Сохранить</Button>
|
|
||||||
</form>
|
|
||||||
</ModalWindow>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
ModalSettings.displayName = "ModalSettings";
|
|
||||||
|
|
||||||
export default ModalSettings;
|
|
||||||
@@ -1,17 +1,13 @@
|
|||||||
import { IAPITag, IViewTagsResponse } from "@/pages/profile_tasks.dto";
|
|
||||||
import apiClient from "@/services/api";
|
|
||||||
import { cn } from "@/utils/class-merge";
|
import { cn } from "@/utils/class-merge";
|
||||||
import { BookOpenIcon, CheckIcon, DocumentDuplicateIcon, PlusCircleIcon } from "@heroicons/react/24/outline";
|
import { BookOpenIcon, DocumentDuplicateIcon } from "@heroicons/react/24/outline";
|
||||||
import { XMarkIcon } from "@heroicons/react/24/solid";
|
|
||||||
import { FunctionComponent } from "preact";
|
import { FunctionComponent } from "preact";
|
||||||
import { Dispatch, StateUpdater, useEffect, useRef, useState } from "preact/hooks";
|
import { Dispatch, StateUpdater, useEffect, useState } from "preact/hooks";
|
||||||
import Button from "./ui/Button";
|
import Button from "./ui/Button";
|
||||||
import Dialog from "./ui/Dialog";
|
|
||||||
import ModalWindow, { ModalWindowProps } from "./ui/Modal";
|
import ModalWindow, { ModalWindowProps } from "./ui/Modal";
|
||||||
|
|
||||||
export interface ITags {
|
export interface ITags {
|
||||||
first: number;
|
first: string;
|
||||||
second: number;
|
second: string;
|
||||||
overdue: boolean;
|
overdue: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,10 +18,9 @@ interface ModalTagsProps extends ModalWindowProps {
|
|||||||
value?: ITags;
|
value?: ITags;
|
||||||
onChange?: Dispatch<StateUpdater<ITags>>;
|
onChange?: Dispatch<StateUpdater<ITags>>;
|
||||||
tagsList?: {
|
tagsList?: {
|
||||||
first: IAPITag[];
|
first: string[];
|
||||||
second: IAPITag[];
|
second: string[];
|
||||||
};
|
};
|
||||||
refreshTags: () => Promise<IViewTagsResponse | void>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const ModalTags: FunctionComponent<ModalTagsProps> = ({
|
const ModalTags: FunctionComponent<ModalTagsProps> = ({
|
||||||
@@ -35,234 +30,103 @@ const ModalTags: FunctionComponent<ModalTagsProps> = ({
|
|||||||
onChange,
|
onChange,
|
||||||
value,
|
value,
|
||||||
tagsList,
|
tagsList,
|
||||||
refreshTags,
|
|
||||||
...rest
|
...rest
|
||||||
}) => {
|
}) => {
|
||||||
const [showFirstTags, setShowFirstTags] = useState(false);
|
const [showFirstTags, setShowFirstTags] = useState(false);
|
||||||
const [showSecondTags, setShowSecondTags] = useState(false);
|
const [showSecondTags, setShowSecondTags] = useState(false);
|
||||||
const [showAddFirstTag, setShowAddFirstTag] = useState(false);
|
|
||||||
const [showAddSecondTag, setShowAddSecondTag] = useState(false);
|
|
||||||
const [showErrorDialog, setShowErrorDialog] = useState(false);
|
|
||||||
const [errorMessage, setErrorMessage] = useState<string[]>([]);
|
|
||||||
const addFirstTagRef = useRef<HTMLInputElement>(null);
|
|
||||||
const addSecondTagRef = useRef<HTMLInputElement>(null);
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (showFirstTags && showSecondTags) setShowFirstTags(false);
|
if (showFirstTags && showSecondTags) setShowFirstTags(false);
|
||||||
}, [showSecondTags]);
|
}, [showSecondTags]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (showFirstTags && showSecondTags) setShowSecondTags(false);
|
if (showFirstTags && showSecondTags) setShowSecondTags(false);
|
||||||
}, [showFirstTags]);
|
}, [showFirstTags]);
|
||||||
|
|
||||||
const handleCreateTag = async () => {
|
|
||||||
if (!addFirstTagRef.current?.value && !addSecondTagRef.current?.value) return;
|
|
||||||
|
|
||||||
const data: { subject_name?: string; taskType_name?: string } = {};
|
|
||||||
if (addFirstTagRef.current && addFirstTagRef.current.value) data.subject_name = addFirstTagRef.current.value;
|
|
||||||
if (addSecondTagRef.current && addSecondTagRef.current.value) data.taskType_name = addSecondTagRef.current.value;
|
|
||||||
const response = await apiClient<{ success: boolean; subject?: IAPITag; taskType?: IAPITag }>(
|
|
||||||
"/api/tags/create_tags/",
|
|
||||||
{ method: "POST", body: JSON.stringify(data) }
|
|
||||||
);
|
|
||||||
if (response.success) {
|
|
||||||
await refreshTags();
|
|
||||||
if (showAddFirstTag) {
|
|
||||||
const new_subject_id = response.subject!.id;
|
|
||||||
onChange!((prev) => ({ ...prev, first: new_subject_id }));
|
|
||||||
setShowAddFirstTag(false);
|
|
||||||
}
|
|
||||||
if (showAddSecondTag) {
|
|
||||||
const new_taskType_id = response.taskType!.id;
|
|
||||||
onChange!((prev) => ({ ...prev, second: new_taskType_id }));
|
|
||||||
setShowAddSecondTag(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (addFirstTagRef.current) addFirstTagRef.current.value = "";
|
|
||||||
if (addSecondTagRef.current) addSecondTagRef.current.value = "";
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDeleteTag = async (id: number) => {
|
|
||||||
const data: { subject_id?: number; taskType_id?: number } = {};
|
|
||||||
if (showFirstTags) data.subject_id = id;
|
|
||||||
if (showSecondTags) data.taskType_id = id;
|
|
||||||
const response = await apiClient<{ error?: string }>(`/api/tags/delete_tag/`, {
|
|
||||||
method: "DELETE",
|
|
||||||
body: JSON.stringify(data),
|
|
||||||
});
|
|
||||||
if (!response.error) {
|
|
||||||
await refreshTags();
|
|
||||||
} else {
|
|
||||||
setShowErrorDialog(true);
|
|
||||||
const match = response.error?.match(/\[(.+)\]/);
|
|
||||||
if (match) setErrorMessage(match[1].split(", ").map((s) => s.trim().replace(/'/g, "")));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<ModalWindow
|
||||||
<Dialog
|
isOpen={isOpen}
|
||||||
isOpen={showErrorDialog}
|
{...rest}
|
||||||
setIsOpen={setShowErrorDialog}
|
setIsOpen={setIsOpen}
|
||||||
title="Ошибка!"
|
onClose={() => {
|
||||||
confirmation={false}
|
onClose!();
|
||||||
cancelText="Ок"
|
setShowFirstTags(false);
|
||||||
>
|
setShowSecondTags(false);
|
||||||
<div class="flex flex-col items-start gap-1">
|
}}
|
||||||
<p class="mb-6 text-sm sm:text-[1rem]">
|
className="relative h-[14rem] justify-between py-4 md:h-[14rem] md:w-[25rem]"
|
||||||
Данный тег есть в других задачах. Поменяйте теги в них и повторите операцию.
|
zIndex={70}
|
||||||
</p>
|
>
|
||||||
<p class="text-sm sm:text-[1rem]">Задачи с этим тегом:</p>
|
<p class="text-2xl font-semibold">Теги</p>
|
||||||
<ul class="ms-6 list-disc">
|
<div class="flex w-[85%] flex-col gap-2 md:w-full">
|
||||||
{errorMessage.map((s, i) => (
|
<Button
|
||||||
<li key={i}>{s}</li>
|
className="flex w-full flex-row items-center justify-center gap-1 text-[1rem]!"
|
||||||
))}
|
onClick={() => setShowFirstTags(!showFirstTags)}
|
||||||
</ul>
|
>
|
||||||
</div>
|
<BookOpenIcon class="size-6" />
|
||||||
</Dialog>
|
{value?.first || "Предмет"}
|
||||||
<ModalWindow
|
</Button>
|
||||||
isOpen={isOpen}
|
<Button
|
||||||
{...rest}
|
className="flex w-full flex-row items-center justify-center gap-1 text-[1rem]! break-words"
|
||||||
setIsOpen={setIsOpen}
|
onClick={() => setShowSecondTags(!showSecondTags)}
|
||||||
onClose={() => {
|
>
|
||||||
onClose!();
|
<DocumentDuplicateIcon class="size-6" />
|
||||||
setShowFirstTags(false);
|
{value?.second || "Тема"}
|
||||||
setShowSecondTags(false);
|
</Button>
|
||||||
setShowAddFirstTag(false);
|
{showFirstTags && (
|
||||||
setShowAddSecondTag(false);
|
<div class="absolute top-full left-0 mt-3 ml-2 flex h-fit w-[18rem] flex-col items-center rounded-[4rem] bg-white px-8 py-4 text-xs md:top-0 md:left-full md:mt-0 md:ml-5">
|
||||||
}}
|
<div class="flex h-fit max-h-[45vh] w-full flex-col gap-3 overflow-y-auto">
|
||||||
className="relative h-[14rem] justify-between py-4 md:h-[14rem] md:w-[25rem]"
|
{tagsList?.first.map((tag) => (
|
||||||
zIndex={70}
|
<div
|
||||||
>
|
class="flex cursor-pointer flex-row gap-2"
|
||||||
<p class="text-2xl font-semibold">Теги</p>
|
onClick={() =>
|
||||||
<div class="flex w-[85%] flex-col gap-2 md:w-full">
|
onChange?.((prev) => {
|
||||||
<Button
|
return { ...prev, first: tag };
|
||||||
className="flex w-full flex-row items-center justify-center gap-1 text-[1rem]!"
|
})
|
||||||
onClick={() => {
|
}
|
||||||
setShowFirstTags(!showFirstTags);
|
|
||||||
setShowSecondTags(false);
|
|
||||||
setShowAddFirstTag(false);
|
|
||||||
setShowAddSecondTag(false);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<BookOpenIcon class="size-6" />
|
|
||||||
{tagsList?.first?.find((tag) => tag.id === value?.first)?.name || "Предмет"}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
className="flex w-full flex-row items-center justify-center gap-1 text-[1rem]! break-words"
|
|
||||||
onClick={() => {
|
|
||||||
setShowSecondTags(!showSecondTags);
|
|
||||||
setShowFirstTags(false);
|
|
||||||
setShowAddFirstTag(false);
|
|
||||||
setShowAddSecondTag(false);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<DocumentDuplicateIcon class="size-6" />
|
|
||||||
{tagsList?.second?.find((tag) => tag.id === value?.second)?.name || "Тема"}
|
|
||||||
</Button>
|
|
||||||
{showFirstTags && (
|
|
||||||
<div class="absolute top-full left-0 mt-3 ml-2 flex h-fit w-[18rem] flex-col items-center gap-3 md:top-0 md:left-full md:mt-0 md:ml-5">
|
|
||||||
<div class="flex h-fit max-h-[15rem] w-full flex-col gap-3 overflow-y-auto rounded-[4rem] bg-white px-8 py-4 text-xs">
|
|
||||||
{tagsList?.first.map((tag) => (
|
|
||||||
<div
|
|
||||||
class="flex cursor-pointer flex-row items-center gap-2"
|
|
||||||
onClick={() =>
|
|
||||||
onChange?.((prev) => {
|
|
||||||
return { ...prev, first: tag.id };
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
class={cn(
|
|
||||||
"pointer-events-none flex aspect-square size-4 flex-col items-center justify-center rounded-full border-1 border-black text-white select-none",
|
|
||||||
{
|
|
||||||
"bg-black": value?.first === tag.id,
|
|
||||||
}
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
✓
|
|
||||||
</div>
|
|
||||||
<p class="flex-1">{tag.name}</p>
|
|
||||||
<XMarkIcon
|
|
||||||
class="size-4 cursor-pointer"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
handleDeleteTag(tag.id);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<button
|
|
||||||
class="mt-2 flex w-full cursor-pointer flex-row items-center gap-2"
|
|
||||||
onClick={() => {
|
|
||||||
setShowAddFirstTag(!showAddFirstTag);
|
|
||||||
setTimeout(() => addFirstTagRef.current?.focus(), 100);
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<PlusCircleIcon class="size-5" />
|
|
||||||
<span>Добавить</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{showAddFirstTag && (
|
|
||||||
<div class="flex w-full flex-row items-center rounded-[4rem] bg-white px-8 py-4 text-xs">
|
|
||||||
<input placeholder="Введите текст" class="flex-1 outline-0" ref={addFirstTagRef} />
|
|
||||||
<CheckIcon class="size-6 cursor-pointer" onClick={handleCreateTag} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{showSecondTags && (
|
|
||||||
<div class="absolute top-full left-0 mt-3 ml-2 flex h-fit w-[18rem] flex-col items-center gap-3 md:top-0 md:left-full md:mt-0 md:ml-5">
|
|
||||||
<div class="flex h-fit max-h-[15rem] w-full flex-col gap-3 overflow-y-auto rounded-[4rem] bg-white px-8 py-4 text-xs">
|
|
||||||
{tagsList?.second.map((tag) => (
|
|
||||||
<div
|
<div
|
||||||
class="flex cursor-pointer flex-row gap-2"
|
class={cn(
|
||||||
onClick={() =>
|
"pointer-events-none flex aspect-square size-4 flex-col items-center justify-center rounded-full border-1 border-black text-white select-none",
|
||||||
onChange?.((prev) => {
|
{
|
||||||
return { ...prev, second: tag.id };
|
"bg-black": value?.first === tag,
|
||||||
})
|
}
|
||||||
}
|
)}
|
||||||
>
|
>
|
||||||
<div
|
✓
|
||||||
class={cn(
|
|
||||||
"pointer-events-none flex aspect-square size-4 flex-col items-center justify-center rounded-full border-1 border-black text-white select-none",
|
|
||||||
{
|
|
||||||
"bg-black": value?.second === tag.id,
|
|
||||||
}
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
✓
|
|
||||||
</div>
|
|
||||||
<p class="flex-1">{tag.name}</p>
|
|
||||||
<XMarkIcon
|
|
||||||
class="size-4 cursor-pointer"
|
|
||||||
onClick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
handleDeleteTag(tag.id);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
<p>{tag}</p>
|
||||||
<button
|
|
||||||
class="mt-2 flex w-full cursor-pointer flex-row items-center gap-2"
|
|
||||||
onClick={() => {
|
|
||||||
setShowAddSecondTag(!showAddSecondTag);
|
|
||||||
setTimeout(() => addSecondTagRef.current?.focus(), 100);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<PlusCircleIcon class="size-5" />
|
|
||||||
<span>Добавить</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{showAddSecondTag && (
|
|
||||||
<div class="flex w-full flex-row items-center rounded-[4rem] bg-white px-8 py-4 text-xs">
|
|
||||||
<input placeholder="Введите текст" class="flex-1 outline-0" ref={addSecondTagRef} />
|
|
||||||
<CheckIcon class="size-6 cursor-pointer" onClick={handleCreateTag} />
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
</div>
|
||||||
</div>
|
)}
|
||||||
</ModalWindow>
|
{showSecondTags && (
|
||||||
</>
|
<div class="absolute top-full left-0 mt-3 ml-2 flex h-fit w-[18rem] flex-col items-center rounded-[4rem] bg-white px-8 py-4 text-xs md:top-0 md:left-full md:mt-0 md:ml-5">
|
||||||
|
<div class="flex h-fit max-h-[45vh] w-full flex-col gap-3 overflow-y-auto">
|
||||||
|
{tagsList?.second.map((tag) => (
|
||||||
|
<div
|
||||||
|
class="flex cursor-pointer flex-row gap-2"
|
||||||
|
onClick={() =>
|
||||||
|
onChange?.((prev) => {
|
||||||
|
return { ...prev, second: tag };
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class={cn(
|
||||||
|
"pointer-events-none flex aspect-square size-4 flex-col items-center justify-center rounded-full border-1 border-black text-white select-none",
|
||||||
|
{
|
||||||
|
"bg-black": value?.second === tag,
|
||||||
|
}
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
✓
|
||||||
|
</div>
|
||||||
|
<p>{tag}</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ModalWindow>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,26 +1,11 @@
|
|||||||
import { useAppContext } from "@/providers/AuthProvider";
|
|
||||||
import apiClient from "@/services/api";
|
|
||||||
import { getAvatarPicUrl } from "@/services/avatar-pic";
|
|
||||||
import { cn } from "@/utils/class-merge";
|
import { cn } from "@/utils/class-merge";
|
||||||
import { CalendarDaysIcon, ListBulletIcon, UserIcon } from "@heroicons/react/24/solid";
|
import { CalendarDaysIcon, ListBulletIcon, UserIcon } from "@heroicons/react/24/solid";
|
||||||
import { FunctionComponent, h } from "preact";
|
import { FunctionComponent, h } from "preact";
|
||||||
import { useLocation } from "preact-iso";
|
import { useLocation } from "preact-iso";
|
||||||
import { useEffect, useState } from "preact/hooks";
|
|
||||||
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";
|
||||||
interface UserProfile {
|
import { useEffect, useState } from "preact/hooks";
|
||||||
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;
|
||||||
@@ -51,29 +36,34 @@ 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);
|
|
||||||
|
// 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]);
|
|
||||||
|
|
||||||
return username ? (
|
return (
|
||||||
<button
|
<button
|
||||||
onClick={() => route("/profile/settings")}
|
onClick={() => route("/profile/settings")}
|
||||||
class={cn("hidden h-32 w-full cursor-pointer overflow-hidden opacity-100 transition-[height,opacity] md:block", {
|
class={cn("hidden h-32 w-full cursor-pointer overflow-hidden opacity-100 transition-[height,opacity] md:block", {
|
||||||
@@ -85,16 +75,14 @@ const Avatar: FunctionComponent = () => {
|
|||||||
"h-full flex-row items-center justify-around rounded-[3rem] bg-[linear-gradient(180.00deg,rgba(249,134,143,0.5)_3.053%,rgb(228,242,252)_96.183%)] px-5 py-5 md:flex"
|
"h-full flex-row items-center justify-around rounded-[3rem] bg-[linear-gradient(180.00deg,rgba(249,134,143,0.5)_3.053%,rgb(228,242,252)_96.183%)] px-5 py-5 md:flex"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div class="my-5 aspect-square h-full rounded-full">
|
<div class="my-5 aspect-square h-full rounded-full bg-white"></div>
|
||||||
<img class="size-full rounded-full" src={getAvatarPicUrl(status)} alt="avatar" />
|
|
||||||
</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>
|
||||||
</button>
|
</button>
|
||||||
) : null;
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
interface MenuItems {
|
interface MenuItems {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
@reference "../index.scss";
|
@reference "../index.scss";
|
||||||
|
|
||||||
.task {
|
.task {
|
||||||
@apply relative flex h-24 w-full cursor-pointer flex-row items-center justify-start gap-4 rounded-[3rem] px-5 py-6 text-xl shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] transition-transform hover:scale-[1.05] active:scale-[1.05] md:w-[500px];
|
@apply relative flex h-24 w-full cursor-pointer flex-row items-center justify-start gap-4 rounded-[3rem] bg-[rgba(251,194,199,0.53)] px-5 py-6 text-xl shadow-[0px_4px_4px_0px_rgba(0,0,0,0.25)] transition-transform hover:scale-[1.05] hover:bg-[rgba(251,194,199,0.7)] active:scale-[1.05] md:w-[500px];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { cn } from "@/utils/class-merge";
|
|
||||||
import { FunctionComponent } from "preact";
|
import { FunctionComponent } from "preact";
|
||||||
import { MouseEventHandler } from "preact/compat";
|
import { MouseEventHandler } from "preact/compat";
|
||||||
import { tv } from "tailwind-variants";
|
import { tv } from "tailwind-variants";
|
||||||
@@ -6,7 +5,6 @@ import classes from "./task.module.scss";
|
|||||||
|
|
||||||
interface TaskProps {
|
interface TaskProps {
|
||||||
name: string;
|
name: string;
|
||||||
priority?: number;
|
|
||||||
checked?: boolean;
|
checked?: boolean;
|
||||||
overdue?: boolean;
|
overdue?: boolean;
|
||||||
onClick?: () => void;
|
onClick?: () => void;
|
||||||
@@ -38,21 +36,11 @@ const Task: FunctionComponent<TaskProps> = ({
|
|||||||
checked = false,
|
checked = false,
|
||||||
onClick = () => {},
|
onClick = () => {},
|
||||||
onMarkClick = () => {},
|
onMarkClick = () => {},
|
||||||
priority = 4,
|
|
||||||
overdue,
|
overdue,
|
||||||
}) => {
|
}) => {
|
||||||
return (
|
return (
|
||||||
<div class="w-[95%]">
|
<div class="w-[95%]">
|
||||||
<div
|
<div class={classes.task} onClick={onClick}>
|
||||||
class={cn(
|
|
||||||
classes.task,
|
|
||||||
{ "bg-[linear-gradient(90.00deg,rgba(18,26,230,0.29),rgba(251,194,199,0.34)_100%)]": priority == 1 },
|
|
||||||
{ "bg-[linear-gradient(90.00deg,rgba(97,200,232,0.6),rgba(251,194,199,0.42)_100%)]": priority == 2 },
|
|
||||||
{ "bg-[linear-gradient(90.00deg,rgba(247,220,52,0.61),rgba(251,194,199,0.38)_97.71%)]": priority == 3 },
|
|
||||||
{ "bg-[rgba(251,194,199,0.53)] hover:bg-[rgba(251,194,199,0.7)]": priority == 4 }
|
|
||||||
)}
|
|
||||||
onClick={onClick}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
class={taskStyle({ checked })}
|
class={taskStyle({ checked })}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
@@ -63,7 +51,7 @@ const Task: FunctionComponent<TaskProps> = ({
|
|||||||
<p class={markStyle({ checked })}>✓</p>
|
<p class={markStyle({ checked })}>✓</p>
|
||||||
</div>
|
</div>
|
||||||
{name}
|
{name}
|
||||||
{overdue && !checked && <span class="absolute top-2 right-16 text-xs text-red-500">Просрочено</span>}
|
{overdue && <span class="absolute top-2 right-16 text-xs text-red-500">Просрочено</span>}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -5,21 +5,20 @@ interface DialogProps {
|
|||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
setIsOpen: (isOpen: boolean) => void;
|
setIsOpen: (isOpen: boolean) => void;
|
||||||
title: string;
|
title: string;
|
||||||
onConfirm?: () => void;
|
content: string;
|
||||||
|
onConfirm: () => void;
|
||||||
confirmText?: string;
|
confirmText?: string;
|
||||||
cancelText?: string;
|
cancelText?: string;
|
||||||
confirmation?: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const Dialog: FunctionComponent<DialogProps> = ({
|
const Dialog: FunctionComponent<DialogProps> = ({
|
||||||
isOpen,
|
isOpen,
|
||||||
setIsOpen,
|
setIsOpen,
|
||||||
title,
|
title,
|
||||||
children,
|
content,
|
||||||
onConfirm = () => {},
|
onConfirm,
|
||||||
confirmText = "Подтвердить",
|
confirmText = "Подтвердить",
|
||||||
cancelText = "Отмена",
|
cancelText = "Отмена",
|
||||||
confirmation = true,
|
|
||||||
}) => {
|
}) => {
|
||||||
if (!isOpen) return null;
|
if (!isOpen) return null;
|
||||||
|
|
||||||
@@ -27,28 +26,20 @@ const Dialog: FunctionComponent<DialogProps> = ({
|
|||||||
<div class="fixed inset-0 z-150 flex items-center justify-center bg-black/50">
|
<div class="fixed inset-0 z-150 flex items-center justify-center bg-black/50">
|
||||||
<div class="w-full max-w-md rounded-[4rem] bg-white p-6 shadow-lg">
|
<div class="w-full max-w-md rounded-[4rem] bg-white p-6 shadow-lg">
|
||||||
<h2 class="mb-4 text-xl font-semibold">{title}</h2>
|
<h2 class="mb-4 text-xl font-semibold">{title}</h2>
|
||||||
{children}
|
<p class="mb-6 text-sm sm:text-[1rem]">{content}</p>
|
||||||
<div class="flex justify-end gap-4">
|
<div class="flex justify-end gap-4">
|
||||||
{confirmation ? (
|
<Button onClick={() => setIsOpen(false)} className="bg-gray-200 text-gray-800 hover:bg-gray-300">
|
||||||
<>
|
{cancelText}
|
||||||
<Button onClick={() => setIsOpen(false)} className="bg-gray-200 text-gray-800 hover:bg-gray-300">
|
</Button>
|
||||||
{cancelText}
|
<Button
|
||||||
</Button>
|
onClick={() => {
|
||||||
<Button
|
onConfirm();
|
||||||
onClick={() => {
|
setIsOpen(false);
|
||||||
onConfirm();
|
}}
|
||||||
setIsOpen(false);
|
color="red"
|
||||||
}}
|
>
|
||||||
color="red"
|
{confirmText}
|
||||||
>
|
</Button>
|
||||||
{confirmText}
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<Button onClick={() => setIsOpen(false)} className="bg-gray-200 text-gray-800 hover:bg-gray-300">
|
|
||||||
{cancelText}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,5 +4,4 @@ export enum UrlsTitle {
|
|||||||
TASKS = "Задачи",
|
TASKS = "Задачи",
|
||||||
CALENDAR = "Календарь",
|
CALENDAR = "Календарь",
|
||||||
PAGE404 = "404",
|
PAGE404 = "404",
|
||||||
REGISTER = "Регистрация",
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,37 +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);
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
if (data.login !== testUser.login || data.password !== testUser.password) {
|
||||||
const response = await apiClient<{ success: boolean; user?: any; error?: string }>(
|
setError("login", { message: "Неверный логин или пароль" });
|
||||||
"/api/login/",
|
setError("password", { message: "Неверный логин или пароль" });
|
||||||
{
|
return;
|
||||||
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: " " });
|
|
||||||
}
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
} 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 ? (
|
||||||
@@ -90,17 +71,6 @@ const LoginPage: FunctionComponent = () => {
|
|||||||
Войти
|
Войти
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
<span class="mt-5 text-center text-xs">
|
|
||||||
Еще нет аккаунта?{" "}
|
|
||||||
<button
|
|
||||||
class="cursor-pointer text-blue-500 underline"
|
|
||||||
onClick={() => {
|
|
||||||
route("/register", true);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Зарегистрироваться
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -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}>
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import Dialog from "@/components/ui/Dialog";
|
|||||||
import ModalWindow from "@/components/ui/Modal";
|
import ModalWindow from "@/components/ui/Modal";
|
||||||
import { withTitle } from "@/constructors/Component";
|
import { withTitle } from "@/constructors/Component";
|
||||||
import { UrlsTitle } from "@/enums/urls";
|
import { UrlsTitle } from "@/enums/urls";
|
||||||
import apiClient from "@/services/api";
|
|
||||||
import { cn } from "@/utils/class-merge";
|
import { cn } from "@/utils/class-merge";
|
||||||
import {
|
import {
|
||||||
BookOpenIcon,
|
BookOpenIcon,
|
||||||
@@ -16,24 +15,16 @@ import {
|
|||||||
TrashIcon,
|
TrashIcon,
|
||||||
} from "@heroicons/react/24/outline";
|
} from "@heroicons/react/24/outline";
|
||||||
import { FunctionComponent } from "preact";
|
import { FunctionComponent } from "preact";
|
||||||
import { useEffect, useMemo, useState } from "preact/hooks";
|
import { useEffect, useState } from "preact/hooks";
|
||||||
import { Calendar, CalendarDateTemplateEvent } from "primereact/calendar";
|
import { Calendar, CalendarDateTemplateEvent } from "primereact/calendar";
|
||||||
import { Dropdown } from "primereact/dropdown";
|
|
||||||
import { Nullable } from "primereact/ts-helpers";
|
import { Nullable } from "primereact/ts-helpers";
|
||||||
import { SubmitHandler, useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { priorities } from "./profile_tasks";
|
import { ITask, ITaskForm } from "./profile_tasks.dto";
|
||||||
import {
|
|
||||||
IApiResponse,
|
const example_tags: { first: string[]; second: string[] } = {
|
||||||
IAPITag,
|
first: ["Программирование", "Информатика", "Физика", "Математика"],
|
||||||
ICreateTaskResponse,
|
second: ["Лабораторная работа", "Практическая работа", "Домашнее задание", "Экзамен"],
|
||||||
IDeleteTaskResponse,
|
};
|
||||||
IEditTaskResponse,
|
|
||||||
ITask,
|
|
||||||
ITaskDetails,
|
|
||||||
ITaskForm,
|
|
||||||
IViewTagsResponse,
|
|
||||||
} from "./profile_tasks.dto";
|
|
||||||
import { DropdownStyles, selectedPriorityTemplate } from "./profile_tasks.prime.styles";
|
|
||||||
|
|
||||||
const calendarStyles = {
|
const calendarStyles = {
|
||||||
root: "inline-flex w-full relative",
|
root: "inline-flex w-full relative",
|
||||||
@@ -66,12 +57,8 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
const [isEditModal, setIsEditModal] = useState(false);
|
const [isEditModal, setIsEditModal] = useState(false);
|
||||||
const [editContent, setEditContent] = useState<ITask | null>(null);
|
const [editContent, setEditContent] = useState<ITask | null>(null);
|
||||||
const [calendarDate, setCalendarDate] = useState<Nullable<Date>>();
|
const [calendarDate, setCalendarDate] = useState<Nullable<Date>>();
|
||||||
const [tags, setTags] = useState<ITags>({ first: 0, second: 0, overdue: false });
|
const [tags, setTags] = useState<ITags>({ first: "", second: "", overdue: false });
|
||||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||||
const [subjectChoices, setSubjectChoices] = useState<IAPITag[]>([]);
|
|
||||||
const [taskTypeChoices, setTaskTypeChoices] = useState<IAPITag[]>([]);
|
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
|
||||||
const [selectedPriority, setSelectedPriority] = useState(4);
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
@@ -80,191 +67,27 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
setError,
|
setError,
|
||||||
formState: { errors },
|
formState: { errors },
|
||||||
} = useForm<ITaskForm>({
|
} = useForm<ITaskForm>({
|
||||||
defaultValues: {},
|
defaultValues: {
|
||||||
|
tags: [],
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchTasks();
|
const storedTasks = localStorage.getItem("tasks");
|
||||||
fetchTags();
|
if (storedTasks) {
|
||||||
}, []);
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const parsedTasks: ITask[] = JSON.parse(storedTasks).map((task: any) => ({
|
||||||
const fetchTags = async () => {
|
...task,
|
||||||
try {
|
date: new Date(task.date),
|
||||||
const response = await apiClient<IViewTagsResponse>("/api/tags/view_tags/");
|
|
||||||
setSubjectChoices(response.subjects);
|
|
||||||
setTaskTypeChoices(response.taskTypes);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to fetch tags:", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchTasks = async () => {
|
|
||||||
try {
|
|
||||||
setIsLoading(true);
|
|
||||||
const response = await apiClient<IApiResponse>("/api/tasks/view_tasks/");
|
|
||||||
|
|
||||||
const convertedTasks: ITask[] = response.tasks.map((apiTask) => ({
|
|
||||||
id: apiTask.id.toString(),
|
|
||||||
name: apiTask.title,
|
|
||||||
checked: apiTask.isCompleted,
|
|
||||||
date: new Date(apiTask.due_date),
|
|
||||||
description: apiTask.description,
|
|
||||||
priority: apiTask.priority,
|
|
||||||
subject: apiTask.subject,
|
|
||||||
taskType: apiTask.taskType,
|
|
||||||
new: false,
|
|
||||||
}));
|
}));
|
||||||
|
setTasks(parsedTasks);
|
||||||
setTasks(convertedTasks);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to fetch tasks:", error);
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
}
|
||||||
};
|
}, []);
|
||||||
|
const handleDeleteTask = () => {
|
||||||
const example_tags = useMemo(
|
|
||||||
() => ({
|
|
||||||
first: subjectChoices,
|
|
||||||
second: taskTypeChoices,
|
|
||||||
}),
|
|
||||||
[subjectChoices, taskTypeChoices]
|
|
||||||
);
|
|
||||||
|
|
||||||
const saveTask: SubmitHandler<ITaskForm> = async (data) => {
|
|
||||||
if (!calendarDate) {
|
|
||||||
setError("date", { message: "Выберите дату" });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if ((!editContent?.subject.id || !editContent.taskType.id) && (!tags.first || !tags.second)) {
|
|
||||||
setError("date", { message: "Выберите теги" });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const selectedSubject = tags.first || editContent?.subject.id;
|
|
||||||
const selectedTaskType = tags.second || editContent?.taskType.id;
|
|
||||||
|
|
||||||
// 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_id: selectedSubject,
|
|
||||||
taskType_id: selectedTaskType,
|
|
||||||
dateTime_due: formattedDate,
|
|
||||||
telegram_notifications: false,
|
|
||||||
priority: selectedPriority,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!editContent) {
|
|
||||||
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);
|
|
||||||
} else if (isEdit)
|
|
||||||
setEditContent({
|
|
||||||
name: response.task.title,
|
|
||||||
id: response.task.id.toString(),
|
|
||||||
description: response.task.description,
|
|
||||||
priority: response.task.priority,
|
|
||||||
checked: response.task.isCompleted,
|
|
||||||
subject: response.task.subject,
|
|
||||||
taskType: response.task.task_type,
|
|
||||||
date: new Date(response.task.dateTime_due),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
await fetchTasks();
|
|
||||||
setIsOpen(false);
|
|
||||||
setTags({ first: 0, second: 0, overdue: false });
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to save task:", error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDeleteTask = async () => {
|
|
||||||
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 handleTaskCheck = 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 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,
|
|
||||||
subject: taskDetails.subject,
|
|
||||||
taskType: taskDetails.task_type,
|
|
||||||
priority: taskDetails.priority,
|
|
||||||
};
|
|
||||||
|
|
||||||
setIsOpen(true);
|
|
||||||
setIsEdit(true);
|
|
||||||
setEditContent(task);
|
|
||||||
setCalendarDate(task.date);
|
|
||||||
setSelectedPriority(task.priority);
|
|
||||||
setIsEditModal(false);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to fetch task details:", error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -286,39 +109,25 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
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();
|
||||||
}, [editContent]);
|
}, [editContent]);
|
||||||
|
useEffect(() => {
|
||||||
|
localStorage.setItem("tasks", JSON.stringify(tasks));
|
||||||
|
}, [tasks]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!editContent) return;
|
if (!editContent) return;
|
||||||
const newEditContent = editContent;
|
const newEditContent = editContent;
|
||||||
if (tags.first) newEditContent.subject = subjectChoices.find((tag) => tag.id === tags.first)!;
|
if (tags.first) newEditContent.tags = [tags.first, newEditContent.tags[1]];
|
||||||
if (tags.second) newEditContent.taskType = taskTypeChoices.find((tag) => tag.id === tags.second)!;
|
if (tags.second) newEditContent.tags = [newEditContent.tags[0], tags.second];
|
||||||
setEditContent(newEditContent);
|
setEditContent(newEditContent);
|
||||||
}, [tags]);
|
}, [tags]);
|
||||||
|
|
||||||
const tasksCount = (date: CalendarDateTemplateEvent) => {
|
const tasksCount = (date: CalendarDateTemplateEvent) => {
|
||||||
const filterTasks = tasks.filter((task) => {
|
return tasks.filter((task) => {
|
||||||
const taskDate = task.date;
|
const taskDate = task.date;
|
||||||
return (
|
return (
|
||||||
taskDate.getDate() === date.day && taskDate.getMonth() === date.month && taskDate.getFullYear() === date.year
|
taskDate.getDate() === date.day && taskDate.getMonth() === date.month && taskDate.getFullYear() === date.year
|
||||||
);
|
);
|
||||||
});
|
}).length;
|
||||||
return {
|
|
||||||
length: filterTasks.length,
|
|
||||||
colors: filterTasks.map((task) => {
|
|
||||||
switch (task.priority) {
|
|
||||||
case 1:
|
|
||||||
return "bg-[rgba(18,26,230,1)]";
|
|
||||||
case 2:
|
|
||||||
return "bg-[rgba(97,200,232,1)]";
|
|
||||||
case 3:
|
|
||||||
return "bg-[rgba(247,220,52,1)]";
|
|
||||||
case 4:
|
|
||||||
return "bg-[rgba(251,194,199,1)]";
|
|
||||||
default:
|
|
||||||
return "bg-[rgba(251,194,199,1)]";
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasTasksOnDate = (date: CalendarDateTemplateEvent) => {
|
const hasTasksOnDate = (date: CalendarDateTemplateEvent) => {
|
||||||
@@ -332,8 +141,7 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
|
|
||||||
const dateTemplate = (date: CalendarDateTemplateEvent) => {
|
const dateTemplate = (date: CalendarDateTemplateEvent) => {
|
||||||
const isHighlighted = hasTasksOnDate(date);
|
const isHighlighted = hasTasksOnDate(date);
|
||||||
const taskInfo = tasksCount(date);
|
const countT = tasksCount(date);
|
||||||
if (taskInfo.length) console.log(taskInfo);
|
|
||||||
const isSelected =
|
const isSelected =
|
||||||
currentDate &&
|
currentDate &&
|
||||||
currentDate.getDate() === date.day &&
|
currentDate.getDate() === date.day &&
|
||||||
@@ -357,16 +165,22 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
<span>{date.day}</span>
|
<span>{date.day}</span>
|
||||||
{isHighlighted && (
|
{isHighlighted && (
|
||||||
<div class="absolute top-2 right-2 flex h-fit w-2 flex-col items-center gap-1 md:h-2 md:w-fit md:flex-row">
|
<div class="absolute top-2 right-2 flex h-fit w-2 flex-col items-center gap-1 md:h-2 md:w-fit md:flex-row">
|
||||||
{Array.from({ length: taskInfo.length > 3 ? 3 : taskInfo.length }).map((_, i) => (
|
{Array.from({ length: countT > 3 ? 3 : countT }).map((_, i) => (
|
||||||
<span key={i} className={cn("size-2 rounded-full", taskInfo.colors[i])} />
|
<span key={i} className="size-2 rounded-full bg-pink-400" />
|
||||||
))}
|
))}
|
||||||
{taskInfo.length > 3 && <span className="text-xs font-bold text-pink-400 select-none">+</span>}
|
{countT > 3 && <span className="text-xs font-bold text-pink-400 select-none">+</span>}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleTaskCheck = (taskId: string) => {
|
||||||
|
const updatedTasks = tasks.map((task) => (task.id === taskId ? { ...task, checked: !task.checked } : task));
|
||||||
|
setTasks(updatedTasks);
|
||||||
|
localStorage.setItem("tasks", JSON.stringify(updatedTasks));
|
||||||
|
};
|
||||||
|
|
||||||
const formatDate = (date: Date) => {
|
const formatDate = (date: Date) => {
|
||||||
return new Intl.DateTimeFormat("ru-RU", {
|
return new Intl.DateTimeFormat("ru-RU", {
|
||||||
day: "numeric",
|
day: "numeric",
|
||||||
@@ -375,6 +189,26 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
}).format(date);
|
}).format(date);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const saveTask = (data: ITaskForm) => {
|
||||||
|
if (!calendarDate) {
|
||||||
|
setError("date", { message: "Выберите дату" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
setTasks(tasks.map((task) => (task.id === eTask.id ? eTask : task)));
|
||||||
|
localStorage.setItem("tasks", JSON.stringify(tasks.map((task) => (task.id === eTask.id ? eTask : task))));
|
||||||
|
setTags({ first: "", second: "", overdue: false });
|
||||||
|
};
|
||||||
|
|
||||||
const pt = {
|
const pt = {
|
||||||
root: { className: calendarStyles.root },
|
root: { className: calendarStyles.root },
|
||||||
input: { root: { className: calendarStyles.input } },
|
input: { root: { className: calendarStyles.input } },
|
||||||
@@ -396,15 +230,33 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div class="flex w-full flex-col items-center">
|
<div class="flex w-full flex-col items-center">
|
||||||
|
<ModalTags
|
||||||
|
isOpen={openModalTags}
|
||||||
|
setIsOpen={setOpenModalTags}
|
||||||
|
tagsList={example_tags}
|
||||||
|
value={tags}
|
||||||
|
onClose={() => {
|
||||||
|
setTags({ first: "", second: "", overdue: false });
|
||||||
|
}}
|
||||||
|
onChange={setTags}
|
||||||
|
/>
|
||||||
|
<ModalCalendar
|
||||||
|
isOpen={openModalCalendar}
|
||||||
|
setIsOpen={setOpenModalCalendar}
|
||||||
|
onClose={() => {
|
||||||
|
if (isEdit && !isEditModal) setCalendarDate(null);
|
||||||
|
}}
|
||||||
|
onChange={(e) => isEditModal && setCalendarDate(e.value)}
|
||||||
|
value={calendarDate!}
|
||||||
|
/>
|
||||||
<ModalWindow
|
<ModalWindow
|
||||||
isOpen={openModal}
|
isOpen={openModal}
|
||||||
setIsOpen={setIsOpen}
|
setIsOpen={setIsOpen}
|
||||||
onClose={() => {
|
onClose={() => {
|
||||||
setIsEdit(false);
|
setIsEdit(false);
|
||||||
setEditContent(null);
|
setEditContent(null);
|
||||||
setSelectedPriority(4);
|
|
||||||
setIsEditModal(false);
|
setIsEditModal(false);
|
||||||
setTags({ first: 0, second: 0, overdue: false });
|
setTags({ first: "", second: "", overdue: false });
|
||||||
setCalendarDate(null);
|
setCalendarDate(null);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -420,9 +272,7 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
<div class="flex w-full flex-row items-start justify-between">
|
<div class="flex w-full flex-row items-start justify-between">
|
||||||
<div class="flex flex-1 flex-col gap-1 pe-2">
|
<div class="flex flex-1 flex-col gap-1 pe-2">
|
||||||
<input
|
<input
|
||||||
class={cn("w-full p-2 text-2xl outline-0", {
|
class="w-full text-2xl outline-0"
|
||||||
"rounded-md bg-gray-400/30 ring-1 ring-gray-400": isEditModal,
|
|
||||||
})}
|
|
||||||
disabled={!isEditModal}
|
disabled={!isEditModal}
|
||||||
placeholder="Название"
|
placeholder="Название"
|
||||||
{...register("name", {
|
{...register("name", {
|
||||||
@@ -431,9 +281,7 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
})}
|
})}
|
||||||
/>
|
/>
|
||||||
<textarea
|
<textarea
|
||||||
class={cn("h-[5rem] w-full resize-none p-2 outline-0", {
|
class="h-[5rem] w-full resize-none outline-0"
|
||||||
"rounded-md bg-gray-400/30 ring-1 ring-gray-400": isEditModal,
|
|
||||||
})}
|
|
||||||
disabled={!isEditModal}
|
disabled={!isEditModal}
|
||||||
placeholder={isEditModal ? "Описание" : ""}
|
placeholder={isEditModal ? "Описание" : ""}
|
||||||
{...register("description", {
|
{...register("description", {
|
||||||
@@ -482,6 +330,7 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
{errors.name && <p class="text-red-500">{errors.name.message}</p>}
|
{errors.name && <p class="text-red-500">{errors.name.message}</p>}
|
||||||
{errors.description && <p class="text-red-500">{errors.description.message}</p>}
|
{errors.description && <p class="text-red-500">{errors.description.message}</p>}
|
||||||
{errors.date && <p class="text-red-500">{errors.date.message}</p>}
|
{errors.date && <p class="text-red-500">{errors.date.message}</p>}
|
||||||
|
{errors.tags && <p class="text-red-500">{errors.tags.message}</p>}
|
||||||
<div class="flex flex-col items-center gap-6 self-center md:flex-row md:justify-start md:self-start">
|
<div class="flex flex-col items-center gap-6 self-center md:flex-row md:justify-start md:self-start">
|
||||||
<div
|
<div
|
||||||
class={cn("flex h-full flex-row items-center gap-1 rounded-2xl bg-[rgba(251,194,199,0.38)] px-2 py-1", {
|
class={cn("flex h-full flex-row items-center gap-1 rounded-2xl bg-[rgba(251,194,199,0.38)] px-2 py-1", {
|
||||||
@@ -510,97 +359,64 @@ const ProfileCalendar: FunctionComponent = () => {
|
|||||||
})}
|
})}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!isEditModal) return;
|
if (!isEditModal) return;
|
||||||
setTags({ first: editContent.subject.id, second: editContent.taskType.id, overdue: false });
|
setTags({ first: editContent.tags[0], second: editContent.tags[1], overdue: false });
|
||||||
setOpenModalTags(true);
|
setOpenModalTags(true);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<p class="flex flex-row gap-2">
|
<p class="flex flex-row gap-2">
|
||||||
<BookOpenIcon class="size-5" />
|
<BookOpenIcon class="size-5" />
|
||||||
{editContent.subject.name}
|
{editContent.tags[0]}
|
||||||
</p>
|
</p>
|
||||||
<p class="flex flex-row gap-2">
|
<p class="flex flex-row gap-2">
|
||||||
<DocumentDuplicateIcon class="size-5" />
|
<DocumentDuplicateIcon class="size-5" />
|
||||||
{editContent.taskType.name}
|
{editContent.tags[1]}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Dropdown
|
|
||||||
disabled={!isEditModal}
|
|
||||||
pt={DropdownStyles}
|
|
||||||
options={priorities}
|
|
||||||
value={selectedPriority}
|
|
||||||
onChange={(e) => setSelectedPriority(e.value)}
|
|
||||||
itemTemplate={selectedPriorityTemplate}
|
|
||||||
valueTemplate={selectedPriorityTemplate}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
</ModalWindow>
|
</ModalWindow>
|
||||||
{isLoading ? (
|
<Dialog
|
||||||
<div class="flex w-full flex-1 items-center justify-center">Загрузка...</div>
|
isOpen={showDeleteDialog}
|
||||||
) : (
|
setIsOpen={setShowDeleteDialog}
|
||||||
<>
|
title="Удаление задачи"
|
||||||
<ModalTags
|
content="Вы уверены, что хотите удалить эту задачу?"
|
||||||
refreshTags={fetchTags}
|
onConfirm={handleDeleteTask}
|
||||||
isOpen={openModalTags}
|
confirmText="Удалить"
|
||||||
setIsOpen={setOpenModalTags}
|
cancelText="Отмена"
|
||||||
tagsList={example_tags}
|
/>
|
||||||
value={tags}
|
<Calendar
|
||||||
onClose={() => {
|
value={currentDate}
|
||||||
setTags({ first: 0, second: 0, overdue: false });
|
onChange={(e) => setCurrentDate(e ? e.value! : new Date())}
|
||||||
}}
|
inline
|
||||||
onChange={setTags}
|
pt={pt}
|
||||||
/>
|
dateTemplate={dateTemplate}
|
||||||
<ModalCalendar
|
className="[&_.p-datepicker]:!border-0 [&_.p-datepicker-calendar]:border-separate [&_.p-datepicker-calendar]:border-spacing-2 [&_td]:rounded-lg [&_td]:border [&_td]:border-[rgba(251,194,199,0.38)]"
|
||||||
isOpen={openModalCalendar}
|
/>
|
||||||
setIsOpen={setOpenModalCalendar}
|
|
||||||
onClose={() => {
|
|
||||||
if (isEdit && !isEditModal) setCalendarDate(null);
|
|
||||||
}}
|
|
||||||
onChange={(e) => isEditModal && setCalendarDate(e.value)}
|
|
||||||
value={calendarDate!}
|
|
||||||
/>
|
|
||||||
<Dialog
|
|
||||||
isOpen={showDeleteDialog}
|
|
||||||
setIsOpen={setShowDeleteDialog}
|
|
||||||
title="Удаление задачи"
|
|
||||||
onConfirm={handleDeleteTask}
|
|
||||||
confirmText="Удалить"
|
|
||||||
cancelText="Отмена"
|
|
||||||
>
|
|
||||||
<p class="mb-6 text-sm sm:text-[1rem]">"Вы уверены, что хотите удалить эту задачу?"</p>
|
|
||||||
</Dialog>
|
|
||||||
<Calendar
|
|
||||||
value={currentDate}
|
|
||||||
onChange={(e) => setCurrentDate(e ? e.value! : new Date())}
|
|
||||||
inline
|
|
||||||
pt={pt}
|
|
||||||
dateTemplate={dateTemplate}
|
|
||||||
className="[&_.p-datepicker]:!border-0 [&_.p-datepicker-calendar]:border-separate [&_.p-datepicker-calendar]:border-spacing-2 [&_td]:rounded-lg [&_td]:border [&_td]:border-[rgba(251,194,199,0.38)]"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div class="mt-8 w-full px-4">
|
<div class="mt-8 w-full px-4">
|
||||||
<h2 class="mb-4 text-2xl font-semibold">Задачи на {formatDate(currentDate)}</h2>
|
<h2 class="mb-4 text-2xl font-semibold">Задачи на {formatDate(currentDate)}</h2>
|
||||||
{selectedTasks.length > 0 ? (
|
{selectedTasks.length > 0 ? (
|
||||||
<div class="flex flex-col gap-4">
|
<div class="flex flex-col gap-4">
|
||||||
{selectedTasks.map((task) => (
|
{selectedTasks.map((task) => (
|
||||||
<Task
|
<Task
|
||||||
key={task.id}
|
key={task.id}
|
||||||
name={task.name}
|
name={task.name}
|
||||||
checked={task.checked}
|
checked={task.checked}
|
||||||
priority={task.priority}
|
onClick={() => {
|
||||||
overdue={task.date < new Date()}
|
setIsOpen(true);
|
||||||
onClick={() => handleViewTask(task.id)}
|
setIsEdit(true);
|
||||||
onMarkClick={() => handleTaskCheck(task.id)}
|
setEditContent(task);
|
||||||
/>
|
setCalendarDate(task.date);
|
||||||
))}
|
}}
|
||||||
</div>
|
onMarkClick={() => handleTaskCheck(task.id)}
|
||||||
) : (
|
/>
|
||||||
<div class="rounded-lg bg-[rgba(251,194,199,0.2)] p-4 text-center">На этот день задач нет</div>
|
))}
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</>
|
) : (
|
||||||
)}
|
<div class="rounded-lg bg-[rgba(251,194,199,0.2)] p-4 text-center">На этот день задач нет</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
#avatar {
|
#avatar {
|
||||||
@apply flex aspect-square h-[7rem] flex-col items-center justify-center rounded-full;
|
@apply flex aspect-square h-[7rem] flex-col items-center justify-center rounded-full bg-white;
|
||||||
}
|
}
|
||||||
|
|
||||||
.profile_container {
|
.profile_container {
|
||||||
|
|||||||
@@ -1,104 +1,74 @@
|
|||||||
import ModalSettings from "@/components/ModalSettings";
|
|
||||||
import Button from "@/components/ui/Button";
|
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 { getAvatarPicUrl } from "@/services/avatar-pic";
|
|
||||||
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;
|
|
||||||
status: string;
|
|
||||||
telegram_notifications: boolean;
|
|
||||||
telegram_chat_id: string | null;
|
|
||||||
current_xp: string;
|
|
||||||
xp_for_next_status: 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: "",
|
const maxStatus = 100;
|
||||||
status: "",
|
|
||||||
current_xp: "",
|
|
||||||
xp_for_next_status: "",
|
|
||||||
telegram_notifications: false,
|
|
||||||
telegram_chat_id: "",
|
|
||||||
});
|
|
||||||
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isLoggedIn.value) {
|
const updateStatus = () => {
|
||||||
fetchUserData();
|
const tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
|
||||||
}
|
const completedTasks = tasks.filter((task: { checked: boolean }) => task.checked).length;
|
||||||
}, [isLoggedIn.value]);
|
const points = calculatePoints(completedTasks);
|
||||||
|
setStatus(points);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Initial update
|
||||||
|
updateStatus();
|
||||||
|
|
||||||
|
// Update when tasks change
|
||||||
|
const handleStorage = (e: StorageEvent) => {
|
||||||
|
if (e.key === "tasks") {
|
||||||
|
updateStatus();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener("storage", handleStorage);
|
||||||
|
return () => window.removeEventListener("storage", handleStorage);
|
||||||
|
}, []);
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if (!userData.username)
|
|
||||||
return (
|
|
||||||
<div class="flex h-full w-full flex-1 flex-col items-center justify-center">
|
|
||||||
<div class="flex w-full flex-1 items-center justify-center">Загрузка...</div>;
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
return (
|
return (
|
||||||
<div class={classes.container}>
|
<div class={classes.container}>
|
||||||
<ModalSettings isOpen={isSettingsOpen} setIsOpen={setIsSettingsOpen} onClose={fetchUserData} />
|
|
||||||
<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>
|
||||||
<img class="size-28 rounded-full" src={getAvatarPicUrl(userData.status)} alt="avatar" />
|
|
||||||
</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.current_xp / +userData.xp_for_next_status) * 100}%` }}
|
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.current_xp}/{userData.xp_for_next_status}
|
{status}/{maxStatus}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class={classes.profile_container}>
|
<div class={classes.profile_container}>
|
||||||
<div class={classes.settings_block}>
|
<div class={classes.settings_block}>
|
||||||
<div class={classes.settings_block__buttons}>
|
<div class={classes.settings_block__buttons}>
|
||||||
<Button className="flex flex-row items-center justify-center gap-2" onClick={() => setIsSettingsOpen(true)}>
|
<Button className="flex flex-row items-center justify-center gap-2">
|
||||||
<Cog8ToothIcon class="size-8" /> Настройки
|
<Cog8ToothIcon class="size-8" /> Настройки
|
||||||
</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>
|
||||||
@@ -109,6 +79,4 @@ const ProfileSettings: FunctionComponent = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
ProfileSettings.displayName = "ProfileSettings";
|
|
||||||
|
|
||||||
export default withTitle(UrlsTitle.PROFILE, ProfileSettings);
|
export default withTitle(UrlsTitle.PROFILE, ProfileSettings);
|
||||||
|
|||||||
@@ -1,95 +1,13 @@
|
|||||||
export interface IAPITag {
|
|
||||||
name: string;
|
|
||||||
id: number;
|
|
||||||
}
|
|
||||||
export interface ITask {
|
export interface ITask {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
checked: boolean;
|
checked: boolean;
|
||||||
priority: number;
|
|
||||||
date: Date;
|
date: Date;
|
||||||
description: string;
|
description: string;
|
||||||
subject: IAPITag;
|
tags: string[];
|
||||||
taskType: IAPITag;
|
new?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ITaskView extends Omit<ITask, "taskType"> {
|
export interface ITaskForm extends Omit<ITask, "date"> {
|
||||||
task_type: IAPITag;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ITaskForm extends Omit<ITask, "date" | "subject" | "taskType"> {
|
|
||||||
date: string;
|
date: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IApiTask {
|
|
||||||
id: number;
|
|
||||||
title: string;
|
|
||||||
description: string;
|
|
||||||
priority: number;
|
|
||||||
isCompleted: boolean;
|
|
||||||
due_date: string;
|
|
||||||
subject: IAPITag;
|
|
||||||
taskType: IAPITag;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IApiResponse {
|
|
||||||
profile: string;
|
|
||||||
tasks: IApiTask[];
|
|
||||||
}
|
|
||||||
|
|
||||||
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: IAPITag;
|
|
||||||
task_type: IAPITag;
|
|
||||||
priority: number;
|
|
||||||
dateTime_due: 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: IAPITag;
|
|
||||||
task_type: IAPITag;
|
|
||||||
dateTime_due: string;
|
|
||||||
isCompleted: boolean;
|
|
||||||
priority: number;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IViewTagsResponse {
|
|
||||||
profile: string;
|
|
||||||
subjects: IAPITag[];
|
|
||||||
taskTypes: IAPITag[];
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,86 +0,0 @@
|
|||||||
import { cn } from "@/utils/class-merge";
|
|
||||||
import { FlagIcon as FlagIconSolid } from "@heroicons/react/20/solid";
|
|
||||||
import { DropdownPassThroughMethodOptions, DropdownPassThroughOptions } from "primereact/dropdown";
|
|
||||||
|
|
||||||
export const DropdownStyles: DropdownPassThroughOptions = {
|
|
||||||
root: ({ props }: DropdownPassThroughMethodOptions) => ({
|
|
||||||
className: cn(
|
|
||||||
"cursor-pointer inline-flex relative select-none mb-2",
|
|
||||||
"bg-white border border-gray-400 transition-colors duration-200 ease-in-out rounded-md",
|
|
||||||
"w-full md:w-56",
|
|
||||||
"hover:border-[rgba(251,194,199,0.7)] focus:outline-none focus:outline-offset-0 focus:shadow-[0_0_0_0.2rem_rgba(251,194,199,1)] ",
|
|
||||||
{ "opacity-60 select-none pointer-events-none cursor-default": props.disabled }
|
|
||||||
),
|
|
||||||
}),
|
|
||||||
input: ({ props }: DropdownPassThroughMethodOptions) => ({
|
|
||||||
className: cn(
|
|
||||||
"cursor-pointer flex flex-auto overflow-hidden overflow-ellipsis whitespace-nowrap relative",
|
|
||||||
"bg-transparent border-0 text-gray-800",
|
|
||||||
"p-3 transition duration-200 bg-transparent rounded appearance-none font-sans text-base",
|
|
||||||
"focus:outline-none focus:shadow-none",
|
|
||||||
{ "pr-7": props.showClear }
|
|
||||||
),
|
|
||||||
}),
|
|
||||||
trigger: {
|
|
||||||
className: cn(
|
|
||||||
"flex items-center justify-center shrink-0",
|
|
||||||
"bg-transparent text-gray-500 w-12 rounded-tr-lg rounded-br-lg"
|
|
||||||
),
|
|
||||||
},
|
|
||||||
wrapper: {
|
|
||||||
className: cn("max-h-[200px] overflow-auto", "bg-white text-gray-700 border-0 rounded-md shadow-lg", " "),
|
|
||||||
},
|
|
||||||
list: { className: "py-3 list-none m-0" },
|
|
||||||
item: ({ context }: DropdownPassThroughMethodOptions) => ({
|
|
||||||
className: cn(
|
|
||||||
"cursor-pointer font-normal overflow-hidden relative whitespace-nowrap",
|
|
||||||
"m-0 p-3 border-0 transition-shadow duration-200 rounded-none",
|
|
||||||
"hover:text-gray-700 hover:bg-gray-200",
|
|
||||||
{
|
|
||||||
"text-gray-700": !context.focused && !context.selected,
|
|
||||||
"bg-gray-300 text-gray-700 ": context.focused && !context.selected,
|
|
||||||
"bg-[rgba(251,194,199,0.7)] text-black ": context.focused && context.selected,
|
|
||||||
"bg-blue-50 text-gray-700": !context.focused && context.selected,
|
|
||||||
"opacity-60 select-none pointer-events-none cursor-default": context.disabled,
|
|
||||||
}
|
|
||||||
),
|
|
||||||
}),
|
|
||||||
itemGroup: {
|
|
||||||
className: cn("m-0 p-3 text-gray-800 bg-white font-bold", " ", "cursor-auto"),
|
|
||||||
},
|
|
||||||
header: {
|
|
||||||
className: cn("p-3 border-b border-gray-300 text-gray-700 bg-gray-100 mt-0 rounded-tl-lg rounded-tr-lg"),
|
|
||||||
},
|
|
||||||
filterContainer: {
|
|
||||||
className: "relative",
|
|
||||||
},
|
|
||||||
filterInput: {
|
|
||||||
className: cn(
|
|
||||||
"pr-7 -mr-7",
|
|
||||||
"w-full",
|
|
||||||
"font-sans text-base text-gray-700 bg-white py-3 px-3 border border-gray-300 transition duration-200 rounded-lg appearance-none",
|
|
||||||
"hover:border-[rgba(251,194,199,0.7)] focus:outline-none focus:outline-offset-0 focus:shadow-[0_0_0_0.2rem_rgba(251,194,199,1)] "
|
|
||||||
),
|
|
||||||
},
|
|
||||||
filterIcon: { className: "-mt-2 absolute top-1/2" },
|
|
||||||
clearIcon: { className: "text-gray-500 right-12 -mt-2 absolute top-1/2" },
|
|
||||||
};
|
|
||||||
|
|
||||||
export const selectedPriorityTemplate = (option: { label: string; value: number }) => {
|
|
||||||
return (
|
|
||||||
<div class="flex items-center">
|
|
||||||
<FlagIconSolid
|
|
||||||
className={cn(
|
|
||||||
"mr-2 size-4",
|
|
||||||
{ "text-[rgba(18,26,230,0.29)]": option.value == 1 },
|
|
||||||
{ "text-[rgba(97,200,232,0.6)]": option.value == 2 },
|
|
||||||
{
|
|
||||||
"text-[rgba(247,220,52,0.61)]": option.value == 3,
|
|
||||||
},
|
|
||||||
{ "text-[rgba(251,194,199,0.53)]": option.value == 4 }
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<span>{option.label}</span>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,132 +0,0 @@
|
|||||||
import Button from "@/components/ui/Button";
|
|
||||||
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";
|
|
||||||
import { Controller, SubmitHandler, useForm } from "react-hook-form";
|
|
||||||
import { ILoginForm } from "./login.dto";
|
|
||||||
import classes from "./login.module.scss";
|
|
||||||
|
|
||||||
interface IRegisterForm extends ILoginForm {
|
|
||||||
confirmPassword: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const RegisterPage: FunctionComponent = () => {
|
|
||||||
const { isLoggedIn } = useAppContext();
|
|
||||||
const { route } = useLocation();
|
|
||||||
const { control, handleSubmit, formState, setError } = useForm({
|
|
||||||
defaultValues: {
|
|
||||||
login: "",
|
|
||||||
password: "",
|
|
||||||
confirmPassword: "",
|
|
||||||
},
|
|
||||||
mode: "onChange",
|
|
||||||
});
|
|
||||||
const register: SubmitHandler<IRegisterForm> = async (data) => {
|
|
||||||
if (data.password !== data.confirmPassword) {
|
|
||||||
setError("confirmPassword", { message: "Пароли не совпадают" });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
const response = await apiClient<{ success: boolean; user?: any; error?: string }>("/api/register/", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ username: data.login, password: data.password }),
|
|
||||||
needsCsrf: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.success) {
|
|
||||||
route("/login", true);
|
|
||||||
} else {
|
|
||||||
const errorMessage = response.error || "Неверный логин или пароль";
|
|
||||||
setError("login", { message: errorMessage });
|
|
||||||
setError("password", { message: " " });
|
|
||||||
setError("confirmPassword", { message: " " });
|
|
||||||
}
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error("Register failed:", error);
|
|
||||||
const errorMessage = "Ошибка входа. Попробуйте позже.";
|
|
||||||
setError("login", { message: errorMessage });
|
|
||||||
setError("password", { message: " " });
|
|
||||||
setError("confirmPassword", { message: " " });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if (isLoggedIn.value) route("/profile/tasks", true);
|
|
||||||
return !isLoggedIn.value ? (
|
|
||||||
<div class={classes.login_container}>
|
|
||||||
<div class={classes.login_card}>
|
|
||||||
<p class={classes.login_card_name}>Антихвост</p>
|
|
||||||
<form onSubmit={handleSubmit(register)}>
|
|
||||||
<Controller
|
|
||||||
name="login"
|
|
||||||
control={control}
|
|
||||||
rules={{
|
|
||||||
required: "Введите логин",
|
|
||||||
minLength: { value: 3, message: "Логин должен быть не менее 3 символов" },
|
|
||||||
}}
|
|
||||||
render={({ field }) => (
|
|
||||||
<Input placeholder="Логин" textAlign="center" error={formState.errors.login?.message} {...field} />
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<Controller
|
|
||||||
name="password"
|
|
||||||
control={control}
|
|
||||||
rules={{
|
|
||||||
required: "Введите пароль",
|
|
||||||
minLength: { value: 8, message: "Пароль должен быть не менее 8 символов" },
|
|
||||||
}}
|
|
||||||
render={({ field }) => (
|
|
||||||
<Input
|
|
||||||
placeholder="Пароль"
|
|
||||||
textAlign="center"
|
|
||||||
type="password"
|
|
||||||
error={formState.errors.password?.message}
|
|
||||||
{...field}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<Controller
|
|
||||||
name="confirmPassword"
|
|
||||||
control={control}
|
|
||||||
rules={{
|
|
||||||
required: "Введите пароль",
|
|
||||||
minLength: { value: 8, message: "Пароль должен быть не менее 8 символов" },
|
|
||||||
}}
|
|
||||||
render={({ field }) => (
|
|
||||||
<Input
|
|
||||||
placeholder="Повторите пароль"
|
|
||||||
textAlign="center"
|
|
||||||
type="password"
|
|
||||||
error={formState.errors.confirmPassword?.message}
|
|
||||||
{...field}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<Button type="submit" color="secondary" className="w-full">
|
|
||||||
Зарегистрироваться
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
<span class="mt-5 text-center text-xs">
|
|
||||||
Уже есть аккаунт?{" "}
|
|
||||||
<button
|
|
||||||
class="cursor-pointer text-blue-500 underline"
|
|
||||||
onClick={() => {
|
|
||||||
route("/login", true);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Войти
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<p>Redirecting...</p>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default withTitle(UrlsTitle.REGISTER, RegisterPage);
|
|
||||||
@@ -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;
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import Status1 from "@/assets/status/1.png";
|
|
||||||
import Status2 from "@/assets/status/2.png";
|
|
||||||
import Status3 from "@/assets/status/3.png";
|
|
||||||
import Status4 from "@/assets/status/4.png";
|
|
||||||
import Status5 from "@/assets/status/5.png";
|
|
||||||
export const getAvatarPicUrl = (status: string) => {
|
|
||||||
switch (true) {
|
|
||||||
case status.includes("точно"):
|
|
||||||
return Status1;
|
|
||||||
case status.includes("плана нет"):
|
|
||||||
return Status2;
|
|
||||||
case status.includes("прокрастинации"):
|
|
||||||
return Status3;
|
|
||||||
case status.includes("3000"):
|
|
||||||
return Status4;
|
|
||||||
case status.includes("планирования"):
|
|
||||||
return Status5;
|
|
||||||
default:
|
|
||||||
return Status1;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
Reference in New Issue
Block a user