page.tsx 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. 'use client';
  2. import { useState, useEffect, useMemo } from 'react';
  3. import Link from 'next/link';
  4. import { fetchApi, getDateTime } from '@/lib/utils/client';
  5. import type { WalletWithdrawResponse } from '@/types/response/wallet/withdraw';
  6. import { LoginLogType } from '@/constants/common';
  7. import { PERIOD_TABS, WITHDRAW_STATUS_MAP, WITHHOLDING_TAX_RATE, MIN_WITHDRAW_AMOUNT } from '../constants';
  8. import Loading from '@/app/component/Loading';
  9. import Pagination from '@/app/component/Pagination';
  10. export default function WalletWithdrawPage() {
  11. const [loading, setLoading] = useState(true);
  12. const [submitting, setSubmitting] = useState(false);
  13. const [page, setPage] = useState(1);
  14. const [period, setPeriod] = useState<LoginLogType>(LoginLogType.Month);
  15. const [data, setData] = useState<WalletWithdrawResponse>({
  16. total: 0,
  17. withdrawableBalance: 0,
  18. accounts: [],
  19. list: [],
  20. });
  21. const [amount, setAmount] = useState('');
  22. const [selectedAccountID, setSelectedAccountID] = useState<number>(0);
  23. const numericAmount = useMemo(() => {
  24. const n = parseInt(amount, 10);
  25. return isNaN(n) ? 0 : n;
  26. }, [amount]);
  27. const withholdingTax = useMemo(() => Math.floor(numericAmount * WITHHOLDING_TAX_RATE), [numericAmount]);
  28. const netAmount = useMemo(() => numericAmount - withholdingTax, [numericAmount, withholdingTax]);
  29. const canSubmit = useMemo(() => {
  30. return (
  31. selectedAccountID > 0 &&
  32. numericAmount >= MIN_WITHDRAW_AMOUNT &&
  33. numericAmount <= data.withdrawableBalance &&
  34. !submitting
  35. );
  36. }, [selectedAccountID, numericAmount, data.withdrawableBalance, submitting]);
  37. useEffect(() => {
  38. setLoading(true);
  39. fetchApi<WalletWithdrawResponse>(`/api/studio/wallet/withdraw?period=${period}&page=${page}&perPage=20`)
  40. .then(res => {
  41. if (res.data) {
  42. setData(res.data);
  43. // 계좌가 1개면 자동 선택
  44. if (res.data.accounts.length === 1 && selectedAccountID === 0) {
  45. setSelectedAccountID(res.data.accounts[0].id);
  46. }
  47. }
  48. })
  49. .catch(() => {})
  50. .finally(() => setLoading(false));
  51. }, [period, page]);
  52. useEffect(() => {
  53. setPage(1);
  54. }, [period]);
  55. const handleSubmit = async () => {
  56. if (!canSubmit) {
  57. return;
  58. }
  59. const selectedAccount = data.accounts.find(a => a.id === selectedAccountID);
  60. const confirmed = confirm(
  61. `출금 신청하시겠습니까?\n\n` +
  62. `입금 계좌: ${selectedAccount?.bankName} ${selectedAccount?.accountNumber}\n` +
  63. `신청 금액: ${numericAmount.toLocaleString()}원\n` +
  64. `원천징수(3.3%): -${withholdingTax.toLocaleString()}원\n` +
  65. `실수령액: ${netAmount.toLocaleString()}원`
  66. );
  67. if (!confirmed) {
  68. return;
  69. }
  70. setSubmitting(true);
  71. try {
  72. await fetchApi('/api/studio/wallet/withdraw', {
  73. method: 'POST',
  74. body: { accountID: selectedAccountID, amount: numericAmount },
  75. });
  76. alert('출금 신청이 완료되었습니다.');
  77. setAmount('');
  78. // 목록 새로고침
  79. const res = await fetchApi<WalletWithdrawResponse>(`/api/studio/wallet/withdraw?period=${period}&page=1&perPage=20`);
  80. if (res.data) {
  81. setData(res.data);
  82. }
  83. setPage(1);
  84. } catch (err: unknown) {
  85. alert(err instanceof Error ? err.message : '출금 신청에 실패했습니다.');
  86. } finally {
  87. setSubmitting(false);
  88. }
  89. };
  90. const getStatus = (status: string) => WITHDRAW_STATUS_MAP[status] ?? { label: status, cls: '' };
  91. return (
  92. <div className="studio-page wallet">
  93. <div className="studio-page__header">
  94. <h1 className="studio-page__title">출금</h1>
  95. </div>
  96. {loading && <Loading />}
  97. {/* Withdraw Form */}
  98. <div className="wallet__withdraw-form">
  99. <div className="wallet__withdraw-balance">
  100. {data.withdrawableBalance.toLocaleString()}원
  101. <small>(M) 출금 가능</small>
  102. </div>
  103. {/* 계좌 미등록 경고 */}
  104. {data.accounts.length === 0 && (
  105. <div className="wallet__withdraw-warning">
  106. 계좌가 등록되지 않았습니다.
  107. <Link href="/studio/settlement/account">계좌 등록하기</Link>
  108. </div>
  109. )}
  110. {/* 계좌 선택 */}
  111. {data.accounts.length > 0 && (
  112. <div className="wallet__withdraw-field">
  113. <label htmlFor="withdraw-account">입금 계좌</label>
  114. <select
  115. id="withdraw-account"
  116. className="wallet__withdraw-select"
  117. value={selectedAccountID}
  118. onChange={e => setSelectedAccountID(Number(e.target.value))}
  119. >
  120. {data.accounts.length > 1 && (
  121. <option value={0}>계좌를 선택하세요</option>
  122. )}
  123. {data.accounts.map(acc => (
  124. <option key={acc.id} value={acc.id}>
  125. {acc.bankName} {acc.accountNumber} ({acc.accountHolder})
  126. </option>
  127. ))}
  128. </select>
  129. <Link href="/studio/settlement/account" className="wallet__withdraw-account-link">계좌 관리</Link>
  130. </div>
  131. )}
  132. {/* 금액 입력 */}
  133. <div className="wallet__withdraw-field">
  134. <label htmlFor="withdraw-amount">출금 금액</label>
  135. <input
  136. id="withdraw-amount"
  137. type="text"
  138. inputMode="numeric"
  139. className="wallet__withdraw-input"
  140. placeholder={`최소 ${MIN_WITHDRAW_AMOUNT.toLocaleString()}원`}
  141. value={amount}
  142. onChange={e => setAmount(e.target.value.replace(/\D/g, ''))}
  143. disabled={data.accounts.length === 0}
  144. />
  145. </div>
  146. {/* 차감 프리뷰 */}
  147. {numericAmount > 0 && (
  148. <div className="wallet__withdraw-preview">
  149. <div className="wallet__withdraw-row">
  150. <span>신청 금액</span>
  151. <span>{numericAmount.toLocaleString()}원</span>
  152. </div>
  153. <div className="wallet__withdraw-row">
  154. <span>원천징수 (3.3%)</span>
  155. <span className="wallet__amount--minus">-{withholdingTax.toLocaleString()}원</span>
  156. </div>
  157. <div className="wallet__withdraw-total">
  158. <span>실수령액</span>
  159. <span>{netAmount.toLocaleString()}원</span>
  160. </div>
  161. </div>
  162. )}
  163. {/* 안내사항 */}
  164. <ul className="wallet__withdraw-info">
  165. <li>최소 출금 금액: {MIN_WITHDRAW_AMOUNT.toLocaleString()}원</li>
  166. <li>원천징수 3.3% (소득세 3% + 지방소득세 0.3%)</li>
  167. <li>매월 10일까지 신청 시 당월 말 입금</li>
  168. </ul>
  169. {/* 제출 */}
  170. <button
  171. type="button"
  172. className="wallet__withdraw-submit"
  173. disabled={!canSubmit}
  174. onClick={handleSubmit}
  175. >
  176. {submitting ? '신청 중...' : '출금 신청'}
  177. </button>
  178. </div>
  179. {/* Withdraw History */}
  180. <h2 className="wallet__section-title">출금 내역</h2>
  181. <div className="wallet__header">
  182. <div className="wallet__summary">합계: {data.total}건</div>
  183. <div className="wallet__tabs">
  184. {PERIOD_TABS.map((tab) => (
  185. <button
  186. type="button"
  187. key={tab.value}
  188. className={period === tab.value ? 'active' : ''}
  189. onClick={() => setPeriod(tab.value)}
  190. >
  191. {tab.label}
  192. </button>
  193. ))}
  194. </div>
  195. </div>
  196. <div className="wallet__table-wrap">
  197. <table className="wallet__table">
  198. <thead>
  199. <tr>
  200. <th>신청일</th>
  201. <th style={{ textAlign: 'right' }}>신청 금액</th>
  202. <th style={{ textAlign: 'right' }}>원천징수</th>
  203. <th style={{ textAlign: 'right' }}>실수령액</th>
  204. <th>계좌</th>
  205. <th>상태</th>
  206. </tr>
  207. </thead>
  208. <tbody>
  209. {data.list.length > 0 ? (
  210. data.list.map((row) => {
  211. const st = getStatus(row.status);
  212. return (
  213. <tr key={row.id}>
  214. <td>{getDateTime(row.requestedAt)}</td>
  215. <td style={{ textAlign: 'right' }}>{row.requestedAmount.toLocaleString()}원</td>
  216. <td style={{ textAlign: 'right' }}>
  217. <span className="wallet__amount--minus">-{row.withholdingTax.toLocaleString()}원</span>
  218. </td>
  219. <td style={{ textAlign: 'right' }}>
  220. <span className="wallet__amount--plus">{row.netAmount.toLocaleString()}원</span>
  221. </td>
  222. <td>{row.bankName} {row.accountNumber}</td>
  223. <td><span className={st.cls}>{st.label}</span></td>
  224. </tr>
  225. );
  226. })
  227. ) : (
  228. <tr>
  229. <td colSpan={6} className="wallet__empty">출금 내역이 없습니다.</td>
  230. </tr>
  231. )}
  232. </tbody>
  233. </table>
  234. </div>
  235. {data.total > 0 && (
  236. <Pagination total={data.total} page={page} perPage={20} onChange={setPage} />
  237. )}
  238. </div>
  239. );
  240. }