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
15 changes: 15 additions & 0 deletions src/features/audit-logs/pages/audit-logs.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,21 @@ describe('감사 로그', () => {
updatedAt: '2026-09-27T02:34:00.000Z',
items: [],
statusHistories: [],
requestNote: null,
payment: null,
refunds: [],
cancellation: null,
cancelOptions: { cancelable: false, reasons: [], refundRule: null, paidAmount: 0 },
confirmDeadlineAt: null,
autoPickupAt: null,
noShowAt: null,
pickupChanges: [],
commissionRateBps: 0,
expectedPayoutAmount: null,
settlementBaseAmount: null,
commissionAmount: null,
settlementFinalizedAt: null,
settlementId: null,
},
}),
);
Expand Down
2 changes: 2 additions & 0 deletions src/features/dashboard/api/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ const AdminDashboardSummaryDocument = graphql(/* GraphQL */ `
newUserCount
newSellerCount
orderCounts {
pendingPayment
submitted
confirmed
made
pickedUp
noShow
canceled
}
orderAmountSum
Expand Down
6 changes: 3 additions & 3 deletions src/features/dashboard/components/kpi-tiles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Link } from '@tanstack/react-router';
import { formatCount, formatKrw } from '@/shared/lib/format';
import { Card } from '@/shared/ui/card';

import { orderCountTotal } from '../order-count-keys';
import { type DashboardSummary } from './types';

function Tile({
Expand Down Expand Up @@ -36,12 +37,11 @@ function Tile({
}

export function KpiTiles({ summary }: { summary: DashboardSummary }) {
const c = summary.orderCounts;
const orderTotal = c.submitted + c.confirmed + c.made + c.pickedUp + c.canceled;
const orderTotal = orderCountTotal(summary.orderCounts);
return (
<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
<Tile
label="주문 금액 (취소 제외)"
label="주문 금액 (취소·입금 대기 제외)"
value={formatKrw(summary.orderAmountSum)}
note={`주문 ${formatCount(orderTotal)}건`}
/>
Expand Down
22 changes: 7 additions & 15 deletions src/features/dashboard/components/order-status-chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,19 @@ import {
} from 'recharts';

import { orderStatusMeta } from '@/features/orders';
import { type OrderStatusType } from '@/graphql/generated/graphql';
import { formatCount } from '@/shared/lib/format';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/shared/ui/card';

import { ORDER_COUNT_KEYS } from '../order-count-keys';
import { type DashboardSummary } from './types';

// 라벨은 주문 화면과 한 벌(주문 확정 등)
const STATUS: { key: keyof DashboardSummary['orderCounts']; status: OrderStatusType }[] = [
{ key: 'submitted', status: 'SUBMITTED' },
{ key: 'confirmed', status: 'CONFIRMED' },
{ key: 'made', status: 'MADE' },
{ key: 'pickedUp', status: 'PICKED_UP' },
{ key: 'canceled', status: 'CANCELED' },
];
// 흐름 밖에서 끝난 상태는 회색으로 가른다
const MUTED = new Set(['noShow', 'canceled']);

/** 기간 내 주문 상태 분포. 단일 계열(진행 단계)이라 색 1개, 취소만 회색. 표는 스크린리더·색각 보조용. */
/** 기간 내 주문 상태 분포. 단일 계열(진행 단계)이라 색 1개, 노쇼·취소만 회색. 표는 스크린리더·색각 보조용. */
export function OrderStatusChart({ summary }: { summary: DashboardSummary }) {
const data = STATUS.map((s) => ({
// 라벨은 주문 화면과 한 벌(주문 확정 등)
const data = ORDER_COUNT_KEYS.map((s) => ({
key: s.key,
label: orderStatusMeta(s.status).label,
count: summary.orderCounts[s.key],
Expand Down Expand Up @@ -73,10 +68,7 @@ export function OrderStatusChart({ summary }: { summary: DashboardSummary }) {
/>
<Bar dataKey="count" radius={[4, 4, 0, 0]} maxBarSize={56}>
{data.map((d) => (
<Cell
key={d.key}
fill={d.key === 'canceled' ? 'var(--chart-4)' : 'var(--chart-1)'}
/>
<Cell key={d.key} fill={MUTED.has(d.key) ? 'var(--chart-4)' : 'var(--chart-1)'} />
))}
<LabelList
dataKey="count"
Expand Down
25 changes: 25 additions & 0 deletions src/features/dashboard/order-count-keys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { type OrderStatusType } from '@/graphql/generated/graphql';

import { type DashboardSummary } from './components/types';

type CountKey = keyof DashboardSummary['orderCounts'];

// 주문 건수 키는 이 표 한 곳에서 상태와 잇는다. Record라 조회 문서에 키를 더하면 tsc가 여기를 요구한다
const STATUS_BY_KEY: Record<CountKey, OrderStatusType> = {
pendingPayment: 'PENDING_PAYMENT',
submitted: 'SUBMITTED',
confirmed: 'CONFIRMED',
made: 'MADE',
pickedUp: 'PICKED_UP',
noShow: 'NO_SHOW',
canceled: 'CANCELED',
};

/** 흐름 순서(차트 막대 순서) */
export const ORDER_COUNT_KEYS = (Object.keys(STATUS_BY_KEY) as CountKey[]).map((key) => ({
key,
status: STATUS_BY_KEY[key],
}));

export const orderCountTotal = (counts: DashboardSummary['orderCounts']) =>
ORDER_COUNT_KEYS.reduce((sum, { key }) => sum + counts[key], 0);
31 changes: 28 additions & 3 deletions src/features/dashboard/pages/dashboard-page.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,15 @@ const summary = {
to: 'y',
newUserCount: 128,
newSellerCount: 3,
orderCounts: { submitted: 21, confirmed: 34, made: 18, pickedUp: 78, canceled: 12 },
orderCounts: {
pendingPayment: 5,
submitted: 21,
confirmed: 34,
made: 18,
pickedUp: 78,
noShow: 2,
canceled: 12,
},
orderAmountSum: 4812000,
activeStoreCount: 42,
activeProductCount: 517,
Expand Down Expand Up @@ -66,7 +74,7 @@ describe('DashboardPage', () => {
);
boot();
expect(await screen.findByText('4,812,000원')).toBeInTheDocument();
expect(screen.getByText('주문 163건')).toBeInTheDocument();
expect(screen.getByText('주문 170건')).toBeInTheDocument();
expect(screen.getByText('7건')).toBeInTheDocument();
expect(screen.getByRole('link', { name: '처리 필요' })).toHaveAttribute('href', '/reports');
const table = screen.getByRole('table', { name: '주문 상태별 건수' });
Expand All @@ -91,10 +99,12 @@ describe('DashboardPage', () => {
);

it.each([
['입금 대기', '5건'],
['접수', '21건'],
['주문 확정', '34건'],
['제작 완료', '18건'],
['픽업 완료', '78건'],
['노쇼', '2건'],
['취소', '12건'],
])('상태 분포 표에서 %s는 %s', async (label, count) => {
server.use(
Expand All @@ -107,9 +117,24 @@ describe('DashboardPage', () => {
expect(header.closest('tr')).toHaveTextContent(`${label}${count}`);
});

it('상태 분포는 흐름 순서 뒤에 종료 상태로 7개 상태를 모두 싣고 주문 금액은 입금 대기를 뺀다', async () => {
server.use(
gqlOk('AdminDashboardSummary', { adminDashboardSummary: summary }),
gqlOk('AdminSearchKeywordSnapshot', { adminSearchKeywordSnapshot: snapshot }),
);
boot();
const table = await screen.findByRole('table', { name: '주문 상태별 건수' });
expect(
within(table)
.getAllByRole('rowheader')
.map((h) => h.textContent),
).toEqual(['입금 대기', '접수', '주문 확정', '제작 완료', '픽업 완료', '노쇼', '취소']);
expect(screen.getByText('주문 금액 (취소·입금 대기 제외)')).toBeInTheDocument();
});

// CardHeader는 grid라 flex-row를 덧붙여도 한 줄이 되지 않았다. 보조 문구는 CardDescription 자리에 둔다
it.each([
['주문 상태 분포', '기간 내 주문 163건'],
['주문 상태 분포', '기간 내 주문 170건'],
['검색어 순위', '09-27 17:00 기준 집계'],
])('%s 카드의 보조 문구는 카드 설명 자리에 있다', async (title, caption) => {
server.use(
Expand Down
134 changes: 118 additions & 16 deletions src/features/orders/api/queries.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type QueryClient, queryOptions } from '@tanstack/react-query';

import { graphql } from '@/graphql/generated';
import { type AdminOrderListInput } from '@/graphql/generated/graphql';
import { type AdminCancelOrderInput, type AdminOrderListInput } from '@/graphql/generated/graphql';
import { gqlRequest } from '@/shared/api';
import { type EntityOption } from '@/shared/ui/entity-picker';

Expand All @@ -14,7 +14,7 @@ const ordersKeys = {
// 필터 선택기·링크 이름. 매장·구매자 화면의 캐시와 섞이지 않게 주문 아래에 둔다
storeOptions: (keyword: string) => [...ordersKeys.all, 'store-options', keyword] as const,
buyerOptions: (keyword: string) => [...ordersKeys.all, 'buyer-options', keyword] as const,
storeName: (storeId: string) => [...ordersKeys.all, 'store-name', storeId] as const,
store: (storeId: string) => [...ordersKeys.all, 'store', storeId] as const,
buyerName: (accountId: string) => [...ordersKeys.all, 'buyer-name', accountId] as const,
};

Expand Down Expand Up @@ -57,6 +57,25 @@ const AdminOrderDocument = graphql(/* GraphQL */ `
pickupAt
buyerName
buyerPhone
requestNote
payment {
method
status
amount
depositorName
depositBank {
code
name
}
depositAccountNumber
depositAccountHolder
expiresAt
buyerClaimedAt
confirmedAt
confirmSource
confirmedByLabel
confirmNote
}
subtotalPrice
discountPrice
totalPrice
Expand Down Expand Up @@ -125,7 +144,59 @@ const AdminOrderDocument = graphql(/* GraphQL */ `
toStatus
changedAt
note
actorType
cancelReason
cancelFault
refundAmount
}
refunds {
id
kind
amount
status
bank {
code
name
}
accountHolder
accountNumberMasked
requestedAt
accountSubmittedAt
completedAt
}
cancellation {
actorType
reason
reasonLabel
note
fault
refundAmount
refundStatus
refundCompletedAt
canceledAt
}
cancelOptions {
cancelable
reasons
refundRule
paidAmount
}
confirmDeadlineAt
autoPickupAt
noShowAt
pickupChanges {
id
fromPickupAt
toPickupAt
changedAt
note
}
commissionRateBps
expectedPayoutAmount
settlementBaseAmount
commissionAmount
settlementFinalizedAt
settlementId
}
}
`);
Expand Down Expand Up @@ -163,6 +234,7 @@ const AdminOrdersStoreNameDocument = graphql(/* GraphQL */ `
store {
id
storeName
isActive
}
}
}
Expand All @@ -188,6 +260,15 @@ const AdminCancelOrderDocument = graphql(/* GraphQL */ `
}
`);

const AdminCompleteOrderPickupDocument = graphql(/* GraphQL */ `
mutation AdminCompleteOrderPickup($input: AdminCompleteOrderPickupInput!) {
adminCompleteOrderPickup(input: $input) {
id
status
}
}
`);

export function ordersListQueryOptions(input: AdminOrderListInput) {
return queryOptions({
queryKey: ordersKeys.list(input),
Expand Down Expand Up @@ -248,12 +329,12 @@ export function buyerOptionsQueryOptions(keyword: string) {
});
}

/** 주소로 들어온 매장 ID의 이름. 찾지 못하면 오류로 두고 부르는 쪽은 #ID를 보인다 */
export function storeNameQueryOptions(storeId: string) {
/** 매장 이름·숨김 여부. 찾지 못하면 오류로 두고 부르는 쪽은 #ID를 보인다 */
export function storeRefQueryOptions(storeId: string) {
return queryOptions({
queryKey: ordersKeys.storeName(storeId),
queryKey: ordersKeys.store(storeId),
queryFn: async () =>
(await gqlRequest(AdminOrdersStoreNameDocument, { storeId })).adminStore.store.storeName,
(await gqlRequest(AdminOrdersStoreNameDocument, { storeId })).adminStore.store,
retry: false,
});
}
Expand All @@ -267,14 +348,35 @@ export function buyerNameQueryOptions(accountId: string) {
});
}

/** 사유 코드 선택은 아직 없어 '기타' + 입력한 메모로 보낸다 */
export async function cancelOrder(queryClient: QueryClient, orderId: string, note: string) {
const result = (
await gqlRequest(AdminCancelOrderDocument, { input: { orderId, reason: 'OTHER', note } })
).adminCancelOrder;
await Promise.all([
queryClient.invalidateQueries({ queryKey: ordersKeys.detail(orderId) }),
queryClient.invalidateQueries({ queryKey: ordersKeys.lists() }),
]);
return result;
/** 처리했든 거절됐든(다른 곳에서 상태가 바뀐 경우 등) 상세·목록을 다시 불러 지금 상태와 선택지를 보인다 */
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() }),
]);
}
}

export function cancelOrder(queryClient: QueryClient, input: AdminCancelOrderInput) {
return withRefresh(
queryClient,
String(input.orderId),
async () => (await gqlRequest(AdminCancelOrderDocument, { input })).adminCancelOrder,
);
}

export function completeOrderPickup(queryClient: QueryClient, orderId: string, note: string) {
return withRefresh(
queryClient,
orderId,
async () =>
(
await gqlRequest(AdminCompleteOrderPickupDocument, {
input: { orderId, note: note || null },
})
).adminCompleteOrderPickup,
);
}
Loading