diff --git a/src/features/audit-logs/pages/audit-logs.spec.tsx b/src/features/audit-logs/pages/audit-logs.spec.tsx index 6bd30bf..ae8b46a 100644 --- a/src/features/audit-logs/pages/audit-logs.spec.tsx +++ b/src/features/audit-logs/pages/audit-logs.spec.tsx @@ -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, }, }), ); diff --git a/src/features/dashboard/api/queries.ts b/src/features/dashboard/api/queries.ts index d4cdb5f..a14a6e2 100644 --- a/src/features/dashboard/api/queries.ts +++ b/src/features/dashboard/api/queries.ts @@ -18,10 +18,12 @@ const AdminDashboardSummaryDocument = graphql(/* GraphQL */ ` newUserCount newSellerCount orderCounts { + pendingPayment submitted confirmed made pickedUp + noShow canceled } orderAmountSum diff --git a/src/features/dashboard/components/kpi-tiles.tsx b/src/features/dashboard/components/kpi-tiles.tsx index b083e40..673a1fc 100644 --- a/src/features/dashboard/components/kpi-tiles.tsx +++ b/src/features/dashboard/components/kpi-tiles.tsx @@ -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({ @@ -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 (
diff --git a/src/features/dashboard/components/order-status-chart.tsx b/src/features/dashboard/components/order-status-chart.tsx index 16edf32..902b35c 100644 --- a/src/features/dashboard/components/order-status-chart.tsx +++ b/src/features/dashboard/components/order-status-chart.tsx @@ -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], @@ -73,10 +68,7 @@ export function OrderStatusChart({ summary }: { summary: DashboardSummary }) { /> {data.map((d) => ( - + ))} = { + 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); diff --git a/src/features/dashboard/pages/dashboard-page.spec.tsx b/src/features/dashboard/pages/dashboard-page.spec.tsx index bff5430..5df2093 100644 --- a/src/features/dashboard/pages/dashboard-page.spec.tsx +++ b/src/features/dashboard/pages/dashboard-page.spec.tsx @@ -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, @@ -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: '주문 상태별 건수' }); @@ -91,10 +99,12 @@ describe('DashboardPage', () => { ); it.each([ + ['입금 대기', '5건'], ['접수', '21건'], ['주문 확정', '34건'], ['제작 완료', '18건'], ['픽업 완료', '78건'], + ['노쇼', '2건'], ['취소', '12건'], ])('상태 분포 표에서 %s는 %s', async (label, count) => { server.use( @@ -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( diff --git a/src/features/orders/api/queries.ts b/src/features/orders/api/queries.ts index cb08804..dacb707 100644 --- a/src/features/orders/api/queries.ts +++ b/src/features/orders/api/queries.ts @@ -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'; @@ -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, }; @@ -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 @@ -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 } } `); @@ -163,6 +234,7 @@ const AdminOrdersStoreNameDocument = graphql(/* GraphQL */ ` store { id storeName + isActive } } } @@ -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), @@ -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, }); } @@ -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(queryClient: QueryClient, orderId: string, run: () => Promise) { + 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, + ); } diff --git a/src/features/orders/auto-transition.spec.ts b/src/features/orders/auto-transition.spec.ts new file mode 100644 index 0000000..583c8be --- /dev/null +++ b/src/features/orders/auto-transition.spec.ts @@ -0,0 +1,87 @@ +import { type OrderStatusType } from '@/graphql/generated/graphql'; + +import { autoTransitionNote, storeHiddenOf } from './auto-transition'; + +const payment = (buyerClaimedAt: string | null) => ({ + method: 'BANK_TRANSFER' as const, + status: 'PENDING' as const, + amount: 30000, + depositorName: '김서연', + depositAccountNumber: '1002123456789', + depositAccountHolder: '케이퀵', + expiresAt: '2026-11-19T01:00:00.000Z', + buyerClaimedAt, + confirmedAt: null, + confirmSource: null, + confirmedByLabel: null, + confirmNote: null, + depositBank: { code: '020', name: '우리은행' }, +}); +const order = (status: OrderStatusType, patch: object = {}) => ({ + status, + payment: payment(null), + confirmDeadlineAt: null, + autoPickupAt: null, + ...patch, +}); +const AT = '2026-11-20T05:00:00.000Z'; + +describe('autoTransitionNote', () => { + it.each([ + [ + '입금 대기는 입금 기한', + order('PENDING_PAYMENT'), + false, + '11-19 10:00까지 입금이 확인되지 않으면 자동 취소됩니다.', + ], + [ + "'입금했어요'를 누른 입금 대기는 자동 취소에서 빠진다", + order('PENDING_PAYMENT', { payment: payment('2026-11-19T00:30:00.000Z') }), + false, + '구매자가 11-19 09:30에 입금했다고 알려 자동 취소되지 않습니다. 입금을 확인하거나 미입금으로 취소하세요.', + ], + [ + '접수는 확정 마감', + order('SUBMITTED', { confirmDeadlineAt: AT }), + true, + '11-20 14:00까지 판매자가 확정하지 않으면 자동 취소·전액 환불됩니다.', + ], + [ + '확정은 자동 픽업 완료', + order('CONFIRMED', { autoPickupAt: AT }), + false, + '11-20 14:00에 자동으로 픽업 완료됩니다.', + ], + [ + '숨김 매장의 제작 완료는 직접 처리 안내', + order('MADE', { autoPickupAt: AT }), + true, + '매장이 숨김이라 11-20 14:00에 자동 픽업 완료되지 않습니다. 픽업 완료나 강제 취소로 직접 처리하세요.', + ], + [ + '매장 숨김 여부를 아직 모르면 자동 픽업 완료를 단정하지 않는다', + order('CONFIRMED', { autoPickupAt: AT }), + null, + '11-20 14:00에 자동 픽업 완료 예정입니다. 매장이 숨김이면 자동으로 처리되지 않습니다.', + ], + ['결제 도입 전 입금 대기는 없음', order('PENDING_PAYMENT', { payment: null }), false, null], + ['결제 도입 전 접수(마감 null)는 없음', order('SUBMITTED'), false, null], + ['종료 상태는 없음', order('PICKED_UP'), false, null], + ])('%s', (_, o, hidden, note) => { + expect(autoTransitionNote(o, hidden)).toBe(note); + }); +}); + +describe('storeHiddenOf', () => { + const active = { isActive: true }; + it.each([ + ['처음 조회 중', { isSuccess: false, isFetching: true }, null], + ['처음 조회 실패', { isSuccess: false, isFetching: false }, null], + ['옛 값을 다시 조회 중', { data: active, isSuccess: true, isFetching: true }, null], + ['옛 값이 있는데 다시 조회 실패', { data: active, isSuccess: false, isFetching: false }, null], + ['노출 매장', { data: active, isSuccess: true, isFetching: false }, false], + ['숨김 매장', { data: { isActive: false }, isSuccess: true, isFetching: false }, true], + ])('%s', (_, q, hidden) => { + expect(storeHiddenOf(q)).toBe(hidden); + }); +}); diff --git a/src/features/orders/auto-transition.ts b/src/features/orders/auto-transition.ts new file mode 100644 index 0000000..fc46ee0 --- /dev/null +++ b/src/features/orders/auto-transition.ts @@ -0,0 +1,35 @@ +import { type AdminOrderQuery } from '@/graphql/generated/graphql'; +import { formatKst } from '@/shared/lib/kst'; + +type Order = Pick< + AdminOrderQuery['adminOrder'], + 'status' | 'payment' | 'confirmDeadlineAt' | 'autoPickupAt' +>; + +/** 지금 상태에서 시스템이 언제 무엇을 할지. 숨김 매장은 자동 픽업 완료가 돌지 않는다(null = 아직 모름) */ +export function autoTransitionNote(o: Order, storeHidden: boolean | null): string | null { + if (o.status === 'PENDING_PAYMENT' && o.payment) { + return o.payment.buyerClaimedAt + ? `구매자가 ${formatKst(o.payment.buyerClaimedAt)}에 입금했다고 알려 자동 취소되지 않습니다. 입금을 확인하거나 미입금으로 취소하세요.` + : `${formatKst(o.payment.expiresAt)}까지 입금이 확인되지 않으면 자동 취소됩니다.`; + } + if (o.status === 'SUBMITTED' && o.confirmDeadlineAt) { + return `${formatKst(o.confirmDeadlineAt)}까지 판매자가 확정하지 않으면 자동 취소·전액 환불됩니다.`; + } + if (o.autoPickupAt) { + const at = formatKst(o.autoPickupAt); + if (storeHidden === null) + return `${at}에 자동 픽업 완료 예정입니다. 매장이 숨김이면 자동으로 처리되지 않습니다.`; + return storeHidden + ? `매장이 숨김이라 ${at}에 자동 픽업 완료되지 않습니다. 픽업 완료나 강제 취소로 직접 처리하세요.` + : `${at}에 자동으로 픽업 완료됩니다.`; + } + return null; +} + +/** 매장 조회 → 숨김 여부. 조회 중·실패면 옛 값일 수 있어 null(모른다) */ +export const storeHiddenOf = (q: { + data?: { isActive: boolean }; + isSuccess: boolean; + isFetching: boolean; +}): boolean | null => (q.data && q.isSuccess && !q.isFetching ? !q.data.isActive : null); diff --git a/src/features/orders/cancel-form.spec.ts b/src/features/orders/cancel-form.spec.ts new file mode 100644 index 0000000..9468ee8 --- /dev/null +++ b/src/features/orders/cancel-form.spec.ts @@ -0,0 +1,158 @@ +import { type CancelRefundRuleType } from '@/graphql/generated/graphql'; + +import { + CANCEL_NOTE_MAX, + type CancelForm, + type CancelOptions, + EMPTY_CANCEL_FORM, + buildCancelInput, + cancelSummary, + noteLength, + parseRefundAmount, +} from './cancel-form'; + +const PAID = 30000; +const options = (refundRule: CancelRefundRuleType | null, paidAmount = PAID): CancelOptions => ({ + cancelable: refundRule !== null, + reasons: ['OUT_OF_MATERIALS', 'OTHER'], + refundRule, + paidAmount, +}); +const form = (patch: Partial = {}): CancelForm => ({ + ...EMPTY_CANCEL_FORM, + reason: 'OTHER', + ...patch, +}); +const base = { orderId: '0', reason: 'OTHER', note: null }; + +describe('buildCancelInput', () => { + const FAULTS = ['', 'SELLER', 'BUYER'] as const; + const AMOUNTS = ['', '0', ' 7 ', '30000', '30001', '-1', '1.5', '1e3', '3']; + + /** 기대값은 구현과 따로: BY_FAULT만 사정을 묻고, 구매자 사정만 0~결제액 정수 금액을 받는다 */ + function expected(rule: CancelRefundRuleType, fault: string, amount: string) { + if (rule !== 'BY_FAULT') return { input: base }; + if (fault === '') return { issue: 'FAULT_REQUIRED' }; + if (fault === 'SELLER') return { input: { ...base, fault: 'SELLER' } }; + if (amount === '') return { issue: 'AMOUNT_REQUIRED' }; + const ok: Record = { '0': 0, ' 7 ': 7, '30000': 30000 }; + return amount in ok + ? { input: { ...base, fault: 'BUYER', refundAmount: ok[amount] } } + : { issue: 'AMOUNT_OUT_OF_RANGE' }; + } + + const cases = (['NO_REFUND', 'FULL_REFUND', 'BY_FAULT'] as const).flatMap((rule) => + FAULTS.flatMap((fault) => + AMOUNTS.map((amount) => [rule, fault, amount, expected(rule, fault, amount)] as const), + ), + ); + + it('표는 규칙 3 × 사정 3 × 금액 9를 덮고 금액을 보내는 경우는 3개다', () => { + expect(cases).toHaveLength(81); + const withAmount = cases.filter(([, , , r]) => 'refundAmount' in (r.input ?? {})); + expect(withAmount).toHaveLength(3); + }); + + it.each(cases)('%s fault=%j 금액=%j → %j', (rule, fault, refundAmount, result) => { + // ID "0"도 그대로 보낸다 + expect(buildCancelInput('0', options(rule), form({ fault, refundAmount }))).toEqual(result); + }); + + it('결제액이 0이면 구매자 사정 금액은 0만 받는다', () => { + const o = options('BY_FAULT', 0); + expect(buildCancelInput('1', o, form({ fault: 'BUYER', refundAmount: '0' }))).toMatchObject({ + input: { refundAmount: 0 }, + }); + expect(buildCancelInput('1', o, form({ fault: 'BUYER', refundAmount: '1' }))).toEqual({ + issue: 'AMOUNT_OUT_OF_RANGE', + }); + }); + + it.each([ + ['고르지 않은 사유', { reason: '' }], + ['선택지에 없는 사유', { reason: 'PAYMENT_NOT_RECEIVED' }], + ['프로토타입 키', { reason: 'constructor' }], + ])('%s는 REASON_REQUIRED', (_, patch) => { + expect(buildCancelInput('1', options('FULL_REFUND'), form(patch))).toEqual({ + issue: 'REASON_REQUIRED', + }); + }); + + it('취소할 수 없는 주문은 입력과 관계없이 NOT_CANCELABLE', () => { + expect(buildCancelInput('1', { ...options('FULL_REFUND'), cancelable: false }, form())).toEqual( + { issue: 'NOT_CANCELABLE' }, + ); + }); + + it.each([ + ['앞뒤 공백은 빼고 보낸다', ' 재고 없음 ', '재고 없음'], + ['공백만이면 null', ' ', null], + ['이모지 500자는 받는다', '🎂'.repeat(CANCEL_NOTE_MAX), '🎂'.repeat(CANCEL_NOTE_MAX)], + ])('메모: %s', (_, note, sent) => { + expect(buildCancelInput('1', options('FULL_REFUND'), form({ note }))).toEqual({ + input: { orderId: '1', reason: 'OTHER', note: sent }, + }); + }); + + it('메모는 코드 포인트 501자부터 NOTE_TOO_LONG', () => { + expect(noteLength(` ${'🎂'.repeat(CANCEL_NOTE_MAX)} `)).toBe(CANCEL_NOTE_MAX); + expect( + buildCancelInput('1', options('NO_REFUND'), form({ note: 'a'.repeat(CANCEL_NOTE_MAX + 1) })), + ).toEqual({ issue: 'NOTE_TOO_LONG' }); + }); +}); + +describe('parseRefundAmount', () => { + it.each([ + ['0', 0], + ['007', 7], + ['30000', 30000], + ['30001', null], + ['', null], + ['1,000', null], + ['99999999999999999999', null], + ])('%j → %s', (raw, n) => { + expect(parseRefundAmount(raw, PAID)).toBe(n); + }); +}); + +describe('cancelSummary', () => { + it.each([ + ['NO_REFUND', {}, PAID, '입금 전 주문이라 환불 없이 취소합니다.'], + ['FULL_REFUND', {}, PAID, '결제액 30,000원을 전액 환불합니다.'], + ['FULL_REFUND', {}, 0, '확인된 결제액이 없어 환불 없이 취소합니다.'], + ['BY_FAULT', {}, PAID, '사정을 고르면 환불 금액이 정해집니다.'], + ['BY_FAULT', { fault: 'SELLER' }, PAID, '판매자 사정이라 결제액 30,000원을 전액 환불합니다.'], + [ + 'BY_FAULT', + { fault: 'BUYER', refundAmount: '0' }, + PAID, + '0원을 환불하고, 남은 30,000원은 수수료를 뺀 뒤 매장 정산에 포함합니다.', + ], + [ + 'BY_FAULT', + { fault: 'BUYER', refundAmount: '10000' }, + PAID, + '10,000원을 환불하고, 남은 20,000원은 수수료를 뺀 뒤 매장 정산에 포함합니다.', + ], + [ + 'BY_FAULT', + { fault: 'BUYER', refundAmount: '30000' }, + PAID, + '결제액 30,000원을 전액 환불합니다.', + ], + [ + 'BY_FAULT', + { fault: 'BUYER', refundAmount: '' }, + PAID, + '환불 금액을 0원~30,000원 사이 정수로 입력하세요.', + ], + ] as const)('%s %j 결제액 %i → %s', (rule, patch, paid, text) => { + expect(cancelSummary(options(rule, paid), form(patch))).toBe(text); + }); + + it('취소할 수 없거나 모르는 규칙이면 요약이 없다', () => { + expect(cancelSummary(options(null), form())).toBeNull(); + expect(cancelSummary(options('PARTIAL' as CancelRefundRuleType), form())).toBeNull(); + }); +}); diff --git a/src/features/orders/cancel-form.ts b/src/features/orders/cancel-form.ts new file mode 100644 index 0000000..4826dfc --- /dev/null +++ b/src/features/orders/cancel-form.ts @@ -0,0 +1,82 @@ +import { + type AdminCancelOrderInput, + type AdminOrderQuery, + type OrderCancelFaultType, +} from '@/graphql/generated/graphql'; +import { formatKrw } from '@/shared/lib/format'; + +export type CancelOptions = AdminOrderQuery['adminOrder']['cancelOptions']; + +export const CANCEL_NOTE_MAX = 500; + +export interface CancelForm { + /** '' = 고르지 않음 */ + reason: string; + fault: '' | OrderCancelFaultType; + /** 입력 원문 */ + refundAmount: string; + note: string; +} + +export const EMPTY_CANCEL_FORM: CancelForm = { reason: '', fault: '', refundAmount: '', note: '' }; + +export type CancelFormIssue = + | 'NOT_CANCELABLE' + | 'REASON_REQUIRED' + | 'NOTE_TOO_LONG' + | 'FAULT_REQUIRED' + | 'AMOUNT_REQUIRED' + | 'AMOUNT_OUT_OF_RANGE'; + +/** BE처럼 앞뒤 공백을 뺀 코드 포인트 수(이모지도 1자) */ +export const noteLength = (note: string) => [...note.trim()].length; + +/** 사정을 고르는 규칙인지. 금액 입력은 그중 구매자 사정일 때만 */ +export const asksFault = (o: CancelOptions) => o.refundRule === 'BY_FAULT'; +export const asksAmount = (o: CancelOptions, f: CancelForm) => asksFault(o) && f.fault === 'BUYER'; + +/** 구매자 사정 환불액. 0~결제액 정수만 받고 아니면 null('0'은 유효) */ +export function parseRefundAmount(raw: string, paidAmount: number): number | null { + const t = raw.trim(); + if (!/^\d+$/.test(t)) return null; + const n = Number(t); + return n <= paidAmount ? n : null; +} + +/** 다이얼로그 입력 → adminCancelOrder 입력. 규칙은 cancelOptions가 정하고 화면은 복제하지 않는다 */ +export function buildCancelInput( + orderId: string, + o: CancelOptions, + f: CancelForm, +): { input: AdminCancelOrderInput } | { issue: CancelFormIssue } { + if (!o.cancelable) return { issue: 'NOT_CANCELABLE' }; + const reason = o.reasons.find((r) => r === f.reason); + if (!reason) return { issue: 'REASON_REQUIRED' }; + if (noteLength(f.note) > CANCEL_NOTE_MAX) return { issue: 'NOTE_TOO_LONG' }; + const base = { orderId, reason, note: f.note.trim() || null }; + if (!asksFault(o)) return { input: base }; + if (f.fault === '') return { issue: 'FAULT_REQUIRED' }; + if (f.fault === 'SELLER') return { input: { ...base, fault: 'SELLER' } }; + if (f.refundAmount.trim() === '') return { issue: 'AMOUNT_REQUIRED' }; + const refundAmount = parseRefundAmount(f.refundAmount, o.paidAmount); + if (refundAmount === null) return { issue: 'AMOUNT_OUT_OF_RANGE' }; + return { input: { ...base, fault: 'BUYER', refundAmount } }; +} + +/** 확인 버튼 위 요약. 고른 사정·금액으로 무엇이 일어나는지 */ +export function cancelSummary(o: CancelOptions, f: CancelForm): string | null { + const paid = formatKrw(o.paidAmount); + const full = + o.paidAmount > 0 + ? `결제액 ${paid}을 전액 환불합니다.` + : '확인된 결제액이 없어 환불 없이 취소합니다.'; + if (o.refundRule === 'NO_REFUND') return '입금 전 주문이라 환불 없이 취소합니다.'; + if (o.refundRule === 'FULL_REFUND') return full; + if (!asksFault(o)) return null; + if (f.fault === 'SELLER') return `판매자 사정이라 ${full}`; + if (f.fault !== 'BUYER') return '사정을 고르면 환불 금액이 정해집니다.'; + const r = parseRefundAmount(f.refundAmount, o.paidAmount); + if (r === null) return `환불 금액을 0원~${paid} 사이 정수로 입력하세요.`; + if (r === o.paidAmount) return full; + return `${formatKrw(r)}을 환불하고, 남은 ${formatKrw(o.paidAmount - r)}은 수수료를 뺀 뒤 매장 정산에 포함합니다.`; +} diff --git a/src/features/orders/components/cancel-order-dialog.tsx b/src/features/orders/components/cancel-order-dialog.tsx index 779b879..fb3df80 100644 --- a/src/features/orders/components/cancel-order-dialog.tsx +++ b/src/features/orders/components/cancel-order-dialog.tsx @@ -2,7 +2,9 @@ import { useQueryClient } from '@tanstack/react-query'; import { useState } from 'react'; import { toast } from 'sonner'; -import { messageFor } from '@/shared/api'; +import { ApiError, messageFor } from '@/shared/api'; +import { formatKrw } from '@/shared/lib/format'; +import { cn } from '@/shared/lib/utils'; import { Button } from '@/shared/ui/button'; import { Dialog, @@ -13,77 +15,218 @@ import { DialogTitle, DialogTrigger, } from '@/shared/ui/dialog'; +import { Input } from '@/shared/ui/input'; import { Label } from '@/shared/ui/label'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'; import { Textarea } from '@/shared/ui/textarea'; import { cancelOrder } from '../api/queries'; +import { + CANCEL_NOTE_MAX, + type CancelForm, + type CancelOptions, + EMPTY_CANCEL_FORM, + asksAmount, + asksFault, + buildCancelInput, + cancelSummary, + noteLength, + parseRefundAmount, +} from '../cancel-form'; +import { cancelFaultLabel, cancelReasonLabel } from '../meta'; -const NOTE_MAX = 500; +const FAULTS = ['SELLER', 'BUYER'] as const; export function CancelOrderDialog({ orderId, orderNumber, + options, }: { orderId: string; orderNumber: string; + options: CancelOptions; }) { const queryClient = useQueryClient(); const [open, setOpen] = useState(false); - const [note, setNote] = useState(''); + const [form, setForm] = useState(EMPTY_CANCEL_FORM); const [busy, setBusy] = useState(false); - const trimmed = note.trim(); - const invalid = trimmed.length === 0 || trimmed.length > NOTE_MAX; + const [error, setError] = useState(null); + const set = (patch: Partial) => { + setError(null); + setForm((f) => ({ ...f, ...patch })); + }; + // 거절 뒤 재조회로 선택지에서 빠진 사유는 고르지 않은 것으로 보인다 + const reason = options.reasons.find((r) => r === form.reason) ?? ''; + const built = buildCancelInput(orderId, options, form); + const summary = cancelSummary(options, form); + const noteLen = noteLength(form.note); + const amountInvalid = + form.refundAmount.trim() !== '' && + parseRefundAmount(form.refundAmount, options.paidAmount) === null; const submit = async () => { + if (!('input' in built)) return; setBusy(true); + setError(null); try { - await cancelOrder(queryClient, orderId, trimmed); + await cancelOrder(queryClient, built.input); toast.success(`${orderNumber} 주문을 취소했습니다.`); setOpen(false); - setNote(''); } catch (e) { - toast.error(messageFor(e)); + // 입력 오류는 폼 위에. 취소 불가는 재조회로 다이얼로그가 버튼과 함께 사라지므로 토스트로 알린다 + const inForm = + e instanceof ApiError && + e.classification === 'BAD_USER_INPUT' && + e.code !== 'ORDER_NOT_CANCELLABLE'; + if (inForm) setError(messageFor(e)); + else toast.error(messageFor(e)); } finally { setBusy(false); } }; return ( - + { + setOpen(o); + // 거절 뒤 선택지가 바뀌었을 수 있어 열 때마다 새로 입력받는다 + if (o) setForm(EMPTY_CANCEL_FORM); + setError(null); + }} + > - 주문을 취소할까요? + 주문을 강제 취소할까요? - {orderNumber} 주문을 취소하면 구매자에게 취소 알림을 보냅니다. 사유는 상태 이력과 감사 - 로그에 남고, 취소한 주문은 되돌릴 수 없습니다. + {orderNumber} 주문을 취소하면 구매자에게 알림이 가고, 입금이 확인된 주문이면 + 판매자에게도 알립니다. 사유는 상태 이력과 감사 로그에 남고, 취소한 주문은 되돌릴 수 + 없습니다. -
- -