This commit is contained in:
Primakov Alexandr Alexandrovich 2024-03-01 11:43:31 +03:00
parent ff1f8e0452
commit 9e1c2c9504
12 changed files with 400 additions and 226 deletions

7
.prettierrc.json Normal file
View File

@ -0,0 +1,7 @@
{
"tabWidth": 2,
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"jsxSingleQuote": false
}

View File

@ -2,7 +2,7 @@ import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { getConfigValue } from "@ijl/cli";
import { keycloak } from "../kc";
import { BaseResponse, Lesson } from "../model";
import { AccessCode, BaseResponse, Lesson, UserData } from "../model";
export const api = createApi({
reducerPath: "auth",
@ -15,37 +15,35 @@ export const api = createApi({
headers.set('Authorization', `Bearer ${keycloak.token}`)
}
}),
tagTypes: ['Lesson'],
endpoints: (builder) => ({
lessonList: builder.query<BaseResponse<Lesson[]>, void>({
query: () => '/lesson/list'
query: () => '/lesson/list',
providesTags: ['Lesson']
}),
createLesson: builder.mutation<BaseResponse<Lesson>, Pick<Lesson, 'name'>>({
query: ({ name }) => ({
url: '/lesson',
method: 'POST',
body: {name },
}),
invalidatesTags: ['Lesson']
}),
lessonById: builder.query<BaseResponse<Lesson>, string>({
query: (lessonId: string) => `/api/lesson/${lessonId}`
}),
createAccessCode: builder.query<BaseResponse<AccessCode>, { lessonId: string }>({
query: ({ lessonId }) => ({
url: '/lesson/access-code',
method: 'POST',
body: { lessonId },
})
}),
getAccess: builder.query<BaseResponse<{ user: UserData, accessCode: AccessCode }>, { accessCode: string }>({
query: ({ accessCode }) => ({
url: `/lesson/access-code/${accessCode}`,
method: 'GET',
})
})
// signIn: builder.mutation<SignInResponce, SignInRequestBody>({
// query: ({ login, password }) => ({
// url: URLs.queryApi.login,
// method: 'POST',
// body: { login, password },
// }),
// }),
// recoverPassword: builder.mutation<{ error?: string }, { email: string }>({
// query: ({ email }) => ({
// url: URLs.queryApi.revoverPassword,
// method: 'POST',
// body: { email }
// })
// }),
// recoverPasswordConfirm: builder.mutation<{ error?: string }, { code: string }>({
// query: ({ code }) => ({
// url: URLs.queryApi.revoverPasswordConfirm,
// method: 'POST',
// body: { code }
// })
// }),
// recoverPasswordNewPassword: builder.mutation<{ error?: string }, { newPassword: string }>({
// query: ({ newPassword }) => ({
// url: URLs.queryApi.revoverPasswordNew,
// method: 'POST',
// body: { newPassword }
// })
// })
}),
});

View File

@ -52,7 +52,27 @@ export type BaseResponse<Data> = {
export interface Lesson {
_id: string;
name: string;
students: any[];
students: Student[];
date: string;
created: string;
}
export interface AccessCode {
expires: string;
lesson: Lesson;
_id: string;
created: string;
__v: number;
}
export interface Student {
sub: string;
email_verified: boolean;
gravatar: string;
name: string;
groups: string[];
preferred_username: string;
given_name: string;
family_name: string;
email: string;
}

View File

@ -21,7 +21,7 @@ export const Dashboard = ({ store }) => (
<Routes>
<Route path="/journal" element={<Redirect path="/journal/main" />} />
<Route path="/journal/main" element={<MainPage />} />
<Route path="/journal/u/:lessonId" element={<UserPage />} />
<Route path="/journal/u/:lessonId/:accessId" element={<UserPage />} />
<Route path="/journal/l/:lessonId" element={<Lesson />} />
</Routes>
</Provider>

View File

@ -1,7 +1,7 @@
import React, { useCallback, useEffect, useRef, useState } from "react";
import dayjs from "dayjs";
import { Link } from "react-router-dom";
import { getConfigValue } from "@ijl/cli";
import React, { useCallback, useEffect, useRef, useState } from 'react'
import dayjs from 'dayjs'
import { Link } from 'react-router-dom'
import { getConfigValue } from '@ijl/cli'
import {
ArrowImg,
@ -12,105 +12,88 @@ import {
StartWrapper,
LessonItem,
Lessonname,
} from "./style";
Papper,
ErrorSpan,
Cross,
AddButton,
} from './style'
import arrow from "../assets/36-arrow-right.svg";
import { keycloak } from "../__data__/kc";
import { useAppSelector } from "../__data__/store";
import arrow from '../assets/36-arrow-right.svg'
import { keycloak } from '../__data__/kc'
import { useAppSelector } from '../__data__/store'
import { api } from '../__data__/api/api'
import { isTeacher } from "../utils/user";
import { isTeacher } from '../utils/user'
export const Journal = () => {
const [lessons, setLessons] = useState(null);
const user = useAppSelector((s) => s.user);
const { data, isLoading, error } = api.useLessonListQuery();
const user = useAppSelector((s) => s.user)
const { data, isLoading, error } = api.useLessonListQuery()
const [createLesson, crLQuery] = api.useCreateLessonMutation()
const [value, setValue] = useState('')
const [showForm, setShowForm] = useState(false)
useEffect(() => {
const check = async () => {
if (keycloak.authenticated) {
keycloak;
const rq = await fetch(`${getConfigValue("journal.back.url")}/check`, {
headers: {
accept: "application/json",
authorization: `Bearer ${keycloak.token}`,
},
});
const data = await rq.json();
console.log("check", data);
} else {
keycloak.onAuthSuccess = check;
}
};
check();
}, []);
const [answer, setAnswer] = useState(null);
const send = async () => {
if (keycloak.authenticated) {
keycloak;
const rq = await fetch(`${getConfigValue("journal.back.url")}/test`, {
headers: {
accept: "application/json",
authorization: `Bearer ${keycloak.token}`,
},
});
const data = await rq.json();
setAnswer(data);
} else {
setAnswer({ message: "Пользователь не авторизован" });
}
};
const [value, setValue] = useState("");
const handleChange = useCallback(
(event) => {
setValue(event.target.value.toUpperCase());
setValue(event.target.value.toUpperCase())
},
[setValue]
);
const inputRef = useRef<HTMLInputElement>(null);
[setValue],
)
const handleSubmit = useCallback(
(event) => {
event.preventDefault();
// const socket = getSocket();
// socket.emit("create-lesson", { lessonName: value });
setValue("");
event.preventDefault()
createLesson({ name: value })
},
[value]
);
[value],
)
useEffect(() => {
if (crLQuery.isSuccess) {
setValue('')
}
}, [crLQuery.isSuccess])
return (
<StartWrapper>
{isTeacher(user) && (
<form onSubmit={handleSubmit}>
<InputWrapper>
<InputLabel htmlFor="input">Название новой лекции:</InputLabel>
<InputElement
value={value}
onChange={handleChange}
ref={inputRef}
id="input"
type="text"
autoComplete="off"
/>
<IconButton type="submit">
<ArrowImg src={arrow} />
</IconButton>
</InputWrapper>
</form>
<>
{showForm ? (
<Papper>
<Cross role="button" onClick={() => setShowForm(false)}>X</Cross>
<form onSubmit={handleSubmit}>
<InputWrapper>
<InputLabel htmlFor="input">
Название новой лекции:
</InputLabel>
<InputElement
value={value}
onChange={handleChange}
id="input"
type="text"
autoComplete="off"
/>
<IconButton type="submit">
<ArrowImg src={arrow} />
</IconButton>
</InputWrapper>
{crLQuery.error && (
<ErrorSpan>{crLQuery.error.error}</ErrorSpan>
)}
</form>
</Papper>
) : (
<AddButton onClick={() => setShowForm(true)}>Добавить</AddButton>
)}
</>
)}
<ul style={{ paddingLeft: 0 }}>
{data?.body?.map((lesson) => (
<LessonItem key={lesson._id}>
<Link to={isTeacher(user) ? `/journal/l/${lesson._id}` : ''} style={{ display: "flex" }}>
<Link
to={isTeacher(user) ? `/journal/l/${lesson._id}` : ''}
style={{ display: 'flex' }}
>
<Lessonname>{lesson.name}</Lessonname>
<span>{dayjs(lesson.date).format("DD MMMM YYYYг.")}</span>
<span style={{ marginLeft: "auto" }}>
<span>{dayjs(lesson.date).format('DD MMMM YYYYг.')}</span>
<span style={{ marginLeft: 'auto' }}>
Участников - {lesson.students.length}
</span>
</Link>
@ -118,5 +101,5 @@ export const Journal = () => {
))}
</ul>
</StartWrapper>
);
};
)
}

View File

@ -1,37 +1,56 @@
import React, { useEffect, useState, useRef } from 'react';
import { useParams } from 'react-router-dom';
import dayjs from 'dayjs';
import QRCode from 'qrcode';
import React, { useEffect, useState, useRef } from 'react'
import { useParams } from 'react-router-dom'
import dayjs from 'dayjs'
import QRCode from 'qrcode'
import { MainWrapper, StartWrapper, QRCanvas, LessonItem, Lessonname } from './style';
import {
MainWrapper,
StartWrapper,
QRCanvas,
LessonItem,
Lessonname,
} from './style'
import { api } from '../__data__/api/api'
export const Lesson = () => {
const { lessonId } = useParams();
const canvRef = useRef(null);
const [lesson, setLesson] = useState(null);
const { lessonId } = useParams()
const canvRef = useRef(null)
const [lesson, setLesson] = useState(null)
const { isFetching, isLoading, data: accessCode, error, isSuccess } =
api.useCreateAccessCodeQuery(
{ lessonId },
{
pollingInterval: 3000,
skipPollingIfUnfocused: true,
},
)
useEffect(() => {
// socket.on('lessons', data => {
// setLesson(data.find(lesson => lesson.id === lessonId));
// })
QRCode.toCanvas(canvRef.current, `${location.origin}/journal/u/${lessonId}` , function (error) {
if (error) console.error(error)
console.log('success!');
})
}, []);
if (!isFetching && isSuccess) {
console.log(`${location.origin}/journal/u/${lessonId}/${accessCode.body._id}`)
QRCode.toCanvas(
canvRef.current,
`${location.origin}/journal/u/${lessonId}/${accessCode.body._id}`,
{ width: 600 },
function (error) {
if (error) console.error(error)
console.log('success!')
},
)
}
}, [isFetching, isSuccess])
return (
<MainWrapper>
<StartWrapper>
<h1>Lesson - {lesson?.name}</h1>
<span>{dayjs(lesson?.ts).format('DD MMMM YYYYг.')}</span>
<h1>Тема занятия - {accessCode?.body?.lesson?.name}</h1>
<span>{dayjs(accessCode?.body?.lesson?.date).format('DD MMMM YYYYг.')} Отмечено - {accessCode?.body?.lesson?.students?.length} человек</span>
<QRCanvas ref={canvRef} />
<ul style={{ paddingLeft: 0 }}>
{lesson?.padavans?.map((padavan, index) => (
{accessCode?.body?.lesson?.students?.map((student, index) => (
<LessonItem key={index}>
<Lessonname>{padavan.name}</Lessonname>
<Lessonname>{student.preferred_username || student.name}</Lessonname>
</LessonItem>
))}
</ul>

View File

@ -1,13 +1,22 @@
import React, { useCallback, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { ArrowImg, IconButton, InputElement, InputLabel, InputWrapper, MainWrapper, StartWrapper } from './style';
import { ArrowImg, IconButton, InputElement, InputLabel, InputWrapper, LessonItem, Lessonname, MainWrapper, StartWrapper } from './style';
import arrow from '../assets/36-arrow-right.svg';
import { api } from '../__data__/api/api';
import dayjs from 'dayjs';
export const UserPage = () => {
const [socketId, setSocketId] = useState(null);
const [error, setError] = useState(null);
const { lessonId } = useParams();
const { lessonId, accessId } = useParams();
const acc = api.useGetAccessQuery({ accessCode: accessId })
const ls = api.useLessonByIdQuery(lessonId, {
pollingInterval: 1000,
skipPollingIfUnfocused: true
});
useEffect(() => {
// socket.on('connect', () => {
// const id = localStorage.getItem('socketId');
@ -30,39 +39,23 @@ export const UserPage = () => {
}, []);
const [value, setValue] = useState(localStorage.getItem('name') || '');
const handleChange = useCallback(event => {
setValue(event.target.value.toUpperCase())
}, [setValue]);
const handleSubmit = useCallback((event) => {
event.preventDefault();
localStorage.setItem('name', value)
// socket.emit('add', { socketId: localStorage.getItem('socketId') || socketId, name: value, lessonid: lessonId });
}, [value])
return (
<MainWrapper>
<StartWrapper>
<form onSubmit={handleSubmit}>
<InputWrapper>
<InputLabel
htmlFor='input'
>
Как вас зовут:
</InputLabel>
<InputElement
value={value}
onChange={handleChange}
id="input"
type="text"
autoComplete="off"
/>
<IconButton type="submit">
<ArrowImg src={arrow} />
</IconButton>
</InputWrapper>
</form>
{acc.isLoading && <h1>Отправляем запрос</h1>}
{acc.isSuccess && <h1>Успешно</h1>}
<h1>Тема занятия - {ls.data?.body?.name}</h1>
<span>{dayjs(ls.data?.body?.date).format('DD MMMM YYYYг.')}</span>
<ul style={{ paddingLeft: 0 }}>
{ls.data?.body?.students?.map((student, index) => (
<LessonItem key={index}>
<Lessonname>{student.preferred_username || student.name}</Lessonname>
</LessonItem>
))}
</ul>
</StartWrapper>
</MainWrapper>
)

View File

@ -1,50 +1,51 @@
import styled from '@emotion/styled';
import { css, keyframes } from '@emotion/react';
import styled from '@emotion/styled'
import { css, keyframes } from '@emotion/react'
export const MainWrapper = styled.main`
display: flex;
justify-content: center;
align-items: center;
height: 100%;
`;
display: flex;
justify-content: center;
align-items: center;
height: 100%;
`
export const InputWrapper = styled.div`
position: relative;
padding: 12px;
display: flex;
align-items: center;
position: relative;
padding: 12px;
display: flex;
align-items: center;
@media screen and (max-width: 600px) {
flex-direction: column;
}
`;
@media screen and (max-width: 600px) {
flex-direction: column;
}
`
export const InputLabel = styled.label`
position: absolute;
top: -8px;
left: 24px;
z-index: 2;
`;
position: absolute;
top: -8px;
left: 24px;
z-index: 2;
`
export const InputElement = styled.input`
border: 1px solid #ccc;
padding: 12px;
font-size: 24px;
border-radius: 8px;
color: #117623;
max-width: 90vw;
`;
border: 1px solid #ccc;
padding: 12px;
font-size: 24px;
border-radius: 8px;
color: #117623;
max-width: 90vw;
box-shadow: inset 7px 8px 20px 8px #4990db12;
`
export const ArrowImg = styled.img`
width: 48px;
height: 48px;
`;
width: 48px;
height: 48px;
`
export const IconButton = styled.button`
border: none;
background-color: rgba(0, 0, 0, 0);
display: flex;
align-items: center;
height: 100%;
`;
border: none;
background-color: rgba(0, 0, 0, 0);
display: flex;
align-items: center;
height: 100%;
`
const reveal = keyframes`
0% {
@ -54,25 +55,33 @@ const reveal = keyframes`
100% {
transform: scale(1);
}
`;
`
export const StartWrapper = styled.div`
animation: ${reveal} 1s ease forwards;
/* box-shadow: 0 -2px 5px rgba(255,255,255,0.05), 0 2px 5px rgba(255,255,255,0.1); */
width: 650px;
height: calc(100vh - 300px);
/* margin: 60px auto; */
position: relative;
`;
animation: ${reveal} 1s ease forwards;
/* box-shadow: 0 -2px 5px rgba(255,255,255,0.05), 0 2px 5px rgba(255,255,255,0.1); */
width: 650px;
height: calc(100vh - 300px);
/* margin: 60px auto; */
position: relative;
`
export const Svg = styled.svg`
position: absolute;
top: 50%;
left: 50%;
transform-origin: 50% 50%;
transform: translate(-50%, -50%);
/* stroke-dasharray: 600; */
`;
position: absolute;
top: 50%;
left: 50%;
transform-origin: 50% 50%;
transform: translate(-50%, -50%);
/* stroke-dasharray: 600; */
`
export const Papper = styled.div`
position: relative;
background-color: #ffffff;
border-radius: 12px;
padding: 32px 16px 16px;
box-shadow: 2px 2px 6px #0000005c;
`
export const LessonItem = styled.li`
list-style: none;
@ -81,13 +90,47 @@ export const LessonItem = styled.li`
border-radius: 12px;
box-shadow: 2px 2px 6px #0000005c;
margin-bottom: 12px;
`;
`
export const Lessonname = styled.span`
display: inline-box;
margin-right: 12px;
`;
`
export const QRCanvas = styled.canvas`
display: block;
`;
`
export const ErrorSpan = styled.span`
color: #f9e2e2;
display: block;
padding: 16px;
background-color: #d32f0b;
border-radius: 11px;
`
export const Cross = styled.button`
position: absolute;
right: 19px;
top: 14px;
font-size: 24px;
padding: 7px;
cursor: pointer;
background-color: #fff;
border: none;
:hover {
background-color: #d7181812;
border-radius: 20px;
}
`
export const AddButton = styled.button`
background-color: transparent;
border: none;
cursor: pointer;
:hover {
box-shadow: 3px 2px 5px #00000038;
}
`

View File

@ -1,6 +1,8 @@
const router = require('express').Router();
const router = require('express').Router()
const fs = require('node:fs')
const path = require('node:path')
router.get('/check', function (req, res){
router.get('/check', function (req, res) {
res.send({ ok: true })
})
@ -8,4 +10,22 @@ router.get('/lesson/list', (req, res) => {
res.send(require('../mocks/lessons/list/success.json'))
})
module.exports = router;
router.post('/lesson', (req, res) => {
res.send(require('../mocks/lessons/create/success.json'))
})
router.post('/lesson/access-code', (req, res) => {
const answer = fs.readFileSync(path.resolve(__dirname, '../mocks/lessons/access-code/create/success.json'))
// res.send(require('../mocks/lessons/access-code/create/success.json'))
res.send(answer)
})
router.get('/lesson/access-code/:accessCode', (req, res) => {
res.send(require('../mocks/lessons/access-code/get/success.json'))
})
router.get('/api/lesson/:lessonId', (req, res) => {
res.send(require('../mocks/lessons/byid/success.json'))
})
module.exports = router

View File

@ -0,0 +1,32 @@
{
"success": true,
"body": {
"expires": "2024-03-01T07:52:16.374Z",
"lesson": {
"_id": "65df996c584b172772d69706",
"name": "Проверочное занятие",
"students": [
{
"sub": "f62905b1-e223-40ca-910f-c8d84c6137c1",
"email_verified": true,
"gravatar": "true",
"name": "Александр Примаков",
"groups": [
"/inno-staff",
"/microfrontend-admin-user"
],
"preferred_username": "primakov",
"given_name": "Александр",
"family_name": "Примаков",
"email": "primakovpro@gmail.com"
}
],
"date": "2024-02-28T20:37:00.057Z",
"created": "2024-02-28T20:37:00.057Z",
"__v": 0
},
"_id": "65e18926584b172772d69722",
"created": "2024-03-01T07:52:06.375Z",
"__v": 0
}
}

View File

@ -0,0 +1,33 @@
{
"success": true,
"body": {
"user": {
"sub": "f62905b1-e223-40ca-910f-c8d84c6137c1",
"email_verified": true,
"gravatar": "true",
"name": "Александр Примаков",
"groups": [
"/inno-staff",
"/microfrontend-admin-user"
],
"preferred_username": "primakov",
"given_name": "Александр",
"family_name": "Примаков",
"email": "primakovpro@gmail.com"
},
"accessCode": {
"_id": "65e1891f584b172772d6971b",
"expires": "2024-03-01T07:52:09.233Z",
"lesson": {
"_id": "65df996c584b172772d69706",
"name": "Проверочное занятие",
"students": [],
"date": "2024-02-28T20:37:00.057Z",
"created": "2024-02-28T20:37:00.057Z",
"__v": 0
},
"created": "2024-03-01T07:51:59.234Z",
"__v": 0
}
}
}

View File

@ -0,0 +1,26 @@
{
"success": true,
"body": {
"_id": "65df996c584b172772d69706",
"name": "Проверочное занятие",
"students": [
{
"sub": "f62905b1-e223-40ca-910f-c8d84c6137c1",
"email_verified": true,
"gravatar": "true",
"name": "Александр Примаков",
"groups": [
"/inno-staff",
"/microfrontend-admin-user"
],
"preferred_username": "primakov",
"given_name": "Александр",
"family_name": "Примаков",
"email": "primakovpro@gmail.com"
}
],
"date": "2024-02-28T20:37:00.057Z",
"created": "2024-02-28T20:37:00.057Z",
"__v": 0
}
}