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 { getConfigValue } from "@ijl/cli";
import { keycloak } from "../kc"; import { keycloak } from "../kc";
import { BaseResponse, Lesson } from "../model"; import { AccessCode, BaseResponse, Lesson, UserData } from "../model";
export const api = createApi({ export const api = createApi({
reducerPath: "auth", reducerPath: "auth",
@ -15,37 +15,35 @@ export const api = createApi({
headers.set('Authorization', `Bearer ${keycloak.token}`) headers.set('Authorization', `Bearer ${keycloak.token}`)
} }
}), }),
tagTypes: ['Lesson'],
endpoints: (builder) => ({ endpoints: (builder) => ({
lessonList: builder.query<BaseResponse<Lesson[]>, void>({ 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 { export interface Lesson {
_id: string; _id: string;
name: string; name: string;
students: any[]; students: Student[];
date: string; date: string;
created: 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> <Routes>
<Route path="/journal" element={<Redirect path="/journal/main" />} /> <Route path="/journal" element={<Redirect path="/journal/main" />} />
<Route path="/journal/main" element={<MainPage />} /> <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 />} /> <Route path="/journal/l/:lessonId" element={<Lesson />} />
</Routes> </Routes>
</Provider> </Provider>

View File

@ -1,7 +1,7 @@
import React, { useCallback, useEffect, useRef, useState } from "react"; import React, { useCallback, useEffect, useRef, useState } from 'react'
import dayjs from "dayjs"; import dayjs from 'dayjs'
import { Link } from "react-router-dom"; import { Link } from 'react-router-dom'
import { getConfigValue } from "@ijl/cli"; import { getConfigValue } from '@ijl/cli'
import { import {
ArrowImg, ArrowImg,
@ -12,88 +12,60 @@ import {
StartWrapper, StartWrapper,
LessonItem, LessonItem,
Lessonname, Lessonname,
} from "./style"; Papper,
ErrorSpan,
Cross,
AddButton,
} from './style'
import arrow from "../assets/36-arrow-right.svg"; import arrow from '../assets/36-arrow-right.svg'
import { keycloak } from "../__data__/kc"; import { keycloak } from '../__data__/kc'
import { useAppSelector } from "../__data__/store"; import { useAppSelector } from '../__data__/store'
import { api } from '../__data__/api/api' import { api } from '../__data__/api/api'
import { isTeacher } from "../utils/user"; import { isTeacher } from '../utils/user'
export const Journal = () => { export const Journal = () => {
const [lessons, setLessons] = useState(null); const user = useAppSelector((s) => s.user)
const user = useAppSelector((s) => s.user); const { data, isLoading, error } = api.useLessonListQuery()
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( const handleChange = useCallback(
(event) => { (event) => {
setValue(event.target.value.toUpperCase()); setValue(event.target.value.toUpperCase())
}, },
[setValue] [setValue],
); )
const inputRef = useRef<HTMLInputElement>(null);
const handleSubmit = useCallback( const handleSubmit = useCallback(
(event) => { (event) => {
event.preventDefault(); event.preventDefault()
createLesson({ name: value })
// const socket = getSocket();
// socket.emit("create-lesson", { lessonName: value });
setValue("");
}, },
[value] [value],
); )
useEffect(() => {
if (crLQuery.isSuccess) {
setValue('')
}
}, [crLQuery.isSuccess])
return ( return (
<StartWrapper> <StartWrapper>
{isTeacher(user) && ( {isTeacher(user) && (
<>
{showForm ? (
<Papper>
<Cross role="button" onClick={() => setShowForm(false)}>X</Cross>
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
<InputWrapper> <InputWrapper>
<InputLabel htmlFor="input">Название новой лекции:</InputLabel> <InputLabel htmlFor="input">
Название новой лекции:
</InputLabel>
<InputElement <InputElement
value={value} value={value}
onChange={handleChange} onChange={handleChange}
ref={inputRef}
id="input" id="input"
type="text" type="text"
autoComplete="off" autoComplete="off"
@ -102,15 +74,26 @@ export const Journal = () => {
<ArrowImg src={arrow} /> <ArrowImg src={arrow} />
</IconButton> </IconButton>
</InputWrapper> </InputWrapper>
{crLQuery.error && (
<ErrorSpan>{crLQuery.error.error}</ErrorSpan>
)}
</form> </form>
</Papper>
) : (
<AddButton onClick={() => setShowForm(true)}>Добавить</AddButton>
)}
</>
)} )}
<ul style={{ paddingLeft: 0 }}> <ul style={{ paddingLeft: 0 }}>
{data?.body?.map((lesson) => ( {data?.body?.map((lesson) => (
<LessonItem key={lesson._id}> <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> <Lessonname>{lesson.name}</Lessonname>
<span>{dayjs(lesson.date).format("DD MMMM YYYYг.")}</span> <span>{dayjs(lesson.date).format('DD MMMM YYYYг.')}</span>
<span style={{ marginLeft: "auto" }}> <span style={{ marginLeft: 'auto' }}>
Участников - {lesson.students.length} Участников - {lesson.students.length}
</span> </span>
</Link> </Link>
@ -118,5 +101,5 @@ export const Journal = () => {
))} ))}
</ul> </ul>
</StartWrapper> </StartWrapper>
); )
}; }

View File

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

View File

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

View File

@ -1,12 +1,12 @@
import styled from '@emotion/styled'; import styled from '@emotion/styled'
import { css, keyframes } from '@emotion/react'; import { css, keyframes } from '@emotion/react'
export const MainWrapper = styled.main` export const MainWrapper = styled.main`
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
height: 100%; height: 100%;
`; `
export const InputWrapper = styled.div` export const InputWrapper = styled.div`
position: relative; position: relative;
@ -17,13 +17,13 @@ export const InputWrapper = styled.div`
@media screen and (max-width: 600px) { @media screen and (max-width: 600px) {
flex-direction: column; flex-direction: column;
} }
`; `
export const InputLabel = styled.label` export const InputLabel = styled.label`
position: absolute; position: absolute;
top: -8px; top: -8px;
left: 24px; left: 24px;
z-index: 2; z-index: 2;
`; `
export const InputElement = styled.input` export const InputElement = styled.input`
border: 1px solid #ccc; border: 1px solid #ccc;
padding: 12px; padding: 12px;
@ -31,12 +31,13 @@ export const InputElement = styled.input`
border-radius: 8px; border-radius: 8px;
color: #117623; color: #117623;
max-width: 90vw; max-width: 90vw;
`; box-shadow: inset 7px 8px 20px 8px #4990db12;
`
export const ArrowImg = styled.img` export const ArrowImg = styled.img`
width: 48px; width: 48px;
height: 48px; height: 48px;
`; `
export const IconButton = styled.button` export const IconButton = styled.button`
border: none; border: none;
@ -44,7 +45,7 @@ export const IconButton = styled.button`
display: flex; display: flex;
align-items: center; align-items: center;
height: 100%; height: 100%;
`; `
const reveal = keyframes` const reveal = keyframes`
0% { 0% {
@ -54,7 +55,7 @@ const reveal = keyframes`
100% { 100% {
transform: scale(1); transform: scale(1);
} }
`; `
export const StartWrapper = styled.div` export const StartWrapper = styled.div`
animation: ${reveal} 1s ease forwards; animation: ${reveal} 1s ease forwards;
@ -63,7 +64,7 @@ export const StartWrapper = styled.div`
height: calc(100vh - 300px); height: calc(100vh - 300px);
/* margin: 60px auto; */ /* margin: 60px auto; */
position: relative; position: relative;
`; `
export const Svg = styled.svg` export const Svg = styled.svg`
position: absolute; position: absolute;
@ -72,7 +73,15 @@ export const Svg = styled.svg`
transform-origin: 50% 50%; transform-origin: 50% 50%;
transform: translate(-50%, -50%); transform: translate(-50%, -50%);
/* stroke-dasharray: 600; */ /* 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` export const LessonItem = styled.li`
list-style: none; list-style: none;
@ -81,13 +90,47 @@ export const LessonItem = styled.li`
border-radius: 12px; border-radius: 12px;
box-shadow: 2px 2px 6px #0000005c; box-shadow: 2px 2px 6px #0000005c;
margin-bottom: 12px; margin-bottom: 12px;
`; `
export const Lessonname = styled.span` export const Lessonname = styled.span`
display: inline-box; display: inline-box;
margin-right: 12px; margin-right: 12px;
`; `
export const QRCanvas = styled.canvas` export const QRCanvas = styled.canvas`
display: block; 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 }) res.send({ ok: true })
}) })
@ -8,4 +10,22 @@ router.get('/lesson/list', (req, res) => {
res.send(require('../mocks/lessons/list/success.json')) 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
}
}