Compare commits

..

No commits in common. "00488de4604937e41b1cf1f5381c3fb8fca65660" and "e30974acb787d5478cf223ef2aacaf23bf393e3b" have entirely different histories.

7 changed files with 206 additions and 405 deletions

2
.gitignore vendored
View File

@ -9,8 +9,6 @@ pids
*.pid *.pid
*.seed *.seed
*prom.json
# Directory for instrumented libs generated by jscoverage/JSCover # Directory for instrumented libs generated by jscoverage/JSCover
lib-cov lib-cov

1
Jenkinsfile vendored
View File

@ -8,6 +8,7 @@ pipeline {
stages { stages {
stage('install') { stage('install') {
steps { steps {
sh 'ls -a'
sh 'node -v' sh 'node -v'
sh 'npm -v' sh 'npm -v'
sh 'npm ci' sh 'npm ci'

View File

@ -1,112 +1,80 @@
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' 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 { import { AccessCode, BaseResponse, Course, Lesson, User, UserData } from "../model";
AccessCode,
BaseResponse,
Course,
Lesson,
User,
UserData,
} from '../model'
export const api = createApi({ export const api = createApi({
reducerPath: 'auth', reducerPath: "auth",
baseQuery: fetchBaseQuery({ baseQuery: fetchBaseQuery({
baseUrl: getConfigValue('journal.back.url'), baseUrl: getConfigValue("journal.back.url"),
fetchFn: async ( fetchFn: async (input: RequestInfo | URL, init?: RequestInit | undefined) => {
input: RequestInfo | URL, const response = await fetch(input, init);
init?: RequestInit | undefined,
) => {
const response = await fetch(input, init)
if (response.status === 403) keycloak.login() if (response.status === 403) keycloak.login()
return response return response;
}, },
headers: { headers: {
'Content-Type': 'application/json;charset=utf-8', "Content-Type": "application/json;charset=utf-8",
}, },
prepareHeaders: (headers) => { prepareHeaders: (headers) => {
headers.set('Authorization', `Bearer ${keycloak.token}`) headers.set('Authorization', `Bearer ${keycloak.token}`)
}, }
}), }),
tagTypes: ['LessonList', 'CourseList'], tagTypes: ['LessonList', 'CourseList'],
endpoints: (builder) => ({ endpoints: (builder) => ({
coursesList: builder.query<BaseResponse<Course[]>, void>({ coursesList: builder.query<BaseResponse<Course[]>, void>({
query: () => '/course/list', query: () => '/course/list',
providesTags: ['CourseList'], providesTags: ['CourseList']
}), }),
createUpdateCourse: builder.mutation< createUpdateCourse: builder.mutation<BaseResponse<Course>, Partial<Course> & Pick<Course, 'name'>>({
BaseResponse<Course>,
Partial<Course> & Pick<Course, 'name'>
>({
query: (course) => ({ query: (course) => ({
url: '/course', url: '/course',
method: 'POST', method: 'POST',
body: course, body: course,
}), }),
invalidatesTags: ['CourseList'], invalidatesTags: ['CourseList']
}), }),
courseAllStudents: builder.query<BaseResponse<User[]>, string>({ courseAllStudents: builder.query<BaseResponse<User[]>, string>({
query: (courseId) => `/course/students/${courseId}`, query: (courseId) => `/course/students/${courseId}`
}), }),
manualAddStudent: builder.mutation< manualAddStudent: builder.mutation<BaseResponse<void>, { lessonId: string, user: User }>({
BaseResponse<void>, query: ({lessonId, user}) => ({
{ lessonId: string; user: User }
>({
query: ({ lessonId, user }) => ({
url: `/lesson/add-student/${lessonId}`, url: `/lesson/add-student/${lessonId}`,
method: 'POST', method: 'POST',
body: user, body: user
}), })
}), }),
lessonList: builder.query<BaseResponse<Lesson[]>, string>({ lessonList: builder.query<BaseResponse<Lesson[]>, string>({
query: (courseId) => `/lesson/list/${courseId}`, query: (courseId) => `/lesson/list/${courseId}`,
providesTags: ['LessonList'], providesTags: ['LessonList']
}), }),
createLesson: builder.mutation< createLesson: builder.mutation<BaseResponse<Lesson>, Pick<Lesson, 'name' | 'date'> & { courseId: string }>({
BaseResponse<Lesson>, query: ({ name, courseId, date }) => ({
Partial<Lesson> & Pick<Lesson, 'name' | 'date'> & { courseId: string }
>({
query: (data) => ({
url: '/lesson', url: '/lesson',
method: 'POST', method: 'POST',
body: data, body: { name, courseId, date },
}), }),
invalidatesTags: ['LessonList'], invalidatesTags: ['LessonList']
}),
deleteLesson: builder.mutation<null, string>({
query: (lessonId) => ({
url: `/lesson/${lessonId}`,
method: 'DELETE',
}),
invalidatesTags: ['LessonList'],
}), }),
lessonById: builder.query<BaseResponse<Lesson>, string>({ lessonById: builder.query<BaseResponse<Lesson>, string>({
query: (lessonId: string) => `/lesson/${lessonId}`, query: (lessonId: string) => `/lesson/${lessonId}`
}), }),
createAccessCode: builder.query< createAccessCode: builder.query<BaseResponse<AccessCode>, { lessonId: string }>({
BaseResponse<AccessCode>,
{ lessonId: string }
>({
query: ({ lessonId }) => ({ query: ({ lessonId }) => ({
url: '/lesson/access-code', url: '/lesson/access-code',
method: 'POST', method: 'POST',
body: { lessonId }, body: { lessonId },
}), })
}), }),
getAccess: builder.query< getAccess: builder.query<BaseResponse<{ user: UserData, accessCode: AccessCode }>, { accessCode: string }>({
BaseResponse<{ user: UserData; accessCode: AccessCode }>,
{ accessCode: string }
>({
query: ({ accessCode }) => ({ query: ({ accessCode }) => ({
url: `/lesson/access-code/${accessCode}`, url: `/lesson/access-code/${accessCode}`,
method: 'GET', method: 'GET',
}), })
}), })
}), }),
}) });

View File

@ -35,7 +35,6 @@ 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'
import { AddIcon, ArrowDownIcon, ArrowUpIcon, LinkIcon } from '@chakra-ui/icons' import { AddIcon, ArrowDownIcon, ArrowUpIcon, LinkIcon } from '@chakra-ui/icons'
import { Course } from '../__data__/model'
interface NewCourseForm { interface NewCourseForm {
startDt: string startDt: string
@ -227,15 +226,7 @@ const CoursesList = () => {
) )
} }
const CourseCard = ({ const CourseCard = ({ course, isOpened, openDetails }) => {
course,
isOpened,
openDetails,
}: {
course: Course
isOpened: boolean
openDetails: () => void
}) => {
const [getLessonList, lessonList] = api.useLazyLessonListQuery() const [getLessonList, lessonList] = api.useLazyLessonListQuery()
useEffect(() => { useEffect(() => {
if (isOpened) { if (isOpened) {
@ -271,7 +262,6 @@ const CourseCard = ({
{lessonList.data?.body?.map((lesson) => ( {lessonList.data?.body?.map((lesson) => (
<Link <Link
as={ConnectedLink} as={ConnectedLink}
key={lesson._id}
to={ to={
isTeacher(user) isTeacher(user)
? `${getNavigationsValue('journal.main')}/lesson/${course._id}/${lesson._id}` ? `${getNavigationsValue('journal.main')}/lesson/${course._id}/${lesson._id}`

View File

@ -20,7 +20,6 @@ import {
Lessonname, Lessonname,
AddMissedButton, AddMissedButton,
UnorderList, UnorderList,
BreadcrumbsWrapper,
} from './style' } from './style'
import { api } from '../__data__/api/api' import { api } from '../__data__/api/api'
import { User } from '../__data__/model' import { User } from '../__data__/model'
@ -87,8 +86,8 @@ const LessonDetail = () => {
}, [accessCode?.body, AllStudents.data]) }, [accessCode?.body, AllStudents.data])
return ( return (
<> <Container maxW="container.xl" centerContent px="200">
<BreadcrumbsWrapper> <VStack align="left">
<Breadcrumb> <Breadcrumb>
<BreadcrumbItem> <BreadcrumbItem>
<BreadcrumbLink as={Link} to={getNavigationsValue('journal.main')}> <BreadcrumbLink as={Link} to={getNavigationsValue('journal.main')}>
@ -109,45 +108,41 @@ const LessonDetail = () => {
<BreadcrumbLink href="#">Лекция</BreadcrumbLink> <BreadcrumbLink href="#">Лекция</BreadcrumbLink>
</BreadcrumbItem> </BreadcrumbItem>
</Breadcrumb> </Breadcrumb>
</BreadcrumbsWrapper> <Heading as='h3' mt='4' mb='3'>
<Container maxW="container.xl" centerContent px="200"> Тема занятия:
<VStack align="left"> </Heading>
<Heading as="h3" mt="4" mb="3"> <Box as="span">
Тема занятия: {accessCode?.body?.lesson?.name}
</Heading> </Box>
<Box as="span">{accessCode?.body?.lesson?.name}</Box> <Box as='span'>
<Box as="span"> {dayjs(accessCode?.body?.lesson?.date).format('DD MMMM YYYYг.')}{' '}
{dayjs(accessCode?.body?.lesson?.date).format('DD MMMM YYYYг.')}{' '} Отмечено - {accessCode?.body?.lesson?.students?.length}{' '}
Отмечено - {accessCode?.body?.lesson?.students?.length}{' '} {AllStudents.isSuccess ? `/ ${AllStudents?.data?.body?.length}` : ''}{' '}
{AllStudents.isSuccess человек
? `/ ${AllStudents?.data?.body?.length}` </Box>
: ''}{' '} </VStack>
человек <HStack spacing="8">
</Box> <a href={userUrl}>
</VStack> <QRCanvas ref={canvRef} />
<HStack spacing="8"> </a>
<a href={userUrl}> <UnorderList>
<QRCanvas ref={canvRef} /> {studentsArr.map((student) => (
</a> <LessonItem key={student.sub} warn={!student.present}>
<UnorderList> <Lessonname>
{studentsArr.map((student) => ( {student.name || student.preferred_username}{' '}
<LessonItem key={student.sub} warn={!student.present}> {!student.present && (
<Lessonname> <AddMissedButton
{student.name || student.preferred_username}{' '} onClick={() => manualAdd({ lessonId, user: student })}
{!student.present && ( >
<AddMissedButton add
onClick={() => manualAdd({ lessonId, user: student })} </AddMissedButton>
> )}
add </Lessonname>
</AddMissedButton> </LessonItem>
)} ))}
</Lessonname> </UnorderList>
</LessonItem> </HStack>
))} </Container>
</UnorderList>
</HStack>
</Container>
</>
) )
} }

View File

@ -14,45 +14,26 @@ import {
CardHeader, CardHeader,
Heading, Heading,
Button, Button,
ButtonGroup,
CloseButton, CloseButton,
useToast, useToast,
Stack,
VStack, VStack,
FormControl, FormControl,
FormLabel, FormLabel,
Toast,
FormHelperText, FormHelperText,
FormErrorMessage, FormErrorMessage,
Input, Input,
TableContainer,
Table,
Thead,
Tr,
Th,
Tbody,
Td,
Menu,
MenuButton,
MenuItem,
Text,
MenuList,
Center,
Spinner,
AlertDialog,
AlertDialogBody,
AlertDialogContent,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogOverlay,
} from '@chakra-ui/react' } from '@chakra-ui/react'
import { AddIcon, EditIcon } from '@chakra-ui/icons'
import { ErrorSpan, BreadcrumbsWrapper } from './style' import { AddIcon } from '@chakra-ui/icons'
import { LessonItem, Lessonname, ErrorSpan } from './style'
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'
import { qrCode } from '../assets'
import { Lesson } from '../__data__/model'
interface NewLessonForm { interface NewLessonForm {
name: string name: string
@ -64,10 +45,8 @@ const LessonList = () => {
const user = useAppSelector((s) => s.user) const user = useAppSelector((s) => s.user)
const { data, isLoading, error } = api.useLessonListQuery(courseId) const { data, isLoading, error } = api.useLessonListQuery(courseId)
const [createLesson, crLQuery] = api.useCreateLessonMutation() const [createLesson, crLQuery] = api.useCreateLessonMutation()
const [deleteLesson, deletingRqst] = api.useDeleteLessonMutation() const [value, setValue] = useState('')
const [showForm, setShowForm] = useState(false) const [showForm, setShowForm] = useState(false)
const [lessonToDelete, setlessonToDelete] = useState<Lesson>(null)
const cancelRef = React.useRef()
const { const {
control, control,
handleSubmit, handleSubmit,
@ -83,6 +62,12 @@ const LessonList = () => {
const toast = useToast() const toast = useToast()
const toastRef = useRef(null) const toastRef = useRef(null)
const handleChange = useCallback(
(event) => {
setValue(event.target.value.toUpperCase())
},
[setValue],
)
const onSubmit = ({ name, date }) => { const onSubmit = ({ name, date }) => {
toastRef.current = toast({ toastRef.current = toast({
title: 'Отправляем', title: 'Отправляем',
@ -92,46 +77,6 @@ const LessonList = () => {
createLesson({ name, courseId, date }) createLesson({ name, courseId, date })
} }
useEffect(() => {
if (deletingRqst.isError) {
toast({
title: (deletingRqst.error as any)?.error,
status: 'error',
duration: 3000,
})
}
if (deletingRqst.isSuccess) {
const lesson = { ...lessonToDelete }
toast({
status: 'warning',
duration: 9000,
render(props) {
return (
<Toast
{...props}
title={
<>
<Box pb={3}>
<Text fontSize="xl">{`Удалена лекция ${lesson.name}`}</Text>
</Box>
<Button
onClick={() =>
createLesson({ courseId, ...lesson })
}
>
Восстановить
</Button>
</>
}
/>
)
},
})
setlessonToDelete(null)
}
}, [deletingRqst.isLoading, deletingRqst.isSuccess, deletingRqst.isError])
useEffect(() => { useEffect(() => {
if (crLQuery.isSuccess) { if (crLQuery.isSuccess) {
const values = getValues() const values = getValues()
@ -148,229 +93,136 @@ const LessonList = () => {
} }
}, [crLQuery.isSuccess]) }, [crLQuery.isSuccess])
if (isLoading) {
return (
<Container maxW="container.xl">
<Center h="300px">
<Spinner
thickness="4px"
speed="0.65s"
emptyColor="gray.200"
color="blue.500"
size="xl"
/>
</Center>
</Container>
)
}
return ( return (
<> <Container maxW="container.xl">
<AlertDialog <Breadcrumb>
isOpen={Boolean(lessonToDelete)} <BreadcrumbItem>
leastDestructiveRef={cancelRef} <BreadcrumbLink as={Link} to={getNavigationsValue('journal.main')}>
onClose={() => setlessonToDelete(null)} Журнал
> </BreadcrumbLink>
<AlertDialogOverlay> </BreadcrumbItem>
<AlertDialogContent>
<AlertDialogHeader fontSize="lg" fontWeight="bold">
Удалить занятие от{' '}
{dayjs(lessonToDelete?.date).format('DD.MM.YY')}?
</AlertDialogHeader>
<AlertDialogBody> <BreadcrumbItem isCurrentPage>
Все данные о посещении данного занятия будут удалены <BreadcrumbLink href="#">Курс</BreadcrumbLink>
</AlertDialogBody> </BreadcrumbItem>
</Breadcrumb>
<AlertDialogFooter> {isTeacher(user) && (
<Button <Box mt="15" mb="15">
isDisabled={deletingRqst.isLoading} {showForm ? (
ref={cancelRef} <Card align="left">
onClick={() => setlessonToDelete(null)} <CardHeader display="flex">
> <Heading as="h2" mt="0">
Cancel Создание лекции
</Button> </Heading>
<Button <CloseButton ml="auto" onClick={() => setShowForm(false)} />
colorScheme="red" </CardHeader>
loadingText="" <CardBody>
isLoading={deletingRqst.isLoading} <form onSubmit={handleSubmit(onSubmit)}>
onClick={() => deleteLesson(lessonToDelete._id)} <VStack spacing="10" align="left">
ml={3} <Controller
> control={control}
Delete name="date"
</Button> rules={{ required: 'Обязательное поле' }}
</AlertDialogFooter> render={({ field }) => (
</AlertDialogContent> <FormControl>
</AlertDialogOverlay> <FormLabel>Дата</FormLabel>
</AlertDialog> <Input
<BreadcrumbsWrapper> {...field}
<Breadcrumb> required={false}
<BreadcrumbItem> placeholder="Укажите дату лекции"
<BreadcrumbLink as={Link} to={getNavigationsValue('journal.main')}> size="md"
Журнал type="datetime-local"
</BreadcrumbLink> />
</BreadcrumbItem> {errors.date ? (
<FormErrorMessage>
{errors.date?.message}
</FormErrorMessage>
) : (
<FormHelperText>
Укажите дату и время лекции
</FormHelperText>
)}
</FormControl>
)}
/>
<BreadcrumbItem isCurrentPage> <Controller
<BreadcrumbLink href="#">Курс</BreadcrumbLink> control={control}
</BreadcrumbItem> name="name"
</Breadcrumb> rules={{ required: 'Обязательное поле' }}
</BreadcrumbsWrapper> render={({ field }) => (
<Container maxW="container.xl"> <FormControl
{isTeacher(user) && ( isRequired
<Box mt="15" mb="15"> isInvalid={Boolean(errors.name)}
{showForm ? (
<Card align="left">
<CardHeader display="flex">
<Heading as="h2" mt="0">
Создание лекции
</Heading>
<CloseButton ml="auto" onClick={() => setShowForm(false)} />
</CardHeader>
<CardBody>
<form onSubmit={handleSubmit(onSubmit)}>
<VStack spacing="10" align="left">
<Controller
control={control}
name="date"
rules={{ required: 'Обязательное поле' }}
render={({ field }) => (
<FormControl>
<FormLabel>Дата</FormLabel>
<Input
{...field}
required={false}
placeholder="Укажите дату лекции"
size="md"
type="datetime-local"
/>
{errors.date ? (
<FormErrorMessage>
{errors.date?.message}
</FormErrorMessage>
) : (
<FormHelperText>
Укажите дату и время лекции
</FormHelperText>
)}
</FormControl>
)}
/>
<Controller
control={control}
name="name"
rules={{ required: 'Обязательное поле' }}
render={({ field }) => (
<FormControl
isRequired
isInvalid={Boolean(errors.name)}
>
<FormLabel>Название новой лекции:</FormLabel>
<Input
{...field}
required={false}
placeholder="Название лекции"
size="md"
/>
{errors.name && (
<FormErrorMessage>
{errors.name.message}
</FormErrorMessage>
)}
</FormControl>
)}
/>
<Box mt="10">
<Button
size="lg"
type="submit"
leftIcon={<AddIcon />}
colorScheme="blue"
> >
Создать <FormLabel>Название новой лекции:</FormLabel>
</Button> <Input
</Box> {...field}
</VStack> required={false}
placeholder="Название лекции"
{crLQuery.error && ( size="md"
<ErrorSpan>{(crLQuery.error as any).error}</ErrorSpan> />
)} {errors.name && (
</form> <FormErrorMessage>
</CardBody> {errors.name.message}
</Card> </FormErrorMessage>
) : ( )}
<Box p="2" m="2"> </FormControl>
<Button )}
leftIcon={<AddIcon />} />
colorScheme="green" <Box mt="10">
onClick={() => setShowForm(true)} <Button
> size="lg"
Добавить type="submit"
</Button> leftIcon={<AddIcon />}
</Box> colorScheme="blue"
)}
</Box>
)}
<TableContainer whiteSpace="wrap">
<Table variant="striped" colorScheme="cyan">
<Thead>
<Tr>
{isTeacher(user) && (
<Th align="center" width={1}>
ссылка
</Th>
)}
<Th textAlign="center" width={1}>
Дата
</Th>
<Th>Название</Th>
<Th>action</Th>
<Th isNumeric>Отмечено</Th>
</Tr>
</Thead>
<Tbody>
{data?.body?.map((lesson) => (
<Tr key={lesson._id}>
{isTeacher(user) && (
<Td>
<Link
to={`${getNavigationsValue('journal.main')}/lesson/${courseId}/${lesson._id}`}
style={{ display: 'flex' }}
> >
<img Создать
width={24} </Button>
src={qrCode} </Box>
style={{ margin: '0 auto' }} </VStack>
/>
</Link> {crLQuery.error && (
</Td> <ErrorSpan>{(crLQuery.error as any).error}</ErrorSpan>
)} )}
<Td textAlign="center"> </form>
{dayjs(lesson.date).format('H:mm DD.MM.YY')} </CardBody>
</Td> </Card>
<Td>{lesson.name}</Td> ) : (
<Td> <Box p="2" m="2">
<Menu> <Button
<MenuButton as={Button}> leftIcon={<AddIcon />}
<EditIcon /> colorScheme="green"
</MenuButton> onClick={() => setShowForm(true)}
<MenuList> >
<MenuItem isDisabled>Edit</MenuItem> Добавить
<MenuItem onClick={() => setlessonToDelete(lesson)}> </Button>
Delete </Box>
</MenuItem> )}
</MenuList> </Box>
</Menu> )}
</Td> <ul style={{ paddingLeft: 0 }}>
<Td isNumeric>{lesson.students.length}</Td> {data?.body?.map((lesson) => (
</Tr> <LessonItem key={lesson._id}>
))} <Link
</Tbody> to={
</Table> isTeacher(user)
</TableContainer> ? `${getNavigationsValue('journal.main')}/lesson/${courseId}/${lesson._id}`
</Container> : ''
</> }
style={{ display: 'flex' }}
>
<Lessonname>{lesson.name}</Lessonname>
<span>{dayjs(lesson.date).format('DD MMMM YYYYг.')}</span>
<span style={{ marginLeft: 'auto' }}>
Участников - {lesson.students.length}
</span>
</Link>
</LessonItem>
))}
</ul>
</Container>
) )
} }

View File

@ -4,9 +4,6 @@ import {
Card Card
} from '@chakra-ui/react' } from '@chakra-ui/react'
export const BreadcrumbsWrapper = styled.div`
padding: 12px;
`;
export const MainWrapper = styled.main` export const MainWrapper = styled.main`
display: flex; display: flex;