All files / lib/pages/Question/Modal ExcelModal.tsx

0% Statements 0/52
0% Branches 0/24
0% Functions 0/19
0% Lines 0/46

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import { InboxOutlined } from '@ant-design/icons';
import { usePostQuestionsMutation } from '@lib/api/mutations';
import { planeStringToDelta } from '@lib/utils/planeStringToDelta';
import {
  CreateOrUpdateHintDto,
  CreateOrUpdateQuestionDto
} from '@uniquegood/realworld-adventure-interface';
import { Button, Modal, ModalProps, Table, UploadProps, message } from 'antd';
import { ColumnsType } from 'antd/es/table';
import Dragger from 'antd/es/upload/Dragger';
import Excel from 'exceljs';
import React from 'react';
import { v4 as uuidv4 } from 'uuid';
 
interface ExcelModalProps {
  modalData: ModalProps;
  closeModal: () => unknown;
}
 
export default function ExcelModal({ modalData, closeModal }: ExcelModalProps) {
  const [excelData, setExcelData] =
    React.useState<(CreateOrUpdateQuestionDto & { id: string })[]>();
  const [pageSize, setPageSize] = React.useState(20);
 
  const { mutateAsync } = usePostQuestionsMutation();
 
  const handleRemoveClick = (e: React.MouseEvent, id: string) => {
    e.stopPropagation();
 
    setExcelData((prev) => prev?.filter((item) => item.id !== id));
  };
 
  const columns: ColumnsType<{
    title: string;
    content: string;
    answer: string;
    createOrUpdateHint: CreateOrUpdateHintDto;
  }> = [
    {
      key: 'title',
      dataIndex: 'title',
      title: '문제 제목'
    },
    {
      key: 'content',
      dataIndex: 'content',
      title: '문제 내용'
    },
    {
      key: 'questionHint',
      title: '문제 힌트',
      render: (record) => {
        return record.createOrUpdateHint.content;
      }
    },
    {
      key: 'questionDeductionScore',
      title: '감점 점수',
      render: (record) => {
        return record.createOrUpdateHint.deductionScore;
      }
    },
    {
      key: 'answer',
      dataIndex: 'answer',
      title: '정답'
    },
    {
      key: 'isRandomAllowed',
      dataIndex: 'isRandomAllowed',
      title: '랜덤 문제 여부',
      render: (value) => (value ? 'O' : 'X')
    },
    {
      key: 'objectVideoUrl',
      dataIndex: 'objectVideoUrl',
      title: '비디오 URL (선택)'
    },
    {
      title: '동작',
      render: (record) => {
        return (
          <Button danger size="small" onClick={(e) => handleRemoveClick(e, record.id)}>
            삭제
          </Button>
        );
      }
    }
  ];
 
  const props: UploadProps = {
    name: 'file',
    async beforeUpload(file) {
      const wb = new Excel.Workbook();
      const reader = new FileReader();
 
      reader.readAsArrayBuffer(file);
      reader.onload = () => {
        const buffer = reader.result;
 
        wb.xlsx.load(buffer as Buffer).then((workbook) => {
          const data: CreateOrUpdateQuestionDto[] = [];
          workbook.getWorksheet(1).eachRow((row, rowIndex) => {
            if (rowIndex === 1) return;
 
            if (!Array.isArray(row.values)) return;
 
            row.values.some((value, index) => {
              if (value) {
                if (!Array.isArray(row.values)) return false;
 
                const [
                  title,
                  content,
                  questionHint,
                  questionDeductionScore,
                  answer,
                  isRandomAllowed,
                  objectVideoUrl
                ] = row.values.slice(index);
 
                data.push({
                  title: title as string,
                  content: content as string,
                  answer: answer as string,
                  objectVideoUrl: objectVideoUrl ? (objectVideoUrl as string) : undefined,
                  isQuestionHintAllowed: true,
                  isRandomAllowed: isRandomAllowed === 'O' || isRandomAllowed === 'o',
                  createOrUpdateHint: {
                    content: questionHint,
                    deductionScore: questionDeductionScore
                  } as CreateOrUpdateHintDto
                });
 
                return true;
              }
 
              return false;
            });
          });
 
          setExcelData(
            data.map((item) => {
              return {
                ...item,
                isRandomAllowed: item.isRandomAllowed,
                id: uuidv4()
              };
            })
          );
        });
      };
 
      return false;
    }
  };
 
  const handleSubmit = async () => {
    try {
      if (!excelData || excelData.length === 0) return;
 
      const { success } = await mutateAsync(
        excelData.map((item) => ({
          ...item,
          content: JSON.stringify(planeStringToDelta(item.content)),
          createOrUpdateHint: {
            ...item.createOrUpdateHint,
            content: JSON.stringify(planeStringToDelta(item.createOrUpdateHint.content))
          }
        }))
      );
 
      if (success) {
        message.success('문제를 추가했습니다.');
        closeModal();
      } else {
        throw new Error('failed to add questions');
      }
    } catch (e) {
      message.error('문제를 추가하지 못했습니다. 형식을 확인해주세요.');
    }
  };
 
  return (
    <Modal
      {...modalData}
      title="엑셀 파일 추가"
      width={1000}
      afterClose={() => setExcelData([])}
      onOk={handleSubmit}
      okText="확인"
      cancelText="닫기"
    >
      <div style={{ marginBottom: '16px' }}>
        엑셀 파일을 업로드해서 여러 개의 문제를 한 번에 등록할 수 있습니다.
        <br />
        엑셀 파일 템플릿은{' '}
        <a
          href="/question_sheet_example.xlsx"
          download="트레저_엑셀_업로드_예시.xlsx"
          style={{ fontWeight: 'bold' }}
        >
          여기
        </a>
        를 눌러 다운로드 받으세요.
      </div>
      {excelData && excelData.length > 0 ? (
        <Table
          columns={columns}
          dataSource={excelData}
          rowKey="id"
          pagination={{
            pageSize,
            onShowSizeChange(current, size) {
              setPageSize(size);
            }
          }}
        />
      ) : (
        <Dragger
          {...props}
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">
            여기를 클릭하거나 드래그해서 엑셀 파일을 업로드 해보세요.
          </p>
          <p className="ant-upload-hint">.xlsx 파일 확장자를 지원합니다.</p>
        </Dragger>
      )}
    </Modal>
  );
}