All files / lib/pages/Question index.tsx

0% Statements 0/72
0% Branches 0/16
0% Functions 0/25
0% Lines 0/71

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
'use client';
 
import { useGetQuestionsQuery } from '@lib/api/queries';
import useModalState from '@lib/hooks/useModalState';
import { QuestionResponseDto } from '@uniquegood/realworld-adventure-interface';
import { Button, Input, Switch, Tooltip, message } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import styled from 'styled-components';
import React from 'react';
import {
  useActiveQuestionMutation,
  useDeleteQuestionMutation,
  useDeleteQuestionsMutation,
  usePatchRandomQuestionMutation
} from '@lib/api/mutations';
import ConfirmDeleteModal from '@lib/components/ConfirmDeleteModal';
import CreateQuestionModal from './Modal/CreateQuestionModal';
import ModifyQuestionModal from './Modal/ModifyQuestionModal';
import ExcelModal from './Modal/ExcelModal';
 
export default function QuestionPage() {
  const [currentData, setCurrentData] = React.useState<QuestionResponseDto>();
  const [page, setPage] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(20);
  const [selectedRowKeys, setSelectedRowKeys] = React.useState<string[]>([]);
  const [keyword, setKeyword] = React.useState('');
  const hasSelection = React.useMemo(() => selectedRowKeys.length > 0, [selectedRowKeys]);
 
  const {
    openModal: openCreateModal,
    closeModal: closeCreateModal,
    modal: createModal
  } = useModalState();
  const {
    openModal: openModifyModal,
    closeModal: closeModifyModal,
    modal: modifyModal
  } = useModalState();
  const {
    openModal: openConfirmModal,
    closeModal: closeConfirmModal,
    modal: confirmModal
  } = useModalState();
  const {
    openModal: openExcelModal,
    closeModal: closeExcelModal,
    modal: excelModal
  } = useModalState();
 
  const { data } = useGetQuestionsQuery({ page, size: pageSize, keyword });
  const { mutateAsync } = useDeleteQuestionMutation();
  const { mutateAsync: mutateAsyncActiveQuestion } = useActiveQuestionMutation();
  const { mutateAsync: patchRandomQuestion } = usePatchRandomQuestionMutation();
  const { mutateAsync: deleteQuestions } = useDeleteQuestionsMutation();
 
  const handleRemoveClick = (event: React.MouseEvent<HTMLElement>, questionId: string) => {
    event.stopPropagation();
 
    openConfirmModal({
      onOk: async () => {
        try {
          const { success } = await mutateAsync(questionId);
 
          if (success) {
            closeConfirmModal();
            message.success('문제를 삭제했습니다.');
          }
        } catch (e) {
          console.error(e);
        }
      },
      title: '정말 삭제하시겠어요?'
    });
  };
 
  const handleActivationChange = async (questionId: string) => {
    try {
      const { success } = await mutateAsyncActiveQuestion(questionId);
 
      if (success) {
        message.success('문제 활성화 상태를 변경했습니다.');
      }
    } catch (e) {
      console.error(e);
      message.error('문제 활성화 상태 변경에 실패했습니다.');
    }
  };
 
  const handleRandomChange = async (record: QuestionResponseDto, value: boolean) => {
    try {
      const { id, ...rest } = record;
      const data = await patchRandomQuestion({
        questionId: id,
        ...rest,
        isRandomAllowed: value,
        createOrUpdateHint: {
          hintId: rest.hintList[0].id,
          deductionScore: rest.hintList[0].deductionScore,
          content: rest.hintList[0].content || ''
        }
      });
 
      if (data.success) {
        message.success('랜덤 문제 여부를 변경했습니다.');
      } else {
        message.error('랜덤 문제 여부 변경에 실패했습니다.');
      }
    } catch {
      message.error('랜덤 문제 여부 변경에 실패했습니다.');
    }
  };
 
  const handleQuestionsDelete = async () => {
    const { success } = await deleteQuestions(selectedRowKeys);
 
    if (success) {
      message.success('문제를 삭제했습니다.');
      setSelectedRowKeys([]);
      closeConfirmModal();
    }
  };
 
  const handleSearch = (value: string) => {
    setKeyword(value);
 
    setPage(0);
  };
 
  const columns: ColumnsType<QuestionResponseDto> = [
    {
      key: 'id',
      dataIndex: 'id',
      title: '문제 ID',
      width: 200,
      ellipsis: true,
      render: (value) => {
        return (
          <Tooltip title={value} placement="topLeft">
            {value}
          </Tooltip>
        );
      }
    },
    {
      key: 'title',
      dataIndex: 'title',
      title: '문제'
    },
    {
      key: 'answer',
      dataIndex: 'answer',
      title: '정답'
    },
    {
      key: 'isActive',
      dataIndex: 'isActive',
      title: '활성화 여부',
      render: (value, record) => {
        return (
          // eslint-disable-next-line jsx-a11y/click-events-have-key-events
          <span onClick={(e) => e.stopPropagation()}>
            <Switch checked={value} onChange={() => handleActivationChange(record.id)} />
          </span>
        );
      }
    },
    {
      key: 'isRandomAllowed',
      dataIndex: 'isRandomAllowed',
      title: '랜덤 문제 여부',
      // render: (value) => (value ? <Tag color="blue">O</Tag> : <Tag color="red">X</Tag>)
      render: (value, record) => {
        return (
          // eslint-disable-next-line jsx-a11y/click-events-have-key-events
          <span onClick={(e) => e.stopPropagation()}>
            <Switch checked={value} onChange={(value) => handleRandomChange(record, value)} />
          </span>
        );
      }
    },
    {
      title: '동작',
      width: '100px',
      render: (record) => {
        return (
          <Button danger size="small" onClick={(e) => handleRemoveClick(e, record.id)}>
            삭제
          </Button>
        );
      }
    }
  ];
 
  return (
    <>
      <HeaderContainer>
        <h1>문제 목록</h1>
        <HeaderControllerContainer>
          <Input.Search
            placeholder="검색어를 입력해주세요."
            onSearch={handleSearch}
            enterButton
            style={{ width: '300px' }}
          />
          <StyledExcelButton onClick={() => openExcelModal({})}>엑셀로 추가하기</StyledExcelButton>
          <Button onClick={() => openCreateModal({})}>문제 추가하기</Button>
        </HeaderControllerContainer>
      </HeaderContainer>
      {hasSelection && (
        <Button
          type="primary"
          danger
          onClick={() => {
            openConfirmModal({
              title: '선택한 문제를 삭제하시겠어요?',
              onOk: handleQuestionsDelete
            });
          }}
          style={{ marginBottom: '8px' }}
        >
          선택 삭제
        </Button>
      )}
      <Table
        columns={columns}
        dataSource={data?.data?.content || []}
        rowKey="id"
        loading={!data?.data?.content}
        pagination={{
          current: page + 1,
          total: data?.data?.totalElements,
          onShowSizeChange(current, size) {
            setPageSize(size);
          },
          pageSize,
          onChange: (page) => setPage(page - 1)
        }}
        onRow={(record) => {
          return {
            onClick: () => {
              setCurrentData(record);
              openModifyModal({});
            }
          };
        }}
        rowSelection={{
          type: 'checkbox',
          onChange: (values) => {
            setSelectedRowKeys(values as string[]);
          }
        }}
      />
      <CreateQuestionModal modalData={createModal} closeModal={closeCreateModal} />
      {currentData && (
        <ModifyQuestionModal
          modalData={modifyModal}
          closeModal={closeModifyModal}
          initialData={currentData}
        />
      )}
      <ConfirmDeleteModal modalData={confirmModal} />
      <ExcelModal modalData={excelModal} closeModal={closeExcelModal} />
    </>
  );
}
 
const HeaderContainer = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
`;
 
const HeaderControllerContainer = styled.div`
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: min-content;
  gap: 8px;
`;
 
const StyledExcelButton = styled(Button)`
  color: #fff !important;
  background-color: #10793f !important;
`;