From eaaabd2763dabb0b9e081b0c82efff18620d4588 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 09:02:39 +0900 Subject: [PATCH 1/5] =?UTF-8?q?feat:=20=EC=B2=98=EB=A6=AC=20=EB=8C=80?= =?UTF-8?q?=EA=B8=B0=20=ED=97=88=EB=B8=8C(=EC=9E=85=EA=B8=88=20=ED=99=95?= =?UTF-8?q?=EC=9D=B8=C2=B7=EC=9E=85=EA=B8=88=20=EB=B0=98=ED=99=98=C2=B7?= =?UTF-8?q?=ED=99=98=EB=B6=88=20=EC=86=A1=EA=B8=88=C2=B7=EC=A0=95=EC=82=B0?= =?UTF-8?q?=20=EC=86=A1=EA=B8=88)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ① 무엇·왜 - 계좌이체 수동 입금 확인(관리자만)과 환불·정산 송금을 한 화면에서 처리한다. BE 경보 딥링크(/tasks/deposits?orderId=·/tasks/refunds?refundId=·/tasks/settlements?periodStart=)가 그 건의 시트를 바로 연다. - 금액이 틀린 입금은 확인할 수 없어 반환 대상으로 연결하고, 주인 모를 입금은 메모와 함께 종결 기록한다. 픽업이 지난 주문은 확인을 막고 미입금 취소 뒤 반환으로 처리한다. - 명세에 없는 결정: 탭·사이드바 배지는 지금 처리할 수 있는 건만 센다(입금 대기 전체 + 환불 송금 대기 + 정산 송금 대기). 계좌 입력 대기 환불은 구매자를 기다리므로 환불 탭 안 칩과 대시보드 타일에만 보인다. - 명세에 없는 결정: 입금 기록 감사 링크는 단건 조회 API가 없어 입금 기록 목록으로 연다. 정산 [다음 건]은 계좌가 등록된 정산만 고른다. ② 변경점 - features/tasks 신설: adminTaskCounts(60초 폴링 + 창 포커스 재조회) 한 조회를 사이드바 '처리 대기'(운영 맨 위)·탭·대시보드 타일이 같이 쓴다. - 입금 탭: 확인 요청(claimedOnly)·입금 대기(금액·입금자명 검색)·입금 기록(반환·종결, 종결 기록 주문 연결). 픽업 3시간 미만 caution, 지남 negative, 입금 기한 지남 표시. - 주문 시트: [입금 확인](입금액 필수·메모 선택, 0원 주문은 0), DEPOSIT_AMOUNT_MISMATCH면 오류 문구와 함께 반환 연결을 입력 금액·입금자명으로 미리 채워 연다. [미입금 취소](PAYMENT_NOT_RECEIVED), [반환 대상으로 연결](금액·입금자명·입금 일시·메모). 상단 [주인 모를 입금 기록](메모 필수). - 환불 탭: 송금 대기·계좌 입력 대기(연락처)·종류 칩. 시트에서 전체 계좌번호 복사, [송금 완료] 확인 문구, 계좌 입력 전이면 비활성. - 정산 송금 탭: 송금 대기 정산, 기간 필터, 계좌 미등록이면 비활성 + 매장 링크. 시트에서 지금 정산 계좌 복사와 [송금 완료]. - 처리 성공·409면 건수·목록·단건을 다시 읽어 '처리됨'(처리자·시각)과 [다음 건 (N건 남음)]을 보인다. 409는 토스트로 알린다. - 감사 로그 대상 링크: REFUND → 환불 시트, DEPOSIT_RECORD → 입금 기록 목록. - 문서 이름은 AdminTasks* 접두로 다른 화면의 정산·환불 문서와 겹치지 않게 했다. 테스트 MSW 서버에 셸 공용 건수 기본 응답(0건)을 둔다. ③ 테스트 - meta·search·forms 순수 함수 표(픽업 경계 6, 다음 건 8, 금액 파싱 12, 폼 경계, 오류 분류). - 화면: 딥링크 시트, 세션 없는 복귀, 409(입금·환불·정산), 다음 건, 입금액 불일치 → 반환 시트 금액·입금자명 채움, 종결 메모 필수, 금액·주문 ID "0", 픽업 지남 확인 차단과 미입금 취소, 종결 기록 주문 연결, 배지·탭·타일 건수. - 반증 8건(픽업 경계, 다음 건 차감, 배지 계좌 대기 제외, Int 상한, 금액 0 truthy, 0원 입금 확인, 종결 메모 필수, 정산 다음 건 계좌 필터)이 각각 테스트를 실패시키는 것을 확인했다. --- src/app/router.spec.ts | 3 + src/app/shell/nav.spec.ts | 1 + src/app/shell/nav.ts | 8 + src/app/shell/sidebar-nav.tsx | 1 + .../audit-logs/components/audit-links.tsx | 13 + .../audit-logs/pages/audit-logs.spec.tsx | 2 + .../dashboard/pages/dashboard-page.tsx | 2 + src/features/tasks/api/queries.ts | 493 ++++++++++ .../tasks/components/deposit-dialog.tsx | 151 +++ .../tasks/components/deposit-order-sheet.tsx | 326 +++++++ .../tasks/components/link-deposit-dialog.tsx | 85 ++ .../tasks/components/refund-sheet.tsx | 155 ++++ .../tasks/components/settlement-sheet.tsx | 141 +++ src/features/tasks/components/task-counts.tsx | 101 ++ src/features/tasks/components/task-sheet.tsx | 105 +++ src/features/tasks/forms.spec.ts | 112 +++ src/features/tasks/forms.ts | 126 +++ src/features/tasks/hub.spec.tsx | 155 ++++ src/features/tasks/index.ts | 5 + src/features/tasks/meta.spec.ts | 116 +++ src/features/tasks/meta.ts | 98 ++ src/features/tasks/pages/deposits-page.tsx | 402 ++++++++ src/features/tasks/pages/deposits.spec.tsx | 871 ++++++++++++++++++ src/features/tasks/pages/refunds-page.tsx | 178 ++++ .../tasks/pages/refunds-settlements.spec.tsx | 553 +++++++++++ src/features/tasks/pages/settlements-page.tsx | 158 ++++ src/features/tasks/search.spec.ts | 120 +++ src/features/tasks/search.ts | 136 +++ src/graphql/generated/gql.ts | 96 ++ src/graphql/generated/graphql.ts | 481 ++++++++++ src/routeTree.gen.ts | 86 ++ src/routes/_authed/_shell/tasks/deposits.tsx | 16 + src/routes/_authed/_shell/tasks/index.tsx | 7 + src/routes/_authed/_shell/tasks/refunds.tsx | 16 + .../_authed/_shell/tasks/settlements.tsx | 19 + src/test/msw/server.ts | 13 +- 36 files changed, 5350 insertions(+), 1 deletion(-) create mode 100644 src/features/tasks/api/queries.ts create mode 100644 src/features/tasks/components/deposit-dialog.tsx create mode 100644 src/features/tasks/components/deposit-order-sheet.tsx create mode 100644 src/features/tasks/components/link-deposit-dialog.tsx create mode 100644 src/features/tasks/components/refund-sheet.tsx create mode 100644 src/features/tasks/components/settlement-sheet.tsx create mode 100644 src/features/tasks/components/task-counts.tsx create mode 100644 src/features/tasks/components/task-sheet.tsx create mode 100644 src/features/tasks/forms.spec.ts create mode 100644 src/features/tasks/forms.ts create mode 100644 src/features/tasks/hub.spec.tsx create mode 100644 src/features/tasks/index.ts create mode 100644 src/features/tasks/meta.spec.ts create mode 100644 src/features/tasks/meta.ts create mode 100644 src/features/tasks/pages/deposits-page.tsx create mode 100644 src/features/tasks/pages/deposits.spec.tsx create mode 100644 src/features/tasks/pages/refunds-page.tsx create mode 100644 src/features/tasks/pages/refunds-settlements.spec.tsx create mode 100644 src/features/tasks/pages/settlements-page.tsx create mode 100644 src/features/tasks/search.spec.ts create mode 100644 src/features/tasks/search.ts create mode 100644 src/routes/_authed/_shell/tasks/deposits.tsx create mode 100644 src/routes/_authed/_shell/tasks/index.tsx create mode 100644 src/routes/_authed/_shell/tasks/refunds.tsx create mode 100644 src/routes/_authed/_shell/tasks/settlements.tsx diff --git a/src/app/router.spec.ts b/src/app/router.spec.ts index 9e0ac6e..2ae9d89 100644 --- a/src/app/router.spec.ts +++ b/src/app/router.spec.ts @@ -57,6 +57,9 @@ describe('ID 검색 파라미터 정밀도', () => { '/_authed/_shell/reviews storeId', '/_authed/_shell/settlements/ storeId', '/_authed/_shell/stores/ regionId', + '/_authed/_shell/tasks/deposits orderId', + '/_authed/_shell/tasks/refunds refundId', + '/_authed/_shell/tasks/settlements settlementId', ].sort(), ); }); diff --git a/src/app/shell/nav.spec.ts b/src/app/shell/nav.spec.ts index 0b527bb..838e082 100644 --- a/src/app/shell/nav.spec.ts +++ b/src/app/shell/nav.spec.ts @@ -14,6 +14,7 @@ describe('nav', () => { { path: '/settlements/monthly', want: '정산' }, { path: '/settlements/31', want: '정산' }, { path: '/settings', want: '결제 설정' }, + { path: '/tasks/deposits', want: '처리 대기' }, ])('하위 화면도 메뉴 제목을 따른다: $path → $want', ({ path, want }) => { expect(titleFor(path)).toBe(want); }); diff --git a/src/app/shell/nav.ts b/src/app/shell/nav.ts index 319be97..ab40634 100644 --- a/src/app/shell/nav.ts +++ b/src/app/shell/nav.ts @@ -1,6 +1,7 @@ import { type LucideIcon, BriefcaseIcon, + InboxIcon, LayoutDashboardIcon, PackageIcon, TagsIcon, @@ -20,11 +21,15 @@ import { UsersIcon, WalletIcon, } from 'lucide-react'; +import { type ComponentType } from 'react'; + +import { TaskCountBadge } from '@/features/tasks'; /** 사이드바 메뉴. 각 영역 PR이 자기 항목을 붙인다 — Link의 to가 라우트 타입으로 검사되므로 있는 경로만 둔다. */ interface NavItem { to: | '/' + | '/tasks' | '/orders' | '/settlements' | '/users' @@ -45,6 +50,8 @@ interface NavItem { | '/settings'; label: string; icon: LucideIcon; + /** 메뉴 오른쪽 건수 배지 */ + badge?: ComponentType; } export interface NavGroup { label: string | null; @@ -56,6 +63,7 @@ export const NAV_GROUPS: NavGroup[] = [ { label: '운영', items: [ + { to: '/tasks', label: '처리 대기', icon: InboxIcon, badge: TaskCountBadge }, { to: '/orders', label: '주문', icon: ShoppingBagIcon }, { to: '/settlements', label: '정산', icon: WalletIcon }, { to: '/reports', label: '신고', icon: FlagIcon }, diff --git a/src/app/shell/sidebar-nav.tsx b/src/app/shell/sidebar-nav.tsx index 215632c..c5ab391 100644 --- a/src/app/shell/sidebar-nav.tsx +++ b/src/app/shell/sidebar-nav.tsx @@ -27,6 +27,7 @@ export function SidebarNav({ onNavigate }: { onNavigate?: () => void }) { > {item.label} + {item.badge && } ))} diff --git a/src/features/audit-logs/components/audit-links.tsx b/src/features/audit-logs/components/audit-links.tsx index 6ae9085..2268ded 100644 --- a/src/features/audit-logs/components/audit-links.tsx +++ b/src/features/audit-logs/components/audit-links.tsx @@ -78,6 +78,19 @@ export function TargetLink({ {text} ); + case 'REFUND': + return ( + + {text} + + ); + case 'DEPOSIT_RECORD': + // 입금 기록은 단건 조회가 없어 목록으로 연다 + return ( + + {text} + + ); default: return {text}; } diff --git a/src/features/audit-logs/pages/audit-logs.spec.tsx b/src/features/audit-logs/pages/audit-logs.spec.tsx index 9c85b9b..b81740e 100644 --- a/src/features/audit-logs/pages/audit-logs.spec.tsx +++ b/src/features/audit-logs/pages/audit-logs.spec.tsx @@ -131,6 +131,8 @@ describe('감사 로그', () => { ['BANNER', '배너 #5', '/banners/5'], ['REVIEW', '리뷰 #5', '/reviews?reviewId=5&deleted=true'], ['REVIEW_REPORT', '신고 #5', '/reports/5'], + ['REFUND', '환불 #5', '/tasks/refunds?refundId=5'], + ['DEPOSIT_RECORD', '입금 기록 #5', '/tasks/deposits?view=records'], ['ACCOUNT', '계정 #5', null], ['CHANGE_PASSWORD', '비밀번호 변경 #5', null], ['CATEGORY', '카테고리 #5', null], diff --git a/src/features/dashboard/pages/dashboard-page.tsx b/src/features/dashboard/pages/dashboard-page.tsx index 1eab663..eb9ce51 100644 --- a/src/features/dashboard/pages/dashboard-page.tsx +++ b/src/features/dashboard/pages/dashboard-page.tsx @@ -1,5 +1,6 @@ import { useQuery } from '@tanstack/react-query'; +import { TasksTile } from '@/features/tasks'; import { messageFor } from '@/shared/api'; import { PageHeader } from '@/shared/ui/page-header'; import { Skeleton } from '@/shared/ui/skeleton'; @@ -26,6 +27,7 @@ export function DashboardPage({ period, onPeriodChange }: Props) { meta={periodLabel(period)} actions={} /> + {summary.isError ? (

{messageFor(summary.error)} diff --git a/src/features/tasks/api/queries.ts b/src/features/tasks/api/queries.ts new file mode 100644 index 0000000..07cb26c --- /dev/null +++ b/src/features/tasks/api/queries.ts @@ -0,0 +1,493 @@ +import { type QueryClient, keepPreviousData, queryOptions } from '@tanstack/react-query'; + +import { graphql } from '@/graphql/generated'; +import { + type AdminConfirmPaymentInput, + type AdminCreateDepositReturnInput, + type AdminDepositRecordListInput, + type AdminTasksDepositRecordsQuery, + type AdminPendingPaymentListInput, + type AdminRecordUnidentifiedDepositInput, + type AdminRefundListInput, + type AdminSettlementListInput, + type AdminTasksOrderQuery, + type AdminTasksPendingPaymentsQuery, + type AdminTasksRefundQuery, + type AdminTasksRefundsQuery, + type AdminTasksSettlementQuery, + type AdminTasksSettlementsQuery, +} from '@/graphql/generated/graphql'; +import { gqlRequest } from '@/shared/api'; +import { formatKrw } from '@/shared/lib/format'; +import { MAX_KEYWORD_LENGTH } from '@/shared/lib/list-search'; +import { type EntityOption } from '@/shared/ui/entity-picker'; + +/** 건수·목록 폴링 주기. 디스코드 알림은 다시 올 수 있어 건수와 목록을 진실로 둔다 */ +export const TASK_POLL_MS = 60_000; + +const tasksKeys = { + all: ['tasks'] as const, + counts: () => [...tasksKeys.all, 'counts'] as const, + pendingPayments: (input: AdminPendingPaymentListInput) => + [...tasksKeys.all, 'pending-payments', input] as const, + order: (orderId: string) => [...tasksKeys.all, 'order', orderId] as const, + depositRecords: (input: AdminDepositRecordListInput) => + [...tasksKeys.all, 'deposit-records', input] as const, + refunds: (input: AdminRefundListInput) => [...tasksKeys.all, 'refunds', input] as const, + refund: (refundId: string) => [...tasksKeys.all, 'refund', refundId] as const, + settlements: (input: AdminSettlementListInput) => + [...tasksKeys.all, 'settlements', input] as const, + settlement: (settlementId: string) => [...tasksKeys.all, 'settlement', settlementId] as const, + orderOptions: (keyword: string) => [...tasksKeys.all, 'order-options', keyword] as const, +}; + +const AdminTaskCountsDocument = graphql(/* GraphQL */ ` + query AdminTaskCounts { + adminTaskCounts { + claimedPayments + pendingPayments + refundsAwaitingAccount + refundsAwaitingTransfer + pendingSettlements + } + } +`); + +const AdminTasksPendingPaymentsDocument = graphql(/* GraphQL */ ` + query AdminTasksPendingPayments($input: AdminPendingPaymentListInput) { + adminPendingPayments(input: $input) { + items { + orderId + orderNumber + storeName + productName + amount + depositorName + buyerName + buyerPhone + createdAt + expiresAt + buyerClaimedAt + pickupAt + } + totalCount + hasMore + nextCursor + } + } +`); +export type PendingPayment = + AdminTasksPendingPaymentsQuery['adminPendingPayments']['items'][number]; + +const AdminTasksOrderDocument = graphql(/* GraphQL */ ` + query AdminTasksOrder($orderId: ID!) { + adminOrder(orderId: $orderId) { + id + orderNumber + status + pickupAt + buyerName + buyerPhone + totalPrice + createdAt + items { + id + productName + } + payment { + status + amount + depositorName + expiresAt + buyerClaimedAt + confirmedAt + confirmedByLabel + confirmNote + } + cancellation { + actorType + reasonLabel + note + canceledAt + } + } + } +`); +export type TaskOrder = AdminTasksOrderQuery['adminOrder']; + +const AdminTasksConfirmPaymentDocument = graphql(/* GraphQL */ ` + mutation AdminTasksConfirmPayment($input: AdminConfirmPaymentInput!) { + adminConfirmPayment(input: $input) { + id + status + } + } +`); + +const AdminTasksCancelUnpaidDocument = graphql(/* GraphQL */ ` + mutation AdminTasksCancelUnpaid($input: AdminCancelOrderInput!) { + adminCancelOrder(input: $input) { + id + status + } + } +`); + +const AdminTasksDepositRecordsDocument = graphql(/* GraphQL */ ` + query AdminTasksDepositRecords($input: AdminDepositRecordListInput) { + adminDepositRecords(input: $input) { + items { + id + kind + orderId + orderNumber + amount + depositorName + depositedAt + note + recordedByLabel + refundId + refundStatus + createdAt + } + totalCount + hasMore + nextCursor + } + } +`); +export type DepositRecord = AdminTasksDepositRecordsQuery['adminDepositRecords']['items'][number]; + +const AdminTasksCreateDepositReturnDocument = graphql(/* GraphQL */ ` + mutation AdminTasksCreateDepositReturn($input: AdminCreateDepositReturnInput!) { + adminCreateDepositReturn(input: $input) { + id + refundId + } + } +`); + +const AdminTasksRecordUnidentifiedDepositDocument = graphql(/* GraphQL */ ` + mutation AdminTasksRecordUnidentifiedDeposit($input: AdminRecordUnidentifiedDepositInput!) { + adminRecordUnidentifiedDeposit(input: $input) { + id + } + } +`); + +const AdminTasksLinkUnidentifiedDepositDocument = graphql(/* GraphQL */ ` + mutation AdminTasksLinkUnidentifiedDeposit($input: AdminLinkUnidentifiedDepositInput!) { + adminLinkUnidentifiedDeposit(input: $input) { + id + } + } +`); + +const AdminTasksOrderOptionsDocument = graphql(/* GraphQL */ ` + query AdminTasksOrderOptions($input: AdminOrderListInput) { + adminOrders(input: $input) { + items { + id + orderNumber + buyerName + totalPrice + } + } + } +`); + +const AdminTasksRefundsDocument = graphql(/* GraphQL */ ` + query AdminTasksRefunds($input: AdminRefundListInput) { + adminRefunds(input: $input) { + items { + id + kind + amount + status + bank { + code + name + } + accountHolder + accountNumberMasked + requestedAt + accountSubmittedAt + orderId + orderNumber + buyerName + buyerPhone + storeName + productName + } + totalCount + hasMore + nextCursor + } + } +`); +export type RefundRow = AdminTasksRefundsQuery['adminRefunds']['items'][number]; + +const AdminTasksRefundDocument = graphql(/* GraphQL */ ` + query AdminTasksRefund($refundId: ID!) { + adminRefund(refundId: $refundId) { + refund { + id + kind + amount + status + bank { + code + name + } + accountHolder + accountNumberMasked + requestedAt + accountSubmittedAt + completedAt + orderId + orderNumber + buyerName + buyerPhone + storeName + productName + completedByLabel + completeNote + } + accountNumber + depositRecord { + id + depositorName + depositedAt + note + } + } + } +`); +export type RefundDetail = AdminTasksRefundQuery['adminRefund']; + +const AdminTasksCompleteRefundDocument = graphql(/* GraphQL */ ` + mutation AdminTasksCompleteRefund($input: AdminCompleteRefundInput!) { + adminCompleteRefund(input: $input) { + id + status + } + } +`); + +const AdminTasksSettlementsDocument = graphql(/* GraphQL */ ` + query AdminTasksSettlements($input: AdminSettlementListInput) { + adminSettlements(input: $input) { + items { + id + storeId + storeName + periodStart + periodEnd + orderCount + settlementBaseAmount + commissionAmount + payoutAmount + status + accountRegistered + createdAt + } + totalCount + hasMore + nextCursor + } + } +`); +export type SettlementRow = AdminTasksSettlementsQuery['adminSettlements']['items'][number]; + +const AdminTasksSettlementDocument = graphql(/* GraphQL */ ` + query AdminTasksSettlement($settlementId: ID!) { + adminSettlement(settlementId: $settlementId) { + id + storeId + storeName + periodStart + periodEnd + orderCount + settlementBaseAmount + commissionAmount + payoutAmount + status + paidAt + accountRegistered + paidByLabel + paidNote + paidAccount { + bank { + code + name + } + accountHolder + accountNumberMasked + } + currentAccount { + bank { + code + name + } + accountHolder + accountNumber + } + } + } +`); +export type SettlementDetail = AdminTasksSettlementQuery['adminSettlement']; + +const AdminTasksMarkSettlementPaidDocument = graphql(/* GraphQL */ ` + mutation AdminTasksMarkSettlementPaid($input: AdminMarkSettlementPaidInput!) { + adminMarkSettlementPaid(input: $input) { + id + status + } + } +`); + +// 폴링 목록은 다시 받는 동안 이전 행을 유지한다 +const listOptions = { + placeholderData: keepPreviousData, + refetchInterval: TASK_POLL_MS, + refetchOnWindowFocus: true, +} as const; + +/** 사이드바·탭·대시보드가 같이 쓰는 처리 대기 건수 */ +export function taskCountsQueryOptions() { + return queryOptions({ + queryKey: tasksKeys.counts(), + queryFn: async () => (await gqlRequest(AdminTaskCountsDocument)).adminTaskCounts, + refetchInterval: TASK_POLL_MS, + refetchOnWindowFocus: true, + }); +} + +export function pendingPaymentsQueryOptions(input: AdminPendingPaymentListInput) { + return queryOptions({ + queryKey: tasksKeys.pendingPayments(input), + queryFn: async () => + (await gqlRequest(AdminTasksPendingPaymentsDocument, { input })).adminPendingPayments, + ...listOptions, + }); +} + +export function taskOrderQueryOptions(orderId: string) { + return queryOptions({ + queryKey: tasksKeys.order(orderId), + queryFn: async () => (await gqlRequest(AdminTasksOrderDocument, { orderId })).adminOrder, + retry: false, + }); +} + +export function depositRecordsQueryOptions(input: AdminDepositRecordListInput) { + return queryOptions({ + queryKey: tasksKeys.depositRecords(input), + queryFn: async () => + (await gqlRequest(AdminTasksDepositRecordsDocument, { input })).adminDepositRecords, + ...listOptions, + }); +} + +export function refundsQueryOptions(input: AdminRefundListInput) { + return queryOptions({ + queryKey: tasksKeys.refunds(input), + queryFn: async () => (await gqlRequest(AdminTasksRefundsDocument, { input })).adminRefunds, + ...listOptions, + }); +} + +export function refundQueryOptions(refundId: string) { + return queryOptions({ + queryKey: tasksKeys.refund(refundId), + queryFn: async () => (await gqlRequest(AdminTasksRefundDocument, { refundId })).adminRefund, + retry: false, + }); +} + +export function settlementsQueryOptions(input: AdminSettlementListInput) { + return queryOptions({ + queryKey: tasksKeys.settlements(input), + queryFn: async () => + (await gqlRequest(AdminTasksSettlementsDocument, { input })).adminSettlements, + ...listOptions, + }); +} + +export function settlementQueryOptions(settlementId: string) { + return queryOptions({ + queryKey: tasksKeys.settlement(settlementId), + queryFn: async () => + (await gqlRequest(AdminTasksSettlementDocument, { settlementId })).adminSettlement, + retry: false, + }); +} + +/** 종결 기록을 연결할 주문 검색(주문번호·주문자 이름·연락처) */ +export function orderOptionsQueryOptions(keyword: string) { + return queryOptions({ + queryKey: tasksKeys.orderOptions(keyword), + queryFn: async () => + ( + await gqlRequest(AdminTasksOrderOptionsDocument, { + input: { + keyword: keyword === '' ? null : [...keyword].slice(0, MAX_KEYWORD_LENGTH).join(''), + limit: 20, + }, + }) + ).adminOrders.items, + select: (items): EntityOption[] => + items.map((o) => ({ + id: o.id, + label: o.orderNumber, + description: `${o.buyerName} · ${formatKrw(o.totalPrice)}`, + })), + }); +} + +/** 처리 뒤·충돌 뒤 건수·목록·단건을 다시 읽는다. 처리자·시각은 다시 읽은 단건이 보인다 */ +const refreshTasks = (qc: QueryClient) => qc.invalidateQueries({ queryKey: tasksKeys.all }); + +async function run(qc: QueryClient, request: Promise): Promise { + try { + return await request; + } finally { + await refreshTasks(qc); + } +} + +export const taskMutations = { + confirmPayment: (qc: QueryClient, input: AdminConfirmPaymentInput) => + run(qc, gqlRequest(AdminTasksConfirmPaymentDocument, { input })), + cancelUnpaid: (qc: QueryClient, orderId: string, note: string) => + run( + qc, + gqlRequest(AdminTasksCancelUnpaidDocument, { + input: { orderId, reason: 'PAYMENT_NOT_RECEIVED', note: note || null }, + }), + ), + createDepositReturn: async (qc: QueryClient, input: AdminCreateDepositReturnInput) => + (await run(qc, gqlRequest(AdminTasksCreateDepositReturnDocument, { input }))) + .adminCreateDepositReturn, + recordUnidentifiedDeposit: (qc: QueryClient, input: AdminRecordUnidentifiedDepositInput) => + run(qc, gqlRequest(AdminTasksRecordUnidentifiedDepositDocument, { input })), + linkUnidentifiedDeposit: (qc: QueryClient, depositRecordId: string, orderId: string) => + run( + qc, + gqlRequest(AdminTasksLinkUnidentifiedDepositDocument, { + input: { depositRecordId, orderId }, + }), + ), + completeRefund: (qc: QueryClient, refundId: string, note: string) => + run( + qc, + gqlRequest(AdminTasksCompleteRefundDocument, { input: { refundId, note: note || null } }), + ), + markSettlementPaid: (qc: QueryClient, settlementId: string, note: string) => + run( + qc, + gqlRequest(AdminTasksMarkSettlementPaidDocument, { + input: { settlementId, note: note || null }, + }), + ), +}; diff --git a/src/features/tasks/components/deposit-dialog.tsx b/src/features/tasks/components/deposit-dialog.tsx new file mode 100644 index 0000000..139d2a4 --- /dev/null +++ b/src/features/tasks/components/deposit-dialog.tsx @@ -0,0 +1,151 @@ +import { zodResolver } from '@hookform/resolvers/zod'; +import { useState } from 'react'; +import { useForm } from 'react-hook-form'; +import { toast } from 'sonner'; + +import { Button } from '@/shared/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/shared/ui/dialog'; +import { Input } from '@/shared/ui/input'; +import { Label } from '@/shared/ui/label'; +import { Textarea } from '@/shared/ui/textarea'; + +import { + type DepositValues, + depositFormError, + depositReturnSchema, + emptyDeposit, + unidentifiedDepositSchema, +} from '../forms'; + +interface Props { + open: boolean; + onOpenChange: (open: boolean) => void; + title: string; + description: string; + /** 폼 위에 먼저 보일 안내(입금 확인이 금액 불일치로 거절된 경우 등) */ + notice?: string; + /** true면 메모 필수(주인 모를 입금 종결) */ + noteRequired: boolean; + defaults?: Partial; + submitLabel: string; + /** reject면 열린 채 오류를 보인다 */ + onSubmit: (v: DepositValues) => Promise; +} + +/** 은행 앱에서 본 입금 1건을 적는 폼(반환 대상 연결·주인 모를 입금 종결 공용) */ +export function DepositDialog(props: Props) { + return ( +

+ + {/* 열 때마다 새로 마운트해 미리 채운 값으로 시작한다 */} + + + + ); +} + +function DepositForm({ + onOpenChange, + title, + description, + notice, + noteRequired, + defaults, + submitLabel, + onSubmit, +}: Props) { + const [error, setError] = useState(null); + const form = useForm({ + resolver: zodResolver(noteRequired ? unidentifiedDepositSchema : depositReturnSchema), + defaultValues: emptyDeposit(defaults), + }); + const { errors, isSubmitting } = form.formState; + + const submit = form.handleSubmit(async (v) => { + setError(null); + try { + await onSubmit(v); + onOpenChange(false); + } catch (e) { + const r = depositFormError(e); + if (r.field) form.setError(r.field, { type: 'server', message: r.message }); + else if (r.inForm) setError(r.message); + else toast.error(r.message); + } + }); + + const fieldError = (name: keyof DepositValues) => + errors[name] &&

{errors[name].message}

; + + return ( +
+ + {title} + {description} + + {(error ?? notice) && ( +

+ {error ?? notice} +

+ )} +
+
+ + + {fieldError('amount')} +
+
+ + + {fieldError('depositorName')} +
+
+
+ + +
+
+ +