diff --git a/docs/guide/architecture-conventions.md b/docs/guide/architecture-conventions.md index b30e42e..0abbd63 100644 --- a/docs/guide/architecture-conventions.md +++ b/docs/guide/architecture-conventions.md @@ -38,6 +38,7 @@ src/ - **요청**은 `gqlRequest(Document, variables)`(`@/shared/api`) 하나로. 인증 헤더·쿠키·401 갱신·에러 정규화(`ApiError`)를 여기서 끝낸다. REST는 `authRequest`. - **쿼리 키**는 feature별 팩토리(`ordersKeys.list(filters)`, `ordersKeys.detail(id)`)로만 만든다. 문자열 리터럴 키 금지. - **mutation 뒤**에는 그 feature의 list·detail 키를 invalidate한다. 낙관적 업데이트는 쓰지 않는다 — 감사 대상 작업이라 서버 결과가 진실이다. +- 다른 feature의 화면도 바꾸는 mutation(처리 대기 처리 → 주문·정산·대시보드, 강제 취소·정산 송금 완료 → 처리 대기)은 상대 배럴의 `invalidate*` helper를 부른다. 키는 소유 feature만 만든다. 서로 부르는 feature는 순환 import가 되므로 상대 export를 모듈 평가 때(최상위 상수·zod 스키마) 쓰지 않는다. - **목록**은 커서 방식(`items · totalCount · hasMore · nextCursor`). 필터·커서는 URL 검색 파라미터(zod)로 유지해 새로고침·공유가 된다. - **ID**는 문자열 그대로. `"0"`·빈 문자열을 truthy 검사로 버리지 않는다. - **enum 라벨**은 `Record<생성 enum, …>`로 둬 값이 늘면 tsc가 잡게 하고, 조회는 모르는 값에 원문으로 폴백한다. BE가 먼저 배포돼 새 값이 와도 화면이 죽지 않아야 한다. 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/api/queries.ts b/src/features/dashboard/api/queries.ts index a14a6e2..7c53140 100644 --- a/src/features/dashboard/api/queries.ts +++ b/src/features/dashboard/api/queries.ts @@ -1,11 +1,12 @@ -import { queryOptions } from '@tanstack/react-query'; +import { type QueryClient, queryOptions } from '@tanstack/react-query'; import { graphql } from '@/graphql/generated'; import { gqlRequest } from '@/shared/api'; const dashboardKeys = { all: ['dashboard'] as const, - summary: (from: string, to: string) => [...dashboardKeys.all, 'summary', from, to] as const, + summaries: () => [...dashboardKeys.all, 'summary'] as const, + summary: (from: string, to: string) => [...dashboardKeys.summaries(), from, to] as const, keywords: (rankedAt: string | null, limit: number) => [...dashboardKeys.all, 'keywords', rankedAt, limit] as const, }; @@ -65,3 +66,7 @@ export function searchKeywordQueryOptions(rankedAt: string | null = null, limit .adminSearchKeywordSnapshot, }); } + +/** 기간 요약(주문 상태별 건수 등)을 다시 읽게 한다. 주문 상태를 바꾸는 다른 화면(처리 대기)이 부른다 */ +export const invalidateDashboard = (queryClient: QueryClient) => + queryClient.invalidateQueries({ queryKey: dashboardKeys.summaries() }); diff --git a/src/features/dashboard/index.ts b/src/features/dashboard/index.ts index 8261fa8..9d3267f 100644 --- a/src/features/dashboard/index.ts +++ b/src/features/dashboard/index.ts @@ -1,2 +1,3 @@ +export { invalidateDashboard } from './api/queries'; export { DashboardPage } from './pages/dashboard-page'; export { periodSearchSchema, resolvePeriod } from './period'; 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/orders/api/queries.spec.ts b/src/features/orders/api/queries.spec.ts new file mode 100644 index 0000000..36da79d --- /dev/null +++ b/src/features/orders/api/queries.spec.ts @@ -0,0 +1,54 @@ +import { QueryClient, QueryObserver } from '@tanstack/react-query'; + +import { taskCountsQueryOptions } from '@/features/tasks/api/queries'; +import { gqlCounted, gqlError } from '@/test/msw/graphql'; +import { server } from '@/test/msw/server'; + +import { cancelOrder, completeOrderPickup } from './queries'; + +/** 사이드바처럼 처리 대기 건수를 구독한다. invalidate는 구독 중인 쿼리만 다시 요청한다 */ +async function watchTaskCounts(answers: Record>) { + const { counts, handler } = gqlCounted({ AdminTaskCounts: { adminTaskCounts: {} }, ...answers }); + server.use(handler); + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const stop = new QueryObserver(qc, taskCountsQueryOptions()).subscribe(() => undefined); + await vi.waitFor(() => expect(counts.AdminTaskCounts).toBe(1)); + return { qc, counts, stop }; +} + +describe('주문 처리 뒤 처리 대기 건수', () => { + it('강제 취소 뒤 다시 요청한다', async () => { + const { qc, counts, stop } = await watchTaskCounts({ + AdminCancelOrder: { adminCancelOrder: { id: '1' } }, + }); + await cancelOrder(qc, { orderId: '1', reason: 'PAYMENT_NOT_RECEIVED' }); + expect(counts.AdminTaskCounts).toBe(2); + stop(); + }); + + it('관리자 픽업 완료 뒤 다시 요청한다', async () => { + const { qc, counts, stop } = await watchTaskCounts({ + AdminCompleteOrderPickup: { adminCompleteOrderPickup: { id: '1' } }, + }); + await completeOrderPickup(qc, '1', ''); + expect(counts.AdminTaskCounts).toBe(2); + stop(); + }); + + it('취소가 거절돼도(409) 다시 요청한다', async () => { + const { qc, counts, stop } = await watchTaskCounts({}); + server.use( + gqlError('AdminCancelOrder', { + message: '취소할 수 없는 상태입니다.', + code: 'ORDER_NOT_CANCELLABLE', + classification: 'CONFLICT', + statusCode: 409, + }), + ); + await expect(cancelOrder(qc, { orderId: '1', reason: 'PAYMENT_NOT_RECEIVED' })).rejects.toThrow( + '취소할 수 없는 상태입니다.', + ); + expect(counts.AdminTaskCounts).toBe(2); + stop(); + }); +}); diff --git a/src/features/orders/api/queries.ts b/src/features/orders/api/queries.ts index dacb707..b3ec31b 100644 --- a/src/features/orders/api/queries.ts +++ b/src/features/orders/api/queries.ts @@ -1,5 +1,6 @@ import { type QueryClient, queryOptions } from '@tanstack/react-query'; +import { invalidateTasks } from '@/features/tasks'; import { graphql } from '@/graphql/generated'; import { type AdminCancelOrderInput, type AdminOrderListInput } from '@/graphql/generated/graphql'; import { gqlRequest } from '@/shared/api'; @@ -348,7 +349,18 @@ export function buyerNameQueryOptions(accountId: string) { }); } -/** 처리했든 거절됐든(다른 곳에서 상태가 바뀐 경우 등) 상세·목록을 다시 불러 지금 상태와 선택지를 보인다 */ +/** 주문 목록·상세를 다시 읽게 한다. 주문 상태·환불을 바꾸는 다른 화면(처리 대기)이 부른다 */ +export async function invalidateOrders(queryClient: QueryClient) { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ordersKeys.lists() }), + queryClient.invalidateQueries({ queryKey: ordersKeys.details() }), + ]); +} + +/** + * 처리했든 거절됐든(다른 곳에서 상태가 바뀐 경우 등) 상세·목록을 다시 불러 지금 상태와 선택지를 보인다. + * 입금 대기 취소·환불 생성은 처리 대기 건수·목록도 바꾼다 + */ async function withRefresh(queryClient: QueryClient, orderId: string, run: () => Promise) { try { return await run(); @@ -356,6 +368,7 @@ async function withRefresh(queryClient: QueryClient, orderId: string, run: () await Promise.all([ queryClient.invalidateQueries({ queryKey: ordersKeys.detail(orderId) }), queryClient.invalidateQueries({ queryKey: ordersKeys.lists() }), + invalidateTasks(queryClient), ]); } } diff --git a/src/features/orders/index.ts b/src/features/orders/index.ts index 0bfdf88..78af62a 100644 --- a/src/features/orders/index.ts +++ b/src/features/orders/index.ts @@ -1,3 +1,5 @@ +export { invalidateOrders } from './api/queries'; +export { actorLabel, refundKindLabel, refundStatusMeta } from './meta'; export { OrderDetailPage } from './pages/order-detail-page'; export { OrdersListPage } from './pages/orders-list-page'; export { ordersSearchSchema } from './search'; diff --git a/src/features/settlements/api/queries.spec.ts b/src/features/settlements/api/queries.spec.ts new file mode 100644 index 0000000..1609a77 --- /dev/null +++ b/src/features/settlements/api/queries.spec.ts @@ -0,0 +1,71 @@ +import { QueryClient, QueryObserver } from '@tanstack/react-query'; + +import { settlementsQueryOptions, taskCountsQueryOptions } from '@/features/tasks/api/queries'; +import { gqlCounted, gqlError } from '@/test/msw/graphql'; +import { server } from '@/test/msw/server'; + +import { markSettlementPaid, upsertStoreSettlementAccount } from './queries'; + +const page = { items: [], totalCount: 0, hasMore: false, nextCursor: null }; + +/** 처리 대기 건수·정산 송금 목록을 화면처럼 구독한다. invalidate는 구독 중인 쿼리만 다시 요청한다 */ +async function watchTasks(answers: Record>) { + const { counts, handler } = gqlCounted({ + AdminTaskCounts: { adminTaskCounts: {} }, + AdminTasksSettlements: { adminSettlements: page }, + ...answers, + }); + server.use(handler); + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const stops = [ + new QueryObserver(qc, taskCountsQueryOptions()), + new QueryObserver(qc, settlementsQueryOptions({})), + ].map((o) => o.subscribe(() => undefined)); + await vi.waitFor(() => + expect([counts.AdminTaskCounts, counts.AdminTasksSettlements]).toEqual([1, 1]), + ); + return { qc, counts, stop: () => stops.forEach((s) => s()) }; +} + +describe('정산 처리 뒤 처리 대기', () => { + it('송금 완료 뒤 건수·정산 송금 목록을 다시 요청한다', async () => { + const { qc, counts, stop } = await watchTasks({ + AdminMarkSettlementPaid: { adminMarkSettlementPaid: { id: '1' } }, + }); + await markSettlementPaid(qc, '1', null); + expect(counts).toMatchObject({ AdminTaskCounts: 2, AdminTasksSettlements: 2 }); + stop(); + }); + + it('송금 완료가 거절돼도(409) 다시 요청한다', async () => { + const { qc, counts, stop } = await watchTasks({}); + server.use( + gqlError('AdminMarkSettlementPaid', { + message: '이미 송금 완료로 처리된 정산이에요.', + code: 'SETTLEMENT_ALREADY_PAID', + classification: 'CONFLICT', + statusCode: 409, + }), + ); + await expect(markSettlementPaid(qc, '1', null)).rejects.toThrow( + '이미 송금 완료로 처리된 정산이에요.', + ); + expect(counts).toMatchObject({ AdminTaskCounts: 2, AdminTasksSettlements: 2 }); + stop(); + }); + + it('매장 정산 계좌를 등록하면 정산 송금 목록(계좌 등록 여부)을 다시 요청한다', async () => { + const { qc, counts, stop } = await watchTasks({ + AdminUpsertStoreSettlementAccount: { adminUpsertStoreSettlementAccount: { storeId: '5' } }, + }); + await upsertStoreSettlementAccount(qc, { + storeId: '5', + bankCode: '004', + accountNumber: '12345678', + accountHolder: '루미', + reason: '등록', + }); + expect(counts.AdminTasksSettlements).toBe(2); + stop(); + }); +}); diff --git a/src/features/settlements/api/queries.ts b/src/features/settlements/api/queries.ts index 24b2059..0885980 100644 --- a/src/features/settlements/api/queries.ts +++ b/src/features/settlements/api/queries.ts @@ -1,5 +1,6 @@ import { type QueryClient, queryOptions } from '@tanstack/react-query'; +import { invalidateTasks } from '@/features/tasks'; import { graphql } from '@/graphql/generated'; import { type AdminSettlementListInput, @@ -264,7 +265,7 @@ export function storePickerQuery(keyword: string) { }); } -/** 다른 관리자가 먼저 처리했을 때(409)도 불러 처리자·시각을 다시 받는다 */ +/** 정산 목록·상세를 다시 읽게 한다. 처리 대기 화면도 처리 뒤 부른다 */ export async function invalidateSettlements(queryClient: QueryClient) { await Promise.all([ queryClient.invalidateQueries({ queryKey: settlementsKeys.lists() }), @@ -272,15 +273,18 @@ export async function invalidateSettlements(queryClient: QueryClient) { ]); } +/** 처리했든 409로 거절됐든 다시 읽어 처리자·시각을 보인다. 처리 대기 건수·목록도 함께 줄어든다 */ export async function markSettlementPaid( queryClient: QueryClient, settlementId: string, note: string | null, ) { - const r = (await gqlRequest(AdminMarkSettlementPaidDocument, { input: { settlementId, note } })) - .adminMarkSettlementPaid; - await invalidateSettlements(queryClient); - return r; + try { + return (await gqlRequest(AdminMarkSettlementPaidDocument, { input: { settlementId, note } })) + .adminMarkSettlementPaid; + } finally { + await Promise.all([invalidateSettlements(queryClient), invalidateTasks(queryClient)]); + } } export async function upsertStoreSettlementAccount( @@ -289,12 +293,13 @@ export async function upsertStoreSettlementAccount( ) { const r = (await gqlRequest(AdminUpsertStoreSettlementAccountDocument, { input })) .adminUpsertStoreSettlementAccount; - // 정산 목록·상세의 계좌 등록 여부와 현재 계좌도 바뀐다 + // 정산 목록·상세(처리 대기 정산 송금 포함)의 계좌 등록 여부와 현재 계좌도 바뀐다 await Promise.all([ queryClient.invalidateQueries({ queryKey: settlementsKeys.storeAccount(String(input.storeId)), }), invalidateSettlements(queryClient), + invalidateTasks(queryClient), ]); return r; } diff --git a/src/features/settlements/components/mark-paid-dialog.tsx b/src/features/settlements/components/mark-paid-dialog.tsx index a84703e..9e34d8c 100644 --- a/src/features/settlements/components/mark-paid-dialog.tsx +++ b/src/features/settlements/components/mark-paid-dialog.tsx @@ -6,7 +6,7 @@ import { formatKrw } from '@/shared/lib/format'; import { Button } from '@/shared/ui/button'; import { ReasonDialog } from '@/shared/ui/reason-dialog'; -import { invalidateSettlements, markSettlementPaid } from '../api/queries'; +import { markSettlementPaid } from '../api/queries'; interface Props { settlementId: string; @@ -30,11 +30,8 @@ export function MarkPaidDialog({ settlementId, payoutAmount, account }: Props) { toast.success('송금 완료로 처리했습니다.'); } catch (e) { toast.error(messageFor(e)); - // 다른 관리자가 먼저 처리했으면 닫고 처리자·시각을 다시 받아 보인다 - if (e instanceof ApiError && e.classification === 'CONFLICT') { - await invalidateSettlements(queryClient); - return; - } + // 다른 관리자가 먼저 처리했으면 닫는다. 처리자·시각은 다시 읽은 상세가 보인다 + if (e instanceof ApiError && e.classification === 'CONFLICT') return; throw e; } }} diff --git a/src/features/settlements/index.ts b/src/features/settlements/index.ts index 0abcf02..aef2e61 100644 --- a/src/features/settlements/index.ts +++ b/src/features/settlements/index.ts @@ -1,3 +1,6 @@ +export { invalidateSettlements } from './api/queries'; +export { AccountNumber } from './components/account-number'; +export { MarkPaidDialog } from './components/mark-paid-dialog'; export { StoreSettlementAccountCard } from './components/store-settlement-account-card'; export { MonthlyCommissionsPage } from './pages/monthly-commissions-page'; export { PaymentSettingsPage } from './pages/payment-settings-page'; diff --git a/src/features/tasks/api/queries.spec.ts b/src/features/tasks/api/queries.spec.ts new file mode 100644 index 0000000..235271d --- /dev/null +++ b/src/features/tasks/api/queries.spec.ts @@ -0,0 +1,108 @@ +import { QueryClient, QueryObserver } from '@tanstack/react-query'; + +import { dashboardSummaryQueryOptions } from '@/features/dashboard/api/queries'; +import { ordersListQueryOptions } from '@/features/orders/api/queries'; +import { settlementsListQueryOptions } from '@/features/settlements/api/queries'; +import { gqlCounted, gqlError } from '@/test/msw/graphql'; +import { server } from '@/test/msw/server'; + +import { taskCountsQueryOptions, taskMutations } from './queries'; + +const page = { items: [], totalCount: 0, hasMore: false, nextCursor: null }; +const watched = { + AdminOrders: { adminOrders: page }, + AdminSettlements: { adminSettlements: page }, + AdminDashboardSummary: { adminDashboardSummary: {} }, + AdminTaskCounts: { adminTaskCounts: {} }, +}; + +/** 주문·정산·대시보드·처리 대기 건수를 화면처럼 구독한다. invalidate는 구독 중인 쿼리만 다시 요청한다 */ +async function watchOthers(answers: Record>) { + const { counts, handler } = gqlCounted({ ...watched, ...answers }); + server.use(handler); + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const stops = [ + new QueryObserver(qc, ordersListQueryOptions({})), + new QueryObserver(qc, settlementsListQueryOptions({})), + new QueryObserver( + qc, + dashboardSummaryQueryOptions('2026-11-18T15:00:00.000Z', '2026-11-19T14:59:59.999Z'), + ), + new QueryObserver(qc, taskCountsQueryOptions()), + ].map((o) => o.subscribe(() => undefined)); + await vi.waitFor(() => + expect(Object.keys(watched).map((op) => counts[op])).toEqual([1, 1, 1, 1]), + ); + return { qc, counts, stop: () => stops.forEach((s) => s()) }; +} + +describe('처리 뒤 교차 무효화', () => { + it.each([ + [ + '입금 확인', + { AdminTasksConfirmPayment: { adminConfirmPayment: { id: '1' } } }, + (qc: QueryClient) => taskMutations.confirmPayment(qc, { orderId: '1', depositedAmount: 0 }), + ], + [ + '미입금 취소', + { AdminTasksCancelUnpaid: { adminCancelOrder: { id: '1' } } }, + (qc: QueryClient) => taskMutations.cancelUnpaid(qc, '1', ''), + ], + [ + '입금 반환', + { AdminTasksCreateDepositReturn: { adminCreateDepositReturn: { id: '1', refundId: '2' } } }, + (qc: QueryClient) => + taskMutations.createDepositReturn(qc, { orderId: '1', amount: 1, depositorName: '김' }), + ], + [ + '주인 모를 입금 기록', + { AdminTasksRecordUnidentifiedDeposit: { adminRecordUnidentifiedDeposit: { id: '1' } } }, + (qc: QueryClient) => + taskMutations.recordUnidentifiedDeposit(qc, { + amount: 1, + depositorName: '김', + note: '메모', + }), + ], + [ + '종결 기록 연결', + { AdminTasksLinkUnidentifiedDeposit: { adminLinkUnidentifiedDeposit: { id: '1' } } }, + (qc: QueryClient) => taskMutations.linkUnidentifiedDeposit(qc, '3', '1'), + ], + [ + '환불 송금 완료', + { AdminTasksCompleteRefund: { adminCompleteRefund: { id: '1' } } }, + (qc: QueryClient) => taskMutations.completeRefund(qc, '1', ''), + ], + ] as const)( + '%s 뒤 주문·정산·대시보드·처리 대기 건수를 다시 요청한다', + async (_, answers, mutate) => { + const { qc, counts, stop } = await watchOthers(answers); + await mutate(qc); + expect(counts).toMatchObject({ + AdminOrders: 2, + AdminSettlements: 2, + AdminDashboardSummary: 2, + AdminTaskCounts: 2, + }); + stop(); + }, + ); + + it('거절돼도(409) 다른 화면을 다시 요청한다', async () => { + const { qc, counts, stop } = await watchOthers({}); + server.use( + gqlError('AdminTasksConfirmPayment', { + message: '이미 처리됐습니다.', + code: 'PAYMENT_NOT_PENDING', + classification: 'CONFLICT', + statusCode: 409, + }), + ); + await expect( + taskMutations.confirmPayment(qc, { orderId: '1', depositedAmount: 0 }), + ).rejects.toThrow('이미 처리됐습니다.'); + expect(counts).toMatchObject({ AdminOrders: 2, AdminSettlements: 2, AdminDashboardSummary: 2 }); + stop(); + }); +}); diff --git a/src/features/tasks/api/queries.ts b/src/features/tasks/api/queries.ts new file mode 100644 index 0000000..4676ed6 --- /dev/null +++ b/src/features/tasks/api/queries.ts @@ -0,0 +1,492 @@ +import { type QueryClient, queryOptions } from '@tanstack/react-query'; + +import { invalidateDashboard } from '@/features/dashboard'; +import { invalidateOrders } from '@/features/orders'; +import { invalidateSettlements } from '@/features/settlements'; +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'; + +/** 건수·목록 폴링 주기. 디스코드 알림은 다시 올 수 있어 건수와 목록을 진실로 둔다 */ +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 pollOptions = { + 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, + ...pollOptions, + }); +} + +export function taskOrderQueryOptions(orderId: string) { + return queryOptions({ + queryKey: tasksKeys.order(orderId), + queryFn: async () => (await gqlRequest(AdminTasksOrderDocument, { orderId })).adminOrder, + retry: false, + ...pollOptions, + }); +} + +export function depositRecordsQueryOptions(input: AdminDepositRecordListInput) { + return queryOptions({ + queryKey: tasksKeys.depositRecords(input), + queryFn: async () => + (await gqlRequest(AdminTasksDepositRecordsDocument, { input })).adminDepositRecords, + ...pollOptions, + }); +} + +export function refundsQueryOptions(input: AdminRefundListInput) { + return queryOptions({ + queryKey: tasksKeys.refunds(input), + queryFn: async () => (await gqlRequest(AdminTasksRefundsDocument, { input })).adminRefunds, + ...pollOptions, + }); +} + +export function refundQueryOptions(refundId: string) { + return queryOptions({ + queryKey: tasksKeys.refund(refundId), + queryFn: async () => (await gqlRequest(AdminTasksRefundDocument, { refundId })).adminRefund, + retry: false, + ...pollOptions, + }); +} + +export function settlementsQueryOptions(input: AdminSettlementListInput) { + return queryOptions({ + queryKey: tasksKeys.settlements(input), + queryFn: async () => + (await gqlRequest(AdminTasksSettlementsDocument, { input })).adminSettlements, + ...pollOptions, + }); +} + +export function settlementQueryOptions(settlementId: string) { + return queryOptions({ + queryKey: tasksKeys.settlement(settlementId), + queryFn: async () => + (await gqlRequest(AdminTasksSettlementDocument, { settlementId })).adminSettlement, + retry: false, + ...pollOptions, + }); +} + +/** 종결 기록을 연결할 주문 검색(주문번호·주문자 이름·연락처) */ +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)}`, + })), + }); +} + +/** 건수·목록·단건을 다시 읽게 한다. 처리 대기 건을 바꾸는 다른 화면(강제 취소·정산 송금 완료 등)도 부른다 */ +export const invalidateTasks = (qc: QueryClient) => + qc.invalidateQueries({ queryKey: tasksKeys.all }); + +/** + * 처리 뒤·충돌 뒤 다시 읽는다. 처리자·시각은 다시 읽은 단건이 보인다. + * 처리는 주문 상태·환불을 바꾸므로 주문·정산·대시보드도 다시 읽게 한다. 정산 송금 완료는 정산 feature가 맡는다 + */ +async function run(qc: QueryClient, request: Promise): Promise { + try { + return await request; + } finally { + await Promise.all([ + invalidateTasks(qc), + invalidateOrders(qc), + invalidateSettlements(qc), + invalidateDashboard(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 } }), + ), +}; 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')} +
+
+
+ + +
+
+ +