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 (
+
+ );
+}
diff --git a/src/features/tasks/components/deposit-order-sheet.tsx b/src/features/tasks/components/deposit-order-sheet.tsx
new file mode 100644
index 0000000..966d5c4
--- /dev/null
+++ b/src/features/tasks/components/deposit-order-sheet.tsx
@@ -0,0 +1,335 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { Link } from '@tanstack/react-router';
+import { useState } from 'react';
+import { useForm } from 'react-hook-form';
+import { toast } from 'sonner';
+
+import { actorLabel, orderStatusMeta } from '@/features/orders';
+import { ApiError, messageFor } from '@/shared/api';
+import { formatKrw } from '@/shared/lib/format';
+import { formatKst } from '@/shared/lib/kst';
+import { Button } from '@/shared/ui/button';
+import { Input } from '@/shared/ui/input';
+import { Label } from '@/shared/ui/label';
+import { ReasonDialog } from '@/shared/ui/reason-dialog';
+import { StatusPill } from '@/shared/ui/status-pill';
+import { Textarea } from '@/shared/ui/textarea';
+
+import { type TaskOrder, taskMutations, taskOrderQueryOptions } from '../api/queries';
+import {
+ type ConfirmPaymentValues,
+ type DepositValues,
+ confirmPaymentSchema,
+ toConfirmPaymentInput,
+ toDepositReturnInput,
+} from '../forms';
+import {
+ isAmountInvalid,
+ isAmountMismatch,
+ isConflict,
+ isPast,
+ isPickupPassed,
+ loadDescription,
+ pickupTone,
+} from '../meta';
+import { parseWon } from '../search';
+import { DepositDialog } from './deposit-dialog';
+import { DoneSection, Field, Fields, TaskSheet, type NextTask } from './task-sheet';
+
+const PICKUP_PASSED =
+ '픽업 시각이 지난 주문은 입금 확인할 수 없어요. 미입금 취소 뒤 반환 대상으로 연결해 주세요.';
+
+interface Props {
+ /** 열린 주문 ID. undefined면 닫힌다 */
+ orderId: string | undefined;
+ /** 지금 목록 기준 다음 건 */
+ next: (orderId: string) => NextTask;
+ onOpen: (orderId: string | undefined) => void;
+}
+
+/** 입금 확인 대상 주문 1건. 주소(orderId)로 열려 경보 링크에서 바로 처리한다 */
+export function DepositOrderSheet({ orderId, next, onOpen }: Props) {
+ const q = useQuery({
+ ...taskOrderQueryOptions(orderId ?? ''),
+ enabled: orderId !== undefined,
+ });
+ const order = q.data;
+ return (
+ onOpen(undefined)}
+ title={
+ order ? (
+ <>
+ 주문 {order.orderNumber}
+
+ {orderStatusMeta(order.status).label}
+
+ >
+ ) : (
+ '주문'
+ )
+ }
+ description={loadDescription(
+ q.isPending,
+ q.isError ? q.error : null,
+ order ? `${formatKst(order.createdAt, true)} 주문` : '',
+ )}
+ >
+ {order && }
+
+ );
+}
+
+function doneInfo(order: TaskOrder): string {
+ const p = order.payment;
+ if (p?.status === 'CONFIRMED' && p.confirmedAt)
+ return `입금 확인 · ${p.confirmedByLabel ?? '관리자'} · ${formatKst(p.confirmedAt, true)}`;
+ const c = order.cancellation;
+ if (c)
+ return `취소 · ${actorLabel(c.actorType)} · ${c.reasonLabel} · ${formatKst(c.canceledAt, true)}`;
+ return `입금 확인 대기 주문이 아닙니다(${orderStatusMeta(order.status).label}).`;
+}
+
+function OrderBody({
+ order,
+ next,
+ onNext,
+}: {
+ order: TaskOrder;
+ next: NextTask;
+ onNext: (id: string) => void;
+}) {
+ const qc = useQueryClient();
+ // 열어 둔 사이 시각이 지나도 다시 그릴 때 강조가 따라오도록 매번 잰다
+ const now = new Date();
+ // 서버가 픽업 지남으로 거절했으면 화면 시각과 관계없이 확인을 막는다
+ const [pickupPassed, setPickupPassed] = useState(false);
+ const [returnOpen, setReturnOpen] = useState(false);
+ const [returnDefaults, setReturnDefaults] = useState<{ amount?: string; notice?: string }>({});
+ // 이번에 연결한 반환들의 환불. 시트가 모달이라 토스트 안 버튼은 누를 수 없어 시트 안에 둔다
+ const [returnedRefundIds, setReturnedRefundIds] = useState([]);
+ const p = order.payment;
+ const pending = order.status === 'PENDING_PAYMENT' && p?.status === 'PENDING';
+ const tone = pickupPassed ? 'negative' : pickupTone(order.pickupAt, now);
+
+ const openReturn = (amount?: string, notice?: string) => {
+ setReturnDefaults({ amount, notice });
+ setReturnOpen(true);
+ };
+
+ const submitReturn = async (v: DepositValues) => {
+ const r = await taskMutations.createDepositReturn(qc, toDepositReturnInput(order.id, v));
+ toast.success('반환 대상으로 연결했습니다. 구매자에게 환불 계좌 입력을 요청했어요.');
+ if (r.refundId) setReturnedRefundIds((ids) => [...ids, r.refundId!]);
+ };
+
+ const cancelUnpaid = async (note: string) => {
+ try {
+ await taskMutations.cancelUnpaid(qc, order.id, note);
+ toast.success(`${order.orderNumber} 주문을 미입금으로 취소했습니다.`);
+ } catch (e) {
+ toast.error(messageFor(e));
+ // 그사이 처리됐으면 다시 읽은 상태를 보이도록 닫는다
+ if (!isConflict(e)) throw e;
+ }
+ };
+
+ return (
+ <>
+
+ {order.items[0]?.productName ?? '-'}
+ {formatKrw(p?.amount ?? order.totalPrice)}
+ {p?.depositorName ?? '-'}
+
+ {order.buyerName} · {order.buyerPhone}
+
+ {p && (
+
+ {formatKst(p.expiresAt, true)}
+ {/* '입금했어요'를 누른 주문은 기한이 멈춰 자동 취소되지 않는다 */}
+ {pending && !p.buyerClaimedAt && isPast(p.expiresAt, now) && (
+
+ 기한 지남
+
+ )}
+
+ )}
+ {p && (
+
+ {p.buyerClaimedAt ? formatKst(p.buyerClaimedAt, true) : '누르지 않음'}
+
+ )}
+
+ {formatKst(order.pickupAt, true)}
+ {pending && tone && (
+
+ {tone === 'negative' ? '픽업 지남' : '3시간 미만'}
+
+ )}
+
+
+
+ 주문 화면에서 보기
+
+
+
+
+ {pending ? (
+ tone === 'negative' ? (
+
+ {PICKUP_PASSED}
+
+ ) : (
+ openReturn(amount, message)}
+ onPickupPassed={() => setPickupPassed(true)}
+ />
+ )
+ ) : (
+
+ )}
+
+ {returnedRefundIds.length > 0 && (
+
+ 반환 연결로 생긴 환불:
+ {returnedRefundIds.map((refundId) => (
+
+ 환불 #{refundId} 보기
+
+ ))}
+
+ )}
+
+
+ {pending && (
+
+ 미입금 취소
+
+ }
+ title="미입금으로 취소할까요?"
+ description={`${order.orderNumber} 주문을 미입금 사유로 취소합니다. 구매자에게 미입금 취소 알림이 가고, 이미 들어온 입금은 반환 대상으로 연결해 돌려줍니다.`}
+ reasonLabel="메모"
+ reasonRequired={false}
+ confirmLabel="미입금 취소"
+ destructive
+ onConfirm={cancelUnpaid}
+ />
+ )}
+
+
+
+
+ >
+ );
+}
+
+function ConfirmForm({
+ order,
+ onMismatch,
+ onPickupPassed,
+}: {
+ order: TaskOrder;
+ onMismatch: (amount: string, message: string) => void;
+ onPickupPassed: () => void;
+}) {
+ const qc = useQueryClient();
+ const [error, setError] = useState(null);
+ const form = useForm({
+ resolver: zodResolver(confirmPaymentSchema),
+ defaultValues: { depositedAmount: '', note: '' },
+ });
+ const { errors, isSubmitting } = form.formState;
+
+ const submit = form.handleSubmit(async (v) => {
+ setError(null);
+ try {
+ await taskMutations.confirmPayment(qc, toConfirmPaymentInput(order.id, v));
+ toast.success(`${order.orderNumber} 입금을 확인했습니다. 판매자에게 새 주문으로 보입니다.`);
+ } catch (e) {
+ const message = messageFor(e);
+ if (isAmountMismatch(e)) {
+ setError(message);
+ onMismatch(String(parseWon(v.depositedAmount)), message);
+ } else if (isAmountInvalid(e)) {
+ form.setError('depositedAmount', { type: 'server', message });
+ } else if (isPickupPassed(e)) {
+ onPickupPassed();
+ } else if (e instanceof ApiError && e.classification === 'BAD_USER_INPUT') {
+ setError(message);
+ } else {
+ toast.error(message);
+ }
+ }
+ });
+
+ return (
+
+ );
+}
diff --git a/src/features/tasks/components/link-deposit-dialog.tsx b/src/features/tasks/components/link-deposit-dialog.tsx
new file mode 100644
index 0000000..3726e77
--- /dev/null
+++ b/src/features/tasks/components/link-deposit-dialog.tsx
@@ -0,0 +1,85 @@
+import { useQueryClient } from '@tanstack/react-query';
+import { useState } from 'react';
+import { toast } from 'sonner';
+
+import { messageFor } from '@/shared/api';
+import { formatKrw } from '@/shared/lib/format';
+import { Button } from '@/shared/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/shared/ui/dialog';
+import { EntityPicker } from '@/shared/ui/entity-picker';
+
+import { type DepositRecord, orderOptionsQueryOptions, taskMutations } from '../api/queries';
+import { isConflict } from '../meta';
+
+/** 종결 기록의 주인을 찾았을 때 그 주문의 반환 대상으로 바꾼다(같은 입금을 새로 기록하지 않는다) */
+export function LinkDepositDialog({
+ record,
+ onClose,
+}: {
+ record: DepositRecord | null;
+ onClose: () => void;
+}) {
+ return (
+
+ );
+}
+
+function LinkForm({ record, onClose }: { record: DepositRecord; onClose: () => void }) {
+ const qc = useQueryClient();
+ const [orderId, setOrderId] = useState();
+ const [busy, setBusy] = useState(false);
+
+ const submit = async () => {
+ if (orderId === undefined) return;
+ setBusy(true);
+ try {
+ await taskMutations.linkUnidentifiedDeposit(qc, record.id, orderId);
+ toast.success(
+ '종결 기록을 반환 대상으로 바꿨습니다. 구매자에게 환불 계좌 입력을 요청했어요.',
+ );
+ onClose();
+ } catch (e) {
+ toast.error(messageFor(e));
+ if (isConflict(e)) onClose();
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <>
+
+ 주문에 연결
+
+ {record.depositorName} {formatKrw(record.amount)} 종결 기록을 고른 주문의 반환 대상으로
+ 바꿉니다. 입금액 전액의 환불이 생기고 구매자에게 환불 계좌 입력을 요청합니다.
+
+
+ setOrderId(id)}
+ searchQuery={orderOptionsQueryOptions}
+ idEntry={false}
+ />
+
+
+
+
+ >
+ );
+}
diff --git a/src/features/tasks/components/refund-sheet.tsx b/src/features/tasks/components/refund-sheet.tsx
new file mode 100644
index 0000000..e987ae6
--- /dev/null
+++ b/src/features/tasks/components/refund-sheet.tsx
@@ -0,0 +1,156 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { Link } from '@tanstack/react-router';
+import { toast } from 'sonner';
+
+import { refundKindLabel, refundStatusMeta } from '@/features/orders';
+import { messageFor } from '@/shared/api';
+import { formatKrw } from '@/shared/lib/format';
+import { formatKst } from '@/shared/lib/kst';
+import { Button } from '@/shared/ui/button';
+import { ReasonDialog } from '@/shared/ui/reason-dialog';
+import { StatusPill } from '@/shared/ui/status-pill';
+
+import { type RefundDetail, refundQueryOptions, taskMutations } from '../api/queries';
+import { isConflict, loadDescription } from '../meta';
+import { AccountToCopy, DoneSection, Field, Fields, TaskSheet, type NextTask } from './task-sheet';
+
+interface Props {
+ refundId: string | undefined;
+ next: (refundId: string) => NextTask;
+ onOpen: (refundId: string | undefined) => void;
+}
+
+/** 환불 1건. 송금할 계좌 전체 번호는 여기서만 보인다 */
+export function RefundSheet({ refundId, next, onOpen }: Props) {
+ const q = useQuery({ ...refundQueryOptions(refundId ?? ''), enabled: refundId !== undefined });
+ const r = q.data?.refund;
+ const status = r ? refundStatusMeta(r.status) : null;
+ return (
+ onOpen(undefined)}
+ title={
+ r && status ? (
+ <>
+ {refundKindLabel(r.kind)} {formatKrw(r.amount)}
+ {status.label}
+ >
+ ) : (
+ '환불'
+ )
+ }
+ description={loadDescription(
+ q.isPending,
+ q.isError ? q.error : null,
+ r ? `주문 ${r.orderNumber} · ${formatKst(r.requestedAt, true)} 요청` : '',
+ )}
+ >
+ {q.data && }
+
+ );
+}
+
+function RefundBody({
+ detail,
+ next,
+ onNext,
+}: {
+ detail: RefundDetail;
+ next: NextTask;
+ onNext: (id: string) => void;
+}) {
+ const qc = useQueryClient();
+ const { refund: r, accountNumber, depositRecord } = detail;
+ const ready = r.status === 'AWAITING_TRANSFER' && r.bank && r.accountHolder && accountNumber;
+
+ const complete = async (note: string) => {
+ try {
+ await taskMutations.completeRefund(qc, r.id, note);
+ toast.success(`${formatKrw(r.amount)} 환불을 송금 완료로 처리했습니다.`);
+ } catch (e) {
+ toast.error(messageFor(e));
+ if (!isConflict(e)) throw e;
+ }
+ };
+
+ return (
+ <>
+
+
+
+ {r.orderNumber}
+
+ {r.productName && · {r.productName}}
+
+ {r.storeName && {r.storeName}}
+
+ {r.buyerName} · {r.buyerPhone}
+
+
+ {r.bank && r.accountHolder && accountNumber ? (
+
+ ) : (
+ '구매자가 아직 입력하지 않았습니다.'
+ )}
+
+ {r.accountSubmittedAt && (
+ {formatKst(r.accountSubmittedAt, true)}
+ )}
+ {depositRecord && (
+
+ {depositRecord.depositorName}
+ {depositRecord.depositedAt && ` · ${formatKst(depositRecord.depositedAt, true)}`}
+ {depositRecord.note && (
+
+ {depositRecord.note}
+
+ )}
+
+ )}
+
+
+ {r.status === 'COMPLETED' ? (
+
+ ) : (
+
+ {!ready && (
+
+ 계좌 입력 전이라 송금할 수 없어요. 구매자에게 연락해 계좌 입력을 요청하세요.
+
+ )}
+ 송금 완료}
+ title="송금 완료로 처리할까요?"
+ description={
+ ready
+ ? `${r.bank!.name} ${accountNumber}(${r.accountHolder})로 ${formatKrw(r.amount)}을 송금했나요?`
+ : undefined
+ }
+ reasonLabel="메모"
+ reasonRequired={false}
+ confirmLabel="송금 완료"
+ onConfirm={complete}
+ />
+
+ )}
+ >
+ );
+}
diff --git a/src/features/tasks/components/settlement-sheet.tsx b/src/features/tasks/components/settlement-sheet.tsx
new file mode 100644
index 0000000..94a9203
--- /dev/null
+++ b/src/features/tasks/components/settlement-sheet.tsx
@@ -0,0 +1,128 @@
+import { useQuery } from '@tanstack/react-query';
+import { Link } from '@tanstack/react-router';
+
+import { MarkPaidDialog } from '@/features/settlements';
+import { formatCount, formatKrw } from '@/shared/lib/format';
+import { formatKst } from '@/shared/lib/kst';
+import { Button } from '@/shared/ui/button';
+
+import { type SettlementDetail, settlementQueryOptions } from '../api/queries';
+import { loadDescription } from '../meta';
+import { AccountToCopy, DoneSection, Field, Fields, TaskSheet, type NextTask } from './task-sheet';
+
+interface Props {
+ settlementId: string | undefined;
+ next: (settlementId: string) => NextTask;
+ onOpen: (settlementId: string | undefined) => void;
+}
+
+export function StoreAccountLink({ storeId }: { storeId: string }) {
+ return (
+
+ 매장에서 정산 계좌 등록
+
+ );
+}
+
+/** 주간 정산 1건의 송금. 지금 매장 정산 계좌 전체 번호는 여기서만 보인다 */
+export function SettlementSheet({ settlementId, next, onOpen }: Props) {
+ const q = useQuery({
+ ...settlementQueryOptions(settlementId ?? ''),
+ enabled: settlementId !== undefined,
+ });
+ const s = q.data;
+ return (
+ onOpen(undefined)}
+ title={s ? `${s.storeName} 정산 ${formatKrw(s.payoutAmount)}` : '정산'}
+ description={loadDescription(
+ q.isPending,
+ q.isError ? q.error : null,
+ s ? `${s.periodStart} ~ ${s.periodEnd}` : '',
+ )}
+ >
+ {s && }
+
+ );
+}
+
+function SettlementBody({
+ s,
+ next,
+ onNext,
+}: {
+ s: SettlementDetail;
+ next: NextTask;
+ onNext: (id: string) => void;
+}) {
+ const account = s.currentAccount;
+
+ return (
+ <>
+
+ {formatCount(s.orderCount)}건
+ {formatKrw(s.settlementBaseAmount)}
+ {formatKrw(s.commissionAmount)}
+
+ {formatKrw(s.payoutAmount)}
+
+
+ {account ? (
+
+ ) : (
+
+ 등록된 정산 계좌가 없습니다.
+
+
+ )}
+
+
+
+ {s.status === 'PAID' ? (
+
+ ) : (
+
+ {!account && (
+
+ 정산 계좌가 없어 송금 완료로 처리할 수 없어요.
+
+ )}
+ {account ? (
+
+ ) : (
+
+ )}
+
+ )}
+ >
+ );
+}
diff --git a/src/features/tasks/components/task-counts.tsx b/src/features/tasks/components/task-counts.tsx
new file mode 100644
index 0000000..7e470f0
--- /dev/null
+++ b/src/features/tasks/components/task-counts.tsx
@@ -0,0 +1,101 @@
+import { useQuery } from '@tanstack/react-query';
+import { Link } from '@tanstack/react-router';
+import { type ReactNode } from 'react';
+
+import { formatCount } from '@/shared/lib/format';
+import { Badge } from '@/shared/ui/badge';
+import { Card } from '@/shared/ui/card';
+import { PageHeader } from '@/shared/ui/page-header';
+
+import { taskCountsQueryOptions } from '../api/queries';
+import { taskBadges } from '../meta';
+
+function CountBadge({ count }: { count: number | undefined }) {
+ if (!count) return null;
+ // 앞 공백·숨긴 '건'은 링크 이름을 '처리 대기 9건'으로 읽히게 한다(flex라 화면에는 영향 없음)
+ return (
+ <>
+ {' '}
+
+ {formatCount(count)}
+ 건
+
+ >
+ );
+}
+
+/** 사이드바 '처리 대기' 옆 배지. 지금 처리할 수 있는 건수 합계 */
+export function TaskCountBadge() {
+ const counts = useQuery(taskCountsQueryOptions());
+ return ;
+}
+
+const TABS = [
+ { to: '/tasks/deposits', label: '입금', key: 'deposits' },
+ { to: '/tasks/refunds', label: '환불', key: 'refunds' },
+ { to: '/tasks/settlements', label: '정산 송금', key: 'settlements' },
+] as const;
+
+/** 처리 대기 화면 머리글과 탭(입금·환불·정산 송금) */
+export function TasksHeader({ actions }: { actions?: ReactNode }) {
+ const counts = useQuery(taskCountsQueryOptions());
+ const badges = counts.data && taskBadges(counts.data);
+ return (
+ <>
+
+
+ >
+ );
+}
+
+function TileLine({ to, children }: { to: (typeof TABS)[number]['to']; children: ReactNode }) {
+ return (
+
+ {children}
+
+ );
+}
+
+/** 대시보드 '처리 대기' 타일 */
+export function TasksTile() {
+ const counts = useQuery(taskCountsQueryOptions());
+ const c = counts.data;
+ return (
+
+ 처리 대기
+
+ {c ? `${formatCount(taskBadges(c).total)}건` : '-'}
+
+ {c && (
+
+
+ 입금 확인 {formatCount(c.pendingPayments)}건(입금했어요 {formatCount(c.claimedPayments)}
+ 건)
+
+
+ 환불 송금 {formatCount(c.refundsAwaitingTransfer)}건 · 계좌 입력 대기{' '}
+ {formatCount(c.refundsAwaitingAccount)}건
+
+
+ 정산 송금 {formatCount(c.pendingSettlements)}건
+
+
+ )}
+
+ );
+}
diff --git a/src/features/tasks/components/task-sheet.tsx b/src/features/tasks/components/task-sheet.tsx
new file mode 100644
index 0000000..a1eb8cc
--- /dev/null
+++ b/src/features/tasks/components/task-sheet.tsx
@@ -0,0 +1,94 @@
+import { type ReactNode } from 'react';
+
+import { AccountNumber } from '@/features/settlements';
+import { formatCount } from '@/shared/lib/format';
+import { Button } from '@/shared/ui/button';
+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@/shared/ui/sheet';
+
+interface ShellProps {
+ open: boolean;
+ onClose: () => void;
+ title: ReactNode;
+ /** 읽기 상태 문구. 데이터가 있으면 부르는 쪽이 요약을 준다 */
+ description: string;
+ children?: ReactNode;
+}
+
+export function TaskSheet({ open, onClose, title, description, children }: ShellProps) {
+ return (
+ !o && onClose()}>
+
+
+ {title}
+ {description}
+
+ {children && {children}
}
+
+
+ );
+}
+
+export function Fields({ children }: { children: ReactNode }) {
+ return {children}
;
+}
+
+export function Field({ label, children }: { label: string; children: ReactNode }) {
+ return (
+ <>
+ {label}
+ {children}
+ >
+ );
+}
+
+/** 송금할 계좌 전체 번호와 복사(정산 화면과 같은 AccountNumber) */
+export function AccountToCopy({
+ bankName,
+ accountNumber,
+ holder,
+}: {
+ bankName: string;
+ accountNumber: string;
+ holder: string;
+}) {
+ return (
+
+ {bankName} ({holder})
+
+ );
+}
+
+export type NextTask = { nextId: string | null; remaining: number } | null;
+
+/** 처리가 끝난 건: 누가 언제 처리했는지와 [다음 건]. next가 null이면 처리할 목록 밖에서 연 것이다 */
+export function DoneSection({
+ info,
+ next,
+ onNext,
+}: {
+ info: ReactNode;
+ next: NextTask;
+ onNext: (id: string) => void;
+}) {
+ return (
+
+
+ {next && (
+
+ {next.nextId ? (
+
+ ) : (
+
+ {next.remaining > 0 ? '다음 건은 목록에서 골라 주세요.' : '남은 건이 없습니다.'}
+
+ )}
+
+ )}
+
+ );
+}
diff --git a/src/features/tasks/forms.spec.ts b/src/features/tasks/forms.spec.ts
new file mode 100644
index 0000000..211b49c
--- /dev/null
+++ b/src/features/tasks/forms.spec.ts
@@ -0,0 +1,112 @@
+import { ApiError } from '@/shared/api';
+
+import {
+ FORM_MESSAGES,
+ confirmPaymentSchema,
+ depositFormError,
+ depositReturnSchema,
+ emptyDeposit,
+ toConfirmPaymentInput,
+ toDepositReturnInput,
+ toUnidentifiedDepositInput,
+ unidentifiedDepositSchema,
+} from './forms';
+
+const issues = (r: {
+ success: boolean;
+ error?: { issues: { path: PropertyKey[]; message: string }[] };
+}) => (r.success ? [] : r.error!.issues.map((i) => [i.path.join('.'), i.message]));
+
+describe('입금 확인 폼', () => {
+ it.each([
+ ['0', true],
+ ['12,000', true],
+ ['', false],
+ ['-1', false],
+ ['1.5', false],
+ ])('입금액 "%s" → 유효 %s(0원 주문은 0으로 확인)', (depositedAmount, ok) => {
+ expect(confirmPaymentSchema.safeParse({ depositedAmount, note: '' }).success).toBe(ok);
+ });
+
+ it('메모는 500자(코드 포인트)까지다', () => {
+ expect(
+ confirmPaymentSchema.safeParse({ depositedAmount: '1', note: '😀'.repeat(500) }).success,
+ ).toBe(true);
+ expect(
+ issues(confirmPaymentSchema.safeParse({ depositedAmount: '1', note: '가'.repeat(501) })),
+ ).toEqual([['note', FORM_MESSAGES.noteTooLong]]);
+ });
+
+ it('입력을 정수·정리된 메모로 바꾼다', () => {
+ expect(toConfirmPaymentInput('0', { depositedAmount: '12,000', note: ' 확인 ' })).toEqual({
+ orderId: '0',
+ depositedAmount: 12000,
+ note: '확인',
+ });
+ expect(toConfirmPaymentInput('1', { depositedAmount: '0', note: ' ' }).note).toBeNull();
+ });
+});
+
+describe('입금 기록 폼', () => {
+ const valid = emptyDeposit({ amount: '9000', depositorName: '김구매' });
+
+ it('반환 연결은 메모 없이 저장할 수 있다', () => {
+ expect(depositReturnSchema.safeParse(valid).success).toBe(true);
+ });
+
+ it('종결 기록은 메모가 필수다(공백만은 비운 것)', () => {
+ expect(issues(unidentifiedDepositSchema.safeParse({ ...valid, note: ' ' }))).toEqual([
+ ['note', FORM_MESSAGES.noteRequired],
+ ]);
+ expect(unidentifiedDepositSchema.safeParse({ ...valid, note: '확인 불가' }).success).toBe(true);
+ });
+
+ it.each([
+ [{ amount: '0' }, 'amount', FORM_MESSAGES.amount],
+ [{ amount: '' }, 'amount', FORM_MESSAGES.amount],
+ [{ depositorName: ' ' }, 'depositorName', FORM_MESSAGES.depositorRequired],
+ [{ depositorName: '가'.repeat(51) }, 'depositorName', FORM_MESSAGES.depositorTooLong],
+ [{ note: '가'.repeat(501) }, 'note', FORM_MESSAGES.noteTooLong],
+ ])('%o → %s 오류', (over, path, message) => {
+ expect(issues(depositReturnSchema.safeParse({ ...valid, ...over }))).toEqual([[path, message]]);
+ });
+
+ it('입금자명 50자는 통과한다', () => {
+ expect(
+ depositReturnSchema.safeParse({ ...valid, depositorName: '가'.repeat(50) }).success,
+ ).toBe(true);
+ });
+
+ it('입금 일시는 KST로 읽어 UTC로 보내고 비우면 null', () => {
+ expect(
+ toDepositReturnInput('7', { ...valid, depositedAt: '2026-11-19T10:30', note: ' 늦은 입금 ' }),
+ ).toEqual({
+ orderId: '7',
+ amount: 9000,
+ depositorName: '김구매',
+ depositedAt: '2026-11-19T01:30:00.000Z',
+ note: '늦은 입금',
+ });
+ expect(toUnidentifiedDepositInput({ ...valid, note: ' 메모 ' })).toEqual({
+ amount: 9000,
+ depositorName: '김구매',
+ depositedAt: null,
+ note: '메모',
+ });
+ });
+});
+
+describe('depositFormError', () => {
+ const api = (classification: 'BAD_USER_INPUT' | 'NOT_FOUND', code: string) =>
+ new ApiError('서버 문구', classification, code, 200);
+
+ it.each([
+ [api('BAD_USER_INPUT', 'DEPOSIT_AMOUNT_INVALID'), { field: 'amount', inForm: true }],
+ [api('BAD_USER_INPUT', 'DEPOSIT_NOTE_REQUIRED'), { field: 'note', inForm: true }],
+ [api('BAD_USER_INPUT', 'TEXT_TOO_LONG'), { field: null, inForm: true, message: '서버 문구' }],
+ [api('NOT_FOUND', 'ORDER_NOT_FOUND'), { field: null, inForm: false, message: '서버 문구' }],
+ [new Error('x'), { field: null, inForm: false }],
+ ])('%#', (e, want) => {
+ expect(depositFormError(e)).toMatchObject(want);
+ });
+});
diff --git a/src/features/tasks/forms.ts b/src/features/tasks/forms.ts
new file mode 100644
index 0000000..237e3c7
--- /dev/null
+++ b/src/features/tasks/forms.ts
@@ -0,0 +1,126 @@
+import { z } from 'zod';
+
+import {
+ type AdminConfirmPaymentInput,
+ type AdminCreateDepositReturnInput,
+ type AdminRecordUnidentifiedDepositInput,
+} from '@/graphql/generated/graphql';
+import { ApiError, messageFor } from '@/shared/api';
+import { localToIso } from '@/shared/lib/kst';
+
+import { parseWon } from './search';
+
+const NOTE_MAX = 500;
+const DEPOSITOR_MAX = 50;
+/** BE처럼 앞뒤 공백을 빼고 코드 포인트로 센다 */
+const length = (s: string) => [...s.trim()].length;
+
+export const FORM_MESSAGES = {
+ depositedAmount: '입금액을 원 단위 숫자로 입력해 주세요.',
+ amount: '입금액을 1원 이상 숫자로 입력해 주세요.',
+ depositorRequired: '입금자명을 입력해 주세요.',
+ depositorTooLong: `입금자명은 ${DEPOSITOR_MAX}자 이하로 입력해 주세요.`,
+ noteRequired: '주인 모를 입금은 메모를 남겨야 기록할 수 있어요.',
+ noteTooLong: `메모는 ${NOTE_MAX}자 이하로 입력해 주세요.`,
+} as const;
+
+export const confirmPaymentSchema = z
+ .object({ depositedAmount: z.string(), note: z.string() })
+ .superRefine((v, ctx) => {
+ if (parseWon(v.depositedAmount) === null)
+ ctx.addIssue({
+ path: ['depositedAmount'],
+ code: 'custom',
+ message: FORM_MESSAGES.depositedAmount,
+ });
+ if (length(v.note) > NOTE_MAX)
+ ctx.addIssue({ path: ['note'], code: 'custom', message: FORM_MESSAGES.noteTooLong });
+ });
+export type ConfirmPaymentValues = z.infer;
+
+export function toConfirmPaymentInput(
+ orderId: string,
+ v: ConfirmPaymentValues,
+): AdminConfirmPaymentInput {
+ return { orderId, depositedAmount: parseWon(v.depositedAmount)!, note: v.note.trim() || null };
+}
+
+const depositShape = {
+ amount: z.string(),
+ depositorName: z.string(),
+ /** datetime-local(KST). 비우면 보내지 않는다 */
+ depositedAt: z.string(),
+ note: z.string(),
+};
+export type DepositValues = z.infer>;
+
+function checkDeposit(v: DepositValues, ctx: z.RefinementCtx, noteRequired: boolean) {
+ const amount = parseWon(v.amount);
+ if (amount === null || amount < 1)
+ ctx.addIssue({ path: ['amount'], code: 'custom', message: FORM_MESSAGES.amount });
+ const name = length(v.depositorName);
+ if (name === 0)
+ ctx.addIssue({
+ path: ['depositorName'],
+ code: 'custom',
+ message: FORM_MESSAGES.depositorRequired,
+ });
+ else if (name > DEPOSITOR_MAX)
+ ctx.addIssue({
+ path: ['depositorName'],
+ code: 'custom',
+ message: FORM_MESSAGES.depositorTooLong,
+ });
+ const note = length(v.note);
+ if (noteRequired && note === 0)
+ ctx.addIssue({ path: ['note'], code: 'custom', message: FORM_MESSAGES.noteRequired });
+ else if (note > NOTE_MAX)
+ ctx.addIssue({ path: ['note'], code: 'custom', message: FORM_MESSAGES.noteTooLong });
+}
+
+export const depositReturnSchema = z
+ .object(depositShape)
+ .superRefine((v, ctx) => checkDeposit(v, ctx, false));
+export const unidentifiedDepositSchema = z
+ .object(depositShape)
+ .superRefine((v, ctx) => checkDeposit(v, ctx, true));
+
+export const emptyDeposit = (over: Partial = {}): DepositValues => ({
+ amount: '',
+ depositorName: '',
+ depositedAt: '',
+ note: '',
+ ...over,
+});
+
+const depositFields = (v: DepositValues) => ({
+ amount: parseWon(v.amount)!,
+ depositorName: v.depositorName.trim(),
+ depositedAt: localToIso(v.depositedAt),
+});
+
+export function toDepositReturnInput(
+ orderId: string,
+ v: DepositValues,
+): AdminCreateDepositReturnInput {
+ return { orderId, ...depositFields(v), note: v.note.trim() || null };
+}
+
+export function toUnidentifiedDepositInput(v: DepositValues): AdminRecordUnidentifiedDepositInput {
+ return { ...depositFields(v), note: v.note.trim() };
+}
+
+/** 저장 실패를 어디에 보일지. 입력 칸에 붙일 수 있으면 field, 입력 오류는 폼 상단, 그 밖은 토스트 */
+export function depositFormError(e: unknown): {
+ field: 'amount' | 'note' | null;
+ inForm: boolean;
+ message: string;
+} {
+ const code = e instanceof ApiError ? e.code : null;
+ if (code === 'DEPOSIT_AMOUNT_INVALID')
+ return { field: 'amount', inForm: true, message: FORM_MESSAGES.amount };
+ if (code === 'DEPOSIT_NOTE_REQUIRED')
+ return { field: 'note', inForm: true, message: FORM_MESSAGES.noteRequired };
+ const inForm = e instanceof ApiError && e.classification === 'BAD_USER_INPUT';
+ return { field: null, inForm, message: messageFor(e) };
+}
diff --git a/src/features/tasks/hub.spec.tsx b/src/features/tasks/hub.spec.tsx
new file mode 100644
index 0000000..7a7d9b1
--- /dev/null
+++ b/src/features/tasks/hub.spec.tsx
@@ -0,0 +1,231 @@
+import { QueryClientProvider, useQuery } from '@tanstack/react-query';
+import { act, render, screen, within } from '@testing-library/react';
+import { HttpResponse, graphql } from 'msw';
+
+import { App } from '@/app/app';
+import { createQueryClient } from '@/app/query-client';
+import { useAuthStore } from '@/features/auth';
+import { forgetSearches } from '@/shared/lib/list-return';
+import { gqlOk, restOk } from '@/test/msw/graphql';
+import { server } from '@/test/msw/server';
+
+import {
+ refundQueryOptions,
+ settlementQueryOptions,
+ taskCountsQueryOptions,
+ taskOrderQueryOptions,
+} from './api/queries';
+
+const me = {
+ accountId: '1',
+ username: 'ops.admin',
+ email: null,
+ name: null,
+ status: 'ACTIVE',
+ mustChangePassword: false,
+ lastLoginAt: null,
+ createdAt: '2026-09-27T00:00:00.000Z',
+};
+const counts = {
+ claimedPayments: 2,
+ pendingPayments: 5,
+ refundsAwaitingAccount: 7,
+ refundsAwaitingTransfer: 3,
+ pendingSettlements: 1,
+};
+const noCounts = {
+ claimedPayments: 0,
+ pendingPayments: 0,
+ refundsAwaitingAccount: 0,
+ refundsAwaitingTransfer: 0,
+ pendingSettlements: 0,
+};
+const noPayments = gqlOk('AdminTasksPendingPayments', {
+ adminPendingPayments: { items: [], totalCount: 0, hasMore: false, nextCursor: null },
+});
+
+function boot(path: string, taskCounts = counts) {
+ server.use(
+ restOk('/admin/refresh', {
+ accessToken: 'at',
+ tokenType: 'Bearer',
+ accountStatus: 'ACTIVE',
+ mustChangePassword: false,
+ }),
+ gqlOk('AdminMe', { adminMe: me }),
+ gqlOk('AdminTaskCounts', { adminTaskCounts: taskCounts }),
+ );
+ window.history.pushState({}, '', path);
+ render();
+}
+
+describe('처리 대기 허브', () => {
+ beforeEach(() => {
+ useAuthStore.setState({ status: 'unknown', accessToken: null, mustChangePassword: false });
+ forgetSearches();
+ });
+
+ it('건수는 60초마다, 창에 돌아올 때마다 다시 읽는다', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ let reads = 0;
+ server.use(
+ graphql.query('AdminTaskCounts', () => {
+ reads += 1;
+ return HttpResponse.json({ data: { adminTaskCounts: counts } });
+ }),
+ );
+ function Counts() {
+ useQuery(taskCountsQueryOptions());
+ return null;
+ }
+ // 앱 기본값(포커스 재조회 끔·staleTime 15초) 위에서 본다
+ render(
+
+
+ ,
+ );
+ await vi.waitFor(() => expect(reads).toBe(1));
+ act(() => {
+ vi.advanceTimersByTime(60_000);
+ });
+ await vi.waitFor(() => expect(reads).toBe(2));
+
+ act(() => {
+ vi.advanceTimersByTime(20_000);
+ window.dispatchEvent(new Event('visibilitychange'));
+ });
+ await vi.waitFor(() => expect(reads).toBe(3));
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('열린 시트의 상세(주문·환불·정산)도 60초마다 다시 읽는다', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ const reads = { order: 0, refund: 0, settlement: 0 };
+ server.use(
+ graphql.query('AdminTasksOrder', () => {
+ reads.order += 1;
+ return HttpResponse.json({ data: { adminOrder: null } });
+ }),
+ graphql.query('AdminTasksRefund', () => {
+ reads.refund += 1;
+ return HttpResponse.json({ data: { adminRefund: null } });
+ }),
+ graphql.query('AdminTasksSettlement', () => {
+ reads.settlement += 1;
+ return HttpResponse.json({ data: { adminSettlement: null } });
+ }),
+ );
+ function Details() {
+ useQuery(taskOrderQueryOptions('1'));
+ useQuery(refundQueryOptions('2'));
+ useQuery(settlementQueryOptions('3'));
+ return null;
+ }
+ render(
+
+
+ ,
+ );
+ await vi.waitFor(() => expect(reads).toEqual({ order: 1, refund: 1, settlement: 1 }));
+ act(() => {
+ vi.advanceTimersByTime(60_000);
+ });
+ await vi.waitFor(() => expect(reads).toEqual({ order: 2, refund: 2, settlement: 2 }));
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('/tasks는 입금 탭으로 보내고, 사이드바 운영 맨 위에 처리 가능한 건수 합계를 단다', async () => {
+ server.use(noPayments);
+ boot('/tasks');
+ await vi.waitFor(() => expect(window.location.pathname).toBe('/tasks/deposits'));
+ expect(screen.getByRole('heading', { level: 1, name: '처리 대기' })).toBeInTheDocument();
+
+ const nav = screen.getByRole('navigation', { name: '주 메뉴' });
+ const links = within(nav).getAllByRole('link');
+ const tasks = await within(nav).findByRole('link', { name: '처리 대기 9건' });
+ // 운영 묶음의 첫 메뉴(대시보드 다음)
+ expect(links.indexOf(tasks)).toBe(1);
+ expect(tasks).toHaveAttribute('data-status', 'active');
+
+ const tabs = screen.getByRole('navigation', { name: '처리 대기 종류' });
+ expect(within(tabs).getByRole('link', { name: '입금 5건' })).toHaveAttribute(
+ 'data-status',
+ 'active',
+ );
+ // 계좌 입력 대기(7)는 구매자를 기다리므로 탭 배지에 넣지 않는다
+ expect(within(tabs).getByRole('link', { name: '환불 3건' })).toHaveAttribute(
+ 'href',
+ '/tasks/refunds',
+ );
+ expect(within(tabs).getByRole('link', { name: '정산 송금 1건' })).toHaveAttribute(
+ 'href',
+ '/tasks/settlements',
+ );
+ expect(await screen.findByText("'입금했어요'를 누른 주문이 없습니다.")).toBeInTheDocument();
+ });
+
+ it('처리할 건이 없으면 사이드바·탭 배지를 달지 않는다', async () => {
+ server.use(noPayments);
+ boot('/tasks/deposits', noCounts);
+ // 보기 탭은 0도 그리므로, 이게 보이면 건수를 받은 뒤다
+ await screen.findByRole('tab', { name: '확인 요청 0' });
+ const nav = screen.getByRole('navigation', { name: '주 메뉴' });
+ expect(within(nav).getByRole('link', { name: '처리 대기' })).toHaveAttribute('href', '/tasks');
+ const tabs = screen.getByRole('navigation', { name: '처리 대기 종류' });
+ expect(
+ within(tabs)
+ .getAllByRole('link')
+ .map((l) => l.textContent),
+ ).toEqual(['입금', '환불', '정산 송금']);
+ });
+
+ it('대시보드 타일은 같은 건수를 종류별 링크로 보인다', async () => {
+ server.use(
+ gqlOk('AdminDashboardSummary', {
+ adminDashboardSummary: {
+ from: 'x',
+ to: 'y',
+ orderAmountSum: 0,
+ newUserCount: 0,
+ newSellerCount: 0,
+ activeStoreCount: 0,
+ activeProductCount: 0,
+ pendingReportCount: 0,
+ orderCounts: {
+ pendingPayment: 0,
+ submitted: 0,
+ confirmed: 0,
+ made: 0,
+ pickedUp: 0,
+ noShow: 0,
+ canceled: 0,
+ },
+ },
+ }),
+ gqlOk('AdminSearchKeywordSnapshot', {
+ adminSearchKeywordSnapshot: { rankedAt: '2026-09-27T08:00:00.000Z', items: [] },
+ }),
+ );
+ boot('/');
+ const tile = (await screen.findByText('처리 대기', { selector: 'div' })).closest(
+ '[data-slot="card"]',
+ )!;
+ expect(await within(tile).findByText('9건')).toBeInTheDocument();
+ expect(
+ within(tile).getByRole('link', { name: '입금 확인 5건(입금했어요 2건)' }),
+ ).toHaveAttribute('href', '/tasks/deposits');
+ expect(
+ within(tile).getByRole('link', { name: '환불 송금 3건 · 계좌 입력 대기 7건' }),
+ ).toHaveAttribute('href', '/tasks/refunds');
+ expect(within(tile).getByRole('link', { name: '정산 송금 1건' })).toHaveAttribute(
+ 'href',
+ '/tasks/settlements',
+ );
+ });
+});
diff --git a/src/features/tasks/index.ts b/src/features/tasks/index.ts
new file mode 100644
index 0000000..b0eddaa
--- /dev/null
+++ b/src/features/tasks/index.ts
@@ -0,0 +1,6 @@
+export { invalidateTasks } from './api/queries';
+export { TaskCountBadge, TasksTile } from './components/task-counts';
+export { DepositsTasksPage } from './pages/deposits-page';
+export { RefundsTasksPage } from './pages/refunds-page';
+export { SettlementsTasksPage } from './pages/settlements-page';
+export { depositsSearchSchema, refundsSearchSchema, settlementsSearchSchema } from './search';
diff --git a/src/features/tasks/meta.spec.ts b/src/features/tasks/meta.spec.ts
new file mode 100644
index 0000000..515427e
--- /dev/null
+++ b/src/features/tasks/meta.spec.ts
@@ -0,0 +1,104 @@
+import { ApiError } from '@/shared/api';
+
+import {
+ REFUND_KIND_VALUES,
+ isAmountInvalid,
+ isAmountMismatch,
+ isConflict,
+ isPickupPassed,
+ loadDescription,
+ nextTask,
+ pickupTone,
+ recordKindLabel,
+ taskBadges,
+} from './meta';
+
+describe('pickupTone', () => {
+ const now = new Date('2026-11-19T03:00:00.000Z');
+ const at = (ms: number) => new Date(now.getTime() + ms).toISOString();
+ const H = 3600_000;
+
+ it.each([
+ ['지난 시각', at(-1), 'negative'],
+ ['지금(경계)', at(0), 'negative'],
+ ['1ms 뒤', at(1), 'caution'],
+ ['3시간 1ms 전', at(3 * H - 1), 'caution'],
+ ['3시간 뒤(경계)', at(3 * H), null],
+ ['하루 뒤', at(24 * H), null],
+ ])('%s → %s', (_, pickupAt, want) => {
+ expect(pickupTone(pickupAt, now)).toBe(want);
+ });
+});
+
+describe('nextTask', () => {
+ it.each([
+ ['목록을 아직 못 받음', undefined, undefined, '1', { nextId: null, remaining: 0 }],
+ ['방금 처리한 건이 아직 목록에 있음', ['1', '2', '3'], 3, '1', { nextId: '2', remaining: 2 }],
+ ['다시 받아 빠짐', ['2', '3'], 2, '1', { nextId: '2', remaining: 2 }],
+ ['목록 밖에서 연 건', ['2'], 5, '9', { nextId: '2', remaining: 5 }],
+ ['마지막 건', ['1'], 1, '1', { nextId: null, remaining: 0 }],
+ ['빈 목록', [], 0, '1', { nextId: null, remaining: 0 }],
+ ['이 페이지엔 없지만 남음', [], 4, '1', { nextId: null, remaining: 4 }],
+ ['ID "0"도 다음 건이다', ['1', '0'], 2, '1', { nextId: '0', remaining: 1 }],
+ ])('%s', (_, ids, total, current, want) => {
+ expect(nextTask(ids, total, current)).toEqual(want);
+ });
+});
+
+describe('taskBadges', () => {
+ it('계좌 입력 대기 환불은 배지 합계에 넣지 않는다', () => {
+ expect(
+ taskBadges({
+ claimedPayments: 2,
+ pendingPayments: 5,
+ refundsAwaitingAccount: 7,
+ refundsAwaitingTransfer: 3,
+ pendingSettlements: 1,
+ }),
+ ).toEqual({ deposits: 5, refunds: 3, settlements: 1, total: 9 });
+ });
+});
+
+// 주체·환불 종류·환불 상태 라벨은 orders/meta.spec이 검사한다
+describe('라벨', () => {
+ it.each([
+ ['RETURN', '반환'],
+ ['UNIDENTIFIED', '종결'],
+ ])('입금 기록 종류 %s → %s', (value, want) => {
+ expect(recordKindLabel(value)).toBe(want);
+ });
+
+ it.each(['NEW_VALUE', 'constructor', 'toString', ''])('모르는 값 "%s"는 원문으로 보인다', (v) => {
+ expect(recordKindLabel(v)).toBe(v);
+ });
+
+ it('환불 종류 필터 값은 취소 환불 → 입금 반환 순이다', () => {
+ expect(REFUND_KIND_VALUES).toEqual(['CANCEL', 'DEPOSIT_RETURN']);
+ });
+});
+
+describe('오류 분류', () => {
+ const err = (classification: 'CONFLICT' | 'BAD_USER_INPUT', code: string) =>
+ new ApiError('msg', classification, code, 200);
+
+ it('CONFLICT 분류만 충돌로 본다', () => {
+ expect(isConflict(err('CONFLICT', 'PAYMENT_NOT_PENDING'))).toBe(true);
+ expect(isConflict(err('BAD_USER_INPUT', 'DEPOSIT_AMOUNT_MISMATCH'))).toBe(false);
+ expect(isConflict(new Error('x'))).toBe(false);
+ });
+
+ it('입금 확인 거절 코드를 구분한다', () => {
+ expect(isAmountMismatch(err('BAD_USER_INPUT', 'DEPOSIT_AMOUNT_MISMATCH'))).toBe(true);
+ expect(isAmountMismatch(err('BAD_USER_INPUT', 'DEPOSIT_AMOUNT_INVALID'))).toBe(false);
+ expect(isAmountInvalid(err('BAD_USER_INPUT', 'DEPOSIT_AMOUNT_INVALID'))).toBe(true);
+ expect(isAmountInvalid('DEPOSIT_AMOUNT_INVALID')).toBe(false);
+ expect(isPickupPassed(err('CONFLICT', 'PAYMENT_PICKUP_PASSED'))).toBe(true);
+ expect(isPickupPassed(err('CONFLICT', 'PAYMENT_NOT_PENDING'))).toBe(false);
+ });
+
+ it('단건 읽기 문구는 오류 → 읽는 중 → 요약 순이다', () => {
+ expect(loadDescription(true, err('CONFLICT', 'X'), '요약')).toBe('msg');
+ expect(loadDescription(true, null, '요약')).toBe('불러오고 있습니다.');
+ expect(loadDescription(false, null, '요약')).toBe('요약');
+ });
+});
diff --git a/src/features/tasks/meta.ts b/src/features/tasks/meta.ts
new file mode 100644
index 0000000..7382ed8
--- /dev/null
+++ b/src/features/tasks/meta.ts
@@ -0,0 +1,78 @@
+import {
+ type AdminTaskCountsQuery,
+ type DepositRecordKindType,
+ type RefundKindType,
+} from '@/graphql/generated/graphql';
+import { ApiError, messageFor } from '@/shared/api';
+import { type PillTone } from '@/shared/ui/status-pill';
+
+// Record라 codegen enum에 값이 늘면 tsc가 잡는다. 모르는 값은 원문으로 보인다.
+// 주체·환불 종류·환불 상태 라벨은 주문 화면과 한 벌이라 @/features/orders의 것을 쓴다
+const RECORD_KIND: Record = {
+ RETURN: '반환',
+ UNIDENTIFIED: '종결',
+};
+// 환불 종류는 값(주소·칩 순서)만 둔다. 주소 스키마가 모듈 평가 때 쓰는데 주문 feature와 서로 import하는
+// 사이라, 평가 순서에 따라 그쪽 값이 아직 없을 수 있다
+const REFUND_KIND_KEYS: Record = { CANCEL: true, DEPOSIT_RETURN: true };
+
+export const RECORD_KINDS = (Object.keys(RECORD_KIND) as DepositRecordKindType[]).map((value) => ({
+ value,
+ label: RECORD_KIND[value],
+}));
+export const REFUND_KIND_VALUES = Object.keys(REFUND_KIND_KEYS) as [
+ RefundKindType,
+ ...RefundKindType[],
+];
+export const recordKindLabel = (v: string) =>
+ Object.hasOwn(RECORD_KIND, v) ? RECORD_KIND[v as DepositRecordKindType] : v;
+
+const PICKUP_SOON_MS = 3 * 3600_000;
+
+/** 입금 확인 목록의 픽업 강조: 지났으면 negative(확인 불가), 3시간 미만이면 caution */
+export function pickupTone(pickupAt: string, now: Date): PillTone | null {
+ const left = new Date(pickupAt).getTime() - now.getTime();
+ if (left <= 0) return 'negative';
+ return left < PICKUP_SOON_MS ? 'caution' : null;
+}
+
+export const isPast = (iso: string, now: Date) => new Date(iso).getTime() <= now.getTime();
+
+type Counts = AdminTaskCountsQuery['adminTaskCounts'];
+
+/**
+ * 탭·사이드바 배지. 지금 처리할 수 있는 건만 센다 — 계좌 입력 대기 환불은 구매자를 기다리므로
+ * 환불 탭 안의 칩에만 보인다
+ */
+export function taskBadges(c: Counts) {
+ const deposits = c.pendingPayments;
+ const refunds = c.refundsAwaitingTransfer;
+ const settlements = c.pendingSettlements;
+ return { deposits, refunds, settlements, total: deposits + refunds + settlements };
+}
+
+/** 처리 뒤 [다음 건]. 다시 받기 전 목록에 방금 처리한 건이 남아 있어도 세지 않는다 */
+export function nextTask(
+ ids: readonly string[] | undefined,
+ totalCount: number | undefined,
+ currentId: string,
+): { nextId: string | null; remaining: number } {
+ if (!ids || totalCount === undefined) return { nextId: null, remaining: 0 };
+ const listed = ids.includes(currentId);
+ return {
+ nextId: ids.find((id) => id !== currentId) ?? null,
+ remaining: Math.max(totalCount - (listed ? 1 : 0), 0),
+ };
+}
+
+const codeOf = (e: unknown) => (e instanceof ApiError ? e.code : null);
+export const isConflict = (e: unknown) => e instanceof ApiError && e.classification === 'CONFLICT';
+export const isAmountMismatch = (e: unknown) => codeOf(e) === 'DEPOSIT_AMOUNT_MISMATCH';
+export const isAmountInvalid = (e: unknown) => codeOf(e) === 'DEPOSIT_AMOUNT_INVALID';
+export const isPickupPassed = (e: unknown) => codeOf(e) === 'PAYMENT_PICKUP_PASSED';
+
+/** 단건 읽기 상태 문구. 없는 ID는 404로 오므로 오류 문구를 그대로 보인다 */
+export function loadDescription(isLoading: boolean, error: Error | null, ready: string): string {
+ if (error) return messageFor(error);
+ return isLoading ? '불러오고 있습니다.' : ready;
+}
diff --git a/src/features/tasks/pages/deposits-page.tsx b/src/features/tasks/pages/deposits-page.tsx
new file mode 100644
index 0000000..1fc2c8e
--- /dev/null
+++ b/src/features/tasks/pages/deposits-page.tsx
@@ -0,0 +1,405 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { Link } from '@tanstack/react-router';
+import { type ColumnDef } from '@tanstack/react-table';
+import { useState } from 'react';
+import { toast } from 'sonner';
+
+import { refundStatusMeta } from '@/features/orders';
+import { messageFor } from '@/shared/api';
+import { formatCount, formatKrw } from '@/shared/lib/format';
+import { formatKst } from '@/shared/lib/kst';
+import { Button } from '@/shared/ui/button';
+import { Card } from '@/shared/ui/card';
+import { CursorPager } from '@/shared/ui/cursor-pager';
+import { DataTable } from '@/shared/ui/data-table';
+import { FilterBar } from '@/shared/ui/filter-bar';
+import { FilterField } from '@/shared/ui/filter-field';
+import { IdFilterInput } from '@/shared/ui/id-filter-input';
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select';
+import { StatusPill } from '@/shared/ui/status-pill';
+import { Tabs, TabsList, TabsTrigger } from '@/shared/ui/tabs';
+
+import {
+ type DepositRecord,
+ type PendingPayment,
+ depositRecordsQueryOptions,
+ pendingPaymentsQueryOptions,
+ taskCountsQueryOptions,
+ taskMutations,
+} from '../api/queries';
+import { DepositDialog } from '../components/deposit-dialog';
+import { DepositOrderSheet } from '../components/deposit-order-sheet';
+import { LinkDepositDialog } from '../components/link-deposit-dialog';
+import { TasksHeader } from '../components/task-counts';
+import { toUnidentifiedDepositInput } from '../forms';
+import { RECORD_KINDS, isPast, nextTask, pickupTone, recordKindLabel } from '../meta';
+import {
+ DEPOSIT_VIEWS,
+ type DepositView,
+ type DepositsSearch,
+ type DepositsSearchInput,
+ depositView,
+ parseWon,
+ toDepositRecordInput,
+ toPendingPaymentInput,
+} from '../search';
+
+const ALL = '__all__';
+const linkClass = 'text-primary-soft-foreground hover:underline';
+
+interface Props {
+ search: DepositsSearch;
+ onSearchChange: (next: DepositsSearchInput) => void;
+}
+
+export function DepositsTasksPage({ search, onSearchChange }: Props) {
+ const qc = useQueryClient();
+ const view = depositView(search);
+ const { orderId, ...listSearch } = search;
+ const patch = (p: Partial) =>
+ onSearchChange({ ...listSearch, ...p, cursor: undefined });
+ const openOrder = (id: string | undefined) => onSearchChange({ ...listSearch, orderId: id });
+ const counts = useQuery(taskCountsQueryOptions());
+ const payments = useQuery({
+ ...pendingPaymentsQueryOptions(toPendingPaymentInput(search)),
+ enabled: view !== 'records',
+ });
+ const [recordOpen, setRecordOpen] = useState(false);
+
+ const viewCount: Record = {
+ claimed: counts.data?.claimedPayments,
+ pending: counts.data?.pendingPayments,
+ records: undefined,
+ };
+
+ return (
+ <>
+ setRecordOpen(true)}>
+ 주인 모를 입금 기록
+
+ }
+ />
+
+ patch({ depositorName: v || undefined })}
+ hasActiveFilters={(view === 'records'
+ ? [search.kind]
+ : [search.amount, search.depositorName]
+ ).some((v) => v !== undefined)}
+ onReset={() => onSearchChange({ view: search.view, limit: search.limit })}
+ >
+ patch({ view: v as DepositView, kind: undefined })}
+ >
+
+ {DEPOSIT_VIEWS.map((v) => (
+
+ {v.label}
+ {viewCount[v.value] !== undefined && ' '}
+ {viewCount[v.value] !== undefined && (
+ {formatCount(viewCount[v.value]!)}
+ )}
+
+ ))}
+
+
+ {view === 'records' ? (
+
+
+
+ ) : (
+
+ parseWon(v) !== null}
+ invalidMessage="원 단위 금액으로 입력해 주세요."
+ onCommit={(amount) =>
+ patch({ amount: amount === undefined ? undefined : String(parseWon(amount)) })
+ }
+ />
+
+ )}
+
+ {view === 'records' ? (
+
+ ) : payments.isError ? (
+
+ {messageFor(payments.error)}
+
+ ) : (
+ <>
+
+ {payments.data && (
+ onSearchChange({ ...listSearch, cursor })}
+ />
+ )}
+ >
+ )}
+
+
+ view === 'records'
+ ? null
+ : nextTask(
+ payments.data?.items.map((p) => p.orderId),
+ payments.data?.totalCount,
+ id,
+ )
+ }
+ onOpen={openOrder}
+ />
+ {
+ await taskMutations.recordUnidentifiedDeposit(qc, toUnidentifiedDepositInput(v));
+ toast.success('주인 모를 입금을 종결 기록으로 남겼습니다.');
+ }}
+ />
+ >
+ );
+}
+
+function PaymentsTable({
+ rows,
+ isLoading,
+ view,
+ onOpen,
+}: {
+ rows: PendingPayment[];
+ isLoading: boolean;
+ view: DepositView;
+ onOpen: (orderId: string) => void;
+}) {
+ const now = new Date();
+ const columns: ColumnDef[] = [
+ {
+ id: 'order',
+ header: '주문',
+ cell: ({ row }) => (
+
+
+
+ {[row.original.storeName, row.original.productName].filter(Boolean).join(' · ')}
+
+
+ ),
+ },
+ {
+ id: 'amount',
+ header: '금액',
+ meta: { align: 'right' },
+ cell: ({ row }) => formatKrw(row.original.amount),
+ },
+ { id: 'depositor', header: '입금자명', cell: ({ row }) => row.original.depositorName },
+ {
+ id: 'buyer',
+ header: '주문자',
+ cell: ({ row }) => `${row.original.buyerName} · ${row.original.buyerPhone}`,
+ },
+ {
+ id: 'claimed',
+ header: '입금했어요',
+ cell: ({ row }) =>
+ row.original.buyerClaimedAt ? formatKst(row.original.buyerClaimedAt) : '-',
+ },
+ {
+ id: 'expires',
+ header: '입금 기한',
+ cell: ({ row }) => (
+
+ {formatKst(row.original.expiresAt)}
+ {/* '입금했어요'를 누른 주문은 기한이 멈춰 자동 취소되지 않는다 */}
+ {!row.original.buyerClaimedAt && isPast(row.original.expiresAt, now) && (
+ 지남
+ )}
+
+ ),
+ },
+ {
+ id: 'pickup',
+ header: '픽업',
+ cell: ({ row }) => {
+ const tone = pickupTone(row.original.pickupAt, now);
+ return (
+
+ {formatKst(row.original.pickupAt)}
+ {tone && (
+ {tone === 'negative' ? '지남' : '3시간 미만'}
+ )}
+
+ );
+ },
+ },
+ ];
+ return (
+ r.orderId}
+ isLoading={isLoading}
+ emptyMessage={
+ view === 'claimed'
+ ? "'입금했어요'를 누른 주문이 없습니다."
+ : '입금을 기다리는 주문이 없습니다.'
+ }
+ onRowClick={(r) => onOpen(r.orderId)}
+ />
+ );
+}
+
+function RecordsList({ search, onSearchChange }: Props) {
+ const { orderId: _orderId, ...listSearch } = search;
+ const records = useQuery(depositRecordsQueryOptions(toDepositRecordInput(search)));
+ const [linking, setLinking] = useState(null);
+ const columns: ColumnDef[] = [
+ { id: 'createdAt', header: '기록 시각', cell: ({ row }) => formatKst(row.original.createdAt) },
+ { id: 'kind', header: '종류', cell: ({ row }) => recordKindLabel(row.original.kind) },
+ {
+ id: 'amount',
+ header: '입금액',
+ meta: { align: 'right' },
+ cell: ({ row }) => formatKrw(row.original.amount),
+ },
+ {
+ id: 'depositor',
+ header: '입금자명',
+ cell: ({ row }) => (
+
+ {row.original.depositorName}
+ {row.original.depositedAt && (
+
+ {formatKst(row.original.depositedAt)} 입금
+
+ )}
+
+ ),
+ },
+ {
+ id: 'order',
+ header: '주문',
+ cell: ({ row }) =>
+ row.original.orderId ? (
+
+ {row.original.orderNumber ?? `#${row.original.orderId}`}
+
+ ) : (
+ '-'
+ ),
+ },
+ {
+ id: 'refund',
+ header: '환불',
+ cell: ({ row }) => {
+ const { refundId, refundStatus } = row.original;
+ if (!refundId) return '-';
+ return (
+
+ {refundStatus ? refundStatusMeta(refundStatus).label : `#${refundId}`}
+
+ );
+ },
+ },
+ {
+ id: 'note',
+ header: '메모',
+ cell: ({ row }) => (
+
+ {row.original.note ?? '-'}
+
+ ),
+ },
+ {
+ id: 'recordedBy',
+ header: '기록자',
+ cell: ({ row }) => row.original.recordedByLabel ?? '-',
+ },
+ {
+ id: 'actions',
+ header: '',
+ cell: ({ row }) =>
+ row.original.kind === 'UNIDENTIFIED' && (
+
+ ),
+ },
+ ];
+ if (records.isError)
+ return (
+
+ {messageFor(records.error)}
+
+ );
+ return (
+ <>
+ r.id}
+ isLoading={records.isPending}
+ emptyMessage="입금 기록이 없습니다."
+ />
+ {records.data && (
+ onSearchChange({ ...listSearch, cursor })}
+ />
+ )}
+ setLinking(null)} />
+ >
+ );
+}
diff --git a/src/features/tasks/pages/deposits.spec.tsx b/src/features/tasks/pages/deposits.spec.tsx
new file mode 100644
index 0000000..cbf37e8
--- /dev/null
+++ b/src/features/tasks/pages/deposits.spec.tsx
@@ -0,0 +1,956 @@
+import { render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { HttpResponse, graphql } from 'msw';
+
+import { App } from '@/app/app';
+import { useAuthStore } from '@/features/auth';
+import { forgetSearches } from '@/shared/lib/list-return';
+import { formatKst } from '@/shared/lib/kst';
+import { gqlError, gqlOk, restError, restOk } from '@/test/msw/graphql';
+import { server } from '@/test/msw/server';
+
+import { type DepositRecord, type PendingPayment, type TaskOrder } from '../api/queries';
+
+const me = {
+ accountId: '1',
+ username: 'ops.admin',
+ email: null,
+ name: '운영',
+ status: 'ACTIVE',
+ mustChangePassword: false,
+ lastLoginAt: null,
+ createdAt: '2026-09-27T00:00:00.000Z',
+};
+const session = {
+ accessToken: 'at',
+ tokenType: 'Bearer',
+ accountStatus: 'ACTIVE',
+ mustChangePassword: false,
+};
+
+const H = 3600_000;
+const at = (ms: number) => new Date(Date.now() + ms).toISOString();
+
+const order = (id: string, over: Partial = {}): TaskOrder => ({
+ id,
+ orderNumber: `CQ-${id}`,
+ status: 'PENDING_PAYMENT',
+ pickupAt: at(48 * H),
+ buyerName: '김구매',
+ buyerPhone: '010-1234-5678',
+ totalPrice: 30000,
+ createdAt: at(-30 * 60_000),
+ items: [{ id: `i${id}`, productName: '레터링 케이크' }],
+ payment: {
+ status: 'PENDING',
+ amount: 30000,
+ depositorName: '김입금',
+ expiresAt: at(30 * 60_000),
+ buyerClaimedAt: at(-60_000),
+ confirmedAt: null,
+ confirmedByLabel: null,
+ confirmNote: null,
+ },
+ cancellation: null,
+ ...over,
+});
+
+const row = (o: TaskOrder, over: Partial = {}): PendingPayment => ({
+ orderId: o.id,
+ orderNumber: o.orderNumber,
+ storeName: '루미 케이크',
+ productName: '레터링 케이크',
+ amount: o.payment!.amount,
+ depositorName: o.payment!.depositorName,
+ buyerName: o.buyerName,
+ buyerPhone: o.buyerPhone,
+ createdAt: o.createdAt,
+ expiresAt: o.payment!.expiresAt,
+ buyerClaimedAt: o.payment!.buyerClaimedAt ?? null,
+ pickupAt: o.pickupAt,
+ ...over,
+});
+
+/** 입금 대기 주문을 들고 있는 가짜 BE. 처리하면 목록에서 빠진다 */
+function backend(initial: TaskOrder[]) {
+ const orders = new Map(initial.map((o) => [o.id, o]));
+ const calls = { list: [] as Record[], counts: 0, order: [] as string[] };
+ server.use(
+ restOk('/admin/refresh', session),
+ gqlOk('AdminMe', { adminMe: me }),
+ graphql.query('AdminTaskCounts', () => {
+ calls.counts += 1;
+ const pending = [...orders.values()].filter((o) => o.status === 'PENDING_PAYMENT');
+ return HttpResponse.json({
+ data: {
+ adminTaskCounts: {
+ claimedPayments: pending.filter((o) => o.payment?.buyerClaimedAt).length,
+ pendingPayments: pending.length,
+ refundsAwaitingAccount: 0,
+ refundsAwaitingTransfer: 0,
+ pendingSettlements: 0,
+ },
+ },
+ });
+ }),
+ graphql.query('AdminTasksPendingPayments', ({ variables }) => {
+ const input = (variables as { input: Record }).input;
+ calls.list.push(input);
+ const items = [...orders.values()]
+ .filter((o) => o.status === 'PENDING_PAYMENT')
+ .filter((o) => !input.claimedOnly || o.payment?.buyerClaimedAt)
+ .map((o) => row(o));
+ return HttpResponse.json({
+ data: {
+ adminPendingPayments: {
+ items,
+ totalCount: items.length,
+ hasMore: false,
+ nextCursor: null,
+ },
+ },
+ });
+ }),
+ graphql.query('AdminTasksOrder', ({ variables }) => {
+ const { orderId } = variables as { orderId: string };
+ calls.order.push(orderId);
+ const o = orders.get(orderId);
+ return o
+ ? HttpResponse.json({ data: { adminOrder: o } })
+ : HttpResponse.json({
+ data: null,
+ errors: [
+ {
+ message: '주문을 찾을 수 없습니다.',
+ extensions: {
+ code: 'ORDER_NOT_FOUND',
+ classification: 'NOT_FOUND',
+ statusCode: 404,
+ },
+ },
+ ],
+ });
+ }),
+ );
+ return { orders, calls };
+}
+
+function boot(path: string) {
+ window.history.pushState({}, '', path);
+ render();
+}
+
+const sheet = (name: RegExp) => screen.findByRole('dialog', { name });
+const query = () => new URLSearchParams(window.location.search);
+
+describe('처리 대기 — 입금', () => {
+ beforeEach(() => {
+ useAuthStore.setState({ status: 'unknown', accessToken: null, mustChangePassword: false });
+ forgetSearches();
+ });
+
+ it('딥링크 주문을 시트로 열어 입금을 확인하고 처리됨과 다음 건으로 넘어간다', async () => {
+ const { orders, calls } = backend([order('12'), order('13')]);
+ let confirmInput: unknown;
+ server.use(
+ graphql.mutation('AdminTasksConfirmPayment', ({ variables }) => {
+ confirmInput = (variables as { input: unknown }).input;
+ const o = orders.get('12')!;
+ orders.set('12', {
+ ...o,
+ status: 'SUBMITTED',
+ payment: {
+ ...o.payment!,
+ status: 'CONFIRMED',
+ confirmedAt: '2026-11-19T01:00:00.000Z',
+ confirmedByLabel: '운영(ops.admin)',
+ },
+ });
+ return HttpResponse.json({
+ data: { adminConfirmPayment: { id: '12', status: 'SUBMITTED' } },
+ });
+ }),
+ );
+ boot('/tasks/deposits?orderId=12');
+ const s = await sheet(/주문 CQ-12/);
+ expect(s).toHaveTextContent('은행 앱에서 입금자명과 금액을 확인한 뒤 입금액을 입력하세요.');
+ expect(s).toHaveTextContent('김입금');
+ expect(s).toHaveTextContent('30,000원');
+ expect(within(s).getByRole('link', { name: '주문 화면에서 보기' })).toHaveAttribute(
+ 'href',
+ '/orders/12',
+ );
+ const countsBefore = calls.counts;
+
+ await userEvent.type(within(s).getByLabelText('입금액(원) (필수)'), '30,000');
+ await userEvent.click(within(s).getByRole('button', { name: '입금 확인' }));
+
+ expect(confirmInput).toEqual({ orderId: '12', depositedAmount: 30000, note: null });
+ expect(
+ await screen.findByText('CQ-12 입금을 확인했습니다. 판매자에게 새 주문으로 보입니다.'),
+ ).toBeInTheDocument();
+ const done = await within(s).findByRole('status');
+ expect(done).toHaveTextContent('처리됨');
+ expect(done).toHaveTextContent(
+ `입금 확인 · 운영(ops.admin) · ${formatKst('2026-11-19T01:00:00.000Z', true)}`,
+ );
+ expect(within(s).queryByRole('button', { name: '미입금 취소' })).not.toBeInTheDocument();
+ // 처리하면 건수도 다시 읽는다
+ expect(calls.counts).toBeGreaterThan(countsBefore);
+
+ await userEvent.click(within(s).getByRole('button', { name: '다음 건 (1건 남음)' }));
+ await vi.waitFor(() => expect(query().get('orderId')).toBe('13'));
+ expect(await sheet(/주문 CQ-13/)).toBeInTheDocument();
+ });
+
+ it('그사이 다른 관리자가 처리했으면(409) 토스트를 보이고 다시 읽어 처리자·시각을 보인다', async () => {
+ const { orders } = backend([order('12')]);
+ server.use(
+ graphql.mutation('AdminTasksConfirmPayment', () => {
+ const o = orders.get('12')!;
+ orders.set('12', {
+ ...o,
+ status: 'SUBMITTED',
+ payment: {
+ ...o.payment!,
+ status: 'CONFIRMED',
+ confirmedAt: '2026-11-19T00:59:00.000Z',
+ confirmedByLabel: '김관리(kim)',
+ },
+ });
+ return HttpResponse.json({
+ data: null,
+ errors: [
+ {
+ message: '입금 대기 중인 주문이 아닙니다. 이미 처리됐는지 확인해 주세요.',
+ extensions: {
+ code: 'PAYMENT_NOT_PENDING',
+ classification: 'CONFLICT',
+ statusCode: 409,
+ },
+ },
+ ],
+ });
+ }),
+ );
+ boot('/tasks/deposits?orderId=12');
+ const s = await sheet(/주문 CQ-12/);
+ await userEvent.type(within(s).getByLabelText('입금액(원) (필수)'), '30000');
+ await userEvent.click(within(s).getByRole('button', { name: '입금 확인' }));
+ expect(
+ await screen.findByText('입금 대기 중인 주문이 아닙니다. 이미 처리됐는지 확인해 주세요.'),
+ ).toBeInTheDocument();
+ expect(await within(s).findByRole('status')).toHaveTextContent(
+ `입금 확인 · 김관리(kim) · ${formatKst('2026-11-19T00:59:00.000Z', true)}`,
+ );
+ // 목록에 남은 건이 없다
+ expect(within(s).getByText('남은 건이 없습니다.')).toBeInTheDocument();
+ });
+
+ it('화면은 픽업 전이어도 서버가 픽업 지남(409)으로 거절하면 확인 폼을 안내로 바꾼다', async () => {
+ const { orders } = backend([order('12', { pickupAt: at(60_000) })]);
+ let confirms = 0;
+ server.use(
+ graphql.mutation('AdminTasksConfirmPayment', () => {
+ confirms += 1;
+ return HttpResponse.json({
+ data: null,
+ errors: [
+ {
+ message:
+ '픽업 시각이 지난 주문은 입금 확인할 수 없어요. 미입금 취소 뒤 반환 대상으로 연결해 주세요.',
+ extensions: {
+ code: 'PAYMENT_PICKUP_PASSED',
+ classification: 'CONFLICT',
+ statusCode: 409,
+ },
+ },
+ ],
+ });
+ }),
+ );
+ boot('/tasks/deposits?orderId=12');
+ const s = await sheet(/주문 CQ-12/);
+ expect(within(s).getByText('3시간 미만')).toBeInTheDocument();
+ await userEvent.type(within(s).getByLabelText('입금액(원) (필수)'), '30000');
+ await userEvent.click(within(s).getByRole('button', { name: '입금 확인' }));
+
+ expect(await within(s).findByRole('note')).toHaveTextContent(
+ '픽업 시각이 지난 주문은 입금 확인할 수 없어요. 미입금 취소 뒤 반환 대상으로 연결해 주세요.',
+ );
+ expect(within(s).getByText('픽업 지남')).toBeInTheDocument();
+ expect(within(s).queryByRole('form', { name: '입금 확인' })).not.toBeInTheDocument();
+ expect(within(s).getByRole('button', { name: '미입금 취소' })).toBeInTheDocument();
+ expect(confirms).toBe(1);
+ // 다시 읽은 주문은 여전히 입금 대기다
+ expect(orders.get('12')!.status).toBe('PENDING_PAYMENT');
+ });
+
+ it('입금액이 결제 금액과 다르면 오류 문구와 함께 반환 연결을 입력한 금액으로 미리 채워 연다', async () => {
+ backend([order('12')]);
+ let returnInput: unknown;
+ server.use(
+ gqlError('AdminTasksConfirmPayment', {
+ message: '입금액이 결제 금액과 달라 입금 확인할 수 없어요. 반환 대상으로 연결해 주세요.',
+ code: 'DEPOSIT_AMOUNT_MISMATCH',
+ classification: 'BAD_USER_INPUT',
+ statusCode: 400,
+ }),
+ graphql.mutation('AdminTasksCreateDepositReturn', ({ variables }) => {
+ returnInput = (variables as { input: unknown }).input;
+ return HttpResponse.json({
+ data: { adminCreateDepositReturn: { id: '40', refundId: '41' } },
+ });
+ }),
+ );
+ boot('/tasks/deposits?orderId=12');
+ const s = await sheet(/주문 CQ-12/);
+ await userEvent.type(within(s).getByLabelText('입금액(원) (필수)'), '29,000');
+ await userEvent.click(within(s).getByRole('button', { name: '입금 확인' }));
+
+ const dialog = await screen.findByRole('dialog', { name: '반환 대상으로 연결' });
+ expect(within(dialog).getByRole('alert')).toHaveTextContent(
+ '입금액이 결제 금액과 달라 입금 확인할 수 없어요. 반환 대상으로 연결해 주세요.',
+ );
+ expect(within(dialog).getByLabelText('입금액(원) (필수)')).toHaveValue('29000');
+ expect(within(dialog).getByLabelText('입금자명 (필수)')).toHaveValue('김입금');
+ await userEvent.type(within(dialog).getByLabelText('메모 (선택)'), '금액 틀린 입금');
+ await userEvent.click(within(dialog).getByRole('button', { name: '반환 대상으로 연결' }));
+ await vi.waitFor(() =>
+ expect(returnInput).toEqual({
+ orderId: '12',
+ amount: 29000,
+ depositorName: '김입금',
+ depositedAt: null,
+ note: '금액 틀린 입금',
+ }),
+ );
+ expect(
+ await screen.findByText(
+ '반환 대상으로 연결했습니다. 구매자에게 환불 계좌 입력을 요청했어요.',
+ ),
+ ).toBeInTheDocument();
+ await vi.waitFor(() =>
+ expect(screen.queryByRole('dialog', { name: '반환 대상으로 연결' })).not.toBeInTheDocument(),
+ );
+ // 반환을 연결해도 주문은 입금 대기 그대로라 확인 폼이 남는다
+ expect(within(s).getByRole('alert')).toHaveTextContent('입금액이 결제 금액과 달라');
+ await userEvent.click(within(s).getByRole('link', { name: '환불 #41 보기' }));
+ await vi.waitFor(() => expect(window.location.pathname).toBe('/tasks/refunds'));
+ expect(query().get('refundId')).toBe('41');
+ });
+
+ it('입금액 칸은 숫자만 받고 서버의 입금액 오류는 칸 아래에 보인다', async () => {
+ backend([order('12')]);
+ let calls = 0;
+ server.use(
+ graphql.mutation('AdminTasksConfirmPayment', () => {
+ calls += 1;
+ return HttpResponse.json({
+ data: null,
+ errors: [
+ {
+ message: '입금액이 올바르지 않아요. 원 단위 정수로 입력해 주세요.',
+ extensions: {
+ code: 'DEPOSIT_AMOUNT_INVALID',
+ classification: 'BAD_USER_INPUT',
+ statusCode: 400,
+ },
+ },
+ ],
+ });
+ }),
+ );
+ boot('/tasks/deposits?orderId=12');
+ const s = await sheet(/주문 CQ-12/);
+ await userEvent.type(within(s).getByLabelText('입금액(원) (필수)'), '1.5');
+ await userEvent.click(within(s).getByRole('button', { name: '입금 확인' }));
+ expect(
+ await within(s).findByText('입금액을 원 단위 숫자로 입력해 주세요.'),
+ ).toBeInTheDocument();
+ expect(calls).toBe(0);
+
+ await userEvent.clear(within(s).getByLabelText('입금액(원) (필수)'));
+ await userEvent.type(within(s).getByLabelText('입금액(원) (필수)'), '0');
+ await userEvent.click(within(s).getByRole('button', { name: '입금 확인' }));
+ expect(
+ await within(s).findByText('입금액이 올바르지 않아요. 원 단위 정수로 입력해 주세요.'),
+ ).toBeInTheDocument();
+ expect(calls).toBe(1);
+ });
+
+ it('주소의 금액 "0"과 주문 ID "0"을 그대로 보낸다', async () => {
+ const { calls } = backend([
+ order('0', { totalPrice: 0, payment: { ...order('0').payment!, amount: 0 } }),
+ ]);
+ boot('/tasks/deposits?view=pending&amount=0&orderId=0');
+ expect(await sheet(/주문 CQ-0/)).toBeInTheDocument();
+ expect(calls.order).toContain('0');
+ await vi.waitFor(() =>
+ expect(calls.list.at(-1)).toEqual({
+ limit: 20,
+ cursor: null,
+ claimedOnly: false,
+ amount: 0,
+ depositorName: null,
+ }),
+ );
+ });
+
+ it('픽업이 지난 주문은 확인을 막고 미입금 취소로 닫는다', async () => {
+ const { orders } = backend([
+ order('12', {
+ pickupAt: at(-60_000),
+ payment: { ...order('12').payment!, expiresAt: at(-2 * H) },
+ }),
+ ]);
+ let cancelInput: unknown;
+ server.use(
+ graphql.mutation('AdminTasksCancelUnpaid', ({ variables }) => {
+ cancelInput = (variables as { input: unknown }).input;
+ orders.set('12', {
+ ...orders.get('12')!,
+ status: 'CANCELED',
+ payment: { ...orders.get('12')!.payment!, status: 'CANCELED' },
+ cancellation: {
+ actorType: 'ADMIN',
+ reasonLabel: '입금 확인 안 됨',
+ note: null,
+ canceledAt: '2026-11-19T02:00:00.000Z',
+ },
+ });
+ return HttpResponse.json({ data: { adminCancelOrder: { id: '12', status: 'CANCELED' } } });
+ }),
+ );
+ boot('/tasks/deposits?orderId=12');
+ const s = await sheet(/주문 CQ-12/);
+ expect(within(s).getByRole('note')).toHaveTextContent(
+ '픽업 시각이 지난 주문은 입금 확인할 수 없어요. 미입금 취소 뒤 반환 대상으로 연결해 주세요.',
+ );
+ expect(within(s).getByText('픽업 지남')).toBeInTheDocument();
+ // '입금했어요'를 누른 주문이라 기한이 지나도 기한 지남은 달지 않는다
+ expect(within(s).queryByText('기한 지남')).not.toBeInTheDocument();
+ expect(within(s).queryByRole('button', { name: '입금 확인' })).not.toBeInTheDocument();
+
+ await userEvent.click(within(s).getByRole('button', { name: '미입금 취소' }));
+ const dialog = await screen.findByRole('dialog', { name: '미입금으로 취소할까요?' });
+ await userEvent.click(within(dialog).getByRole('button', { name: '미입금 취소' }));
+ await vi.waitFor(() =>
+ expect(cancelInput).toEqual({ orderId: '12', reason: 'PAYMENT_NOT_RECEIVED', note: null }),
+ );
+ expect(await within(s).findByRole('status')).toHaveTextContent(
+ `취소 · 관리자 · 입금 확인 안 됨 · ${formatKst('2026-11-19T02:00:00.000Z', true)}`,
+ );
+ });
+
+ it('자동 취소된 주문은 취소 주체를 주문 화면과 같은 시스템으로 보인다', async () => {
+ backend([
+ order('14', {
+ status: 'CANCELED',
+ payment: { ...order('14').payment!, status: 'CANCELED' },
+ cancellation: {
+ actorType: 'SYSTEM',
+ reasonLabel: '미입금',
+ note: null,
+ canceledAt: '2026-11-19T02:00:00.000Z',
+ },
+ }),
+ ]);
+ boot('/tasks/deposits?orderId=14');
+ const s = await sheet(/주문 CQ-14/);
+ expect(await within(s).findByRole('status')).toHaveTextContent(
+ `취소 · 시스템 · 미입금 · ${formatKst('2026-11-19T02:00:00.000Z', true)}`,
+ );
+ });
+
+ it('미입금 취소가 거절되면 다이얼로그를 열어 둔다', async () => {
+ backend([order('12')]);
+ server.use(
+ gqlError('AdminTasksCancelUnpaid', {
+ message: '메모가 너무 깁니다.',
+ code: 'TEXT_TOO_LONG',
+ classification: 'BAD_USER_INPUT',
+ statusCode: 400,
+ }),
+ );
+ boot('/tasks/deposits?orderId=12');
+ const s = await sheet(/주문 CQ-12/);
+ await userEvent.click(within(s).getByRole('button', { name: '미입금 취소' }));
+ const dialog = await screen.findByRole('dialog', { name: '미입금으로 취소할까요?' });
+ await userEvent.click(within(dialog).getByRole('button', { name: '미입금 취소' }));
+ expect(await screen.findByText('메모가 너무 깁니다.')).toBeInTheDocument();
+ expect(screen.getByRole('dialog', { name: '미입금으로 취소할까요?' })).toBeInTheDocument();
+ });
+
+ it('주인 모를 입금 기록은 메모가 없으면 보내지 않는다', async () => {
+ backend([]);
+ let input: unknown;
+ let calls = 0;
+ server.use(
+ graphql.mutation('AdminTasksRecordUnidentifiedDeposit', ({ variables }) => {
+ calls += 1;
+ input = (variables as { input: unknown }).input;
+ return HttpResponse.json({ data: { adminRecordUnidentifiedDeposit: { id: '9' } } });
+ }),
+ );
+ boot('/tasks/deposits');
+ await userEvent.click(await screen.findByRole('button', { name: '주인 모를 입금 기록' }));
+ const dialog = await screen.findByRole('dialog', { name: '주인 모를 입금 기록' });
+ await userEvent.type(within(dialog).getByLabelText('입금액(원) (필수)'), '5000');
+ await userEvent.type(within(dialog).getByLabelText('입금자명 (필수)'), '홍길동');
+ await userEvent.click(within(dialog).getByRole('button', { name: '종결 기록' }));
+ expect(
+ await within(dialog).findByText('주인 모를 입금은 메모를 남겨야 기록할 수 있어요.'),
+ ).toBeInTheDocument();
+ expect(calls).toBe(0);
+
+ await userEvent.type(within(dialog).getByLabelText('메모 (필수)'), '주인 확인 불가');
+ await userEvent.type(
+ within(dialog).getByLabelText('입금 일시 (선택, 한국 시간)'),
+ '2026-11-19T10:30',
+ );
+ await userEvent.click(within(dialog).getByRole('button', { name: '종결 기록' }));
+ await vi.waitFor(() =>
+ expect(input).toEqual({
+ amount: 5000,
+ depositorName: '홍길동',
+ depositedAt: '2026-11-19T01:30:00.000Z',
+ note: '주인 확인 불가',
+ }),
+ );
+ expect(
+ await screen.findByText('주인 모를 입금을 종결 기록으로 남겼습니다.'),
+ ).toBeInTheDocument();
+ });
+
+ it('종결 기록이 서버에서 거절되면 칸·폼 위에 이유를 보인다', async () => {
+ backend([]);
+ let round = 0;
+ server.use(
+ graphql.mutation('AdminTasksRecordUnidentifiedDeposit', () => {
+ round += 1;
+ const [code, message] =
+ round === 1
+ ? ['DEPOSIT_NOTE_REQUIRED', '서버: 메모 필요']
+ : ['TEXT_TOO_LONG', '입금자명이 너무 깁니다.'];
+ return HttpResponse.json({
+ data: null,
+ errors: [
+ { message, extensions: { code, classification: 'BAD_USER_INPUT', statusCode: 400 } },
+ ],
+ });
+ }),
+ );
+ boot('/tasks/deposits');
+ await userEvent.click(await screen.findByRole('button', { name: '주인 모를 입금 기록' }));
+ const dialog = await screen.findByRole('dialog', { name: '주인 모를 입금 기록' });
+ await userEvent.type(within(dialog).getByLabelText('입금액(원) (필수)'), '5000');
+ await userEvent.type(within(dialog).getByLabelText('입금자명 (필수)'), '홍길동');
+ await userEvent.type(within(dialog).getByLabelText('메모 (필수)'), '메모');
+ await userEvent.click(within(dialog).getByRole('button', { name: '종결 기록' }));
+ expect(
+ await within(dialog).findByText('주인 모를 입금은 메모를 남겨야 기록할 수 있어요.'),
+ ).toBeInTheDocument();
+ await userEvent.click(within(dialog).getByRole('button', { name: '종결 기록' }));
+ expect(await within(dialog).findByRole('alert')).toHaveTextContent('입금자명이 너무 깁니다.');
+ });
+
+ it('확인 요청 목록은 픽업 3시간 미만·지남과 입금 기한 지남을 강조하고 보기·검색을 입력으로 보낸다', async () => {
+ const soon = order('21', { pickupAt: at(2 * H) });
+ const late = order('22', {
+ pickupAt: at(-H),
+ payment: { ...order('22').payment!, expiresAt: at(-2 * H) },
+ });
+ const later = order('23', {
+ payment: { ...order('23').payment!, buyerClaimedAt: null, expiresAt: at(-60_000) },
+ });
+ const { calls } = backend([soon, late, later]);
+ boot('/tasks/deposits');
+ const soonRow = await screen.findByRole('row', { name: /CQ-21/ });
+ expect(within(soonRow).getByText('3시간 미만')).toBeInTheDocument();
+ // '입금했어요'를 누른 주문은 기한이 멈춰 픽업 지남만 단다
+ const lateRow = screen.getByRole('row', { name: /CQ-22/ });
+ expect(within(lateRow).getAllByText('지남')).toHaveLength(1);
+ // 확인 요청 보기는 '입금했어요'를 누른 주문만
+ expect(screen.queryByRole('button', { name: 'CQ-23' })).not.toBeInTheDocument();
+ expect(await screen.findByRole('tab', { name: '확인 요청 2' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ expect(screen.getByRole('tab', { name: '입금 대기 3' })).toBeInTheDocument();
+
+ await userEvent.click(screen.getByRole('tab', { name: '입금 대기 3' }));
+ expect(await screen.findByRole('button', { name: 'CQ-23' })).toBeInTheDocument();
+ expect(
+ within(screen.getByRole('row', { name: /CQ-23/ })).getByText('지남'),
+ ).toBeInTheDocument();
+ expect(calls.list.at(-1)).toMatchObject({ claimedOnly: false });
+
+ await userEvent.type(screen.getByLabelText('검색어'), '김입금{Enter}');
+ await vi.waitFor(() => expect(calls.list.at(-1)).toMatchObject({ depositorName: '김입금' }));
+ // 금액은 쉼표를 허용하고, Int 범위를 넘으면 필터를 조용히 버리지 않고 알린다
+ await userEvent.type(screen.getByRole('textbox', { name: '금액' }), '30,000{Enter}');
+ await vi.waitFor(() =>
+ expect(calls.list.at(-1)).toMatchObject({ amount: 30000, depositorName: '김입금' }),
+ );
+ expect(window.location.search).toContain('amount=30000');
+ const listCalls = calls.list.length;
+ const amountBox = screen.getByRole('textbox', { name: '금액' });
+ await userEvent.clear(amountBox);
+ await userEvent.type(amountBox, '2147483648{Enter}');
+ expect(await screen.findByText('원 단위 금액으로 입력해 주세요.')).toBeInTheDocument();
+ expect(calls.list).toHaveLength(listCalls);
+ expect(window.location.search).toContain('amount=30000');
+
+ await userEvent.click(screen.getByRole('button', { name: 'CQ-23' }));
+ const s = await sheet(/주문 CQ-23/);
+ expect(s).toHaveTextContent('누르지 않음');
+ expect(within(s).getByText('기한 지남')).toBeInTheDocument();
+ });
+
+ it('입금 기록 보기는 반환·종결을 보이고 종결 기록을 주문에 연결한다', async () => {
+ backend([]);
+ const records: DepositRecord[] = [
+ {
+ id: '31',
+ kind: 'RETURN',
+ orderId: '12',
+ orderNumber: 'CQ-12',
+ amount: 29000,
+ depositorName: '김입금',
+ depositedAt: '2026-11-19T01:00:00.000Z',
+ note: '금액 틀린 입금',
+ recordedByLabel: '운영(ops.admin)',
+ refundId: '41',
+ refundStatus: 'AWAITING_ACCOUNT',
+ createdAt: '2026-11-19T01:05:00.000Z',
+ },
+ {
+ id: '32',
+ kind: 'UNIDENTIFIED',
+ orderId: null,
+ orderNumber: null,
+ amount: 5000,
+ depositorName: '홍길동',
+ depositedAt: null,
+ note: '주인 확인 불가',
+ recordedByLabel: null,
+ refundId: null,
+ refundStatus: null,
+ createdAt: '2026-11-19T01:10:00.000Z',
+ },
+ ];
+ const inputs: unknown[] = [];
+ let linkInput: unknown;
+ server.use(
+ graphql.query('AdminTasksDepositRecords', ({ variables }) => {
+ inputs.push((variables as { input: unknown }).input);
+ return HttpResponse.json({
+ data: {
+ adminDepositRecords: {
+ items: records,
+ totalCount: 2,
+ hasMore: false,
+ nextCursor: null,
+ },
+ },
+ });
+ }),
+ gqlOk('AdminTasksOrderOptions', {
+ adminOrders: {
+ items: [{ id: '77', orderNumber: 'CQ-77', buyerName: '홍길동', totalPrice: 5000 }],
+ },
+ }),
+ graphql.mutation('AdminTasksLinkUnidentifiedDeposit', ({ variables }) => {
+ linkInput = (variables as { input: unknown }).input;
+ return HttpResponse.json({
+ data: { adminLinkUnidentifiedDeposit: { id: '32' } },
+ });
+ }),
+ );
+ boot('/tasks/deposits?view=records');
+ // 셀 내용은 다시 그릴 때 새로 마운트되므로 행(tr)을 잡는다
+ await screen.findByRole('tab', { name: '확인 요청 0' });
+ const returnRow = await screen.findByRole('row', { name: /금액 틀린 입금/ });
+ expect(within(returnRow).getByRole('link', { name: 'CQ-12' })).toHaveAttribute(
+ 'href',
+ '/orders/12',
+ );
+ expect(within(returnRow).getByRole('link', { name: '계좌 입력 대기' })).toHaveAttribute(
+ 'href',
+ '/tasks/refunds?refundId=41',
+ );
+ expect(
+ within(returnRow).queryByRole('button', { name: '주문에 연결' }),
+ ).not.toBeInTheDocument();
+
+ const closedRow = screen.getByRole('row', { name: /주인 확인 불가/ });
+ expect(within(closedRow).getByText('종결')).toBeInTheDocument();
+ await userEvent.click(within(closedRow).getByRole('button', { name: '주문에 연결' }));
+ const dialog = await screen.findByRole('dialog', { name: '주문에 연결' });
+ const submit = within(dialog).getByRole('button', { name: '반환 대상으로 연결' });
+ expect(submit).toBeDisabled();
+ await userEvent.click(within(dialog).getByRole('combobox', { name: /^주문/ }));
+ await userEvent.click(await screen.findByRole('option', { name: /CQ-77/ }));
+ await userEvent.click(submit);
+ await vi.waitFor(() => expect(linkInput).toEqual({ depositRecordId: '32', orderId: '77' }));
+ expect(
+ await screen.findByText(
+ '종결 기록을 반환 대상으로 바꿨습니다. 구매자에게 환불 계좌 입력을 요청했어요.',
+ ),
+ ).toBeInTheDocument();
+
+ await userEvent.click(screen.getByRole('combobox', { name: '기록 종류' }));
+ await userEvent.click(await screen.findByRole('option', { name: '종결' }));
+ await vi.waitFor(() =>
+ expect(inputs.at(-1)).toEqual({ limit: 20, cursor: null, kind: 'UNIDENTIFIED' }),
+ );
+ });
+
+ it('이미 연결된 종결 기록(409)이면 토스트를 보이고 다이얼로그를 닫는다', async () => {
+ backend([]);
+ server.use(
+ gqlOk('AdminTasksDepositRecords', {
+ adminDepositRecords: {
+ items: [
+ {
+ id: '32',
+ kind: 'UNIDENTIFIED',
+ orderId: null,
+ orderNumber: null,
+ amount: 5000,
+ depositorName: '홍길동',
+ depositedAt: null,
+ note: '주인 확인 불가',
+ recordedByLabel: null,
+ refundId: null,
+ refundStatus: null,
+ createdAt: '2026-11-19T01:10:00.000Z',
+ },
+ ],
+ totalCount: 1,
+ hasMore: false,
+ nextCursor: null,
+ },
+ }),
+ gqlOk('AdminTasksOrderOptions', {
+ adminOrders: {
+ items: [{ id: '77', orderNumber: 'CQ-77', buyerName: '홍길동', totalPrice: 5000 }],
+ },
+ }),
+ gqlError('AdminTasksLinkUnidentifiedDeposit', {
+ message: '이미 반환 대상으로 연결된 입금 기록입니다.',
+ code: 'DEPOSIT_RECORD_ALREADY_LINKED',
+ classification: 'CONFLICT',
+ statusCode: 409,
+ }),
+ );
+ boot('/tasks/deposits?view=records');
+ await screen.findByRole('tab', { name: '확인 요청 0' });
+ const row = await screen.findByRole('row', { name: /주인 확인 불가/ });
+ await userEvent.click(within(row).getByRole('button', { name: '주문에 연결' }));
+ const dialog = await screen.findByRole('dialog', { name: '주문에 연결' });
+ await userEvent.click(within(dialog).getByRole('combobox', { name: /^주문/ }));
+ await userEvent.click(await screen.findByRole('option', { name: /CQ-77/ }));
+ await userEvent.click(within(dialog).getByRole('button', { name: '반환 대상으로 연결' }));
+ expect(
+ await screen.findByText('이미 반환 대상으로 연결된 입금 기록입니다.'),
+ ).toBeInTheDocument();
+ await vi.waitFor(() =>
+ expect(screen.queryByRole('dialog', { name: '주문에 연결' })).not.toBeInTheDocument(),
+ );
+ });
+
+ it('없는 주문 ID로 열면 시트에 오류를 보인다', async () => {
+ backend([]);
+ boot('/tasks/deposits?orderId=999');
+ const s = await sheet(/^주문$/);
+ expect(await within(s).findByText('주문을 찾을 수 없습니다.')).toBeInTheDocument();
+ });
+
+ it('입금 확인 대상이 아닌 옛 주문은 처리됨을 보이고, 입금 기록 보기에서 열면 다음 건을 두지 않는다', async () => {
+ backend([order('50', { status: 'SUBMITTED', payment: null })]);
+ server.use(
+ gqlOk('AdminTasksDepositRecords', {
+ adminDepositRecords: { items: [], totalCount: 0, hasMore: false, nextCursor: null },
+ }),
+ gqlError('AdminTasksCreateDepositReturn', {
+ message: '주문을 찾을 수 없습니다.',
+ code: 'ORDER_NOT_FOUND',
+ classification: 'NOT_FOUND',
+ statusCode: 404,
+ }),
+ );
+ boot('/tasks/deposits?view=records&orderId=50');
+ const s = await sheet(/주문 CQ-50/);
+ expect(await within(s).findByRole('status')).toHaveTextContent(
+ '입금 확인 대기 주문이 아닙니다',
+ );
+ expect(within(s).queryByText('남은 건이 없습니다.')).not.toBeInTheDocument();
+ expect(within(s).queryByRole('button', { name: '미입금 취소' })).not.toBeInTheDocument();
+
+ // 상태와 관계없이 반환은 연결할 수 있다. 입력 오류가 아닌 거절은 토스트로 알리고 창을 둔다
+ await userEvent.click(within(s).getByRole('button', { name: '반환 대상으로 연결' }));
+ const dialog = await screen.findByRole('dialog', { name: '반환 대상으로 연결' });
+ expect(within(dialog).queryByRole('alert')).not.toBeInTheDocument();
+ expect(within(dialog).getByLabelText('입금액(원) (필수)')).toHaveValue('');
+ await userEvent.type(within(dialog).getByLabelText('입금액(원) (필수)'), '1000');
+ await userEvent.type(within(dialog).getByLabelText('입금자명 (필수)'), '김입금');
+ await userEvent.click(within(dialog).getByRole('button', { name: '반환 대상으로 연결' }));
+ expect(await screen.findByText('주문을 찾을 수 없습니다.')).toBeInTheDocument();
+ // 첫 번째가 폼의 [닫기], 마지막은 대화상자 모서리의 X
+ await userEvent.click(within(dialog).getAllByRole('button', { name: '닫기' })[0]!);
+ await vi.waitFor(() =>
+ expect(screen.queryByRole('dialog', { name: '반환 대상으로 연결' })).not.toBeInTheDocument(),
+ );
+ await userEvent.keyboard('{Escape}');
+ await vi.waitFor(() => expect(query().get('orderId')).toBeNull());
+ expect(query().get('view')).toBe('records');
+ });
+
+ it('입금액 외 입력 오류는 확인 폼 위에 보인다', async () => {
+ backend([order('12')]);
+ server.use(
+ gqlError('AdminTasksConfirmPayment', {
+ message: '메모가 너무 깁니다.',
+ code: 'TEXT_TOO_LONG',
+ classification: 'BAD_USER_INPUT',
+ statusCode: 400,
+ }),
+ );
+ boot('/tasks/deposits?orderId=12');
+ const s = await sheet(/주문 CQ-12/);
+ await userEvent.type(within(s).getByLabelText('입금액(원) (필수)'), '30000');
+ await userEvent.click(within(s).getByRole('button', { name: '입금 확인' }));
+ expect(await within(s).findByRole('alert')).toHaveTextContent('메모가 너무 깁니다.');
+ expect(screen.queryByRole('dialog', { name: '반환 대상으로 연결' })).not.toBeInTheDocument();
+ });
+
+ it('행을 눌러 시트를 열고, 다음 페이지 커서와 초기화를 입력으로 보낸다', async () => {
+ const inputs: Record[] = [];
+ backend([]);
+ server.use(
+ graphql.query('AdminTasksPendingPayments', ({ variables }) => {
+ const input = (variables as { input: Record }).input;
+ inputs.push(input);
+ return HttpResponse.json({
+ data: {
+ adminPendingPayments: {
+ items: [row(order(input.cursor ? '14' : '12'))],
+ totalCount: 2,
+ hasMore: !input.cursor,
+ nextCursor: input.cursor ? null : 'c2',
+ },
+ },
+ });
+ }),
+ gqlOk('AdminTasksOrder', { adminOrder: order('12') }),
+ );
+ boot('/tasks/deposits?view=pending&depositorName=김');
+ await userEvent.click(await screen.findByRole('row', { name: /CQ-12/ }));
+ expect(await sheet(/주문 CQ-12/)).toBeInTheDocument();
+ await vi.waitFor(() => expect(query().get('orderId')).toBe('12'));
+ await userEvent.keyboard('{Escape}');
+ await vi.waitFor(() => expect(query().get('orderId')).toBeNull());
+
+ await userEvent.click(screen.getByRole('button', { name: /다음/ }));
+ await vi.waitFor(() =>
+ expect(inputs.at(-1)).toMatchObject({ cursor: 'c2', depositorName: '김' }),
+ );
+ await userEvent.click(screen.getByRole('button', { name: '초기화' }));
+ await vi.waitFor(() =>
+ expect(inputs.at(-1)).toMatchObject({
+ cursor: null,
+ depositorName: null,
+ claimedOnly: false,
+ }),
+ );
+ });
+
+ it('목록을 읽지 못하면 이유를 보인다', async () => {
+ backend([]);
+ server.use(
+ gqlError('AdminTasksPendingPayments', {
+ message: '목록 오류',
+ code: 'X',
+ classification: 'BAD_USER_INPUT',
+ statusCode: 400,
+ }),
+ gqlError('AdminTasksDepositRecords', {
+ message: '기록 오류',
+ code: 'X',
+ classification: 'BAD_USER_INPUT',
+ statusCode: 400,
+ }),
+ );
+ boot('/tasks/deposits');
+ expect(await screen.findByRole('alert')).toHaveTextContent('목록 오류');
+ await userEvent.click(screen.getByRole('tab', { name: /입금 기록/ }));
+ expect(await screen.findByText('기록 오류')).toBeInTheDocument();
+ });
+
+ it('입금 기록 다음 페이지와 주문 연결 창 닫기', async () => {
+ backend([]);
+ const inputs: Record[] = [];
+ const record: DepositRecord = {
+ id: '32',
+ kind: 'UNIDENTIFIED',
+ orderId: null,
+ orderNumber: null,
+ amount: 5000,
+ depositorName: '홍길동',
+ depositedAt: null,
+ note: null,
+ recordedByLabel: null,
+ refundId: null,
+ refundStatus: null,
+ createdAt: '2026-11-19T01:10:00.000Z',
+ };
+ server.use(
+ graphql.query('AdminTasksDepositRecords', ({ variables }) => {
+ const input = (variables as { input: Record }).input;
+ inputs.push(input);
+ return HttpResponse.json({
+ data: {
+ adminDepositRecords: {
+ items: [record],
+ totalCount: 2,
+ hasMore: !input.cursor,
+ nextCursor: input.cursor ? null : 'r2',
+ },
+ },
+ });
+ }),
+ );
+ boot('/tasks/deposits?view=records&amount=5000');
+ await screen.findByRole('tab', { name: '확인 요청 0' });
+ const r = await screen.findByRole('row', { name: /홍길동/ });
+ // 입금 기록 보기에 없는 금액 필터는 초기화 대상으로 세지 않는다
+ expect(screen.queryByRole('button', { name: '초기화' })).not.toBeInTheDocument();
+ await userEvent.click(within(r).getByRole('button', { name: '주문에 연결' }));
+ await screen.findByRole('dialog', { name: '주문에 연결' });
+ await userEvent.keyboard('{Escape}');
+ await vi.waitFor(() =>
+ expect(screen.queryByRole('dialog', { name: '주문에 연결' })).not.toBeInTheDocument(),
+ );
+ await userEvent.click(screen.getByRole('button', { name: /다음/ }));
+ await vi.waitFor(() => expect(inputs.at(-1)).toMatchObject({ cursor: 'r2' }));
+ });
+
+ it('세션이 없으면 로그인 뒤 같은 딥링크로 돌아와 시트를 연다', async () => {
+ backend([order('12')]);
+ server.use(
+ restError('/admin/refresh', 401, '없음', 'MISSING_REFRESH_TOKEN'),
+ restOk('/admin/login', session),
+ );
+ boot('/tasks/deposits?orderId=12');
+ expect(await screen.findByText('관리자 로그인')).toBeInTheDocument();
+ expect(query().get('redirect')).toBe('/tasks/deposits?orderId=12');
+ await userEvent.type(screen.getByLabelText('아이디'), 'ops.admin');
+ await userEvent.type(screen.getByLabelText('비밀번호'), 'Password1!');
+ await userEvent.click(screen.getByRole('button', { name: '로그인' }));
+ expect(await sheet(/주문 CQ-12/)).toBeInTheDocument();
+ expect(window.location.pathname).toBe('/tasks/deposits');
+ expect(query().get('orderId')).toBe('12');
+ });
+});
diff --git a/src/features/tasks/pages/refunds-page.tsx b/src/features/tasks/pages/refunds-page.tsx
new file mode 100644
index 0000000..fadf666
--- /dev/null
+++ b/src/features/tasks/pages/refunds-page.tsx
@@ -0,0 +1,182 @@
+import { useQuery } from '@tanstack/react-query';
+import { type ColumnDef } from '@tanstack/react-table';
+
+import { refundKindLabel } from '@/features/orders';
+import { messageFor } from '@/shared/api';
+import { formatCount, formatKrw } from '@/shared/lib/format';
+import { formatKst } from '@/shared/lib/kst';
+import { Button } from '@/shared/ui/button';
+import { Card } from '@/shared/ui/card';
+import { CursorPager } from '@/shared/ui/cursor-pager';
+import { DataTable } from '@/shared/ui/data-table';
+import { FilterBar } from '@/shared/ui/filter-bar';
+import { Tabs, TabsList, TabsTrigger } from '@/shared/ui/tabs';
+
+import { type RefundRow, refundsQueryOptions, taskCountsQueryOptions } from '../api/queries';
+import { RefundSheet } from '../components/refund-sheet';
+import { TasksHeader } from '../components/task-counts';
+import { REFUND_KIND_VALUES, nextTask } from '../meta';
+import {
+ REFUND_VIEWS,
+ type RefundsSearch,
+ type RefundsSearchInput,
+ refundView,
+ toRefundListInput,
+} from '../search';
+
+interface Props {
+ search: RefundsSearch;
+ onSearchChange: (next: RefundsSearchInput) => void;
+}
+
+export function RefundsTasksPage({ search, onSearchChange }: Props) {
+ const view = refundView(search);
+ const { refundId, ...listSearch } = search;
+ const patch = (p: Partial) =>
+ onSearchChange({ ...listSearch, ...p, cursor: undefined });
+ const open = (id: string | undefined) => onSearchChange({ ...listSearch, refundId: id });
+ const counts = useQuery(taskCountsQueryOptions());
+ const list = useQuery(refundsQueryOptions(toRefundListInput(search)));
+ const viewCount = {
+ AWAITING_TRANSFER: counts.data?.refundsAwaitingTransfer,
+ AWAITING_ACCOUNT: counts.data?.refundsAwaitingAccount,
+ };
+
+ const columns: ColumnDef[] = [
+ {
+ id: 'requestedAt',
+ header: '요청 시각',
+ cell: ({ row }) => formatKst(row.original.requestedAt),
+ },
+ {
+ id: 'order',
+ header: '주문',
+ cell: ({ row }) => (
+
+
+
+ {[row.original.storeName, row.original.productName].filter(Boolean).join(' · ')}
+
+
+ ),
+ },
+ { id: 'kind', header: '종류', cell: ({ row }) => refundKindLabel(row.original.kind) },
+ {
+ id: 'amount',
+ header: '금액',
+ meta: { align: 'right' },
+ cell: ({ row }) => formatKrw(row.original.amount),
+ },
+ view === 'AWAITING_TRANSFER'
+ ? {
+ id: 'account',
+ header: '환불 계좌',
+ cell: ({ row }) => {
+ const r = row.original;
+ return r.bank && r.accountNumberMasked
+ ? `${r.bank.name} ${r.accountNumberMasked} (${r.accountHolder ?? '-'})`
+ : '-';
+ },
+ }
+ : {
+ id: 'buyer',
+ header: '주문자 연락처',
+ cell: ({ row }) => `${row.original.buyerName} · ${row.original.buyerPhone}`,
+ },
+ {
+ id: 'submittedAt',
+ header: '계좌 입력',
+ cell: ({ row }) =>
+ row.original.accountSubmittedAt ? formatKst(row.original.accountSubmittedAt) : '-',
+ },
+ ];
+
+ return (
+ <>
+
+
+ onSearchChange({ status: search.status, limit: search.limit })}
+ >
+ patch({ status: v as RefundsSearch['status'] })}>
+
+ {REFUND_VIEWS.map((v) => (
+
+ {v.label}
+ {viewCount[v.value] !== undefined && ' '}
+ {viewCount[v.value] !== undefined && (
+ {formatCount(viewCount[v.value]!)}
+ )}
+
+ ))}
+
+
+
+ {[
+ { value: undefined, label: '전체' },
+ ...REFUND_KIND_VALUES.map((value) => ({ value, label: refundKindLabel(value) })),
+ ].map((k) => (
+
+ ))}
+
+
+ {list.isError ? (
+
+ {messageFor(list.error)}
+
+ ) : (
+ r.id}
+ isLoading={list.isPending}
+ emptyMessage={
+ view === 'AWAITING_TRANSFER'
+ ? '송금을 기다리는 환불이 없습니다.'
+ : '계좌 입력을 기다리는 환불이 없습니다.'
+ }
+ onRowClick={(r) => open(r.id)}
+ />
+ )}
+ {list.data && (
+ onSearchChange({ ...listSearch, cursor })}
+ />
+ )}
+
+
+ nextTask(
+ list.data?.items.map((r) => r.id),
+ list.data?.totalCount,
+ id,
+ )
+ }
+ onOpen={open}
+ />
+ >
+ );
+}
diff --git a/src/features/tasks/pages/refunds-settlements.spec.tsx b/src/features/tasks/pages/refunds-settlements.spec.tsx
new file mode 100644
index 0000000..dd092be
--- /dev/null
+++ b/src/features/tasks/pages/refunds-settlements.spec.tsx
@@ -0,0 +1,553 @@
+import { render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { HttpResponse, graphql } from 'msw';
+
+import { App } from '@/app/app';
+import { useAuthStore } from '@/features/auth';
+import { forgetSearches } from '@/shared/lib/list-return';
+import { formatKst } from '@/shared/lib/kst';
+import { gqlError, gqlOk, restOk } from '@/test/msw/graphql';
+import { server } from '@/test/msw/server';
+
+import {
+ type RefundDetail,
+ type RefundRow,
+ type SettlementDetail,
+ type SettlementRow,
+} from '../api/queries';
+
+const me = {
+ accountId: '1',
+ username: 'ops.admin',
+ email: null,
+ name: '운영',
+ status: 'ACTIVE',
+ mustChangePassword: false,
+ lastLoginAt: null,
+ createdAt: '2026-09-27T00:00:00.000Z',
+};
+
+function boot(path: string) {
+ server.use(
+ restOk('/admin/refresh', {
+ accessToken: 'at',
+ tokenType: 'Bearer',
+ accountStatus: 'ACTIVE',
+ mustChangePassword: false,
+ }),
+ gqlOk('AdminMe', { adminMe: me }),
+ );
+ window.history.pushState({}, '', path);
+ render();
+}
+
+const query = () => new URLSearchParams(window.location.search);
+const bank = { code: '004', name: 'KB국민은행' };
+
+const refund = (
+ id: string,
+ over: Partial = {},
+): RefundDetail['refund'] => ({
+ id,
+ kind: 'CANCEL',
+ amount: 30000,
+ status: 'AWAITING_TRANSFER',
+ bank,
+ accountHolder: '김구매',
+ accountNumberMasked: '****5678',
+ requestedAt: '2026-11-18T03:00:00.000Z',
+ accountSubmittedAt: '2026-11-18T04:00:00.000Z',
+ completedAt: null,
+ orderId: `9${id}`,
+ orderNumber: `CQ-9${id}`,
+ buyerName: '김구매',
+ buyerPhone: '010-1234-5678',
+ storeName: '루미 케이크',
+ productName: '레터링 케이크',
+ completedByLabel: null,
+ completeNote: null,
+ ...over,
+});
+const toRow = ({
+ completedAt: _c,
+ completedByLabel: _l,
+ completeNote: _n,
+ ...r
+}: RefundDetail['refund']): RefundRow => r;
+
+/** 환불을 들고 있는 가짜 BE. 송금 완료하면 송금 대기 목록에서 빠진다 */
+function refundBackend(initial: RefundDetail['refund'][]) {
+ const refunds = new Map(initial.map((r) => [r.id, r]));
+ const inputs: Record[] = [];
+ server.use(
+ graphql.query('AdminTasksRefunds', ({ variables }) => {
+ const input = (variables as { input: Record }).input;
+ inputs.push(input);
+ const items = [...refunds.values()]
+ .filter((r) => r.status === input.status)
+ .filter((r) => !input.kind || r.kind === input.kind)
+ .map(toRow);
+ return HttpResponse.json({
+ data: {
+ adminRefunds: { items, totalCount: items.length, hasMore: false, nextCursor: null },
+ },
+ });
+ }),
+ graphql.query('AdminTasksRefund', ({ variables }) => {
+ const r = refunds.get((variables as { refundId: string }).refundId)!;
+ return HttpResponse.json({
+ data: {
+ adminRefund: {
+ refund: r,
+ accountNumber: r.bank ? '12345678' : null,
+ depositRecord:
+ r.kind === 'DEPOSIT_RETURN'
+ ? { id: '31', depositorName: '김입금', depositedAt: null, note: '늦은 입금' }
+ : null,
+ },
+ },
+ });
+ }),
+ );
+ return { refunds, inputs };
+}
+
+describe('처리 대기 — 환불', () => {
+ beforeEach(() => {
+ useAuthStore.setState({ status: 'unknown', accessToken: null, mustChangePassword: false });
+ forgetSearches();
+ });
+
+ it('딥링크 환불을 시트로 열어 전체 계좌를 복사하고 송금 완료 뒤 다음 건으로 간다', async () => {
+ const { refunds } = refundBackend([refund('5'), refund('6')]);
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
+ let completeInput: unknown;
+ server.use(
+ graphql.mutation('AdminTasksCompleteRefund', ({ variables }) => {
+ completeInput = (variables as { input: unknown }).input;
+ refunds.set('5', {
+ ...refunds.get('5')!,
+ status: 'COMPLETED',
+ completedAt: '2026-11-19T01:00:00.000Z',
+ completedByLabel: '운영(ops.admin)',
+ completeNote: '국민 이체',
+ });
+ return HttpResponse.json({
+ data: { adminCompleteRefund: { id: '5', status: 'COMPLETED' } },
+ });
+ }),
+ );
+ boot('/tasks/refunds?refundId=5');
+ const s = await screen.findByRole('dialog', { name: /취소 환불 30,000원/ });
+ expect(s).toHaveTextContent('KB국민은행 12345678 (김구매)');
+ expect(within(s).getByRole('link', { name: 'CQ-95' })).toHaveAttribute('href', '/orders/95');
+ // 목록은 끝 4자리만 보인다
+ expect(screen.getAllByText('KB국민은행 ****5678 (김구매)')).toHaveLength(2);
+
+ await userEvent.click(within(s).getByRole('button', { name: '계좌번호 복사' }));
+ expect(writeText).toHaveBeenCalledWith('12345678');
+ expect(await screen.findByText('계좌번호를 복사했습니다.')).toBeInTheDocument();
+
+ await userEvent.click(within(s).getByRole('button', { name: '송금 완료' }));
+ const dialog = await screen.findByRole('dialog', { name: '송금 완료로 처리할까요?' });
+ expect(dialog).toHaveTextContent('KB국민은행 12345678(김구매)로 30,000원을 송금했나요?');
+ await userEvent.type(within(dialog).getByLabelText('메모 (선택)'), '국민 이체');
+ await userEvent.click(within(dialog).getByRole('button', { name: '송금 완료' }));
+ await vi.waitFor(() => expect(completeInput).toEqual({ refundId: '5', note: '국민 이체' }));
+ expect(await within(s).findByRole('status')).toHaveTextContent(
+ `송금 완료 · 운영(ops.admin) · ${formatKst('2026-11-19T01:00:00.000Z', true)} · 국민 이체`,
+ );
+ await userEvent.click(within(s).getByRole('button', { name: '다음 건 (1건 남음)' }));
+ await vi.waitFor(() => expect(query().get('refundId')).toBe('6'));
+ Reflect.deleteProperty(navigator, 'clipboard');
+ });
+
+ it('이미 송금이 끝났으면(409) 토스트를 보이고 처리자·시각을 다시 읽어 보인다', async () => {
+ const { refunds } = refundBackend([refund('5')]);
+ server.use(
+ graphql.mutation('AdminTasksCompleteRefund', () => {
+ refunds.set('5', {
+ ...refunds.get('5')!,
+ status: 'COMPLETED',
+ completedAt: '2026-11-19T00:30:00.000Z',
+ completedByLabel: null,
+ });
+ return HttpResponse.json({
+ data: null,
+ errors: [
+ {
+ message: '이미 송금이 끝난 환불입니다.',
+ extensions: {
+ code: 'REFUND_ALREADY_COMPLETED',
+ classification: 'CONFLICT',
+ statusCode: 409,
+ },
+ },
+ ],
+ });
+ }),
+ );
+ boot('/tasks/refunds?refundId=5');
+ const s = await screen.findByRole('dialog', { name: /취소 환불/ });
+ await userEvent.click(within(s).getByRole('button', { name: '송금 완료' }));
+ const dialog = await screen.findByRole('dialog', { name: '송금 완료로 처리할까요?' });
+ await userEvent.click(within(dialog).getByRole('button', { name: '송금 완료' }));
+ expect(await screen.findByText('이미 송금이 끝난 환불입니다.')).toBeInTheDocument();
+ expect(await within(s).findByRole('status')).toHaveTextContent(
+ `송금 완료 · 관리자 · ${formatKst('2026-11-19T00:30:00.000Z', true)}`,
+ );
+ expect(within(s).getByText('남은 건이 없습니다.')).toBeInTheDocument();
+ });
+
+ it('송금 완료가 입력 오류로 거절되면 확인 창을 열어 둔다', async () => {
+ refundBackend([refund('5')]);
+ server.use(
+ gqlError('AdminTasksCompleteRefund', {
+ message: '환불 계좌가 입력되지 않아 송금 완료로 처리할 수 없어요.',
+ code: 'REFUND_NOT_READY',
+ classification: 'BAD_USER_INPUT',
+ statusCode: 400,
+ }),
+ );
+ boot('/tasks/refunds?refundId=5');
+ const s = await screen.findByRole('dialog', { name: /취소 환불/ });
+ await userEvent.click(within(s).getByRole('button', { name: '송금 완료' }));
+ const dialog = await screen.findByRole('dialog', { name: '송금 완료로 처리할까요?' });
+ await userEvent.click(within(dialog).getByRole('button', { name: '송금 완료' }));
+ expect(
+ await screen.findByText('환불 계좌가 입력되지 않아 송금 완료로 처리할 수 없어요.'),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('dialog', { name: '송금 완료로 처리할까요?' })).toBeInTheDocument();
+ });
+
+ it('복사에 실패하면 직접 옮겨 적으라고 알리고, 행을 눌러 열고 다음 페이지·초기화를 보낸다', async () => {
+ const { inputs } = refundBackend([refund('5')]);
+ Object.defineProperty(navigator, 'clipboard', { value: undefined, configurable: true });
+ Object.defineProperty(document, 'execCommand', { value: () => false, configurable: true });
+ server.use(
+ graphql.query('AdminTasksRefunds', ({ variables }) => {
+ const input = (variables as { input: Record }).input;
+ inputs.push(input);
+ return HttpResponse.json({
+ data: {
+ adminRefunds: {
+ items: [toRow(refund('5'))],
+ totalCount: 2,
+ hasMore: !input.cursor,
+ nextCursor: input.cursor ? null : 'f2',
+ },
+ },
+ });
+ }),
+ );
+ boot('/tasks/refunds?kind=CANCEL');
+ await userEvent.click(await screen.findByRole('row', { name: /CQ-95/ }));
+ const s = await screen.findByRole('dialog', { name: /취소 환불/ });
+ await userEvent.click(within(s).getByRole('button', { name: '계좌번호 복사' }));
+ expect(
+ await screen.findByText('복사하지 못했습니다. 계좌번호를 직접 옮겨 적어 주세요.'),
+ ).toBeInTheDocument();
+ await userEvent.keyboard('{Escape}');
+ await vi.waitFor(() => expect(query().get('refundId')).toBeNull());
+
+ await userEvent.click(screen.getByRole('button', { name: /다음/ }));
+ await vi.waitFor(() => expect(inputs.at(-1)).toMatchObject({ cursor: 'f2', kind: 'CANCEL' }));
+ await userEvent.click(screen.getByRole('button', { name: '초기화' }));
+ await vi.waitFor(() => expect(inputs.at(-1)).toMatchObject({ cursor: null, kind: null }));
+ Reflect.deleteProperty(navigator, 'clipboard');
+ Reflect.deleteProperty(document, 'execCommand');
+ });
+
+ it('목록을 읽지 못하면 이유를 보인다', async () => {
+ server.use(
+ gqlError('AdminTasksRefunds', {
+ message: '환불 목록 오류',
+ code: 'X',
+ classification: 'BAD_USER_INPUT',
+ statusCode: 400,
+ }),
+ );
+ boot('/tasks/refunds');
+ expect(await screen.findByRole('alert')).toHaveTextContent('환불 목록 오류');
+ });
+
+ it('계좌 입력 대기는 연락처를 보이고 송금 완료를 막으며, 종류 칩을 입력으로 보낸다', async () => {
+ const waiting = refund('7', {
+ kind: 'DEPOSIT_RETURN',
+ status: 'AWAITING_ACCOUNT',
+ bank: null,
+ accountHolder: null,
+ accountNumberMasked: null,
+ accountSubmittedAt: null,
+ });
+ const { inputs } = refundBackend([waiting, refund('8')]);
+ boot('/tasks/refunds?status=AWAITING_ACCOUNT');
+ const row = await screen.findByRole('row', { name: /CQ-97/ });
+ expect(row).toHaveTextContent('김구매 · 010-1234-5678');
+ expect(row).toHaveTextContent('입금 반환');
+ expect(inputs.at(-1)).toEqual({
+ limit: 20,
+ cursor: null,
+ status: 'AWAITING_ACCOUNT',
+ kind: null,
+ });
+
+ await userEvent.click(within(row).getByRole('button', { name: 'CQ-97' }));
+ const s = await screen.findByRole('dialog', { name: /입금 반환/ });
+ expect(s).toHaveTextContent('구매자가 아직 입력하지 않았습니다.');
+ expect(s).toHaveTextContent('김입금');
+ expect(s).toHaveTextContent('늦은 입금');
+ expect(within(s).getByRole('button', { name: '송금 완료' })).toBeDisabled();
+ expect(s).toHaveTextContent('계좌 입력 전이라 송금할 수 없어요.');
+ await userEvent.keyboard('{Escape}');
+
+ await userEvent.click(screen.getByRole('button', { name: '입금 반환' }));
+ await vi.waitFor(() =>
+ expect(inputs.at(-1)).toMatchObject({ status: 'AWAITING_ACCOUNT', kind: 'DEPOSIT_RETURN' }),
+ );
+ expect(screen.getByRole('button', { name: '입금 반환' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await userEvent.click(screen.getByRole('tab', { name: '송금 대기 0' }));
+ await vi.waitFor(() =>
+ expect(inputs.at(-1)).toMatchObject({ status: 'AWAITING_TRANSFER', kind: 'DEPOSIT_RETURN' }),
+ );
+ });
+});
+
+const settlement = (id: string, over: Partial = {}): SettlementDetail => ({
+ id,
+ storeId: `5${id}`,
+ storeName: `매장 ${id}`,
+ periodStart: '2026-11-09',
+ periodEnd: '2026-11-15',
+ orderCount: 3,
+ settlementBaseAmount: 90000,
+ commissionAmount: 9000,
+ payoutAmount: 81000,
+ status: 'PENDING',
+ paidAt: null,
+ accountRegistered: true,
+ paidByLabel: null,
+ paidNote: null,
+ paidAccount: null,
+ currentAccount: { bank, accountHolder: '루미 대표', accountNumber: '99887766' },
+ ...over,
+});
+const toSettlementRow = (s: SettlementDetail): SettlementRow => ({
+ id: s.id,
+ storeId: s.storeId,
+ storeName: s.storeName,
+ periodStart: s.periodStart,
+ periodEnd: s.periodEnd,
+ orderCount: s.orderCount,
+ settlementBaseAmount: s.settlementBaseAmount,
+ commissionAmount: s.commissionAmount,
+ payoutAmount: s.payoutAmount,
+ status: s.status,
+ accountRegistered: s.accountRegistered,
+ createdAt: '2026-11-16T20:00:00.000Z',
+});
+
+function settlementBackend(initial: SettlementDetail[]) {
+ const settlements = new Map(initial.map((s) => [s.id, s]));
+ const inputs: Record[] = [];
+ server.use(
+ graphql.query('AdminTasksSettlements', ({ variables }) => {
+ inputs.push((variables as { input: Record }).input);
+ const items = [...settlements.values()]
+ .filter((s) => s.status === 'PENDING')
+ .map(toSettlementRow);
+ return HttpResponse.json({
+ data: {
+ adminSettlements: { items, totalCount: items.length, hasMore: false, nextCursor: null },
+ },
+ });
+ }),
+ graphql.query('AdminTasksSettlement', ({ variables }) =>
+ HttpResponse.json({
+ data: {
+ adminSettlement: settlements.get((variables as { settlementId: string }).settlementId),
+ },
+ }),
+ ),
+ );
+ return { settlements, inputs };
+}
+
+describe('처리 대기 — 정산 송금', () => {
+ beforeEach(() => {
+ useAuthStore.setState({ status: 'unknown', accessToken: null, mustChangePassword: false });
+ forgetSearches();
+ });
+
+ it('경보 딥링크의 기간으로 거르고, 계좌 없는 정산은 비활성 + 매장 링크다', async () => {
+ const { inputs } = settlementBackend([
+ settlement('1'),
+ settlement('2', { accountRegistered: false, currentAccount: null }),
+ ]);
+ boot('/tasks/settlements?periodStart=2026-11-09');
+ const noAccount = await screen.findByRole('row', { name: /매장 2/ });
+ expect(inputs.at(-1)).toEqual({
+ limit: 20,
+ cursor: null,
+ status: 'PENDING',
+ periodStart: '2026-11-09',
+ });
+ expect(screen.getByLabelText('정산 기간 시작(월요일)')).toHaveValue('2026-11-09');
+ expect(within(noAccount).getByRole('button', { name: '송금 처리' })).toBeDisabled();
+ expect(
+ within(noAccount).getByRole('link', { name: '매장에서 정산 계좌 등록' }),
+ ).toHaveAttribute('href', '/stores/52');
+ const ok = screen.getByRole('row', { name: /매장 1/ });
+ expect(within(ok).getByRole('button', { name: '송금 처리' })).toBeEnabled();
+
+ await userEvent.click(noAccount);
+ const s = await screen.findByRole('dialog', { name: /매장 2 정산/ });
+ expect(within(s).getByRole('button', { name: '송금 완료' })).toBeDisabled();
+ expect(s).toHaveTextContent('정산 계좌가 없어 송금 완료로 처리할 수 없어요.');
+ await userEvent.keyboard('{Escape}');
+
+ await userEvent.click(screen.getByRole('button', { name: '초기화' }));
+ await vi.waitFor(() => expect(inputs.at(-1)).toMatchObject({ periodStart: null }));
+ });
+
+ it('기간을 고르면 그 날짜로, 다음 페이지는 커서로 다시 읽는다', async () => {
+ const inputs: Record[] = [];
+ server.use(
+ graphql.query('AdminTasksSettlements', ({ variables }) => {
+ const input = (variables as { input: Record }).input;
+ inputs.push(input);
+ return HttpResponse.json({
+ data: {
+ adminSettlements: {
+ items: [toSettlementRow(settlement('1'))],
+ totalCount: 2,
+ hasMore: !input.cursor,
+ nextCursor: input.cursor ? null : 's2',
+ },
+ },
+ });
+ }),
+ );
+ boot('/tasks/settlements');
+ await screen.findByRole('row', { name: /매장 1/ });
+ await userEvent.click(screen.getByRole('button', { name: /다음/ }));
+ await vi.waitFor(() => expect(inputs.at(-1)).toMatchObject({ cursor: 's2' }));
+ await userEvent.type(screen.getByLabelText('정산 기간 시작(월요일)'), '2026-11-16');
+ await vi.waitFor(() =>
+ expect(inputs.at(-1)).toMatchObject({ cursor: null, periodStart: '2026-11-16' }),
+ );
+ });
+
+ it('목록을 읽지 못하면 이유를 보인다', async () => {
+ server.use(
+ gqlError('AdminTasksSettlements', {
+ message: '정산 목록 오류',
+ code: 'X',
+ classification: 'BAD_USER_INPUT',
+ statusCode: 400,
+ }),
+ );
+ boot('/tasks/settlements');
+ expect(await screen.findByRole('alert')).toHaveTextContent('정산 목록 오류');
+ });
+
+ it('송금 완료 뒤 계좌가 있는 다음 정산으로 넘어간다', async () => {
+ const { settlements } = settlementBackend([
+ settlement('1'),
+ settlement('2', { accountRegistered: false, currentAccount: null }),
+ settlement('3'),
+ ]);
+ let input: unknown;
+ server.use(
+ graphql.mutation('AdminMarkSettlementPaid', ({ variables }) => {
+ input = (variables as { input: unknown }).input;
+ settlements.set('1', {
+ ...settlements.get('1')!,
+ status: 'PAID',
+ paidAt: '2026-11-19T01:00:00.000Z',
+ paidByLabel: '운영(ops.admin)',
+ paidAccount: { bank, accountHolder: '루미 대표', accountNumberMasked: '****7766' },
+ });
+ return HttpResponse.json({
+ data: { adminMarkSettlementPaid: { id: '1', status: 'PAID' } },
+ });
+ }),
+ );
+ boot('/tasks/settlements');
+ const row = await screen.findByRole('row', { name: /매장 1/ });
+ await userEvent.click(within(row).getByRole('button', { name: '송금 처리' }));
+ const s = await screen.findByRole('dialog', { name: /매장 1 정산 81,000원/ });
+ expect(s).toHaveTextContent('KB국민은행 99887766 (루미 대표)');
+ await userEvent.click(within(s).getByRole('button', { name: '송금 완료' }));
+ const dialog = await screen.findByRole('dialog', { name: '송금 완료로 처리할까요?' });
+ expect(dialog).toHaveTextContent('KB국민은행 99887766(루미 대표)로 81,000원을 송금했나요?');
+ await userEvent.click(within(dialog).getByRole('button', { name: '송금 완료' }));
+ await vi.waitFor(() => expect(input).toEqual({ settlementId: '1', note: null }));
+ expect(await within(s).findByRole('status')).toHaveTextContent(
+ `송금 완료 · 운영(ops.admin) · ${formatKst('2026-11-19T01:00:00.000Z', true)} · KB국민은행 ****7766(루미 대표)`,
+ );
+ // 남은 2건 중 계좌가 없는 2번은 건너뛴다
+ await userEvent.click(within(s).getByRole('button', { name: '다음 건 (2건 남음)' }));
+ await vi.waitFor(() => expect(query().get('settlementId')).toBe('3'));
+ });
+
+ it('이미 송금 완료된 정산(409)이면 토스트를 보이고 다시 읽는다', async () => {
+ const { settlements } = settlementBackend([settlement('1')]);
+ server.use(
+ graphql.mutation('AdminMarkSettlementPaid', () => {
+ settlements.set('1', {
+ ...settlements.get('1')!,
+ status: 'PAID',
+ paidAt: '2026-11-19T00:10:00.000Z',
+ paidByLabel: '김관리(kim)',
+ paidNote: '먼저 처리',
+ });
+ return HttpResponse.json({
+ data: null,
+ errors: [
+ {
+ message: '이미 송금 완료로 처리된 정산이에요.',
+ extensions: {
+ code: 'SETTLEMENT_ALREADY_PAID',
+ classification: 'CONFLICT',
+ statusCode: 409,
+ },
+ },
+ ],
+ });
+ }),
+ );
+ boot('/tasks/settlements?settlementId=1');
+ const s = await screen.findByRole('dialog', { name: /매장 1 정산/ });
+ await userEvent.click(within(s).getByRole('button', { name: '송금 완료' }));
+ const dialog = await screen.findByRole('dialog', { name: '송금 완료로 처리할까요?' });
+ await userEvent.click(within(dialog).getByRole('button', { name: '송금 완료' }));
+ expect(await screen.findByText('이미 송금 완료로 처리된 정산이에요.')).toBeInTheDocument();
+ expect(await within(s).findByRole('status')).toHaveTextContent(
+ `송금 완료 · 김관리(kim) · ${formatKst('2026-11-19T00:10:00.000Z', true)} · 먼저 처리`,
+ );
+ });
+
+ it('송금 완료가 입력 오류로 거절되면 확인 창을 열어 둔다', async () => {
+ settlementBackend([settlement('1')]);
+ server.use(
+ gqlError('AdminMarkSettlementPaid', {
+ message: '메모가 너무 깁니다.',
+ code: 'TEXT_TOO_LONG',
+ classification: 'BAD_USER_INPUT',
+ statusCode: 400,
+ }),
+ );
+ boot('/tasks/settlements?settlementId=1');
+ const s = await screen.findByRole('dialog', { name: /매장 1 정산/ });
+ await userEvent.click(within(s).getByRole('button', { name: '송금 완료' }));
+ const dialog = await screen.findByRole('dialog', { name: '송금 완료로 처리할까요?' });
+ await userEvent.click(within(dialog).getByRole('button', { name: '송금 완료' }));
+ expect(await screen.findByText('메모가 너무 깁니다.')).toBeInTheDocument();
+ expect(screen.getByRole('dialog', { name: '송금 완료로 처리할까요?' })).toBeInTheDocument();
+ });
+});
diff --git a/src/features/tasks/pages/settlements-page.tsx b/src/features/tasks/pages/settlements-page.tsx
new file mode 100644
index 0000000..52a2738
--- /dev/null
+++ b/src/features/tasks/pages/settlements-page.tsx
@@ -0,0 +1,158 @@
+import { useQuery } from '@tanstack/react-query';
+import { type ColumnDef } from '@tanstack/react-table';
+
+import { messageFor } from '@/shared/api';
+import { formatCount, formatKrw } from '@/shared/lib/format';
+import { formatKst } from '@/shared/lib/kst';
+import { Button } from '@/shared/ui/button';
+import { Card } from '@/shared/ui/card';
+import { CursorPager } from '@/shared/ui/cursor-pager';
+import { DataTable } from '@/shared/ui/data-table';
+import { FilterBar } from '@/shared/ui/filter-bar';
+import { FilterField } from '@/shared/ui/filter-field';
+import { Input } from '@/shared/ui/input';
+import { StatusPill } from '@/shared/ui/status-pill';
+
+import { type SettlementRow, settlementsQueryOptions } from '../api/queries';
+import { SettlementSheet, StoreAccountLink } from '../components/settlement-sheet';
+import { TasksHeader } from '../components/task-counts';
+import { nextTask } from '../meta';
+import {
+ type SettlementsSearch,
+ type SettlementsSearchInput,
+ toSettlementListInput,
+} from '../search';
+
+interface Props {
+ search: SettlementsSearch;
+ onSearchChange: (next: SettlementsSearchInput) => void;
+}
+
+export function SettlementsTasksPage({ search, onSearchChange }: Props) {
+ const { settlementId, ...listSearch } = search;
+ const open = (id: string | undefined) => onSearchChange({ ...listSearch, settlementId: id });
+ const list = useQuery(settlementsQueryOptions(toSettlementListInput(search)));
+
+ const columns: ColumnDef[] = [
+ {
+ id: 'period',
+ header: '정산 기간',
+ cell: ({ row }) => `${row.original.periodStart} ~ ${row.original.periodEnd}`,
+ },
+ { id: 'store', header: '매장', cell: ({ row }) => row.original.storeName },
+ {
+ id: 'orders',
+ header: '주문',
+ meta: { align: 'right' },
+ cell: ({ row }) => `${formatCount(row.original.orderCount)}건`,
+ },
+ {
+ id: 'commission',
+ header: '수수료',
+ meta: { align: 'right' },
+ cell: ({ row }) => formatKrw(row.original.commissionAmount),
+ },
+ {
+ id: 'payout',
+ header: '송금액',
+ meta: { align: 'right' },
+ cell: ({ row }) => (
+ {formatKrw(row.original.payoutAmount)}
+ ),
+ },
+ {
+ id: 'account',
+ header: '정산 계좌',
+ cell: ({ row }) =>
+ row.original.accountRegistered ? (
+ 등록
+ ) : (
+
+ 없음
+ e.stopPropagation()}>
+
+
+
+ ),
+ },
+ { id: 'createdAt', header: '생성', cell: ({ row }) => formatKst(row.original.createdAt) },
+ {
+ id: 'actions',
+ header: '',
+ cell: ({ row }) => (
+
+ ),
+ },
+ ];
+
+ return (
+ <>
+
+
+ onSearchChange({ limit: search.limit })}
+ >
+
+
+ onSearchChange({
+ ...listSearch,
+ periodStart: e.target.value || undefined,
+ cursor: undefined,
+ })
+ }
+ />
+
+
+ {list.isError ? (
+
+ {messageFor(list.error)}
+
+ ) : (
+ r.id}
+ isLoading={list.isPending}
+ emptyMessage="송금을 기다리는 정산이 없습니다."
+ onRowClick={(r) => open(r.id)}
+ />
+ )}
+ {list.data && (
+ onSearchChange({ ...listSearch, cursor })}
+ />
+ )}
+
+
+ // 계좌가 없는 정산은 송금 처리할 수 없어 다음 건으로 고르지 않는다
+ nextTask(
+ list.data?.items.filter((s) => s.accountRegistered).map((s) => s.id),
+ list.data?.totalCount,
+ id,
+ )
+ }
+ onOpen={open}
+ />
+ >
+ );
+}
diff --git a/src/features/tasks/search.spec.ts b/src/features/tasks/search.spec.ts
new file mode 100644
index 0000000..20d0bba
--- /dev/null
+++ b/src/features/tasks/search.spec.ts
@@ -0,0 +1,120 @@
+import {
+ depositsSearchSchema,
+ parseWon,
+ refundsSearchSchema,
+ settlementsSearchSchema,
+ toDepositRecordInput,
+ toPendingPaymentInput,
+ toRefundListInput,
+ toSettlementListInput,
+} from './search';
+
+describe('parseWon', () => {
+ it.each([
+ ['0', 0],
+ ['12000', 12000],
+ ['12,000', 12000],
+ [' 5 ', 5],
+ ['2147483647', 2147483647],
+ ['2147483648', null],
+ ['-1', null],
+ ['1.5', null],
+ ['1e3', null],
+ ['', null],
+ [' ', null],
+ ['abc', null],
+ ])('"%s" → %s', (raw, want) => {
+ expect(parseWon(raw)).toBe(want);
+ });
+});
+
+describe('입금 탭 검색 파라미터', () => {
+ it('금액 "0"과 주문 ID "0"을 버리지 않고 입력으로 보낸다', () => {
+ const s = depositsSearchSchema.parse({ view: 'pending', amount: '0', orderId: '0' });
+ expect(s.amount).toBe('0');
+ expect(s.orderId).toBe('0');
+ expect(toPendingPaymentInput(s)).toEqual({
+ limit: 20,
+ cursor: null,
+ claimedOnly: false,
+ amount: 0,
+ depositorName: null,
+ });
+ });
+
+ it('주소창이 숫자로 파싱한 금액도 문자열로 받는다', () => {
+ expect(depositsSearchSchema.parse({ amount: 0 }).amount).toBe('0');
+ });
+
+ it.each(['-1', '1.5', 'abc', '2147483648'])('형식이 틀린 금액 "%s"는 필터 없음', (amount) => {
+ expect(depositsSearchSchema.parse({ amount }).amount).toBeUndefined();
+ });
+
+ it('보기 기본값은 확인 요청(claimedOnly)이고 모르는 보기는 버린다', () => {
+ const s = depositsSearchSchema.parse({ view: 'nope' });
+ expect(s.view).toBeUndefined();
+ expect(toPendingPaymentInput(s).claimedOnly).toBe(true);
+ });
+
+ it('입금자명은 앞뒤 공백을 빼고 50자(코드 포인트)로 자른다', () => {
+ const long = '가'.repeat(49) + '😀' + '나';
+ expect(depositsSearchSchema.parse({ depositorName: ` ${long} ` }).depositorName).toBe(
+ '가'.repeat(49) + '😀',
+ );
+ expect(depositsSearchSchema.parse({ depositorName: ' ' }).depositorName).toBeUndefined();
+ });
+
+ it('입금 기록 입력은 종류만 넘긴다', () => {
+ expect(toDepositRecordInput(depositsSearchSchema.parse({ kind: 'UNIDENTIFIED' }))).toEqual({
+ limit: 20,
+ cursor: null,
+ kind: 'UNIDENTIFIED',
+ });
+ expect(depositsSearchSchema.parse({ kind: 'X' }).kind).toBeUndefined();
+ });
+});
+
+describe('환불 탭 검색 파라미터', () => {
+ it('상태 기본값은 송금 대기다', () => {
+ expect(toRefundListInput(refundsSearchSchema.parse({}))).toEqual({
+ limit: 20,
+ cursor: null,
+ status: 'AWAITING_TRANSFER',
+ kind: null,
+ });
+ });
+
+ it('완료 상태는 처리 대기 화면에서 고를 수 없다', () => {
+ expect(refundsSearchSchema.parse({ status: 'COMPLETED' }).status).toBeUndefined();
+ });
+
+ it('계좌 입력 대기·종류·환불 ID를 받는다', () => {
+ const s = refundsSearchSchema.parse({
+ status: 'AWAITING_ACCOUNT',
+ kind: 'DEPOSIT_RETURN',
+ refundId: '0',
+ });
+ expect(s.refundId).toBe('0');
+ expect(toRefundListInput(s)).toMatchObject({
+ status: 'AWAITING_ACCOUNT',
+ kind: 'DEPOSIT_RETURN',
+ });
+ });
+});
+
+describe('정산 송금 탭 검색 파라미터', () => {
+ it('딥링크의 정산 기간 시작일로 송금 대기 정산만 거른다', () => {
+ expect(
+ toSettlementListInput(settlementsSearchSchema.parse({ periodStart: '2026-11-09' })),
+ ).toEqual({
+ limit: 20,
+ cursor: null,
+ status: 'PENDING',
+ periodStart: '2026-11-09',
+ });
+ });
+
+ it.each(['2026-02-30', '2026-11-9', 'abc'])('날짜가 아닌 "%s"는 필터 없음', (periodStart) => {
+ expect(settlementsSearchSchema.parse({ periodStart }).periodStart).toBeUndefined();
+ });
+});
diff --git a/src/features/tasks/search.ts b/src/features/tasks/search.ts
new file mode 100644
index 0000000..1f35ee8
--- /dev/null
+++ b/src/features/tasks/search.ts
@@ -0,0 +1,131 @@
+import { z } from 'zod';
+
+import {
+ type AdminDepositRecordListInput,
+ type AdminPendingPaymentListInput,
+ type AdminRefundListInput,
+ type AdminSettlementListInput,
+ type DepositRecordKindType,
+} from '@/graphql/generated/graphql';
+import { parseYmd } from '@/shared/lib/kst';
+import {
+ DEFAULT_LIMIT,
+ listSearchBase,
+ optionalIdText,
+ optionalText,
+} from '@/shared/lib/list-search';
+
+import { RECORD_KINDS, REFUND_KIND_VALUES } from './meta';
+
+/** GraphQL Int 상한 */
+const MAX_INT = 2_147_483_647;
+
+/** 원 단위 금액 문자열 → 정수. 쉼표는 허용하고, 정수가 아니거나 Int 범위를 넘으면 null. "0"은 유효하다 */
+export function parseWon(raw: string): number | null {
+ const v = raw.trim().replaceAll(',', '');
+ if (!/^\d+$/.test(v)) return null;
+ const n = Number(v);
+ return n <= MAX_INT ? n : null;
+}
+
+const wonText = optionalText
+ .refine((v) => v === undefined || parseWon(v) !== null)
+ .catch(undefined);
+
+/** BE 입금자명 필터 상한(50자). 넘으면 오류라 주소로 들어와도 잘라 보낸다 */
+const DEPOSITOR_FILTER_MAX = 50;
+const depositorText = optionalText
+ .transform((v) => {
+ const t = v?.trim() ?? '';
+ return t === '' ? undefined : [...t].slice(0, DEPOSITOR_FILTER_MAX).join('');
+ })
+ .catch(undefined);
+
+export const DEPOSIT_VIEWS = [
+ { value: 'claimed', label: '확인 요청' },
+ { value: 'pending', label: '입금 대기' },
+ { value: 'records', label: '입금 기록' },
+] as const;
+export type DepositView = (typeof DEPOSIT_VIEWS)[number]['value'];
+
+const RECORD_KIND_VALUES = RECORD_KINDS.map((k) => k.value) as [
+ DepositRecordKindType,
+ ...DepositRecordKindType[],
+];
+
+export const depositsSearchSchema = z.object({
+ ...listSearchBase,
+ view: z
+ .enum(DEPOSIT_VIEWS.map((v) => v.value) as [DepositView, ...DepositView[]])
+ .optional()
+ .catch(undefined),
+ orderId: optionalIdText,
+ amount: wonText,
+ depositorName: depositorText,
+ kind: z.enum(RECORD_KIND_VALUES).optional().catch(undefined),
+});
+export type DepositsSearch = z.infer;
+export type DepositsSearchInput = z.input;
+
+export const depositView = (s: DepositsSearch): DepositView => s.view ?? 'claimed';
+
+export function toPendingPaymentInput(s: DepositsSearch): AdminPendingPaymentListInput {
+ return {
+ limit: s.limit ?? DEFAULT_LIMIT,
+ cursor: s.cursor ?? null,
+ claimedOnly: depositView(s) === 'claimed',
+ amount: s.amount === undefined ? null : parseWon(s.amount),
+ depositorName: s.depositorName ?? null,
+ };
+}
+
+export function toDepositRecordInput(s: DepositsSearch): AdminDepositRecordListInput {
+ return { limit: s.limit ?? DEFAULT_LIMIT, cursor: s.cursor ?? null, kind: s.kind ?? null };
+}
+
+export const REFUND_VIEWS = [
+ { value: 'AWAITING_TRANSFER', label: '송금 대기' },
+ { value: 'AWAITING_ACCOUNT', label: '계좌 입력 대기' },
+] as const;
+type RefundView = (typeof REFUND_VIEWS)[number]['value'];
+
+export const refundsSearchSchema = z.object({
+ ...listSearchBase,
+ status: z
+ .enum(REFUND_VIEWS.map((v) => v.value) as [RefundView, ...RefundView[]])
+ .optional()
+ .catch(undefined),
+ kind: z.enum(REFUND_KIND_VALUES).optional().catch(undefined),
+ refundId: optionalIdText,
+});
+export type RefundsSearch = z.infer;
+export type RefundsSearchInput = z.input;
+
+export const refundView = (s: RefundsSearch): RefundView => s.status ?? 'AWAITING_TRANSFER';
+
+export function toRefundListInput(s: RefundsSearch): AdminRefundListInput {
+ return {
+ limit: s.limit ?? DEFAULT_LIMIT,
+ cursor: s.cursor ?? null,
+ status: refundView(s),
+ kind: s.kind ?? null,
+ };
+}
+
+export const settlementsSearchSchema = z.object({
+ ...listSearchBase,
+ /** BE 경보 딥링크의 정산 기간 시작일(KST 월요일, YYYY-MM-DD) */
+ periodStart: optionalText.refine((v) => v === undefined || parseYmd(v) !== null).catch(undefined),
+ settlementId: optionalIdText,
+});
+export type SettlementsSearch = z.infer;
+export type SettlementsSearchInput = z.input;
+
+export function toSettlementListInput(s: SettlementsSearch): AdminSettlementListInput {
+ return {
+ limit: s.limit ?? DEFAULT_LIMIT,
+ cursor: s.cursor ?? null,
+ status: 'PENDING',
+ periodStart: s.periodStart ?? null,
+ };
+}
diff --git a/src/graphql/generated/gql.ts b/src/graphql/generated/gql.ts
index e19af92..8c1259d 100644
--- a/src/graphql/generated/gql.ts
+++ b/src/graphql/generated/gql.ts
@@ -94,6 +94,21 @@ type Documents = {
"\n query AdminStoreInProgressOrderSummary($storeId: ID!) {\n adminStoreInProgressOrderSummary(storeId: $storeId) {\n totalCount\n byStatus {\n status\n count\n }\n }\n }\n": typeof types.AdminStoreInProgressOrderSummaryDocument,
"\n mutation AdminSetStoreActive($input: AdminSetStoreActiveInput!) {\n adminSetStoreActive(input: $input) {\n id\n isActive\n }\n }\n": typeof types.AdminSetStoreActiveDocument,
"\n mutation AdminUpdateStoreBasicInfo($input: AdminUpdateStoreBasicInfoInput!) {\n adminUpdateStoreBasicInfo(input: $input) {\n id\n updatedAt\n }\n }\n": typeof types.AdminUpdateStoreBasicInfoDocument,
+ "\n query AdminTaskCounts {\n adminTaskCounts {\n claimedPayments\n pendingPayments\n refundsAwaitingAccount\n refundsAwaitingTransfer\n pendingSettlements\n }\n }\n": typeof types.AdminTaskCountsDocument,
+ "\n query AdminTasksPendingPayments($input: AdminPendingPaymentListInput) {\n adminPendingPayments(input: $input) {\n items {\n orderId\n orderNumber\n storeName\n productName\n amount\n depositorName\n buyerName\n buyerPhone\n createdAt\n expiresAt\n buyerClaimedAt\n pickupAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": typeof types.AdminTasksPendingPaymentsDocument,
+ "\n query AdminTasksOrder($orderId: ID!) {\n adminOrder(orderId: $orderId) {\n id\n orderNumber\n status\n pickupAt\n buyerName\n buyerPhone\n totalPrice\n createdAt\n items {\n id\n productName\n }\n payment {\n status\n amount\n depositorName\n expiresAt\n buyerClaimedAt\n confirmedAt\n confirmedByLabel\n confirmNote\n }\n cancellation {\n actorType\n reasonLabel\n note\n canceledAt\n }\n }\n }\n": typeof types.AdminTasksOrderDocument,
+ "\n mutation AdminTasksConfirmPayment($input: AdminConfirmPaymentInput!) {\n adminConfirmPayment(input: $input) {\n id\n status\n }\n }\n": typeof types.AdminTasksConfirmPaymentDocument,
+ "\n mutation AdminTasksCancelUnpaid($input: AdminCancelOrderInput!) {\n adminCancelOrder(input: $input) {\n id\n status\n }\n }\n": typeof types.AdminTasksCancelUnpaidDocument,
+ "\n query AdminTasksDepositRecords($input: AdminDepositRecordListInput) {\n adminDepositRecords(input: $input) {\n items {\n id\n kind\n orderId\n orderNumber\n amount\n depositorName\n depositedAt\n note\n recordedByLabel\n refundId\n refundStatus\n createdAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": typeof types.AdminTasksDepositRecordsDocument,
+ "\n mutation AdminTasksCreateDepositReturn($input: AdminCreateDepositReturnInput!) {\n adminCreateDepositReturn(input: $input) {\n id\n refundId\n }\n }\n": typeof types.AdminTasksCreateDepositReturnDocument,
+ "\n mutation AdminTasksRecordUnidentifiedDeposit($input: AdminRecordUnidentifiedDepositInput!) {\n adminRecordUnidentifiedDeposit(input: $input) {\n id\n }\n }\n": typeof types.AdminTasksRecordUnidentifiedDepositDocument,
+ "\n mutation AdminTasksLinkUnidentifiedDeposit($input: AdminLinkUnidentifiedDepositInput!) {\n adminLinkUnidentifiedDeposit(input: $input) {\n id\n }\n }\n": typeof types.AdminTasksLinkUnidentifiedDepositDocument,
+ "\n query AdminTasksOrderOptions($input: AdminOrderListInput) {\n adminOrders(input: $input) {\n items {\n id\n orderNumber\n buyerName\n totalPrice\n }\n }\n }\n": typeof types.AdminTasksOrderOptionsDocument,
+ "\n query AdminTasksRefunds($input: AdminRefundListInput) {\n adminRefunds(input: $input) {\n items {\n id\n kind\n amount\n status\n bank {\n code\n name\n }\n accountHolder\n accountNumberMasked\n requestedAt\n accountSubmittedAt\n orderId\n orderNumber\n buyerName\n buyerPhone\n storeName\n productName\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": typeof types.AdminTasksRefundsDocument,
+ "\n query AdminTasksRefund($refundId: ID!) {\n adminRefund(refundId: $refundId) {\n refund {\n id\n kind\n amount\n status\n bank {\n code\n name\n }\n accountHolder\n accountNumberMasked\n requestedAt\n accountSubmittedAt\n completedAt\n orderId\n orderNumber\n buyerName\n buyerPhone\n storeName\n productName\n completedByLabel\n completeNote\n }\n accountNumber\n depositRecord {\n id\n depositorName\n depositedAt\n note\n }\n }\n }\n": typeof types.AdminTasksRefundDocument,
+ "\n mutation AdminTasksCompleteRefund($input: AdminCompleteRefundInput!) {\n adminCompleteRefund(input: $input) {\n id\n status\n }\n }\n": typeof types.AdminTasksCompleteRefundDocument,
+ "\n query AdminTasksSettlements($input: AdminSettlementListInput) {\n adminSettlements(input: $input) {\n items {\n id\n storeId\n storeName\n periodStart\n periodEnd\n orderCount\n settlementBaseAmount\n commissionAmount\n payoutAmount\n status\n accountRegistered\n createdAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": typeof types.AdminTasksSettlementsDocument,
+ "\n query AdminTasksSettlement($settlementId: ID!) {\n adminSettlement(settlementId: $settlementId) {\n id\n storeId\n storeName\n periodStart\n periodEnd\n orderCount\n settlementBaseAmount\n commissionAmount\n payoutAmount\n status\n paidAt\n accountRegistered\n paidByLabel\n paidNote\n paidAccount {\n bank {\n code\n name\n }\n accountHolder\n accountNumberMasked\n }\n currentAccount {\n bank {\n code\n name\n }\n accountHolder\n accountNumber\n }\n }\n }\n": typeof types.AdminTasksSettlementDocument,
"\n query AdminCategories($input: AdminCategoryListInput) {\n adminCategories(input: $input) {\n id\n categoryType\n name\n description\n sortOrder\n isActive\n productCount\n createdAt\n updatedAt\n }\n }\n": typeof types.AdminCategoriesDocument,
"\n mutation AdminCreateCategory($input: AdminCreateCategoryInput!) {\n adminCreateCategory(input: $input) {\n id\n }\n }\n": typeof types.AdminCreateCategoryDocument,
"\n mutation AdminUpdateCategory($input: AdminUpdateCategoryInput!) {\n adminUpdateCategory(input: $input) {\n id\n }\n }\n": typeof types.AdminUpdateCategoryDocument,
@@ -184,6 +199,21 @@ const documents: Documents = {
"\n query AdminStoreInProgressOrderSummary($storeId: ID!) {\n adminStoreInProgressOrderSummary(storeId: $storeId) {\n totalCount\n byStatus {\n status\n count\n }\n }\n }\n": types.AdminStoreInProgressOrderSummaryDocument,
"\n mutation AdminSetStoreActive($input: AdminSetStoreActiveInput!) {\n adminSetStoreActive(input: $input) {\n id\n isActive\n }\n }\n": types.AdminSetStoreActiveDocument,
"\n mutation AdminUpdateStoreBasicInfo($input: AdminUpdateStoreBasicInfoInput!) {\n adminUpdateStoreBasicInfo(input: $input) {\n id\n updatedAt\n }\n }\n": types.AdminUpdateStoreBasicInfoDocument,
+ "\n query AdminTaskCounts {\n adminTaskCounts {\n claimedPayments\n pendingPayments\n refundsAwaitingAccount\n refundsAwaitingTransfer\n pendingSettlements\n }\n }\n": types.AdminTaskCountsDocument,
+ "\n query AdminTasksPendingPayments($input: AdminPendingPaymentListInput) {\n adminPendingPayments(input: $input) {\n items {\n orderId\n orderNumber\n storeName\n productName\n amount\n depositorName\n buyerName\n buyerPhone\n createdAt\n expiresAt\n buyerClaimedAt\n pickupAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": types.AdminTasksPendingPaymentsDocument,
+ "\n query AdminTasksOrder($orderId: ID!) {\n adminOrder(orderId: $orderId) {\n id\n orderNumber\n status\n pickupAt\n buyerName\n buyerPhone\n totalPrice\n createdAt\n items {\n id\n productName\n }\n payment {\n status\n amount\n depositorName\n expiresAt\n buyerClaimedAt\n confirmedAt\n confirmedByLabel\n confirmNote\n }\n cancellation {\n actorType\n reasonLabel\n note\n canceledAt\n }\n }\n }\n": types.AdminTasksOrderDocument,
+ "\n mutation AdminTasksConfirmPayment($input: AdminConfirmPaymentInput!) {\n adminConfirmPayment(input: $input) {\n id\n status\n }\n }\n": types.AdminTasksConfirmPaymentDocument,
+ "\n mutation AdminTasksCancelUnpaid($input: AdminCancelOrderInput!) {\n adminCancelOrder(input: $input) {\n id\n status\n }\n }\n": types.AdminTasksCancelUnpaidDocument,
+ "\n query AdminTasksDepositRecords($input: AdminDepositRecordListInput) {\n adminDepositRecords(input: $input) {\n items {\n id\n kind\n orderId\n orderNumber\n amount\n depositorName\n depositedAt\n note\n recordedByLabel\n refundId\n refundStatus\n createdAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": types.AdminTasksDepositRecordsDocument,
+ "\n mutation AdminTasksCreateDepositReturn($input: AdminCreateDepositReturnInput!) {\n adminCreateDepositReturn(input: $input) {\n id\n refundId\n }\n }\n": types.AdminTasksCreateDepositReturnDocument,
+ "\n mutation AdminTasksRecordUnidentifiedDeposit($input: AdminRecordUnidentifiedDepositInput!) {\n adminRecordUnidentifiedDeposit(input: $input) {\n id\n }\n }\n": types.AdminTasksRecordUnidentifiedDepositDocument,
+ "\n mutation AdminTasksLinkUnidentifiedDeposit($input: AdminLinkUnidentifiedDepositInput!) {\n adminLinkUnidentifiedDeposit(input: $input) {\n id\n }\n }\n": types.AdminTasksLinkUnidentifiedDepositDocument,
+ "\n query AdminTasksOrderOptions($input: AdminOrderListInput) {\n adminOrders(input: $input) {\n items {\n id\n orderNumber\n buyerName\n totalPrice\n }\n }\n }\n": types.AdminTasksOrderOptionsDocument,
+ "\n query AdminTasksRefunds($input: AdminRefundListInput) {\n adminRefunds(input: $input) {\n items {\n id\n kind\n amount\n status\n bank {\n code\n name\n }\n accountHolder\n accountNumberMasked\n requestedAt\n accountSubmittedAt\n orderId\n orderNumber\n buyerName\n buyerPhone\n storeName\n productName\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": types.AdminTasksRefundsDocument,
+ "\n query AdminTasksRefund($refundId: ID!) {\n adminRefund(refundId: $refundId) {\n refund {\n id\n kind\n amount\n status\n bank {\n code\n name\n }\n accountHolder\n accountNumberMasked\n requestedAt\n accountSubmittedAt\n completedAt\n orderId\n orderNumber\n buyerName\n buyerPhone\n storeName\n productName\n completedByLabel\n completeNote\n }\n accountNumber\n depositRecord {\n id\n depositorName\n depositedAt\n note\n }\n }\n }\n": types.AdminTasksRefundDocument,
+ "\n mutation AdminTasksCompleteRefund($input: AdminCompleteRefundInput!) {\n adminCompleteRefund(input: $input) {\n id\n status\n }\n }\n": types.AdminTasksCompleteRefundDocument,
+ "\n query AdminTasksSettlements($input: AdminSettlementListInput) {\n adminSettlements(input: $input) {\n items {\n id\n storeId\n storeName\n periodStart\n periodEnd\n orderCount\n settlementBaseAmount\n commissionAmount\n payoutAmount\n status\n accountRegistered\n createdAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n": types.AdminTasksSettlementsDocument,
+ "\n query AdminTasksSettlement($settlementId: ID!) {\n adminSettlement(settlementId: $settlementId) {\n id\n storeId\n storeName\n periodStart\n periodEnd\n orderCount\n settlementBaseAmount\n commissionAmount\n payoutAmount\n status\n paidAt\n accountRegistered\n paidByLabel\n paidNote\n paidAccount {\n bank {\n code\n name\n }\n accountHolder\n accountNumberMasked\n }\n currentAccount {\n bank {\n code\n name\n }\n accountHolder\n accountNumber\n }\n }\n }\n": types.AdminTasksSettlementDocument,
"\n query AdminCategories($input: AdminCategoryListInput) {\n adminCategories(input: $input) {\n id\n categoryType\n name\n description\n sortOrder\n isActive\n productCount\n createdAt\n updatedAt\n }\n }\n": types.AdminCategoriesDocument,
"\n mutation AdminCreateCategory($input: AdminCreateCategoryInput!) {\n adminCreateCategory(input: $input) {\n id\n }\n }\n": types.AdminCreateCategoryDocument,
"\n mutation AdminUpdateCategory($input: AdminUpdateCategoryInput!) {\n adminUpdateCategory(input: $input) {\n id\n }\n }\n": types.AdminUpdateCategoryDocument,
@@ -511,6 +541,66 @@ export function graphql(source: "\n mutation AdminSetStoreActive($input: AdminS
* The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/
export function graphql(source: "\n mutation AdminUpdateStoreBasicInfo($input: AdminUpdateStoreBasicInfoInput!) {\n adminUpdateStoreBasicInfo(input: $input) {\n id\n updatedAt\n }\n }\n"): typeof import('./graphql').AdminUpdateStoreBasicInfoDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n query AdminTaskCounts {\n adminTaskCounts {\n claimedPayments\n pendingPayments\n refundsAwaitingAccount\n refundsAwaitingTransfer\n pendingSettlements\n }\n }\n"): typeof import('./graphql').AdminTaskCountsDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n query AdminTasksPendingPayments($input: AdminPendingPaymentListInput) {\n adminPendingPayments(input: $input) {\n items {\n orderId\n orderNumber\n storeName\n productName\n amount\n depositorName\n buyerName\n buyerPhone\n createdAt\n expiresAt\n buyerClaimedAt\n pickupAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n"): typeof import('./graphql').AdminTasksPendingPaymentsDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n query AdminTasksOrder($orderId: ID!) {\n adminOrder(orderId: $orderId) {\n id\n orderNumber\n status\n pickupAt\n buyerName\n buyerPhone\n totalPrice\n createdAt\n items {\n id\n productName\n }\n payment {\n status\n amount\n depositorName\n expiresAt\n buyerClaimedAt\n confirmedAt\n confirmedByLabel\n confirmNote\n }\n cancellation {\n actorType\n reasonLabel\n note\n canceledAt\n }\n }\n }\n"): typeof import('./graphql').AdminTasksOrderDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n mutation AdminTasksConfirmPayment($input: AdminConfirmPaymentInput!) {\n adminConfirmPayment(input: $input) {\n id\n status\n }\n }\n"): typeof import('./graphql').AdminTasksConfirmPaymentDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n mutation AdminTasksCancelUnpaid($input: AdminCancelOrderInput!) {\n adminCancelOrder(input: $input) {\n id\n status\n }\n }\n"): typeof import('./graphql').AdminTasksCancelUnpaidDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n query AdminTasksDepositRecords($input: AdminDepositRecordListInput) {\n adminDepositRecords(input: $input) {\n items {\n id\n kind\n orderId\n orderNumber\n amount\n depositorName\n depositedAt\n note\n recordedByLabel\n refundId\n refundStatus\n createdAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n"): typeof import('./graphql').AdminTasksDepositRecordsDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n mutation AdminTasksCreateDepositReturn($input: AdminCreateDepositReturnInput!) {\n adminCreateDepositReturn(input: $input) {\n id\n refundId\n }\n }\n"): typeof import('./graphql').AdminTasksCreateDepositReturnDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n mutation AdminTasksRecordUnidentifiedDeposit($input: AdminRecordUnidentifiedDepositInput!) {\n adminRecordUnidentifiedDeposit(input: $input) {\n id\n }\n }\n"): typeof import('./graphql').AdminTasksRecordUnidentifiedDepositDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n mutation AdminTasksLinkUnidentifiedDeposit($input: AdminLinkUnidentifiedDepositInput!) {\n adminLinkUnidentifiedDeposit(input: $input) {\n id\n }\n }\n"): typeof import('./graphql').AdminTasksLinkUnidentifiedDepositDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n query AdminTasksOrderOptions($input: AdminOrderListInput) {\n adminOrders(input: $input) {\n items {\n id\n orderNumber\n buyerName\n totalPrice\n }\n }\n }\n"): typeof import('./graphql').AdminTasksOrderOptionsDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n query AdminTasksRefunds($input: AdminRefundListInput) {\n adminRefunds(input: $input) {\n items {\n id\n kind\n amount\n status\n bank {\n code\n name\n }\n accountHolder\n accountNumberMasked\n requestedAt\n accountSubmittedAt\n orderId\n orderNumber\n buyerName\n buyerPhone\n storeName\n productName\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n"): typeof import('./graphql').AdminTasksRefundsDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n query AdminTasksRefund($refundId: ID!) {\n adminRefund(refundId: $refundId) {\n refund {\n id\n kind\n amount\n status\n bank {\n code\n name\n }\n accountHolder\n accountNumberMasked\n requestedAt\n accountSubmittedAt\n completedAt\n orderId\n orderNumber\n buyerName\n buyerPhone\n storeName\n productName\n completedByLabel\n completeNote\n }\n accountNumber\n depositRecord {\n id\n depositorName\n depositedAt\n note\n }\n }\n }\n"): typeof import('./graphql').AdminTasksRefundDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n mutation AdminTasksCompleteRefund($input: AdminCompleteRefundInput!) {\n adminCompleteRefund(input: $input) {\n id\n status\n }\n }\n"): typeof import('./graphql').AdminTasksCompleteRefundDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n query AdminTasksSettlements($input: AdminSettlementListInput) {\n adminSettlements(input: $input) {\n items {\n id\n storeId\n storeName\n periodStart\n periodEnd\n orderCount\n settlementBaseAmount\n commissionAmount\n payoutAmount\n status\n accountRegistered\n createdAt\n }\n totalCount\n hasMore\n nextCursor\n }\n }\n"): typeof import('./graphql').AdminTasksSettlementsDocument;
+/**
+ * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
+ */
+export function graphql(source: "\n query AdminTasksSettlement($settlementId: ID!) {\n adminSettlement(settlementId: $settlementId) {\n id\n storeId\n storeName\n periodStart\n periodEnd\n orderCount\n settlementBaseAmount\n commissionAmount\n payoutAmount\n status\n paidAt\n accountRegistered\n paidByLabel\n paidNote\n paidAccount {\n bank {\n code\n name\n }\n accountHolder\n accountNumberMasked\n }\n currentAccount {\n bank {\n code\n name\n }\n accountHolder\n accountNumber\n }\n }\n }\n"): typeof import('./graphql').AdminTasksSettlementDocument;
/**
* The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/
diff --git a/src/graphql/generated/graphql.ts b/src/graphql/generated/graphql.ts
index 38b825c..d8804bd 100644
--- a/src/graphql/generated/graphql.ts
+++ b/src/graphql/generated/graphql.ts
@@ -84,6 +84,22 @@ export type AdminCompleteOrderPickupInput = {
orderId: string | number;
};
+/** 환불 송금 완료 입력. */
+export type AdminCompleteRefundInput = {
+ /** 처리 메모(선택, 500자 이하). 환불 기록에 남는다. */
+ note?: string | null | undefined;
+ refundId: string | number;
+};
+
+/** 입금 확인 입력. */
+export type AdminConfirmPaymentInput = {
+ /** 은행 앱에서 본 입금액(원, 0 이상 정수). 결제 금액과 같아야 확인된다(0원 주문은 0). */
+ depositedAmount: number;
+ /** 처리 메모(선택, 500자 이하). 결제 기록에 남는다. */
+ note?: string | null | undefined;
+ orderId: string | number;
+};
+
/** 관리자 계정 생성 입력. */
export type AdminCreateAdminInput = {
/** 이메일. 선택. */
@@ -138,6 +154,19 @@ export type AdminCreateCategoryInput = {
sortOrder?: number | null | undefined;
};
+/** 입금 반환 연결 입력. */
+export type AdminCreateDepositReturnInput = {
+ /** 은행 앱에서 본 입금액(원, 1 이상). 이 금액 전액을 돌려준다. */
+ amount: number;
+ /** 은행 앱에 보인 입금 일시(선택). */
+ depositedAt?: string | null | undefined;
+ /** 은행 앱에 보인 입금자명(1~50자). */
+ depositorName: string;
+ /** 처리 메모(선택, 500자 이하). */
+ note?: string | null | undefined;
+ orderId: string | number;
+};
+
/** 지역 생성 입력. */
export type AdminCreateRegionInput = {
/** 중심 위도(문자열, -90~90). 선택. */
@@ -250,6 +279,22 @@ export type AdminDeleteReviewInput = {
reviewId: string | number;
};
+/** 입금 기록 목록 조회 조건. */
+export type AdminDepositRecordListInput = {
+ /** 이전 응답의 nextCursor. 첫 페이지는 생략한다. */
+ cursor?: string | null | undefined;
+ /** 종류 필터. null이면 전체. */
+ kind?: DepositRecordKindType | null | undefined;
+ /** 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. */
+ limit?: number | null | undefined;
+};
+
+/** 종결 기록을 반환 대상으로 바꾸는 입력. */
+export type AdminLinkUnidentifiedDepositInput = {
+ depositRecordId: string | number;
+ orderId: string | number;
+};
+
/** 송금 완료 입력. */
export type AdminMarkSettlementPaidInput = {
/** 송금 메모(선택, 500자 이하). 정산과 감사 로그에 남는다. */
@@ -320,6 +365,20 @@ export type AdminOrderListInput = {
toCreatedAt?: string | null | undefined;
};
+/** 입금 확인 대기 목록 조회 조건. 모든 필터는 AND로 결합된다. */
+export type AdminPendingPaymentListInput = {
+ /** 결제 금액(원) 일치 필터. 은행 앱에서 본 입금액으로 주문을 찾는다. null이면 전체. */
+ amount?: number | null | undefined;
+ /** true면 구매자가 '입금했어요'를 누른 주문만. 기본 false, null도 false(전체)로 본다. */
+ claimedOnly?: boolean | null | undefined;
+ /** 이전 응답의 nextCursor. 첫 페이지는 생략한다. claimedOnly를 바꾸면 커서를 버리고 첫 페이지부터 다시 조회한다. */
+ cursor?: string | null | undefined;
+ /** 입금자명 부분일치 필터(최대 50자). 공백만 보내거나 null이면 전체. */
+ depositorName?: string | null | undefined;
+ /** 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. */
+ limit?: number | null | undefined;
+};
+
/** 상품 목록 조회 조건. */
export type AdminProductListInput = {
/** 이전 응답의 nextCursor. 첫 페이지는 생략한다. */
@@ -334,6 +393,30 @@ export type AdminProductListInput = {
storeId?: string | number | null | undefined;
};
+/** 주인 모를 입금 종결 기록 입력. */
+export type AdminRecordUnidentifiedDepositInput = {
+ /** 은행 앱에서 본 입금액(원, 1 이상). */
+ amount: number;
+ /** 은행 앱에 보인 입금 일시(선택). */
+ depositedAt?: string | null | undefined;
+ /** 은행 앱에 보인 입금자명(1~50자). */
+ depositorName: string;
+ /** 종결 사유 메모(필수, 500자 이하). */
+ note: string;
+};
+
+/** 환불 목록 조회 조건. 모든 필터는 AND로 결합된다. */
+export type AdminRefundListInput = {
+ /** 이전 응답의 nextCursor. 첫 페이지는 생략한다. */
+ cursor?: string | null | undefined;
+ /** 종류 필터. null이면 전체. */
+ kind?: RefundKindType | null | undefined;
+ /** 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. */
+ limit?: number | null | undefined;
+ /** 진행 상태 필터. null이면 전체. */
+ status?: RefundStatusType | null | undefined;
+};
+
/** 지역 목록 조회 조건. */
export type AdminRegionListInput = {
/** 비활성 포함 여부. 기본 false. */
@@ -842,6 +925,13 @@ export type CustomTextAlignType =
/** 오른쪽 정렬. */
| 'RIGHT';
+/** 입금 기록 종류. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. */
+export type DepositRecordKindType =
+ /** 주문에 연결해 돌려주는 입금. 같은 금액의 입금 반환 환불이 함께 있다. */
+ | 'RETURN'
+ /** 주인을 알 수 없어 메모로 종결한 입금. */
+ | 'UNIDENTIFIED';
+
/** 소셜 로그인 Provider 종류 */
export type IdentityProvider =
/** 구글 OIDC. */
@@ -1556,6 +1646,109 @@ export type AdminUpdateStoreBasicInfoMutationVariables = Exact<{
export type AdminUpdateStoreBasicInfoMutation = { adminUpdateStoreBasicInfo: { id: string, updatedAt: string } };
+export type AdminTaskCountsQueryVariables = Exact<{ [key: string]: never; }>;
+
+
+export type AdminTaskCountsQuery = { adminTaskCounts: { claimedPayments: number, pendingPayments: number, refundsAwaitingAccount: number, refundsAwaitingTransfer: number, pendingSettlements: number } };
+
+export type AdminTasksPendingPaymentsQueryVariables = Exact<{
+ input?: AdminPendingPaymentListInput | null | undefined;
+}>;
+
+
+export type AdminTasksPendingPaymentsQuery = { adminPendingPayments: { totalCount: number, hasMore: boolean, nextCursor: string | null, items: Array<{ orderId: string, orderNumber: string, storeName: string | null, productName: string | null, amount: number, depositorName: string, buyerName: string, buyerPhone: string, createdAt: string, expiresAt: string, buyerClaimedAt: string | null, pickupAt: string }> } };
+
+export type AdminTasksOrderQueryVariables = Exact<{
+ orderId: string | number;
+}>;
+
+
+export type AdminTasksOrderQuery = { adminOrder: { id: string, orderNumber: string, status: OrderStatusType, pickupAt: string, buyerName: string, buyerPhone: string, totalPrice: number, createdAt: string, items: Array<{ id: string, productName: string }>, payment: { status: PaymentStatusType, amount: number, depositorName: string, expiresAt: string, buyerClaimedAt: string | null, confirmedAt: string | null, confirmedByLabel: string | null, confirmNote: string | null } | null, cancellation: { actorType: OrderActorType, reasonLabel: string, note: string | null, canceledAt: string } | null } };
+
+export type AdminTasksConfirmPaymentMutationVariables = Exact<{
+ input: AdminConfirmPaymentInput;
+}>;
+
+
+export type AdminTasksConfirmPaymentMutation = { adminConfirmPayment: { id: string, status: OrderStatusType } };
+
+export type AdminTasksCancelUnpaidMutationVariables = Exact<{
+ input: AdminCancelOrderInput;
+}>;
+
+
+export type AdminTasksCancelUnpaidMutation = { adminCancelOrder: { id: string, status: OrderStatusType } };
+
+export type AdminTasksDepositRecordsQueryVariables = Exact<{
+ input?: AdminDepositRecordListInput | null | undefined;
+}>;
+
+
+export type AdminTasksDepositRecordsQuery = { adminDepositRecords: { totalCount: number, hasMore: boolean, nextCursor: string | null, items: Array<{ id: string, kind: DepositRecordKindType, orderId: string | null, orderNumber: string | null, amount: number, depositorName: string, depositedAt: string | null, note: string | null, recordedByLabel: string | null, refundId: string | null, refundStatus: RefundStatusType | null, createdAt: string }> } };
+
+export type AdminTasksCreateDepositReturnMutationVariables = Exact<{
+ input: AdminCreateDepositReturnInput;
+}>;
+
+
+export type AdminTasksCreateDepositReturnMutation = { adminCreateDepositReturn: { id: string, refundId: string | null } };
+
+export type AdminTasksRecordUnidentifiedDepositMutationVariables = Exact<{
+ input: AdminRecordUnidentifiedDepositInput;
+}>;
+
+
+export type AdminTasksRecordUnidentifiedDepositMutation = { adminRecordUnidentifiedDeposit: { id: string } };
+
+export type AdminTasksLinkUnidentifiedDepositMutationVariables = Exact<{
+ input: AdminLinkUnidentifiedDepositInput;
+}>;
+
+
+export type AdminTasksLinkUnidentifiedDepositMutation = { adminLinkUnidentifiedDeposit: { id: string } };
+
+export type AdminTasksOrderOptionsQueryVariables = Exact<{
+ input?: AdminOrderListInput | null | undefined;
+}>;
+
+
+export type AdminTasksOrderOptionsQuery = { adminOrders: { items: Array<{ id: string, orderNumber: string, buyerName: string, totalPrice: number }> } };
+
+export type AdminTasksRefundsQueryVariables = Exact<{
+ input?: AdminRefundListInput | null | undefined;
+}>;
+
+
+export type AdminTasksRefundsQuery = { adminRefunds: { totalCount: number, hasMore: boolean, nextCursor: string | null, items: Array<{ id: string, kind: RefundKindType, amount: number, status: RefundStatusType, accountHolder: string | null, accountNumberMasked: string | null, requestedAt: string, accountSubmittedAt: string | null, orderId: string, orderNumber: string, buyerName: string, buyerPhone: string, storeName: string | null, productName: string | null, bank: { code: string, name: string } | null }> } };
+
+export type AdminTasksRefundQueryVariables = Exact<{
+ refundId: string | number;
+}>;
+
+
+export type AdminTasksRefundQuery = { adminRefund: { accountNumber: string | null, refund: { id: string, kind: RefundKindType, amount: number, status: RefundStatusType, accountHolder: string | null, accountNumberMasked: string | null, requestedAt: string, accountSubmittedAt: string | null, completedAt: string | null, orderId: string, orderNumber: string, buyerName: string, buyerPhone: string, storeName: string | null, productName: string | null, completedByLabel: string | null, completeNote: string | null, bank: { code: string, name: string } | null }, depositRecord: { id: string, depositorName: string, depositedAt: string | null, note: string | null } | null } };
+
+export type AdminTasksCompleteRefundMutationVariables = Exact<{
+ input: AdminCompleteRefundInput;
+}>;
+
+
+export type AdminTasksCompleteRefundMutation = { adminCompleteRefund: { id: string, status: RefundStatusType } };
+
+export type AdminTasksSettlementsQueryVariables = Exact<{
+ input?: AdminSettlementListInput | null | undefined;
+}>;
+
+
+export type AdminTasksSettlementsQuery = { adminSettlements: { totalCount: number, hasMore: boolean, nextCursor: string | null, items: Array<{ id: string, storeId: string, storeName: string, periodStart: string, periodEnd: string, orderCount: number, settlementBaseAmount: number, commissionAmount: number, payoutAmount: number, status: SettlementStatusType, accountRegistered: boolean, createdAt: string }> } };
+
+export type AdminTasksSettlementQueryVariables = Exact<{
+ settlementId: string | number;
+}>;
+
+
+export type AdminTasksSettlementQuery = { adminSettlement: { id: string, storeId: string, storeName: string, periodStart: string, periodEnd: string, orderCount: number, settlementBaseAmount: number, commissionAmount: number, payoutAmount: number, status: SettlementStatusType, paidAt: string | null, accountRegistered: boolean, paidByLabel: string | null, paidNote: string | null, paidAccount: { accountHolder: string, accountNumberMasked: string, bank: { code: string, name: string } } | null, currentAccount: { accountHolder: string, accountNumber: string, bank: { code: string, name: string } } | null } };
+
export type AdminCategoriesQueryVariables = Exact<{
input?: AdminCategoryListInput | null | undefined;
}>;
@@ -2961,6 +3154,279 @@ export const AdminUpdateStoreBasicInfoDocument = new TypedDocumentString(`
}
}
`) as unknown as TypedDocumentString;
+export const AdminTaskCountsDocument = new TypedDocumentString(`
+ query AdminTaskCounts {
+ adminTaskCounts {
+ claimedPayments
+ pendingPayments
+ refundsAwaitingAccount
+ refundsAwaitingTransfer
+ pendingSettlements
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksPendingPaymentsDocument = new TypedDocumentString(`
+ query AdminTasksPendingPayments($input: AdminPendingPaymentListInput) {
+ adminPendingPayments(input: $input) {
+ items {
+ orderId
+ orderNumber
+ storeName
+ productName
+ amount
+ depositorName
+ buyerName
+ buyerPhone
+ createdAt
+ expiresAt
+ buyerClaimedAt
+ pickupAt
+ }
+ totalCount
+ hasMore
+ nextCursor
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksOrderDocument = new TypedDocumentString(`
+ 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
+ }
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksConfirmPaymentDocument = new TypedDocumentString(`
+ mutation AdminTasksConfirmPayment($input: AdminConfirmPaymentInput!) {
+ adminConfirmPayment(input: $input) {
+ id
+ status
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksCancelUnpaidDocument = new TypedDocumentString(`
+ mutation AdminTasksCancelUnpaid($input: AdminCancelOrderInput!) {
+ adminCancelOrder(input: $input) {
+ id
+ status
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksDepositRecordsDocument = new TypedDocumentString(`
+ query AdminTasksDepositRecords($input: AdminDepositRecordListInput) {
+ adminDepositRecords(input: $input) {
+ items {
+ id
+ kind
+ orderId
+ orderNumber
+ amount
+ depositorName
+ depositedAt
+ note
+ recordedByLabel
+ refundId
+ refundStatus
+ createdAt
+ }
+ totalCount
+ hasMore
+ nextCursor
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksCreateDepositReturnDocument = new TypedDocumentString(`
+ mutation AdminTasksCreateDepositReturn($input: AdminCreateDepositReturnInput!) {
+ adminCreateDepositReturn(input: $input) {
+ id
+ refundId
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksRecordUnidentifiedDepositDocument = new TypedDocumentString(`
+ mutation AdminTasksRecordUnidentifiedDeposit($input: AdminRecordUnidentifiedDepositInput!) {
+ adminRecordUnidentifiedDeposit(input: $input) {
+ id
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksLinkUnidentifiedDepositDocument = new TypedDocumentString(`
+ mutation AdminTasksLinkUnidentifiedDeposit($input: AdminLinkUnidentifiedDepositInput!) {
+ adminLinkUnidentifiedDeposit(input: $input) {
+ id
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksOrderOptionsDocument = new TypedDocumentString(`
+ query AdminTasksOrderOptions($input: AdminOrderListInput) {
+ adminOrders(input: $input) {
+ items {
+ id
+ orderNumber
+ buyerName
+ totalPrice
+ }
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksRefundsDocument = new TypedDocumentString(`
+ 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
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksRefundDocument = new TypedDocumentString(`
+ 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
+ }
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksCompleteRefundDocument = new TypedDocumentString(`
+ mutation AdminTasksCompleteRefund($input: AdminCompleteRefundInput!) {
+ adminCompleteRefund(input: $input) {
+ id
+ status
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksSettlementsDocument = new TypedDocumentString(`
+ query AdminTasksSettlements($input: AdminSettlementListInput) {
+ adminSettlements(input: $input) {
+ items {
+ id
+ storeId
+ storeName
+ periodStart
+ periodEnd
+ orderCount
+ settlementBaseAmount
+ commissionAmount
+ payoutAmount
+ status
+ accountRegistered
+ createdAt
+ }
+ totalCount
+ hasMore
+ nextCursor
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const AdminTasksSettlementDocument = new TypedDocumentString(`
+ 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
+ }
+ }
+}
+ `) as unknown as TypedDocumentString;
export const AdminCategoriesDocument = new TypedDocumentString(`
query AdminCategories($input: AdminCategoryListInput) {
adminCategories(input: $input) {
diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts
index 237347b..e983ce6 100644
--- a/src/routeTree.gen.ts
+++ b/src/routeTree.gen.ts
@@ -42,6 +42,10 @@ import { Route as AuthedShellSettlementsSettlementIdRouteImport } from './routes
import { Route as AuthedShellSettlementsMonthlyRouteImport } from './routes/_authed/_shell/settlements/monthly'
import { Route as AuthedShellStoresIndexRouteImport } from './routes/_authed/_shell/stores/index'
import { Route as AuthedShellStoresStoreIdRouteImport } from './routes/_authed/_shell/stores/$storeId'
+import { Route as AuthedShellTasksIndexRouteImport } from './routes/_authed/_shell/tasks/index'
+import { Route as AuthedShellTasksDepositsRouteImport } from './routes/_authed/_shell/tasks/deposits'
+import { Route as AuthedShellTasksRefundsRouteImport } from './routes/_authed/_shell/tasks/refunds'
+import { Route as AuthedShellTasksSettlementsRouteImport } from './routes/_authed/_shell/tasks/settlements'
import { Route as AuthedShellUsersIndexRouteImport } from './routes/_authed/_shell/users/index'
import { Route as AuthedShellUsersAccountIdRouteImport } from './routes/_authed/_shell/users/$accountId'
@@ -221,6 +225,28 @@ const AuthedShellStoresStoreIdRoute =
path: '/stores/$storeId',
getParentRoute: () => AuthedShellRoute,
} as any)
+const AuthedShellTasksIndexRoute = AuthedShellTasksIndexRouteImport.update({
+ id: '/tasks/',
+ path: '/tasks/',
+ getParentRoute: () => AuthedShellRoute,
+} as any)
+const AuthedShellTasksDepositsRoute =
+ AuthedShellTasksDepositsRouteImport.update({
+ id: '/tasks/deposits',
+ path: '/tasks/deposits',
+ getParentRoute: () => AuthedShellRoute,
+ } as any)
+const AuthedShellTasksRefundsRoute = AuthedShellTasksRefundsRouteImport.update({
+ id: '/tasks/refunds',
+ path: '/tasks/refunds',
+ getParentRoute: () => AuthedShellRoute,
+} as any)
+const AuthedShellTasksSettlementsRoute =
+ AuthedShellTasksSettlementsRouteImport.update({
+ id: '/tasks/settlements',
+ path: '/tasks/settlements',
+ getParentRoute: () => AuthedShellRoute,
+ } as any)
const AuthedShellUsersIndexRoute = AuthedShellUsersIndexRouteImport.update({
id: '/users/',
path: '/users/',
@@ -257,6 +283,9 @@ export interface FileRoutesByFullPath {
'/settlements/$settlementId': typeof AuthedShellSettlementsSettlementIdRoute
'/settlements/monthly': typeof AuthedShellSettlementsMonthlyRoute
'/stores/$storeId': typeof AuthedShellStoresStoreIdRoute
+ '/tasks/deposits': typeof AuthedShellTasksDepositsRoute
+ '/tasks/refunds': typeof AuthedShellTasksRefundsRoute
+ '/tasks/settlements': typeof AuthedShellTasksSettlementsRoute
'/users/$accountId': typeof AuthedShellUsersAccountIdRoute
'/banners/': typeof AuthedShellBannersIndexRoute
'/notifications/': typeof AuthedShellNotificationsIndexRoute
@@ -266,6 +295,7 @@ export interface FileRoutesByFullPath {
'/sellers/': typeof AuthedShellSellersIndexRoute
'/settlements/': typeof AuthedShellSettlementsIndexRoute
'/stores/': typeof AuthedShellStoresIndexRoute
+ '/tasks/': typeof AuthedShellTasksIndexRoute
'/users/': typeof AuthedShellUsersIndexRoute
}
export interface FileRoutesByTo {
@@ -292,6 +322,9 @@ export interface FileRoutesByTo {
'/settlements/$settlementId': typeof AuthedShellSettlementsSettlementIdRoute
'/settlements/monthly': typeof AuthedShellSettlementsMonthlyRoute
'/stores/$storeId': typeof AuthedShellStoresStoreIdRoute
+ '/tasks/deposits': typeof AuthedShellTasksDepositsRoute
+ '/tasks/refunds': typeof AuthedShellTasksRefundsRoute
+ '/tasks/settlements': typeof AuthedShellTasksSettlementsRoute
'/users/$accountId': typeof AuthedShellUsersAccountIdRoute
'/banners': typeof AuthedShellBannersIndexRoute
'/notifications': typeof AuthedShellNotificationsIndexRoute
@@ -301,6 +334,7 @@ export interface FileRoutesByTo {
'/sellers': typeof AuthedShellSellersIndexRoute
'/settlements': typeof AuthedShellSettlementsIndexRoute
'/stores': typeof AuthedShellStoresIndexRoute
+ '/tasks': typeof AuthedShellTasksIndexRoute
'/users': typeof AuthedShellUsersIndexRoute
}
export interface FileRoutesById {
@@ -330,6 +364,9 @@ export interface FileRoutesById {
'/_authed/_shell/settlements/$settlementId': typeof AuthedShellSettlementsSettlementIdRoute
'/_authed/_shell/settlements/monthly': typeof AuthedShellSettlementsMonthlyRoute
'/_authed/_shell/stores/$storeId': typeof AuthedShellStoresStoreIdRoute
+ '/_authed/_shell/tasks/deposits': typeof AuthedShellTasksDepositsRoute
+ '/_authed/_shell/tasks/refunds': typeof AuthedShellTasksRefundsRoute
+ '/_authed/_shell/tasks/settlements': typeof AuthedShellTasksSettlementsRoute
'/_authed/_shell/users/$accountId': typeof AuthedShellUsersAccountIdRoute
'/_authed/_shell/banners/': typeof AuthedShellBannersIndexRoute
'/_authed/_shell/notifications/': typeof AuthedShellNotificationsIndexRoute
@@ -339,6 +376,7 @@ export interface FileRoutesById {
'/_authed/_shell/sellers/': typeof AuthedShellSellersIndexRoute
'/_authed/_shell/settlements/': typeof AuthedShellSettlementsIndexRoute
'/_authed/_shell/stores/': typeof AuthedShellStoresIndexRoute
+ '/_authed/_shell/tasks/': typeof AuthedShellTasksIndexRoute
'/_authed/_shell/users/': typeof AuthedShellUsersIndexRoute
}
export interface FileRouteTypes {
@@ -367,6 +405,9 @@ export interface FileRouteTypes {
| '/settlements/$settlementId'
| '/settlements/monthly'
| '/stores/$storeId'
+ | '/tasks/deposits'
+ | '/tasks/refunds'
+ | '/tasks/settlements'
| '/users/$accountId'
| '/banners/'
| '/notifications/'
@@ -376,6 +417,7 @@ export interface FileRouteTypes {
| '/sellers/'
| '/settlements/'
| '/stores/'
+ | '/tasks/'
| '/users/'
fileRoutesByTo: FileRoutesByTo
to:
@@ -402,6 +444,9 @@ export interface FileRouteTypes {
| '/settlements/$settlementId'
| '/settlements/monthly'
| '/stores/$storeId'
+ | '/tasks/deposits'
+ | '/tasks/refunds'
+ | '/tasks/settlements'
| '/users/$accountId'
| '/banners'
| '/notifications'
@@ -411,6 +456,7 @@ export interface FileRouteTypes {
| '/sellers'
| '/settlements'
| '/stores'
+ | '/tasks'
| '/users'
id:
| '__root__'
@@ -439,6 +485,9 @@ export interface FileRouteTypes {
| '/_authed/_shell/settlements/$settlementId'
| '/_authed/_shell/settlements/monthly'
| '/_authed/_shell/stores/$storeId'
+ | '/_authed/_shell/tasks/deposits'
+ | '/_authed/_shell/tasks/refunds'
+ | '/_authed/_shell/tasks/settlements'
| '/_authed/_shell/users/$accountId'
| '/_authed/_shell/banners/'
| '/_authed/_shell/notifications/'
@@ -448,6 +497,7 @@ export interface FileRouteTypes {
| '/_authed/_shell/sellers/'
| '/_authed/_shell/settlements/'
| '/_authed/_shell/stores/'
+ | '/_authed/_shell/tasks/'
| '/_authed/_shell/users/'
fileRoutesById: FileRoutesById
}
@@ -689,6 +739,34 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthedShellStoresStoreIdRouteImport
parentRoute: typeof AuthedShellRoute
}
+ '/_authed/_shell/tasks/': {
+ id: '/_authed/_shell/tasks/'
+ path: '/tasks'
+ fullPath: '/tasks/'
+ preLoaderRoute: typeof AuthedShellTasksIndexRouteImport
+ parentRoute: typeof AuthedShellRoute
+ }
+ '/_authed/_shell/tasks/deposits': {
+ id: '/_authed/_shell/tasks/deposits'
+ path: '/tasks/deposits'
+ fullPath: '/tasks/deposits'
+ preLoaderRoute: typeof AuthedShellTasksDepositsRouteImport
+ parentRoute: typeof AuthedShellRoute
+ }
+ '/_authed/_shell/tasks/refunds': {
+ id: '/_authed/_shell/tasks/refunds'
+ path: '/tasks/refunds'
+ fullPath: '/tasks/refunds'
+ preLoaderRoute: typeof AuthedShellTasksRefundsRouteImport
+ parentRoute: typeof AuthedShellRoute
+ }
+ '/_authed/_shell/tasks/settlements': {
+ id: '/_authed/_shell/tasks/settlements'
+ path: '/tasks/settlements'
+ fullPath: '/tasks/settlements'
+ preLoaderRoute: typeof AuthedShellTasksSettlementsRouteImport
+ parentRoute: typeof AuthedShellRoute
+ }
'/_authed/_shell/users/': {
id: '/_authed/_shell/users/'
path: '/users'
@@ -728,6 +806,9 @@ interface AuthedShellRouteChildren {
AuthedShellSettlementsSettlementIdRoute: typeof AuthedShellSettlementsSettlementIdRoute
AuthedShellSettlementsMonthlyRoute: typeof AuthedShellSettlementsMonthlyRoute
AuthedShellStoresStoreIdRoute: typeof AuthedShellStoresStoreIdRoute
+ AuthedShellTasksDepositsRoute: typeof AuthedShellTasksDepositsRoute
+ AuthedShellTasksRefundsRoute: typeof AuthedShellTasksRefundsRoute
+ AuthedShellTasksSettlementsRoute: typeof AuthedShellTasksSettlementsRoute
AuthedShellUsersAccountIdRoute: typeof AuthedShellUsersAccountIdRoute
AuthedShellBannersIndexRoute: typeof AuthedShellBannersIndexRoute
AuthedShellNotificationsIndexRoute: typeof AuthedShellNotificationsIndexRoute
@@ -737,6 +818,7 @@ interface AuthedShellRouteChildren {
AuthedShellSellersIndexRoute: typeof AuthedShellSellersIndexRoute
AuthedShellSettlementsIndexRoute: typeof AuthedShellSettlementsIndexRoute
AuthedShellStoresIndexRoute: typeof AuthedShellStoresIndexRoute
+ AuthedShellTasksIndexRoute: typeof AuthedShellTasksIndexRoute
AuthedShellUsersIndexRoute: typeof AuthedShellUsersIndexRoute
}
@@ -763,6 +845,9 @@ const AuthedShellRouteChildren: AuthedShellRouteChildren = {
AuthedShellSettlementsSettlementIdRoute,
AuthedShellSettlementsMonthlyRoute: AuthedShellSettlementsMonthlyRoute,
AuthedShellStoresStoreIdRoute: AuthedShellStoresStoreIdRoute,
+ AuthedShellTasksDepositsRoute: AuthedShellTasksDepositsRoute,
+ AuthedShellTasksRefundsRoute: AuthedShellTasksRefundsRoute,
+ AuthedShellTasksSettlementsRoute: AuthedShellTasksSettlementsRoute,
AuthedShellUsersAccountIdRoute: AuthedShellUsersAccountIdRoute,
AuthedShellBannersIndexRoute: AuthedShellBannersIndexRoute,
AuthedShellNotificationsIndexRoute: AuthedShellNotificationsIndexRoute,
@@ -772,6 +857,7 @@ const AuthedShellRouteChildren: AuthedShellRouteChildren = {
AuthedShellSellersIndexRoute: AuthedShellSellersIndexRoute,
AuthedShellSettlementsIndexRoute: AuthedShellSettlementsIndexRoute,
AuthedShellStoresIndexRoute: AuthedShellStoresIndexRoute,
+ AuthedShellTasksIndexRoute: AuthedShellTasksIndexRoute,
AuthedShellUsersIndexRoute: AuthedShellUsersIndexRoute,
}
diff --git a/src/routes/_authed/_shell/tasks/deposits.tsx b/src/routes/_authed/_shell/tasks/deposits.tsx
new file mode 100644
index 0000000..c045ecd
--- /dev/null
+++ b/src/routes/_authed/_shell/tasks/deposits.tsx
@@ -0,0 +1,16 @@
+import { createFileRoute } from '@tanstack/react-router';
+
+import { DepositsTasksPage, depositsSearchSchema } from '@/features/tasks';
+
+export const Route = createFileRoute('/_authed/_shell/tasks/deposits')({
+ validateSearch: depositsSearchSchema,
+ component: DepositsRoute,
+});
+
+function DepositsRoute() {
+ const search = Route.useSearch();
+ const navigate = Route.useNavigate();
+ return (
+ void navigate({ search: next })} />
+ );
+}
diff --git a/src/routes/_authed/_shell/tasks/index.tsx b/src/routes/_authed/_shell/tasks/index.tsx
new file mode 100644
index 0000000..7745d73
--- /dev/null
+++ b/src/routes/_authed/_shell/tasks/index.tsx
@@ -0,0 +1,7 @@
+import { createFileRoute, redirect } from '@tanstack/react-router';
+
+export const Route = createFileRoute('/_authed/_shell/tasks/')({
+ beforeLoad: () => {
+ throw redirect({ to: '/tasks/deposits', replace: true });
+ },
+});
diff --git a/src/routes/_authed/_shell/tasks/refunds.tsx b/src/routes/_authed/_shell/tasks/refunds.tsx
new file mode 100644
index 0000000..7949175
--- /dev/null
+++ b/src/routes/_authed/_shell/tasks/refunds.tsx
@@ -0,0 +1,16 @@
+import { createFileRoute } from '@tanstack/react-router';
+
+import { RefundsTasksPage, refundsSearchSchema } from '@/features/tasks';
+
+export const Route = createFileRoute('/_authed/_shell/tasks/refunds')({
+ validateSearch: refundsSearchSchema,
+ component: RefundsRoute,
+});
+
+function RefundsRoute() {
+ const search = Route.useSearch();
+ const navigate = Route.useNavigate();
+ return (
+ void navigate({ search: next })} />
+ );
+}
diff --git a/src/routes/_authed/_shell/tasks/settlements.tsx b/src/routes/_authed/_shell/tasks/settlements.tsx
new file mode 100644
index 0000000..45a87c0
--- /dev/null
+++ b/src/routes/_authed/_shell/tasks/settlements.tsx
@@ -0,0 +1,19 @@
+import { createFileRoute } from '@tanstack/react-router';
+
+import { SettlementsTasksPage, settlementsSearchSchema } from '@/features/tasks';
+
+export const Route = createFileRoute('/_authed/_shell/tasks/settlements')({
+ validateSearch: settlementsSearchSchema,
+ component: SettlementsRoute,
+});
+
+function SettlementsRoute() {
+ const search = Route.useSearch();
+ const navigate = Route.useNavigate();
+ return (
+ void navigate({ search: next })}
+ />
+ );
+}
diff --git a/src/shared/ui/id-filter-input.tsx b/src/shared/ui/id-filter-input.tsx
index 33fb782..fa4e22c 100644
--- a/src/shared/ui/id-filter-input.tsx
+++ b/src/shared/ui/id-filter-input.tsx
@@ -9,6 +9,9 @@ interface Props {
/** URL 기준 현재 값 */
value: string | undefined;
onCommit: (v: string | undefined) => void;
+ /** 기본은 ID 숫자 검사. 금액처럼 규칙이 다른 필터는 자기 파서로 검사한다 */
+ validate?: (v: string) => boolean;
+ invalidMessage?: string;
}
/** 목록의 ID 필터. Enter나 포커스 이동으로 적용한다. 숫자가 아니면 커밋하지 않고 입력을 남긴 채 알린다(조용히 버리지 않는다). */
@@ -17,14 +20,21 @@ export function IdFilterInput(props: Props) {
return ;
}
-function IdField({ label, placeholder = label, value, onCommit }: Props) {
+function IdField({
+ label,
+ placeholder = label,
+ value,
+ onCommit,
+ validate = isIdText,
+ invalidMessage = '숫자만 입력해 주세요.',
+}: Props) {
const [invalid, setInvalid] = useState(false);
const errorId = useId();
// 마지막으로 적용한 값. 같으면 다시 커밋하지 않는다: Enter 뒤 blur가 한 번 더 오고, 커밋은 목록 커서를 처음으로 돌린다
const committed = useRef(value);
const commit = (raw: string) => {
const v = raw.trim() || undefined;
- if (v !== undefined && !isIdText(v)) return setInvalid(true);
+ if (v !== undefined && !validate(v)) return setInvalid(true);
if (v === committed.current) return;
committed.current = v;
onCommit(v);
@@ -49,7 +59,7 @@ function IdField({ label, placeholder = label, value, onCommit }: Props) {
/>
{invalid && (
- 숫자만 입력해 주세요.
+ {invalidMessage}
)}
diff --git a/src/test/msw/graphql.ts b/src/test/msw/graphql.ts
index 3b23913..0279153 100644
--- a/src/test/msw/graphql.ts
+++ b/src/test/msw/graphql.ts
@@ -48,3 +48,19 @@ export function restOk(path: string, body: T, status = 200) {
: HttpResponse.json(body as Record, { status }),
);
}
+
+/**
+ * operation별 성공 응답을 주고 요청 수를 센다(교차 무효화 검사용). 쿼리·mutation 모두 받는다.
+ * 핸들러는 부르는 쪽이 server.use로 건다.
+ */
+export function gqlCounted(answers: Record>) {
+ const counts: Record = Object.fromEntries(
+ Object.keys(answers).map((op) => [op, 0]),
+ );
+ const handler = graphql.operation(({ operationName }) => {
+ if (!Object.hasOwn(answers, operationName)) return undefined;
+ counts[operationName]! += 1;
+ return HttpResponse.json({ data: answers[operationName] });
+ });
+ return { counts, handler };
+}
diff --git a/src/test/msw/server.ts b/src/test/msw/server.ts
index c443514..e36cdf3 100644
--- a/src/test/msw/server.ts
+++ b/src/test/msw/server.ts
@@ -1,4 +1,15 @@
import { setupServer } from 'msw/node';
+import { gqlOk } from './graphql';
+
+/** 셸 사이드바가 모든 화면에서 부르는 처리 대기 건수. 건수를 보는 spec은 server.use로 덮어쓴다 */
+const emptyTaskCounts = {
+ claimedPayments: 0,
+ pendingPayments: 0,
+ refundsAwaitingAccount: 0,
+ refundsAwaitingTransfer: 0,
+ pendingSettlements: 0,
+};
+
/** 전역 MSW 서버. 핸들러는 각 spec이 server.use로 등록한다(계약별 헬퍼는 ./graphql). */
-export const server = setupServer();
+export const server = setupServer(gqlOk('AdminTaskCounts', { adminTaskCounts: emptyTaskCounts }));