Compare commits
7 Commits
master
...
b5b2439bd8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5b2439bd8 | ||
|
|
35ed595edc | ||
|
|
9c6272db25 | ||
|
|
83af205e7e | ||
|
|
4a5b0a9532 | ||
|
|
48ec88df74 | ||
|
|
7555757ca3 |
1107
package-lock.json
generated
1107
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -13,6 +13,7 @@
|
||||
"dependencies": {
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router-dom": "^7.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import {useEffect, useState} from "react";
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import {DEBUG_MODE} from "../utils/common";
|
||||
import {ApiResponse, PageResponse} from "../types/api.ts";
|
||||
import {PageControl} from "../types/common.ts";
|
||||
import {Institution} from "../types/survey.ts";
|
||||
|
||||
export function hostUrl(url: string){
|
||||
return DEBUG_MODE? "http://localhost:8000"+url: url;
|
||||
@@ -57,7 +58,7 @@ const createQueryString = (params: Record<string, string | number | boolean | un
|
||||
return filteredParams.join('&');
|
||||
};
|
||||
|
||||
export function useDataPage<T>(application:string, endpoint: string, params:{[key:string]:string|number}={}) {
|
||||
export function useDataPage<T>(application:string, endpoint: string, params:{[key:string]:string|number}={}, needLoad:boolean=true):PageControl<T> {
|
||||
const [data, setData] = useState<T[]|null>(null);
|
||||
// const [previousUrl, setPreviousUrl] = useState<string|undefined>(undefined)
|
||||
// const [nextUrl, setNextUrl] = useState<string|undefined>(undefined)
|
||||
@@ -67,7 +68,7 @@ export function useDataPage<T>(application:string, endpoint: string, params:{[ke
|
||||
|
||||
useEffect(
|
||||
()=>{
|
||||
if (data === null){
|
||||
if (data === null && needLoad){
|
||||
getFetch(`/${application}/${endpoint}/?${createQueryString(params)}`).then((r)=>{
|
||||
if (r.success){
|
||||
const pageData = r.body as PageResponse<T>;
|
||||
@@ -82,7 +83,7 @@ export function useDataPage<T>(application:string, endpoint: string, params:{[ke
|
||||
})
|
||||
}
|
||||
},
|
||||
[data, application, endpoint]
|
||||
[data, application, endpoint, needLoad]
|
||||
)
|
||||
|
||||
// function changePage(pageUrl: string|undefined) {
|
||||
@@ -110,8 +111,8 @@ export function useDataPage<T>(application:string, endpoint: string, params:{[ke
|
||||
|
||||
return {
|
||||
items: data,
|
||||
hasPrevious: undefined,//previousUrl !== undefined,
|
||||
hasNext: undefined,//nextUrl !== undefined,
|
||||
hasPrevious: false,//previousUrl !== undefined,
|
||||
hasNext: false,//nextUrl !== undefined,
|
||||
nextPage,
|
||||
previousPage
|
||||
} as PageControl<T>
|
||||
@@ -119,28 +120,68 @@ export function useDataPage<T>(application:string, endpoint: string, params:{[ke
|
||||
|
||||
}
|
||||
|
||||
export function useData<T>(application:string, endpoint: string, id: string|number) {
|
||||
export function useData<T>(application:string, endpoint: string, id: string|number, needLoad:boolean=true): T|null|undefined {
|
||||
|
||||
const [data, setData] = useState<T | null | undefined>(null);
|
||||
|
||||
useEffect(
|
||||
()=>{
|
||||
if (data === null){
|
||||
if (data === null && needLoad){
|
||||
getFetch(`/${application}/${endpoint}/${id}`).then((r)=>{
|
||||
if (r.success){
|
||||
const pageData = r.body as T;
|
||||
setData(pageData);
|
||||
}
|
||||
else {
|
||||
setData(null);
|
||||
setData(undefined);
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
[data, application, endpoint, id]
|
||||
[data, application, endpoint, id, needLoad]
|
||||
)
|
||||
|
||||
return data;
|
||||
|
||||
}
|
||||
|
||||
export function useCachedData<T>(application: string, endpoint: string) {
|
||||
const [cache, setCache] = useState<Map<string | number, T | undefined>>(new Map());
|
||||
|
||||
useEffect(() => {
|
||||
// Очистка кеша или другие побочные эффекты при необходимости
|
||||
return () => {
|
||||
setCache(new Map());
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (id: string | number, needLoad: boolean = true): T | undefined | null => {
|
||||
const cachedData = cache.has(id)?cache.get(id):null;
|
||||
|
||||
if (cachedData !== null) {
|
||||
return cachedData;
|
||||
}
|
||||
|
||||
if (needLoad) {
|
||||
getFetch(`/${application}/${endpoint}/${id}`).then((r) => {
|
||||
if (r.success) {
|
||||
const data = r.body as T;
|
||||
setCache((prevCache) => {
|
||||
const newCache = new Map(prevCache);
|
||||
newCache.set(id, data);
|
||||
return newCache;
|
||||
});
|
||||
} else {
|
||||
setCache((prevCache) => {
|
||||
const newCache = new Map(prevCache);
|
||||
newCache.set(id, undefined);
|
||||
return newCache;
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
79
src/App.tsx
79
src/App.tsx
@@ -1,25 +1,84 @@
|
||||
// App.tsx
|
||||
import {BrowserRouter as Router, Routes, Route, Navigate, Link} from 'react-router-dom';
|
||||
import React from "react";
|
||||
import {BrowserRouter as Router, Routes, Route, Link, Navigate, Outlet, useNavigate} from 'react-router-dom';
|
||||
import {MainPage} from "./pages/MainPage.tsx";
|
||||
import {SurveyPage} from "./pages/SurveyPage.tsx";
|
||||
import {DashboardPage} from "./pages/DashboardPage.tsx";
|
||||
|
||||
import { SurveyResultPage } from './pages/SurveyResultPage.tsx';
|
||||
import { ProfessionPage } from './pages/ProfessionPage.tsx';
|
||||
import React, {useEffect} from "react";
|
||||
import {LoginPage} from "./pages/LoginPage.tsx";
|
||||
import {UserProvider} from "./utils/users/UserProvider.tsx";
|
||||
import {useUser} from "./utils/users/UseUser.ts";
|
||||
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<UserProvider>
|
||||
<Router>
|
||||
<Routes>
|
||||
|
||||
<Route path="/login/" element={<LoginPage />} />
|
||||
|
||||
|
||||
<Route path="/dashboard/*" element={<DashboardLayout />}>
|
||||
<Route index element={<DashboardPage />} />
|
||||
</Route>
|
||||
|
||||
|
||||
<Route path="/" element={<MainLayout />}>
|
||||
<Route index element={<MainPage />} />
|
||||
<Route path="/surveys/results/:scoreVariableId/" element={<SurveyResultPage />} />
|
||||
<Route path="/surveys/professions/:professionId/" element={<ProfessionPage />} />
|
||||
<Route path="/surveys/:surveyId/" element={<SurveyPage />} />
|
||||
</Route>
|
||||
|
||||
<Route path="*" element={<Navigate to="/" />} />
|
||||
</Routes>
|
||||
</Router>
|
||||
</UserProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
export function DashboardLayout() {
|
||||
const { user } = useUser();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) {
|
||||
navigate("/login/")
|
||||
}
|
||||
}, [navigate, user]);
|
||||
|
||||
if (!user){
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="header">
|
||||
<h1 className="logo">Pro-Fi</h1>
|
||||
</div>
|
||||
<div className="content">
|
||||
<Outlet />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
function MainLayout() {
|
||||
return (
|
||||
<>
|
||||
<div className="header">
|
||||
<Link to="/dashboard" className="menu-button">☰</Link>
|
||||
<h1 className="logo">Pro-Fi Test</h1>
|
||||
</div>
|
||||
<Routes>
|
||||
<Route path="/" element={<MainPage/>}/>
|
||||
<Route path="/surveys/:surveyId/" element={<SurveyPage/>}/>
|
||||
<Route path="/dashboard/" element={<DashboardPage/>}/>
|
||||
<Route path="*" element={<Navigate to="/"/>}/>
|
||||
</Routes>
|
||||
</Router>
|
||||
<div className="content">
|
||||
<Outlet />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {ReactElement} from "react";
|
||||
import {Link} from "react-router-dom";
|
||||
|
||||
export function LoadingData({data, children}: {data: object|null|undefined, children: ReactElement}) {
|
||||
export function LoadingData({data, children}: {data: object|null|undefined, children: (ReactElement | null | undefined | boolean)[]}) {
|
||||
|
||||
if (data === null){
|
||||
return <div className={"loading"}>Идёт загрузка...</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {ReactElement} from "react";
|
||||
import {UniqueItem} from "../types/common.ts";
|
||||
import {JSX} from "react";
|
||||
|
||||
export function LoadingList({data, listElement}: {data: UniqueItem[]|null, listElement(e:UniqueItem, i:number):ReactElement}) {
|
||||
export function LoadingList({data, listElement}: {data: UniqueItem[]|null, listElement(e:UniqueItem, i:number):unknown}) {
|
||||
if (data === null){
|
||||
return <div className={"loading"}>Идёт загрузка...</div>
|
||||
}
|
||||
|
||||
3
src/pages/LoginPage.tsx
Normal file
3
src/pages/LoginPage.tsx
Normal file
@@ -0,0 +1,3 @@
|
||||
export function LoginPage() {
|
||||
return null;
|
||||
}
|
||||
57
src/pages/ProfessionPage.tsx
Normal file
57
src/pages/ProfessionPage.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import {Link, useParams} from 'react-router-dom';
|
||||
import {useCachedData, useData, useDataPage} from '../API/common';
|
||||
import { Institution, Profession, Specialty } from '../types/survey';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import { LoadingData } from '../components/LoadingData';
|
||||
import { LoadingList } from '../components/LoadingList';
|
||||
|
||||
|
||||
|
||||
export function ProfessionPage() {
|
||||
const { professionId } = useParams<{ professionId: string }>();
|
||||
const profession = useData<Profession>('surveys', 'professions', professionId || 0);
|
||||
const specialties = useDataPage<Specialty>('surveys', 'specialties', { profession: professionId || 0 }, !!profession);
|
||||
|
||||
const institutions = useCachedData<Institution>("surveys", "institutions");
|
||||
|
||||
return (
|
||||
<div>
|
||||
<LoadingData data={profession}>
|
||||
<h1>{profession?.name}</h1>
|
||||
<div className="description">
|
||||
<ReactMarkdown>{profession?.description || ''}</ReactMarkdown>
|
||||
</div>
|
||||
<div className="specialties-block">
|
||||
{specialties.items != null ? <h2>Где можно обучиться</h2>:null}
|
||||
<LoadingList
|
||||
data={specialties.items}
|
||||
listElement={specialty => (
|
||||
<SpecialtyBlock
|
||||
key={specialty.id}
|
||||
specialty={specialty as Specialty}
|
||||
institution={institutions((specialty as Specialty).institution)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</LoadingData>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SpecialtyBlock({
|
||||
specialty,
|
||||
institution,
|
||||
}: {
|
||||
specialty: Specialty;
|
||||
institution: Institution | undefined | null;
|
||||
}) {
|
||||
return (
|
||||
<div className="specialty-block">
|
||||
<h3>Учебное заведение: {institution?.name || 'Загрузка...'}</h3>
|
||||
<p className={"specialty-name"}>{specialty.name}</p>
|
||||
{specialty.link?<Link to={specialty.link} className={"site"}>Открыть сайт</Link>:null}
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,53 +1,167 @@
|
||||
import {LoadingList} from "../components/LoadingList.tsx";
|
||||
import {Survey} from "../types/survey.ts";
|
||||
import {Link, useParams} from "react-router-dom";
|
||||
import React from "react";
|
||||
import {useData, useDataPage} from "../API/common.ts";
|
||||
import {LoadingData} from "../components/LoadingData.tsx";
|
||||
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Navigate, useNavigate, useParams } from "react-router-dom";
|
||||
import {
|
||||
Survey,
|
||||
Question,
|
||||
QuestionPair,
|
||||
AgreementQuestion,
|
||||
QuestionType,
|
||||
ScoreVariable,
|
||||
} from "../types/survey";
|
||||
import { useData, useDataPage } from "../API/common";
|
||||
import { LoadingData } from "../components/LoadingData";
|
||||
import { LoadingList } from "../components/LoadingList";
|
||||
|
||||
export function SurveyPage() {
|
||||
const { surveyId } = useParams<{ surveyId: string }>();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const {surveyId} = useParams();
|
||||
// Загрузка теста
|
||||
const survey = useData<Survey>("surveys", "surveys", surveyId || 0);
|
||||
|
||||
const survey = useData<Survey>("surveys", "surveys", surveyId);
|
||||
// Загрузка вопросов
|
||||
const [questions, setQuestions] = useState<Question[] | null>(null);
|
||||
const questionsPairs = useDataPage<QuestionPair>("surveys", "question-pairs", { survey: surveyId || 0 });
|
||||
const questionsAgreement = useDataPage<AgreementQuestion>("surveys", "agreement-questions", { survey: surveyId || 0 });
|
||||
|
||||
|
||||
// Состояние для ответов
|
||||
const [answers, setAnswers] = useState<Record<string, number>>({});
|
||||
const [isCompleted, setIsCompleted] = useState(false);
|
||||
|
||||
// Объединение вопросов после загрузки
|
||||
useEffect(() => {
|
||||
if (
|
||||
questions === null &&
|
||||
questionsPairs.items !== null &&
|
||||
questionsAgreement.items !== null
|
||||
) {
|
||||
const mergedQuestions = [
|
||||
...questionsPairs.items.map((q:Question) => ({ ...q, questionType: QuestionType.QuestionPair })),
|
||||
...questionsAgreement.items.map((q:Question) => ({ ...q, questionType: QuestionType.AgreementQuestion })),
|
||||
];
|
||||
mergedQuestions.sort(() => Math.random() - 0.5); // Перемешивание
|
||||
setQuestions(mergedQuestions);
|
||||
}
|
||||
}, [questions, questionsPairs.items, questionsAgreement.items]);
|
||||
|
||||
// Проверка завершения теста
|
||||
useEffect(() => {
|
||||
if (questions && Object.keys(answers).length === questions.length) {
|
||||
setIsCompleted(true);
|
||||
} else {
|
||||
setIsCompleted(false);
|
||||
}
|
||||
}, [questions, answers]);
|
||||
|
||||
// Обработка ответов
|
||||
const handleAnswer = (questionKey: string, answerValue: number) => {
|
||||
setAnswers((prev) => ({ ...prev, [questionKey]: answerValue }));
|
||||
};
|
||||
|
||||
// Вычисление итогового score_variable
|
||||
const calculateResults = () => {
|
||||
if (!questions) return;
|
||||
|
||||
const scoreCounts: Record<string, number> = {};
|
||||
|
||||
questions.forEach((question) => {
|
||||
const questionKey = `${question.questionType}_${question.id}`;
|
||||
const answer = answers[questionKey];
|
||||
if (answer !== undefined) {
|
||||
if (question.questionType === QuestionType.QuestionPair) {
|
||||
const selectedStatement = (question as QuestionPair).statements.find(
|
||||
(s) => s.id === answer
|
||||
);
|
||||
if (selectedStatement) {
|
||||
scoreCounts[selectedStatement.score_variable] =
|
||||
(scoreCounts[selectedStatement.score_variable] || 0) + 1;
|
||||
}
|
||||
} else if (question.questionType === QuestionType.AgreementQuestion) {
|
||||
const scoreVariable = (question as AgreementQuestion).score_variable;
|
||||
scoreCounts[scoreVariable] = (scoreCounts[scoreVariable] || 0) + answer;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const maxScoreVariable = Object.keys(scoreCounts).reduce((a, b) =>
|
||||
scoreCounts[a] > scoreCounts[b] ? a : b
|
||||
);
|
||||
|
||||
navigate(`/surveys/results/${maxScoreVariable}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="survey-page">
|
||||
<LoadingData data={survey}>
|
||||
<h1>
|
||||
{survey?.title}
|
||||
</h1>
|
||||
<div>
|
||||
{survey?.description}
|
||||
</div>
|
||||
<h1>{survey?.title}</h1>
|
||||
<div>{survey?.description}</div>
|
||||
|
||||
<SurveyQuestions survey={survey}/>
|
||||
<LoadingList data={questions} listElement={(question: Question) => (
|
||||
<QuestionBlock
|
||||
key={`${question.questionType}_${question.id}`} // Используем тип вопроса и id для уникальности
|
||||
question={question}
|
||||
onAnswer={handleAnswer}
|
||||
answered={answers[`${question.questionType}_${question.id}`]} // Учитываем тип вопроса в ключе
|
||||
/>
|
||||
)} />
|
||||
|
||||
</LoadingData>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
function SurveyQuestions({survey}: { survey: Survey | null | undefined }) {
|
||||
|
||||
const _survey = survey as Survey;
|
||||
|
||||
const questionsPairs = useDataPage("surveys", "question-pairs", {survey:_survey.id});
|
||||
const questionsAgreement = useDataPage("surveys", "question-pairs", {survey:_survey.id});
|
||||
|
||||
//const questions =
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
|
||||
{isCompleted && (
|
||||
<button onClick={calculateResults}>Завершить тест</button>
|
||||
)}
|
||||
</>
|
||||
</LoadingData>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function QuestionBlock({
|
||||
question,
|
||||
onAnswer,
|
||||
answered,
|
||||
}: {
|
||||
question: Question;
|
||||
onAnswer: (questionId: string, answerValue: number) => void;
|
||||
answered?: number;
|
||||
}) {
|
||||
switch (question.questionType) {
|
||||
case QuestionType.AgreementQuestion:
|
||||
{ const agreementQuestion = question as AgreementQuestion;
|
||||
return (
|
||||
<div className={`question agreement ${answered !== undefined ? "answered" : "unanswered"}`}>
|
||||
{agreementQuestion.question}
|
||||
<button
|
||||
className={`answer ${answered === 1 ? "selected" : "idle"}`}
|
||||
disabled={answered===1}
|
||||
onClick={() => onAnswer(`${question.questionType}_${question.id}`, 1)}>Согласен</button>
|
||||
<button
|
||||
className={`answer ${answered === 0 ? "selected" : "idle"}`}
|
||||
disabled={answered === 0}
|
||||
onClick={() => onAnswer(`${question.questionType}_${question.id}`, 0)}>Не согласен</button>
|
||||
|
||||
</div>
|
||||
); }
|
||||
|
||||
case QuestionType.QuestionPair:
|
||||
{ const pairQuestion = question as QuestionPair;
|
||||
return (
|
||||
<div className={`question pair ${answered !== undefined ? "answered" : "unanswered"}`}>
|
||||
{pairQuestion.statements.map((statement) => (
|
||||
<button
|
||||
className={`answer ${answered === statement.id ? "selected" : "idle"}`}
|
||||
disabled={answered === statement.id}
|
||||
key={statement.id}
|
||||
onClick={() => onAnswer(`${question.questionType}_${question.id}`, statement.id)}
|
||||
>
|
||||
{statement.text}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
); }
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
45
src/pages/SurveyResultPage.tsx
Normal file
45
src/pages/SurveyResultPage.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import { useData, useDataPage } from '../API/common';
|
||||
import { Profession, ScoreVariable, Survey } from '../types/survey';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import { LoadingData } from '../components/LoadingData';
|
||||
import { LoadingList } from '../components/LoadingList';
|
||||
|
||||
export function SurveyResultPage() {
|
||||
const { scoreVariableId } = useParams<{ scoreVariableId: string }>();
|
||||
const scoreVariable = useData<ScoreVariable>('surveys', 'score-variables', scoreVariableId || 0);
|
||||
const survey = useData<Survey>('surveys', 'surveys', scoreVariable?.survey || 0, !!scoreVariable);
|
||||
|
||||
const professions = useDataPage<Profession>(
|
||||
'surveys',
|
||||
'professions',
|
||||
{ score_variable: scoreVariableId || 0 },
|
||||
!!scoreVariable
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<LoadingData data={survey && scoreVariable?survey:scoreVariable}>
|
||||
<h1>{survey?.title}</h1>
|
||||
<div className={"result"}>
|
||||
<h2>Ваш результат</h2>
|
||||
<p>{scoreVariable?.title}</p>
|
||||
</div>
|
||||
<div className={"description"}>
|
||||
<ReactMarkdown>{scoreVariable?.description}</ReactMarkdown>
|
||||
</div>
|
||||
<div className={"profession-list"}>
|
||||
<h3>Подходящие профессии</h3>
|
||||
<LoadingList
|
||||
data={professions.items}
|
||||
listElement={(profession)=>(
|
||||
<Link key={profession.id} to={`/surveys/professions/${profession.id}/`} className={"profession"}>
|
||||
{(profession as Profession).name}
|
||||
</Link>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</LoadingData>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,3 +10,7 @@ export interface PageControl<T>{
|
||||
nextPage(): void;
|
||||
previousPage(): void;
|
||||
}
|
||||
|
||||
export interface CachedData<T>{
|
||||
|
||||
}
|
||||
|
||||
@@ -11,6 +11,47 @@ interface Statement extends UniqueItem{
|
||||
score_variable: number;
|
||||
}
|
||||
|
||||
export interface QuestionPair extends UniqueItem{
|
||||
|
||||
export enum QuestionType{
|
||||
QuestionPair,
|
||||
AgreementQuestion
|
||||
}
|
||||
|
||||
export interface Question extends UniqueItem{
|
||||
questionType: QuestionType
|
||||
}
|
||||
|
||||
|
||||
export interface QuestionPair extends Question{
|
||||
statements: Statement[]
|
||||
}
|
||||
|
||||
|
||||
|
||||
export interface AgreementQuestion extends Question{
|
||||
question: string;
|
||||
score_variable: number;
|
||||
}
|
||||
|
||||
|
||||
export interface ScoreVariable {
|
||||
id: string;
|
||||
name: string;
|
||||
title: string;
|
||||
description: string;
|
||||
survey: number;
|
||||
}
|
||||
|
||||
export interface Profession extends UniqueItem {
|
||||
name: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface Specialty extends UniqueItem {
|
||||
name: string;
|
||||
institution: number;
|
||||
link?: string;
|
||||
}
|
||||
|
||||
export interface Institution extends UniqueItem {
|
||||
name: string;
|
||||
}
|
||||
22
src/types/users.ts
Normal file
22
src/types/users.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import {UniqueItem} from "./common.ts";
|
||||
|
||||
|
||||
export interface ContactData{
|
||||
first_name: string;
|
||||
last_name?: string;
|
||||
middle_name?: string;
|
||||
phone?: string;
|
||||
email?:string;
|
||||
}
|
||||
|
||||
interface Role extends UniqueItem{
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface Account extends UniqueItem, ContactData{
|
||||
login: string;
|
||||
role?: Role;
|
||||
is_staff: boolean;
|
||||
is_active: boolean;
|
||||
|
||||
}
|
||||
13
src/utils/users/UseUser.ts
Normal file
13
src/utils/users/UseUser.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
|
||||
import {UserContext} from "./UserContext.ts";
|
||||
import {useContext} from "react";
|
||||
|
||||
|
||||
|
||||
export function useUser() {
|
||||
const context = useContext(UserContext);
|
||||
if (!context) {
|
||||
throw new Error('useUser must be used within a UserProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
10
src/utils/users/UserContext.ts
Normal file
10
src/utils/users/UserContext.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import {Account} from "../../types/users.ts";
|
||||
import {createContext} from "react";
|
||||
|
||||
export type UserContextType = {
|
||||
user: Account | undefined;
|
||||
login: (userData: Account) => void;
|
||||
logout: () => void;
|
||||
};
|
||||
|
||||
export const UserContext = createContext<UserContextType | undefined>(undefined);
|
||||
35
src/utils/users/UserProvider.tsx
Normal file
35
src/utils/users/UserProvider.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import React, {ReactNode, useEffect, useState} from 'react';
|
||||
import {Account} from '../../types/users.ts';
|
||||
import {UserContext} from "./UserContext.ts";
|
||||
|
||||
|
||||
export function UserProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<Account | undefined>(() => {
|
||||
const storedUser = localStorage.getItem('user');
|
||||
return storedUser ? JSON.parse(storedUser) : undefined;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
localStorage.setItem('user', JSON.stringify(user));
|
||||
document.cookie = `user=${encodeURIComponent(JSON.stringify(user))}; path=/;`;
|
||||
} else {
|
||||
localStorage.removeItem('user');
|
||||
document.cookie = 'user=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const login = (userData: Account) => {
|
||||
setUser(userData);
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
setUser(undefined);
|
||||
};
|
||||
|
||||
return (
|
||||
<UserContext.Provider value={{ user, login, logout }}>
|
||||
{children}
|
||||
</UserContext.Provider>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user