Compare commits

..

No commits in common. "1c08a70525ff365dc72609d7ee87735302cd25dd" and "997f463c08ae4011a8048b578ec60f415f7b9631" have entirely different histories.

3 changed files with 127 additions and 195 deletions

View File

@ -78,14 +78,6 @@ export const api = createApi({
}),
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>({
query: (lessonId) => ({
url: `/lesson/${lessonId}`,

View File

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

View File

@ -45,12 +45,4 @@ router.get('/lesson/:lessonId', (req, res) => {
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