CRUD лекции #17

Merged
primakov merged 2 commits from feature/edit-delete-lesson into master 2024-04-01 23:25:14 +03:00
3 changed files with 216 additions and 81 deletions
Showing only changes of commit 032cdaaa12 - Show all commits

1
Jenkinsfile vendored
View File

@ -8,7 +8,6 @@ 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,80 +1,112 @@
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 { AccessCode, BaseResponse, Course, Lesson, User, UserData } from "../model"; import {
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 (input: RequestInfo | URL, init?: RequestInit | undefined) => { fetchFn: async (
const response = await fetch(input, init); input: RequestInfo | URL,
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<BaseResponse<Course>, Partial<Course> & Pick<Course, 'name'>>({ createUpdateCourse: builder.mutation<
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<BaseResponse<void>, { lessonId: string, user: User }>({ manualAddStudent: builder.mutation<
BaseResponse<void>,
{ lessonId: string; user: User }
>({
query: ({ lessonId, 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<BaseResponse<Lesson>, Pick<Lesson, 'name' | 'date'> & { courseId: string }>({ createLesson: builder.mutation<
query: ({ name, courseId, date }) => ({ BaseResponse<Lesson>,
Partial<Lesson> & Pick<Lesson, 'name' | 'date'> & { courseId: string }
>({
query: (data) => ({
url: '/lesson', url: '/lesson',
method: 'POST', method: 'POST',
body: { name, courseId, date }, body: data,
}), }),
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<BaseResponse<AccessCode>, { lessonId: string }>({ createAccessCode: builder.query<
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<BaseResponse<{ user: UserData, accessCode: AccessCode }>, { accessCode: string }>({ }),
getAccess: builder.query<
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

@ -14,13 +14,12 @@ 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,
@ -31,17 +30,29 @@ import {
Th, Th,
Tbody, Tbody,
Td, 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 { AddIcon } from '@chakra-ui/icons' import { ErrorSpan, BreadcrumbsWrapper } from './style'
import { LessonItem, Lessonname, ErrorSpan, BreadcrumbsWrapper } 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 { qrCode } from '../assets'
import { Lesson } from '../__data__/model'
interface NewLessonForm { interface NewLessonForm {
name: string name: string
@ -53,8 +64,10 @@ 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 [value, setValue] = useState('') const [deleteLesson, deletingRqst] = api.useDeleteLessonMutation()
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,
@ -70,12 +83,6 @@ 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: 'Отправляем',
@ -85,6 +92,46 @@ 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()
@ -101,8 +148,61 @@ 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 (
<> <>
<AlertDialog
isOpen={Boolean(lessonToDelete)}
leastDestructiveRef={cancelRef}
onClose={() => setlessonToDelete(null)}
>
<AlertDialogOverlay>
<AlertDialogContent>
<AlertDialogHeader fontSize="lg" fontWeight="bold">
Удалить занятие от{' '}
{dayjs(lessonToDelete?.date).format('DD.MM.YY')}?
</AlertDialogHeader>
<AlertDialogBody>
Все данные о посещении данного занятия будут удалены
</AlertDialogBody>
<AlertDialogFooter>
<Button
isDisabled={deletingRqst.isLoading}
ref={cancelRef}
onClick={() => setlessonToDelete(null)}
>
Cancel
</Button>
<Button
colorScheme="red"
loadingText=""
isLoading={deletingRqst.isLoading}
onClick={() => deleteLesson(lessonToDelete._id)}
ml={3}
>
Delete
</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialogOverlay>
</AlertDialog>
<BreadcrumbsWrapper> <BreadcrumbsWrapper>
<Breadcrumb> <Breadcrumb>
<BreadcrumbItem> <BreadcrumbItem>
@ -216,55 +316,59 @@ const LessonList = () => {
<Table variant="striped" colorScheme="cyan"> <Table variant="striped" colorScheme="cyan">
<Thead> <Thead>
<Tr> <Tr>
<Th align="center">ссылка</Th> {isTeacher(user) && (
<Th>Дата</Th> <Th align="center" width={1}>
<Th>into</Th> ссылка
<Th isNumeric>Участников</Th> </Th>
)}
<Th textAlign="center" width={1}>
Дата
</Th>
<Th>Название</Th>
<Th>action</Th>
<Th isNumeric>Отмечено</Th>
</Tr> </Tr>
</Thead> </Thead>
<Tbody> <Tbody>
{data?.body?.map((lesson) => ( {data?.body?.map((lesson) => (
<Tr key={lesson._id}> <Tr key={lesson._id}>
{isTeacher(user) && (
<Td> <Td>
<Link <Link
to={ to={`${getNavigationsValue('journal.main')}/lesson/${courseId}/${lesson._id}`}
isTeacher(user)
? `${getNavigationsValue('journal.main')}/lesson/${courseId}/${lesson._id}`
: ''
}
style={{ display: 'flex' }} style={{ display: 'flex' }}
> >
<img width={24} src={qrCode} /> <img
width={24}
src={qrCode}
style={{ margin: '0 auto' }}
/>
</Link> </Link>
</Td> </Td>
<Td>{dayjs(lesson.date).format('H:mm DD.MM.YY')}</Td> )}
<Td textAlign="center">
{dayjs(lesson.date).format('H:mm DD.MM.YY')}
</Td>
<Td>{lesson.name}</Td> <Td>{lesson.name}</Td>
<Td>
<Menu>
<MenuButton as={Button}>
<EditIcon />
</MenuButton>
<MenuList>
<MenuItem isDisabled>Edit</MenuItem>
<MenuItem onClick={() => setlessonToDelete(lesson)}>
Delete
</MenuItem>
</MenuList>
</Menu>
</Td>
<Td isNumeric>{lesson.students.length}</Td> <Td isNumeric>{lesson.students.length}</Td>
</Tr> </Tr>
))} ))}
</Tbody> </Tbody>
</Table> </Table>
</TableContainer> </TableContainer>
{/* <ul style={{ paddingLeft: 0 }}>
{data?.body?.map((lesson) => (
<LessonItem key={lesson._id}>
<Link
to={
isTeacher(user)
? `${getNavigationsValue('journal.main')}/lesson/${courseId}/${lesson._id}`
: ''
}
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> </Container>
</> </>
) )