All files / lib/pages/Reward DetailPage.tsx

0% Statements 0/110
0% Branches 0/84
0% Functions 0/33
0% Lines 0/106

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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
'use client';
 
import { usePatchRewardMutation, usePostImageUploadMutation } from '@lib/api/mutations';
import {
  useGetAllProjectsQuery,
  useGetRewardQuery,
  useGetTotalFestivalsQuery,
  useGetTotalGiftshowListQuery,
  useGetTotalRewardsQuery
} from '@lib/api/queries';
import QuillEditor from '@lib/components/QuillEditor';
import {
  ManageCreateOrUpdateRewardRequestDto,
  ManageCreateOrUpdateRewardRequestDtoCustomData,
  ManageCreateOrUpdateRewardRequestDtoRewardTypeEnum,
  ManageRewardResponseDtoExpirationPeriodEnum
} from '@uniquegood/realworld-adventure-interface';
import {
  Button,
  Form,
  Input,
  InputNumber,
  Select,
  message,
  Upload,
  notification,
  Skeleton,
  UploadFile
} from 'antd';
import { Delta } from 'quill';
import React from 'react';
import styled from 'styled-components';
import { FileImageOutlined, UploadOutlined } from '@ant-design/icons';
import { expirationPeriodToString } from '@lib/constants/reward';
import useModalState from '@lib/hooks/useModalState';
import axios from 'axios';
import AddRewardCountModal from './Modal/AddRewardCountModal';
 
interface RewardDetailPageProps {
  rewardId: string;
}
 
export default function RewardDetailPage({ rewardId }: RewardDetailPageProps) {
  const [currentType, setCurrentType] =
    React.useState<ManageCreateOrUpdateRewardRequestDtoRewardTypeEnum>();
  const [currentGoodsCode, setCurrentGoodsCode] = React.useState<string>();
  const [currentInfo, setCurrentInfo] = React.useState<Delta>();
  const [fileList, setFileList] = React.useState<UploadFile[]>();
  const prevGoodsCode = React.useRef(currentGoodsCode);
  const [form] = Form.useForm();
 
  const { data } = useGetTotalGiftshowListQuery();
  const { data: projects } = useGetAllProjectsQuery();
  const { data: rewards } = useGetTotalRewardsQuery();
  const { data: rewardData } = useGetRewardQuery({ rewardId });
  const { data: festivals } = useGetTotalFestivalsQuery();
  const { mutateAsync } = usePatchRewardMutation({ rewardId });
  const { mutateAsync: mutateImageUpload } = usePostImageUploadMutation();
 
  const getSelectedProductId = React.useCallback(
    (projectId: string) =>
      projects?.data.data.find((project) => project.projectId === projectId)?.productId,
    [projects]
  );
 
  const { openModal: openAddModal, closeModal: closeAddModal, modal: addModal } = useModalState();
 
  const handleSubmit = async (
    values: ManageCreateOrUpdateRewardRequestDto & {
      weight: number;
      count: number;
      projectId: string;
      productId: string;
      rewardIds: string[];
    }
  ) => {
    try {
      const { rewardIds, ...filteredValues } = values;
      const customData: ManageCreateOrUpdateRewardRequestDtoCustomData = (() => {
        if (currentType === 'DiscountTicket') {
          return {
            weight: values.weight,
            count: values.count ?? undefined
          };
        }
        if (currentType === 'ExchangeTicket') {
          return {
            weight: values.weight,
            count: values.count ?? undefined
          };
        }
        if (currentType === 'Project') {
          return {
            weight: values.weight,
            count: values.remainingCount ?? undefined,
            projectId: values.projectId,
            productId: getSelectedProductId(values.projectId)
          };
        }
        if (currentType === 'Draw') {
          return {
            weight: values.weight,
            count: values.remainingCount ?? undefined,
            rewardIds
          };
        }
        return {
          goodsCode: currentGoodsCode,
          weight: values.weight,
          count: values.count ?? undefined
        };
      })();
      const { success } = await mutateAsync({
        ...filteredValues,
        info: JSON.stringify(currentInfo),
        customData
      });
 
      if (success) {
        message.success('보상이 수정되었습니다.');
      } else {
        message.error('보상 수정에 실패했습니다.');
      }
    } catch (e) {
      if (axios.isAxiosError(e)) {
        console.error(e);
 
        const errorRewardIds = e.response?.data.message.split(':')[1].trim().split(',');
        const errorRewards = errorRewardIds.map(
          (id: string) => rewards?.data?.content.find((reward) => reward.id === id)?.name
        );
 
        if (e.response?.data.errorTitle === 'NotFoundWeightInDrawReward') {
          message.error(`[${errorRewards.join(', ')}] 보상의 가중치를 설정해주세요`);
        } else if (e.response?.data.errorTitle === 'NotAllowedRewardDrawType') {
          message.error(`[${errorRewards.join(', ')}] 뽑기 보상을 뽑기 보상에 추가할 수 없습니다`);
        } else if (e.response?.data.errorTitle === 'NotFoundReward') {
          message.error(e.response?.data.message);
        } else if (e.response?.data.errorTitle === 'DuplicateRewardIdInDrawReward') {
          message.error(e.response?.data.message);
        } else if (e.response?.data.errorTitle === 'AlreadyUsedOtherDrawReward') {
          message.error(
            `[${errorRewards.join(
              ', '
            )}] 보상이 이미 사용 중이기 때문에 뽑기 보상에 추가할 수 없습니다`
          );
        } else {
          message.error('알 수 없는 에러가 발생했습니다');
        }
      }
    }
  };
 
  const setInitialValue = React.useCallback(() => {
    if (rewardData && rewardData.data) {
      setCurrentType(rewardData.data.rewardType);
      setCurrentGoodsCode(JSON.parse(rewardData.data.customData).goodsCode);
      setCurrentInfo(JSON.parse(rewardData.data.info));
      setFileList(
        rewardData?.data?.imageUrl
          ? [{ uid: 'uid', name: '이전 이미지', url: rewardData.data.imageUrl }]
          : []
      );
 
      form.setFieldsValue({
        name: rewardData.data.name,
        description: rewardData.data.description,
        imageUrl: rewardData.data.imageUrl,
        remainingCount: rewardData.data.remainingCount,
        buttonName: rewardData.data.buttonName,
        buttonDescription: rewardData.data.buttonDescription,
        rewardType: rewardData.data.rewardType,
        note: rewardData.data.note,
        festivalId: rewardData.data.festivalId,
        expirationPeriod: rewardData.data.expirationPeriod,
        rewardIds: rewardData.data.children?.map((item) => item.id),
        projectId: JSON.parse(rewardData.data.customData).projectId,
        productId: JSON.parse(rewardData.data.customData).productId,
        goodsCode: JSON.parse(rewardData.data.customData).goodsCode,
        weight: JSON.parse(rewardData.data.customData).weight,
        count: JSON.parse(rewardData.data.customData).count
      });
 
      prevGoodsCode.current = JSON.parse(rewardData.data.customData).goodsCode;
    }
  }, [rewardData?.data]);
 
  React.useEffect(() => {
    setInitialValue();
  }, [rewardData?.data]);
 
  React.useEffect(() => {
    if (currentGoodsCode) {
      const goodsData = data?.data?.result.goodsList.find(
        (goods) => goods.goodsCode === currentGoodsCode
      );
 
      if (!goodsData) return;
 
      const delta = {
        ops: [
          { insert: '교환처\n', attributes: { bold: true } },
          { insert: `${goodsData?.affiliate}\n` },
          { insert: '유효기간\n', attributes: { bold: true } },
          { insert: `문자 지급일로부터 ${goodsData?.limitDay}일 유효합니다.\n` },
          { insert: '내용\n', attributes: { bold: true } },
          { insert: `${goodsData?.content}\n` }
        ]
      } as Delta;
 
      setCurrentInfo(delta);
      prevGoodsCode.current = currentGoodsCode;
    }
  }, [currentGoodsCode]);
 
  return (
    <>
      <HeaderContainer>
        <h1>보상 상세 정보</h1>
      </HeaderContainer>
      {data && rewardData ? (
        <Form form={form} onFinish={handleSubmit}>
          <Form.Item
            name="rewardType"
            label="보상 타입"
            rules={[{ required: true, message: '보상 타입을 선택해주세요' }]}
          >
            <Select
              placeholder="보상 타입을 선택해주세요"
              options={[
                { label: '기프티쇼', value: 'GiftShow' },
                { label: '할인권', value: 'DiscountTicket' },
                { label: '교환권', value: 'ExchangeTicket' },
                { label: '뽑기권', value: 'Draw' },
                { label: '프로젝트', value: 'Project' }
              ]}
              onChange={(value) => setCurrentType(value)}
            />
          </Form.Item>
          {currentType === 'GiftShow' && (
            <Form.Item
              name="goodsCode"
              label="기프티쇼"
              rules={[{ required: true, message: '기프티쇼를 선택해주세요' }]}
            >
              <Select
                showSearch
                placeholder="기프티쇼를 선택해주세요"
                options={data?.data?.result.goodsList.map((goods) => ({
                  label: goods.goodsName,
                  value: goods.goodsCode
                }))}
                onChange={(value) => {
                  const selectedGoodsData = data.data?.result.goodsList.find(
                    (goods) => goods.goodsCode === value
                  );
                  setCurrentGoodsCode(value);
 
                  form.setFieldValue('imageUrl', selectedGoodsData?.goodsImgB || undefined);
 
                  setFileList([
                    {
                      uid: value,
                      name: selectedGoodsData?.goodsName || '',
                      url: selectedGoodsData?.goodsImgB || undefined
                    }
                  ]);
                }}
                filterOption={(input, option) => {
                  return option?.label?.includes(input) || false;
                }}
              />
            </Form.Item>
          )}
          {currentType === 'Project' && (
            <Form.Item
              name="projectId"
              label="프로젝트"
              rules={[{ required: true, message: '프로젝트를 선택해주세요' }]}
            >
              <Select
                showSearch
                placeholder="프로젝트를 선택해주세요"
                options={projects?.data?.data?.map((project) => ({
                  label: project.projectName,
                  value: project.projectId
                }))}
                filterOption={(input, option) => {
                  return option?.label?.includes(input) || false;
                }}
              />
            </Form.Item>
          )}
          {currentType === 'Draw' && (
            <Form.Item
              name="rewardIds"
              label="뽑기 보상"
              rules={[{ required: true, message: '보상을 선택해주세요' }]}
            >
              <Select
                showSearch
                mode="multiple"
                placeholder="보상을 선택해주세요"
                options={rewards?.data?.content.map((reward) => ({
                  label: reward.name,
                  value: reward.id
                }))}
                filterOption={(input, option) => {
                  return option?.label?.includes(input) || false;
                }}
              />
            </Form.Item>
          )}
          <Form.Item
            name="name"
            label="보상 이름"
            rules={[{ required: true, message: '보상 이름을 입력해주세요' }]}
          >
            <Input placeholder="보상 이름을 입력해주세요" />
          </Form.Item>
          <Form.Item
            name="description"
            label="보상 설명"
            rules={[{ required: true, message: '보상 설명을 입력해주세요' }]}
          >
            <Input.TextArea placeholder="보상 설명을 입력해주세요" autoSize={{ minRows: 3 }} />
          </Form.Item>
          <Form.Item
            name="expirationPeriod"
            label="만료 기간"
            rules={[{ required: true, message: '만료 기간을 선택해주세요' }]}
          >
            <Select placeholder="만료 기간을 선택해주세요">
              {Object.values(ManageRewardResponseDtoExpirationPeriodEnum).map((value) => (
                <Select.Option key={value} value={value}>
                  {expirationPeriodToString[value]}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="imageUrl"
            label="이미지"
            labelCol={{ span: 24 }}
            wrapperCol={{ span: 24 }}
            rules={[{ required: true, message: '이미지를 업로드해주세요' }]}
            getValueFromEvent={(e) => {
              if (!e) return undefined;
              const { fileList } = e;
              return fileList[0]?.response;
            }}
          >
            <Upload
              fileList={fileList}
              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) => {
                setFileList(info.fileList);
                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.setFieldValue('imageUrl', undefined);
              }}
            >
              <Button type="primary" icon={<UploadOutlined />}>
                업로드
              </Button>
            </Upload>
          </Form.Item>
          <Form.Item
            name="buttonName"
            label="버튼 텍스트"
            rules={[{ required: true, message: '버튼 텍스트를 입력해주세요' }]}
          >
            <Input placeholder="버튼 텍스트를 입력해주세요" />
          </Form.Item>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Form.Item name="count" label="전체 보상 개수" style={{ flex: 1, marginRight: '16px' }}>
              <StyledInputNumber
                controls={false}
                placeholder="전체 보상 개수를 입력해주세요"
                readOnly
                style={{ width: '100%' }}
              />
            </Form.Item>
            <Form.Item name="remainingCount" label="잔여 보상 개수" style={{ flex: 1 }}>
              <StyledInputNumber
                controls={false}
                placeholder="잔여 보상 개수를 입력해주세요"
                readOnly
                style={{ width: '100%' }}
              />
            </Form.Item>
            <Button
              onClick={() => {
                openAddModal({});
              }}
              style={{ marginLeft: '16px' }}
            >
              개수 추가
            </Button>
          </div>
          <Form.Item name="weight" label="가중치">
            <StyledInputNumber placeholder="가중치를 입력해주세요" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="note" label="메모">
            <Input placeholder="메모를 입력해주세요." />
          </Form.Item>
 
          {prevGoodsCode.current === currentGoodsCode && (
            <Form.Item>
              <div>
                <QuillEditor value={currentInfo} onChange={setCurrentInfo} />
              </div>
            </Form.Item>
          )}
 
          <Form.Item name="festivalId" label="축제">
            <Select
              options={[
                { label: '연결된 축제 없음', value: null },
                ...(festivals?.data?.content.map((festival) => ({
                  label: festival.title,
                  value: festival.id
                })) || [])
              ]}
              placeholder="축제를 선택해주세요."
              showSearch
              filterOption={(input, option) => {
                return option?.label?.includes(input) || false;
              }}
            />
          </Form.Item>
 
          <Form.Item>
            <StyledButton type="primary" htmlType="submit">
              수정하기
            </StyledButton>
          </Form.Item>
        </Form>
      ) : (
        <Skeleton />
      )}
      <AddRewardCountModal
        modalData={addModal}
        rewardId={rewardId}
        closeModal={closeAddModal}
        type={currentType || ''}
      />
    </>
  );
}
 
const HeaderContainer = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
`;
 
const StyledButton = styled(Button)`
  float: right;
`;
 
const StyledInputNumber = styled(InputNumber)`
  width: 100%;
`;