Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/guide/architecture-conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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가 먼저 배포돼 새 값이 와도 화면이 죽지 않아야 한다.
Expand Down
3 changes: 3 additions & 0 deletions src/app/router.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
);
});
Expand Down
1 change: 1 addition & 0 deletions src/app/shell/nav.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Expand Down
8 changes: 8 additions & 0 deletions src/app/shell/nav.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
type LucideIcon,
BriefcaseIcon,
InboxIcon,
LayoutDashboardIcon,
PackageIcon,
TagsIcon,
Expand All @@ -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'
Expand All @@ -45,6 +50,8 @@ interface NavItem {
| '/settings';
label: string;
icon: LucideIcon;
/** 메뉴 오른쪽 건수 배지 */
badge?: ComponentType;
}
export interface NavGroup {
label: string | null;
Expand All @@ -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 },
Expand Down
1 change: 1 addition & 0 deletions src/app/shell/sidebar-nav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export function SidebarNav({ onNavigate }: { onNavigate?: () => void }) {
>
<item.icon className="size-4 shrink-0 opacity-70" aria-hidden />
{item.label}
{item.badge && <item.badge />}
</Link>
))}
</div>
Expand Down
13 changes: 13 additions & 0 deletions src/features/audit-logs/components/audit-links.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,19 @@ export function TargetLink({
{text}
</Link>
);
case 'REFUND':
return (
<Link to="/tasks/refunds" search={{ refundId: targetId }} className={linkClass}>
{text}
</Link>
);
case 'DEPOSIT_RECORD':
// 입금 기록은 단건 조회가 없어 목록으로 연다
return (
<Link to="/tasks/deposits" search={{ view: 'records' }} className={linkClass}>
{text}
</Link>
);
default:
return <span>{text}</span>;
}
Expand Down
2 changes: 2 additions & 0 deletions src/features/audit-logs/pages/audit-logs.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down
9 changes: 7 additions & 2 deletions src/features/dashboard/api/queries.ts
Original file line number Diff line number Diff line change
@@ -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,
};
Expand Down Expand Up @@ -65,3 +66,7 @@ export function searchKeywordQueryOptions(rankedAt: string | null = null, limit
.adminSearchKeywordSnapshot,
});
}

/** 기간 요약(주문 상태별 건수 등)을 다시 읽게 한다. 주문 상태를 바꾸는 다른 화면(처리 대기)이 부른다 */
export const invalidateDashboard = (queryClient: QueryClient) =>
queryClient.invalidateQueries({ queryKey: dashboardKeys.summaries() });
1 change: 1 addition & 0 deletions src/features/dashboard/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { invalidateDashboard } from './api/queries';
export { DashboardPage } from './pages/dashboard-page';
export { periodSearchSchema, resolvePeriod } from './period';
2 changes: 2 additions & 0 deletions src/features/dashboard/pages/dashboard-page.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -26,6 +27,7 @@ export function DashboardPage({ period, onPeriodChange }: Props) {
meta={periodLabel(period)}
actions={<PeriodPicker period={period} onChange={onPeriodChange} />}
/>
<TasksTile />
{summary.isError ? (
<p role="alert" className="text-sm text-negative-foreground">
{messageFor(summary.error)}
Expand Down
54 changes: 54 additions & 0 deletions src/features/orders/api/queries.spec.ts
Original file line number Diff line number Diff line change
@@ -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<string, Record<string, unknown>>) {
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();
});
});
15 changes: 14 additions & 1 deletion src/features/orders/api/queries.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -348,14 +349,26 @@ 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<T>(queryClient: QueryClient, orderId: string, run: () => Promise<T>) {
try {
return await run();
} finally {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ordersKeys.detail(orderId) }),
queryClient.invalidateQueries({ queryKey: ordersKeys.lists() }),
invalidateTasks(queryClient),
]);
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/features/orders/index.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down
71 changes: 71 additions & 0 deletions src/features/settlements/api/queries.spec.ts
Original file line number Diff line number Diff line change
@@ -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<string, Record<string, unknown>>) {
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();
});
});
17 changes: 11 additions & 6 deletions src/features/settlements/api/queries.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -264,23 +265,26 @@ export function storePickerQuery(keyword: string) {
});
}

/** 다른 관리자가 먼저 처리했을 때(409)도 불러 처리자·시각을 다시 받는다 */
/** 정산 목록·상세를 다시 읽게 한다. 처리 대기 화면도 처리 뒤 부른다 */
export async function invalidateSettlements(queryClient: QueryClient) {
await Promise.all([
queryClient.invalidateQueries({ queryKey: settlementsKeys.lists() }),
queryClient.invalidateQueries({ queryKey: settlementsKeys.details() }),
]);
}

/** 처리했든 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(
Expand All @@ -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;
}
Expand Down
9 changes: 3 additions & 6 deletions src/features/settlements/components/mark-paid-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
}
}}
Expand Down
3 changes: 3 additions & 0 deletions src/features/settlements/index.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down
Loading