(#16) Редактирование лекции
Some checks failed
platform/bro/pipeline/pr-master This commit looks good
platform/bro/pipeline/head This commit looks good
platform/gitea-bro-js/journal.pl/pipeline/head There was a failure building this commit
platform/bro-js/journal.pl/pipeline/head This commit looks good

This commit is contained in:
Primakov Alexandr Alexandrovich 2024-04-02 16:17:24 +03:00
parent 997f463c08
commit a32e55807b
3 changed files with 195 additions and 127 deletions

View File

@ -78,6 +78,14 @@ export const api = createApi({
}), }),
invalidatesTags: ['LessonList'], invalidatesTags: ['LessonList'],
}), }),
updateLesson: builder.mutation<BaseResponse<Lesson>, Partial<Lesson> & Pick<Lesson, '_id'>>({
query: (data) => ({
method: 'PUT',
url: `/lesson/${data._id}`,
body: data,
}),
invalidatesTags: ['LessonList'],
}),
deleteLesson: builder.mutation<null, string>({ deleteLesson: builder.mutation<null, string>({
query: (lessonId) => ({ query: (lessonId) => ({
url: `/lesson/${lessonId}`, url: `/lesson/${lessonId}`,

View File

@ -46,50 +46,149 @@ import {
} from '@chakra-ui/react' } from '@chakra-ui/react'
import { AddIcon, EditIcon } from '@chakra-ui/icons' import { AddIcon, EditIcon } from '@chakra-ui/icons'
import { ErrorSpan, BreadcrumbsWrapper } from './style'
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' import { Lesson } from '../__data__/model'
import { ErrorSpan, BreadcrumbsWrapper } from './style'
interface NewLessonForm { interface NewLessonForm {
name: string name: string
date: string date: string
} }
interface LessonFormProps {
lesson?: Partial<Lesson>
isLoading: boolean
onCancel: () => void
onSubmit: (lesson: Lesson) => void
error?: string
}
const LessonForm = ({
lesson,
isLoading,
onCancel,
onSubmit,
error,
}: LessonFormProps) => {
const {
control,
handleSubmit,
reset,
formState: { errors },
} = useForm<NewLessonForm>({
defaultValues: lesson || {
name: '',
date: '',
},
})
return (
<Card align="left">
<CardHeader display="flex">
<Heading as="h2" mt="0">
Создание лекции
</Heading>
<CloseButton
ml="auto"
onClick={() => {
reset()
onCancel()
}}
/>
</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"
isLoading={isLoading}
>
Создать
</Button>
</Box>
</VStack>
{error && <ErrorSpan>{error}</ErrorSpan>}
</form>
</CardBody>
</Card>
)
}
const LessonList = () => { const LessonList = () => {
const { courseId } = useParams() const { courseId } = useParams()
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 [deleteLesson, deletingRqst] = api.useDeleteLessonMutation()
const [updateLesson, updateLessonRqst] = api.useUpdateLessonMutation()
const [showForm, setShowForm] = useState(false) const [showForm, setShowForm] = useState(false)
const [lessonToDelete, setlessonToDelete] = useState<Lesson>(null) const [lessonToDelete, setlessonToDelete] = useState<Lesson>(null)
const cancelRef = React.useRef() const cancelRef = React.useRef()
const {
control,
handleSubmit,
reset,
formState: { errors },
getValues,
} = useForm<NewLessonForm>({
defaultValues: {
name: '',
date: '',
},
})
const toast = useToast() const toast = useToast()
const toastRef = useRef(null) const toastRef = useRef(null)
const createdLessonRef = useRef(null)
const [editLesson, setEditLesson] = useState<Lesson>(null)
const onSubmit = ({ name, date }) => { const onSubmit = (lessonData) => {
toastRef.current = toast({ toastRef.current = toast({
title: 'Отправляем', title: 'Отправляем',
status: 'loading', status: 'loading',
duration: 9000, duration: 9000,
}) })
createLesson({ name, courseId, date }) createdLessonRef.current = lessonData
if (editLesson) updateLesson(lessonData)
else createLesson({ courseId, ...lessonData })
} }
useEffect(() => { useEffect(() => {
@ -106,27 +205,27 @@ const LessonList = () => {
toast({ toast({
status: 'warning', status: 'warning',
duration: 9000, duration: 9000,
render(props) { render: ({ id, ...toastProps }) => (
return ( <Toast
<Toast {...toastProps}
{...props} id={id}
title={ title={
<> <>
<Box pb={3}> <Box pb={3}>
<Text fontSize="xl">{`Удалена лекция ${lesson.name}`}</Text> <Text fontSize="xl">{`Удалена лекция ${lesson.name}`}</Text>
</Box> </Box>
<Button <Button
onClick={() => onClick={() => {
createLesson({ courseId, ...lesson }) createLesson({ courseId, ...lesson })
} toast.close(id)
> }}
Восстановить >
</Button> Восстановить
</> </Button>
} </>
/> }
) />
}, ),
}) })
setlessonToDelete(null) setlessonToDelete(null)
} }
@ -134,20 +233,34 @@ const LessonList = () => {
useEffect(() => { useEffect(() => {
if (crLQuery.isSuccess) { if (crLQuery.isSuccess) {
const values = getValues() const toastProps = {
if (toastRef.current) { title: 'Лекция создана',
toast.update(toastRef.current, { description: `Лекция ${createdLessonRef.current.name} успешно создана`,
title: 'Лекция создана', status: 'success' as 'success',
description: `Лекция ${values.name} успешно создана`, duration: 9000,
status: 'success', isClosable: true,
duration: 9000,
isClosable: true,
})
} }
reset() if (toastRef.current) toast.update(toastRef.current, toastProps)
else toast(toastProps)
setShowForm(false)
} }
}, [crLQuery.isSuccess]) }, [crLQuery.isSuccess])
useEffect(() => {
if (updateLessonRqst.isSuccess) {
const toastProps = {
title: 'Лекция Обновлена',
description: `Лекция ${createdLessonRef.current.name} успешно обновлена`,
status: 'success' as 'success',
duration: 9000,
isClosable: true,
}
if (toastRef.current) toast.update(toastRef.current, toastProps)
else toast(toastProps)
setShowForm(false)
}
}, [updateLessonRqst.isSuccess])
if (isLoading) { if (isLoading) {
return ( return (
<Container maxW="container.xl"> <Container maxW="container.xl">
@ -220,85 +333,17 @@ const LessonList = () => {
{isTeacher(user) && ( {isTeacher(user) && (
<Box mt="15" mb="15"> <Box mt="15" mb="15">
{showForm ? ( {showForm ? (
<Card align="left"> <LessonForm
<CardHeader display="flex"> key={editLesson?._id}
<Heading as="h2" mt="0"> isLoading={crLQuery.isLoading}
Создание лекции onSubmit={onSubmit}
</Heading> onCancel={() => {
<CloseButton ml="auto" onClick={() => setShowForm(false)} /> setShowForm(false)
</CardHeader> setEditLesson(null)
<CardBody> }}
<form onSubmit={handleSubmit(onSubmit)}> error={(crLQuery.error as any)?.error}
<VStack spacing="10" align="left"> lesson={editLesson}
<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"
>
Создать
</Button>
</Box>
</VStack>
{crLQuery.error && (
<ErrorSpan>{(crLQuery.error as any).error}</ErrorSpan>
)}
</form>
</CardBody>
</Card>
) : ( ) : (
<Box p="2" m="2"> <Box p="2" m="2">
<Button <Button
@ -356,7 +401,14 @@ const LessonList = () => {
<EditIcon /> <EditIcon />
</MenuButton> </MenuButton>
<MenuList> <MenuList>
<MenuItem isDisabled>Edit</MenuItem> <MenuItem
onClick={() => {
setShowForm(true)
setEditLesson(lesson)
}}
>
Edit
</MenuItem>
<MenuItem onClick={() => setlessonToDelete(lesson)}> <MenuItem onClick={() => setlessonToDelete(lesson)}>
Delete Delete
</MenuItem> </MenuItem>

View File

@ -45,4 +45,12 @@ router.get('/lesson/:lessonId', (req, res) => {
res.send(require('../mocks/lessons/byid/success.json')) res.send(require('../mocks/lessons/byid/success.json'))
}) })
router.delete('/lesson/:lessonId', (req, res) => {
res.send({ success: true, body: { ok: true }})
})
router.put('/lesson/:lessonId', (req, res) => {
res.send({ success: true, body: req.body })
})
module.exports = router module.exports = router