All files / lib/pages/Notice/Modal CreateModal.tsx

0% Statements 0/31
0% Branches 0/14
0% Functions 0/11
0% Lines 0/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144                                                                                                                                                                                                                                                                                               
import { useCreateNoticeMutation, usePostImageUploadMutation } from '@lib/api/mutations';
import { CreateOrUpdateNoticeDto } from '@uniquegood/realworld-adventure-interface';
import { Form, Input, ModalProps, Select, message, Upload, notification, Button } from 'antd';
import Modal from 'antd/es/modal/Modal';
import React from 'react';
import { FileImageOutlined, UploadOutlined } from '@ant-design/icons';
import { useGetTotalFestivalsQuery } from '@lib/api/queries';
 
interface CreateModalProps {
  modalData: ModalProps;
  closeModal: () => unknown;
}
 
export default function CreateModal({ modalData, closeModal }: CreateModalProps) {
  const [form] = Form.useForm();
 
  const { data: festivals } = useGetTotalFestivalsQuery();
  const { mutateAsync } = useCreateNoticeMutation();
  const { mutateAsync: mutateImageUpload } = usePostImageUploadMutation();
 
  const handleSubmit = async (values: CreateOrUpdateNoticeDto) => {
    const { success } = await mutateAsync({ createOrUpdateNoticeDto: values });
 
    if (success) {
      message.success('공지를 생성했습니다.');
      closeModal();
    } else {
      message.error('공지 생성에 실패했습니다.');
    }
  };
  const validateMessages = {
    // eslint-disable-next-line no-template-curly-in-string
    required: '${label}은(는) 필수값입니다!'
  };
 
  return (
    <Modal
      {...modalData}
      title="공지 생성"
      onOk={form.submit}
      okText="확인"
      cancelText="닫기"
      afterClose={form.resetFields}
    >
      <Form form={form} onFinish={handleSubmit} validateMessages={validateMessages}>
        <Form.Item
          name="title"
          label="제목"
          labelCol={{ span: 24 }}
          wrapperCol={{ span: 24 }}
          rules={[{ required: true }]}
        >
          <Input placeholder="제목을 입력해주세요" />
        </Form.Item>
        <Form.Item
          name="description"
          label="내용"
          labelCol={{ span: 24 }}
          wrapperCol={{ span: 24 }}
          rules={[{ required: true }]}
        >
          <Input placeholder="내용을 입력해주세요" />
        </Form.Item>
        <Form.Item
          name="imageUrl"
          label="이미지"
          labelCol={{ span: 24 }}
          wrapperCol={{ span: 24 }}
          rules={[{ required: true }]}
          getValueFromEvent={(e) => {
            if (!e) return undefined;
            const { fileList } = e;
            return fileList[0]?.response;
          }}
        >
          <Upload
            listType="picture"
            maxCount={1}
            accept={'image/*'}
            beforeUpload={(file) => {
              const isImage = file.type.startsWith('image/');
              if (!isImage) {
                notification.error({
                  message: '이미지 업로드 실패',
                  description: `${file.name}은 이미지가 아닙니다!`,
                  icon: <FileImageOutlined />,
                  placement: 'bottomRight'
                });
              }
              return isImage || Upload.LIST_IGNORE;
            }}
            customRequest={({ file: originalFile, onProgress, onSuccess, onError }) => {
              const file = originalFile as File;
 
              return mutateImageUpload({
                file,
                axiosOption: {
                  onUploadProgress: ({ loaded, total }) =>
                    onProgress!({ percent: (loaded / (total ?? loaded)) * 100 })
                }
              })
                .then((res) => onSuccess!(res.data.url))
                .catch((e) => onError!(e));
            }}
            onChange={(info) => {
              if (info.file.status === 'done') {
                notification.success({
                  message: '이미지 업로드 성공',
                  description: `${info.file.name} 이미지 업로드에 성공하였습니다.`,
                  icon: <FileImageOutlined />,
                  placement: 'bottomRight'
                });
              } else if (info.file.status === 'error') {
                notification.error({
                  message: '이미지 업로드 실패',
                  description: `${info.file.name} 이미지 업로드에 성공 실패하였습니다. 다시 시도해주세요`,
                  icon: <FileImageOutlined />,
                  placement: 'bottomRight'
                });
              }
            }}
            onRemove={() => {
              form.resetFields(['imageUrl']);
            }}
          >
            <Button type="primary" icon={<UploadOutlined />}>
              업로드
            </Button>
          </Upload>
        </Form.Item>
        <Form.Item name="festivalId" label="축제">
          <Select
            options={festivals?.data?.content.map((festival) => ({
              label: festival.title,
              value: festival.id
            }))}
            placeholder="축제를 선택해주세요."
          />
        </Form.Item>
      </Form>
    </Modal>
  );
}