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

0% Statements 0/24
0% Branches 0/14
0% Functions 0/9
0% Lines 0/24

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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204                                                                                                                                                                                                                                                                                                                                                                                                                       
import { UploadOutlined } from '@ant-design/icons';
import { usePostCampaignMutation, usePostImageUploadMutation } from '@lib/api/mutations';
import GoogleMapComponent from '@lib/components/GoogleMap';
import QuillEditor from '@lib/components/QuillEditor';
import { adventureStatusToString } from '@lib/constants/campaign';
import {
  AdventureCampaignResponseDtoStatusEnum,
  CreateOrUpdateCampaignDto
} from '@uniquegood/realworld-adventure-interface';
import {
  Button,
  ColorPicker,
  DatePicker,
  Form,
  Input,
  InputNumber,
  ModalProps,
  Select,
  Upload,
  message
} from 'antd';
import { Color } from 'antd/es/color-picker';
import Modal from 'antd/es/modal/Modal';
import { Dayjs } from 'dayjs';
import { DeltaStatic } from 'quill';
import React from 'react';
 
interface CreateModalProps {
  modalData: ModalProps;
  closeModal: () => unknown;
}
 
export default function CreateModal({ modalData, closeModal }: CreateModalProps) {
  const [form] = Form.useForm();
  const [content, setContent] = React.useState<DeltaStatic>();
 
  const { mutateAsync } = usePostCampaignMutation();
  const { mutateAsync: postImage } = usePostImageUploadMutation();
 
  const handleSubmit = async (
    values: CreateOrUpdateCampaignDto & {
      date: [Dayjs, Dayjs];
      image: { file: File; fileList: FileList };
      thumbnailImage: { file: File; fileList: FileList };
      verticalImage: { file: File; fileList: FileList };
    }
  ) => {
    const [startAt, endAt] = values.date || [null, null];
 
    const imageFileList = Array.from(values.image.fileList);
 
    const imageUrls = await Promise.all(
      imageFileList.map(async (file) => {
        const { data } = await postImage({
          file: (file as File & { originFileObj: File }).originFileObj
        });
 
        return data.url || '';
      })
    );
    const thumbnailImageUrl =
      (await postImage({ file: values.thumbnailImage.file })).data.url || '';
    const verticalImageUrl = (await postImage({ file: values.verticalImage.file })).data.url || '';
 
    const { success } = await mutateAsync({
      ...values,
      startAt: startAt.format('YYYY-MM-DDTHH:mm'),
      endAt: endAt?.format('YYYY-MM-DDTHH:mm') || null,
      imageUrls,
      thumbnailImageUrl,
      verticalImageUrl,
      content: JSON.stringify(content),
      color: typeof values.color === 'string' ? values.color : (values.color as Color).toHexString()
    });
 
    if (success) {
      message.success('캠페인을 생성했습니다.');
      closeModal();
    } else {
      message.error('캠페인 생성에 실패했습니다.');
    }
  };
 
  return (
    <Modal
      {...modalData}
      title="캠페인 생성"
      onOk={form.submit}
      okText="확인"
      cancelText="닫기"
      afterClose={form.resetFields}
    >
      <Form
        form={form}
        onFinish={handleSubmit}
        labelCol={{ span: 24 }}
        wrapperCol={{ span: 24 }}
        // eslint-disable-next-line no-template-curly-in-string
        validateMessages={{ required: '${label}을(를) 입력해주세요.' }}
        initialValues={{ color: '#C869FF' }}
      >
        <Form.Item name="title" label="이름" rules={[{ required: true }]}>
          <Input placeholder="이름을 입력해주세요" />
        </Form.Item>
        <Form.Item name="description" label="설명" rules={[{ required: true }]}>
          <Input placeholder="설명을 입력해주세요" />
        </Form.Item>
        <Form.Item name="address" label="주소" rules={[{ required: true }]}>
          <Input placeholder="주소를 입력해주세요." />
        </Form.Item>
        <Form.Item name="content" label="상세 설명" rules={[{ required: true }]}>
          <QuillEditor onChange={(value) => setContent(value)} />
        </Form.Item>
        <Form.Item name="image" label="이미지" rules={[{ required: true }]} valuePropName="file">
          <Upload listType="picture" beforeUpload={() => false}>
            <Button icon={<UploadOutlined />}>이미지 업로드</Button>
          </Upload>
        </Form.Item>
        <Form.Item
          name="thumbnailImage"
          label="대표 이미지"
          rules={[{ required: true }]}
          valuePropName="file"
        >
          <Upload maxCount={1} listType="picture" beforeUpload={() => false}>
            <Button icon={<UploadOutlined />}>이미지 업로드</Button>
          </Upload>
        </Form.Item>
        <Form.Item
          name="verticalImage"
          label="세로형 대표 이미지"
          rules={[{ required: true }]}
          valuePropName="file"
        >
          <Upload maxCount={1} listType="picture" beforeUpload={() => false}>
            <Button icon={<UploadOutlined />}>이미지 업로드</Button>
          </Upload>
        </Form.Item>
        <Form.Item name="zoomLevel" label="줌 레벨" rules={[{ required: true }]}>
          <InputNumber
            controls={false}
            placeholder="줌 레벨을 입력해주세요."
            style={{ width: '100%' }}
          />
        </Form.Item>
        <Form.Item name="color" label="색상" rules={[{ required: true }]}>
          <ColorPicker showText />
        </Form.Item>
        <Form.Item name="position" label="위치" rules={[{ required: true }]}>
          <GoogleMapComponent
            onCenterChange={(center) => {
              form.setFieldsValue({
                position: true,
                latitude: center.lat,
                longitude: center.lng
              });
            }}
          />
        </Form.Item>
        <div style={{ display: 'none' }}>
          <Form.Item name="longitude" label="경도" rules={[{ required: true }]}>
            <InputNumber placeholder="경도를 입력해주세요" />
          </Form.Item>
          <Form.Item name="latitude" label="위도" rules={[{ required: true }]}>
            <InputNumber placeholder="위도를 입력해주세요" />
          </Form.Item>
        </div>
        <Form.Item name="status" label="상태" rules={[{ required: true }]}>
          <Select
            placeholder="상태를 선택해주세요"
            options={Object.values(AdventureCampaignResponseDtoStatusEnum).map((status) => ({
              label: adventureStatusToString[status],
              value: status
            }))}
          />
        </Form.Item>
        <Form.Item name="linkUrl" label="링크 URL" rules={[{ required: true }]}>
          <Input placeholder="링크 URL을 입력해주세요." />
        </Form.Item>
        <Form.Item name="date" label="기간" rules={[{ required: true }]}>
          <DatePicker.RangePicker
            format="YYYY-MM-DD HH:mm"
            showTime={{ format: 'HH:mm' }}
            style={{ width: '100%' }}
            allowEmpty={[false, true]}
          />
        </Form.Item>
        <Form.Item name="surveyUrl" label="설문 URL">
          <Input placeholder="설문 URL을 입력해주세요." />
        </Form.Item>
        <Form.Item name="isActive" label="활성화 여부">
          <Select
            placeholder="활성화 여부를 선택해주세요"
            options={[
              { label: '활성화', value: true },
              { label: '비활성화', value: false }
            ]}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
}