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 @@ -40,6 +40,7 @@ src/
- **mutation 뒤**에는 그 feature의 list·detail 키를 invalidate한다. 낙관적 업데이트는 쓰지 않는다 — 감사 대상 작업이라 서버 결과가 진실이다.
- **목록**은 커서 방식(`items · totalCount · hasMore · nextCursor`). 필터·커서는 URL 검색 파라미터(zod)로 유지해 새로고침·공유가 된다.
- **ID**는 문자열 그대로. `"0"`·빈 문자열을 truthy 검사로 버리지 않는다.
- **enum 라벨**은 `Record<생성 enum, …>`로 둬 값이 늘면 tsc가 잡게 하고, 조회는 모르는 값에 원문으로 폴백한다. BE가 먼저 배포돼 새 값이 와도 화면이 죽지 않아야 한다.
- **날짜**는 표시·입력 KST, 전송 ISO(UTC). 기간 필터의 경계는 KST 하루 시작·끝을 UTC로 바꿔 보낸다.

## 4. 인증
Expand Down
43 changes: 23 additions & 20 deletions docs/guide/decisions.md

Large diffs are not rendered by default.

3,651 changes: 3,277 additions & 374 deletions schema/schema.graphql

Large diffs are not rendered by default.

18 changes: 18 additions & 0 deletions src/features/audit-logs/meta.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,24 @@ describe('감사 대상 유형 라벨', () => {
expect(targetLabel(value)).not.toBe(value);
});

it.each([
['PAYMENT_SETTING', '결제 설정'],
['SETTLEMENT_ACCOUNT', '정산 계좌'],
['SETTLEMENT', '정산'],
['REFUND', '환불'],
['DEPOSIT_RECORD', '입금 기록'],
])('결제·정산 대상 %s의 라벨: %s', (value, label) => {
expect(targetLabel(value)).toBe(label);
});

it.each([['PAYOUT'], ['constructor'], ['']])(
'모르는 유형 %j는 원문으로 보이고 필터에는 나오지 않는다',
(value) => {
expect(targetLabel(value)).toBe(value);
expect(auditSearchSchema.parse({ targetType: value }).targetType).toBeUndefined();
},
);

it('스키마에 없는 유형은 라벨 표에도 없다', () => {
const known = new Set(schemaTargetTypes());
expect(TARGET_TYPES.map((t) => t.value).filter((v) => !known.has(v))).toEqual([]);
Expand Down
5 changes: 5 additions & 0 deletions src/features/audit-logs/meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ const TARGET_LABELS: Record<AuditTargetType, string> = {
REVIEW_REPORT: '신고',
NOTIFICATION: '알림',
CONVERSATION: '대화',
PAYMENT_SETTING: '결제 설정',
SETTLEMENT_ACCOUNT: '정산 계좌',
SETTLEMENT: '정산',
REFUND: '환불',
DEPOSIT_RECORD: '입금 기록',
};
export const TARGET_TYPES = (Object.keys(TARGET_LABELS) as AuditTargetType[]).map((value) => ({
value,
Expand Down
16 changes: 16 additions & 0 deletions src/features/custom/components/color-swatch.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const HEX = /^#[0-9A-Fa-f]{6}$/;

/** 판매자가 고른 글자색 견본과 값. 형식이 어긋난 값은 견본 없이 글자만 보인다 */
export function ColorSwatch({ color }: { color: string }) {
return (
<span className="inline-flex items-center gap-1.5 font-mono text-xs">
<span
aria-hidden
data-slot="color-swatch"
className="size-3.5 shrink-0 rounded-sm border"
style={HEX.test(color) ? { backgroundColor: color } : undefined}
/>
{color}
</span>
);
}
62 changes: 62 additions & 0 deletions src/features/custom/custom-geometry.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { areaToPercent, splitCustomImages } from './custom-geometry';

describe('areaToPercent', () => {
it.each([
['바탕 전체', [0, 0, 10000, 10000], ['0%', '0%', '100%', '100%']],
['소수 둘째 자리', [1234, 5678, 100, 1], ['12.34%', '56.78%', '1%', '0.01%']],
['오른쪽 아래 끝 1칸', [9999, 9999, 1, 1], ['99.99%', '99.99%', '0.01%', '0.01%']],
['넘치는 크기는 바탕 끝까지', [5000, 2500, 6000, 9000], ['50%', '25%', '50%', '75%']],
['범위 밖 시작점은 가장자리로', [-10, 12000, 100, 100], ['0%', '100%', '1%', '0%']],
['음수 크기는 0', [100, 100, -5, -1], ['1%', '1%', '0%', '0%']],
['숫자가 아니면 0', [Number.NaN, 0, Number.POSITIVE_INFINITY, 10], ['0%', '0%', '0%', '0.1%']],
])('%s', (_, [posX, posY, width, height], [left, top, w, h]) => {
expect(areaToPercent({ posX: posX!, posY: posY!, width: width!, height: height! })).toEqual({
left,
top,
width: w,
height: h,
});
});
});

const img = (kind: string) => ({ kind, imageUrl: `https://img.test/${kind}.png` });
const kinds = (list: readonly { kind: string }[]) => list.map((i) => i.kind);

describe('splitCustomImages', () => {
it('3D 5장은 받은 순서와 관계없이 윗면 → 앞·뒤·왼·오다', () => {
const r = splitCustomImages(
['THREE_D_RIGHT', 'THREE_D_BACK', 'THREE_D_TOP', 'THREE_D_LEFT', 'THREE_D_FRONT'].map(img),
);
expect(r.top?.kind).toBe('THREE_D_TOP');
expect(kinds(r.sides)).toEqual([
'THREE_D_FRONT',
'THREE_D_BACK',
'THREE_D_LEFT',
'THREE_D_RIGHT',
]);
expect(r.composite).toBeNull();
});

it('슬롯형 합성은 렌더와 따로 나온다', () => {
const r = splitCustomImages([img('SLOT_COMPOSITE')]);
expect(r).toEqual({ top: null, sides: [], composite: img('SLOT_COMPOSITE') });
});

it('모르는 종류는 버리지 않고 옆면 뒤에 받은 순서대로 둔다', () => {
const r = splitCustomImages(['HOLOGRAM', 'THREE_D_LEFT', 'THREE_D_TOP', 'BOTTOM'].map(img));
expect(r.top?.kind).toBe('THREE_D_TOP');
expect(kinds(r.sides)).toEqual(['THREE_D_LEFT', 'HOLOGRAM', 'BOTTOM']);
});

it('윗면이 없으면 렌더는 전부 옆면 자리에 둔다', () => {
const r = splitCustomImages(['THREE_D_BACK', 'THREE_D_FRONT'].map(img));
expect(r.top).toBeNull();
expect(kinds(r.sides)).toEqual(['THREE_D_FRONT', 'THREE_D_BACK']);
});

it('이미지가 없으면 모두 비어 있고 입력 배열은 바꾸지 않는다', () => {
expect(splitCustomImages([])).toEqual({ top: null, sides: [], composite: null });
const input = Object.freeze(['THREE_D_FRONT', 'THREE_D_TOP'].map(img));
expect(() => splitCustomImages(input)).not.toThrow();
});
});
52 changes: 52 additions & 0 deletions src/features/custom/custom-geometry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/** 커스텀 좌표는 바탕 이미지 한 변을 10000으로 본 정수 비율이고 원점은 왼쪽 위다 */
const SCALE = 10000;

interface Area {
posX: number;
posY: number;
width: number;
height: number;
}

const clamp = (v: number, max: number) => Math.min(Math.max(Number.isFinite(v) ? v : 0, 0), max);
const percent = (v: number) => `${v / 100}%`;

/** 바탕 위 영역을 CSS 백분율 위치로 바꾼다. 범위 밖 값은 바탕 안으로 자른다 */
export function areaToPercent(a: Area) {
const left = clamp(a.posX, SCALE);
const top = clamp(a.posY, SCALE);
return {
left: percent(left),
top: percent(top),
width: percent(clamp(a.width, SCALE - left)),
height: percent(clamp(a.height, SCALE - top)),
};
}

const RENDER_ORDER: readonly string[] = [
'THREE_D_TOP',
'THREE_D_FRONT',
'THREE_D_BACK',
'THREE_D_LEFT',
'THREE_D_RIGHT',
];

/**
* 커스텀 이미지를 윗면 · 옆면(앞·뒤·왼·오) · 슬롯형 합성으로 나눈다.
* 모르는 종류는 버리지 않고 옆면 뒤에 받은 순서대로 둔다.
*/
export function splitCustomImages<T extends { kind: string }>(images: readonly T[]) {
const rank = (kind: string) => {
const i = RENDER_ORDER.indexOf(kind);
return i === -1 ? RENDER_ORDER.length : i;
};
const renders = images
.filter((i) => i.kind !== 'SLOT_COMPOSITE')
.sort((a, b) => rank(a.kind) - rank(b.kind));
const top = renders[0]?.kind === 'THREE_D_TOP' ? renders[0] : null;
return {
top,
sides: top ? renders.slice(1) : renders,
composite: images.find((i) => i.kind === 'SLOT_COMPOSITE') ?? null,
};
}
9 changes: 9 additions & 0 deletions src/features/custom/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export { ColorSwatch } from './components/color-swatch';
export { areaToPercent, splitCustomImages } from './custom-geometry';
export {
customModeLabel,
imageKindLabel,
SLOT_TEXT_STATE_LABEL,
slotTextState,
textAlignLabel,
} from './meta';
78 changes: 78 additions & 0 deletions src/features/custom/meta.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { buildSchema, isEnumType } from 'graphql';

// codegen이 읽는 SDL 스냅샷 원문. 손으로 적은 라벨 표와 대조하는 정답지다
import sdl from '../../../schema/schema.graphql?raw';

import {
customModeLabel,
imageKindLabel,
SLOT_TEXT_STATE_LABEL,
slotTextState,
textAlignLabel,
} from './meta';

function enumValues(name: string): string[] {
const t = buildSchema(sdl).getType(name);
if (!isEnumType(t)) throw new Error(`${name} enum이 스키마에 없다`);
return t.getValues().map((v) => v.name);
}

const TABLES = [
['CustomModeType', customModeLabel],
['CustomTextAlignType', textAlignLabel],
['CustomImageKindType', imageKindLabel],
] as const;

describe('커스텀 enum 라벨', () => {
it.each(TABLES)('%s 값이 스키마에 있다(정답지가 비어 통과하지 않게)', (name) => {
expect(enumValues(name).length).toBeGreaterThanOrEqual(3);
});

it.each(TABLES.flatMap(([name, fn]) => enumValues(name).map((v) => [name, v, fn] as const)))(
'%s.%s는 원문이 아닌 한국어 라벨로 보인다',
(_, value, fn) => {
expect(fn(value)).not.toBe(value);
},
);

it.each([['HOLOGRAM'], ['constructor'], ['toString'], ['']])(
'모르는 값 %j는 원문으로 보인다',
(value) => {
for (const [, fn] of TABLES) expect(fn(value)).toBe(value);
},
);

it('대표 라벨', () => {
expect([customModeLabel('SLOT'), customModeLabel('THREE_D')]).toEqual(['슬롯형', '3D']);
expect(textAlignLabel('CENTER')).toBe('가운데');
expect(imageKindLabel('THREE_D_TOP')).toBe('윗면');
});
});

describe('slotTextState', () => {
it.each([
['기본 문구 그대로', 'DEFAULT', '축하해', '축하해'],
[
'기본 문구의 CRLF·앞뒤 공백은 저장 규칙대로 맞춰 본다',
'DEFAULT',
' 생일\r\n축하해 ',
'생일\n축하해',
],
['기본 문구의 홀로 있는 CR도 LF로 맞춰 본다', 'DEFAULT', '생일\r축하해', '생일\n축하해'],
['바꾼 문구', 'CHANGED', '축하해', '서연아 생일 축하해 🎂'],
['줄바꿈만 다름', 'CHANGED', '생일 축하해', '생일\n축하해'],
['선택 자리를 지움(null)', 'EMPTY', '축하해', null],
['빈 문자열', 'EMPTY', '축하해', ''],
['기본 문구가 비어 있고 입력도 없음', 'EMPTY', '', null],
] as const)('%s → %s', (_, state, defaultText, valueText) => {
expect(slotTextState({ defaultText, valueText })).toBe(state);
});

it('상태마다 라벨이 있다', () => {
expect(SLOT_TEXT_STATE_LABEL).toEqual({
DEFAULT: '기본 그대로',
CHANGED: '바꿈',
EMPTY: '문구 없음',
});
});
});
42 changes: 42 additions & 0 deletions src/features/custom/meta.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {
type CustomImageKindType,
type CustomModeType,
type CustomTextAlignType,
} from '@/graphql/generated/graphql';

// Record라 codegen enum에 값이 늘면 tsc가 잡는다. 화면은 BE가 먼저 배포돼 모르는 값이 와도 원문으로 보인다
const MODE: Record<CustomModeType, string> = { NONE: '없음', SLOT: '슬롯형', THREE_D: '3D' };
const ALIGN: Record<CustomTextAlignType, string> = {
LEFT: '왼쪽',
CENTER: '가운데',
RIGHT: '오른쪽',
};
const IMAGE_KIND: Record<CustomImageKindType, string> = {
THREE_D_TOP: '윗면',
THREE_D_FRONT: '앞',
THREE_D_BACK: '뒤',
THREE_D_LEFT: '왼쪽',
THREE_D_RIGHT: '오른쪽',
SLOT_COMPOSITE: '합성 이미지',
};

/** 표에 있는 값만 라벨로 바꾼다. `constructor` 같은 프로토타입 키도 모르는 값이다 */
const label = (table: Record<string, string>, value: string) =>
Object.hasOwn(table, value) ? table[value]! : value;

export const customModeLabel = (v: string) => label(MODE, v);
export const textAlignLabel = (v: string) => label(ALIGN, v);
export const imageKindLabel = (v: string) => label(IMAGE_KIND, v);

export type SlotTextState = 'DEFAULT' | 'CHANGED' | 'EMPTY';
export const SLOT_TEXT_STATE_LABEL: Record<SlotTextState, string> = {
DEFAULT: '기본 그대로',
CHANGED: '바꿈',
EMPTY: '문구 없음',
};

/** BE는 문구의 CRLF·CR을 LF로 바꾸고 trim해 저장하므로 기본 문구도 같은 규칙으로 맞춰 비교한다 */
export function slotTextState(t: { defaultText: string; valueText: string | null }): SlotTextState {
if (t.valueText === null || t.valueText === '') return 'EMPTY';
return t.valueText === t.defaultText.replace(/\r\n?/g, '\n').trim() ? 'DEFAULT' : 'CHANGED';
}
27 changes: 24 additions & 3 deletions src/features/orders/api/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const AdminOrdersDocument = graphql(/* GraphQL */ `
buyerPhone
totalPrice
createdAt
hasCustom
}
totalCount
hasMore
Expand Down Expand Up @@ -81,16 +82,34 @@ const AdminOrderDocument = graphql(/* GraphQL */ `
optionTitle
priceDelta
}
customMode
customPreviewImageUrl
customBaseImageUrl
customImages {
id
kind
imageUrl
}
customTexts {
id
tokenKey
label
defaultText
valueText
posX
posY
width
height
textColor
textAlign
sortOrder
}
freeEdits {
id
cropImageUrl
posX
posY
width
height
descriptionText
sortOrder
attachments {
Expand Down Expand Up @@ -248,9 +267,11 @@ export function buyerNameQueryOptions(accountId: string) {
});
}

/** 사유 코드 선택은 아직 없어 '기타' + 입력한 메모로 보낸다 */
export async function cancelOrder(queryClient: QueryClient, orderId: string, note: string) {
const result = (await gqlRequest(AdminCancelOrderDocument, { input: { orderId, note } }))
.adminCancelOrder;
const result = (
await gqlRequest(AdminCancelOrderDocument, { input: { orderId, reason: 'OTHER', note } })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the unpaid-order cancellation reason for pending payments

For an unpaid PENDING_PAYMENT order, the newly enabled cancellation dialog always submits OTHER, although the updated adminCancelOrder contract specifies PAYMENT_NOT_RECEIVED for cancellation due to nonpayment (schema/schema.graphql:2611–2615). The input must also use a reason from cancelOptions.reasons, otherwise the server returns CANCEL_REASON_NOT_ALLOWED. Consequently, the new pending-payment cancellation action cannot submit the prescribed nonpayment cancellation. Fetch and use the order's cancellation options, or pass the appropriate pending-payment reason instead of unconditionally sending OTHER.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

미반영(기록): 단계 분할. BE 정책상 관리자는 입금 대기 주문에 OTHER도 허용(CANCEL_REASON_NOT_ALLOWED 아님)이라 지금도 취소는 성공함. 미입금 사유(PAYMENT_NOT_RECEIVED) 선택을 포함한 cancelOptions 기반 취소 다이얼로그는 다음 PR(주문 결제·취소)에서 넣고, 관리자 릴리즈는 그 뒤라 운영 노출 없음.

).adminCancelOrder;
await Promise.all([
queryClient.invalidateQueries({ queryKey: ordersKeys.detail(orderId) }),
queryClient.invalidateQueries({ queryKey: ordersKeys.lists() }),
Expand Down
6 changes: 3 additions & 3 deletions src/features/orders/components/cancel-order-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { Textarea } from '@/shared/ui/textarea';

import { cancelOrder } from '../api/queries';

const NOTE_MAX = 494;
const NOTE_MAX = 500;

export function CancelOrderDialog({
orderId,
Expand Down Expand Up @@ -59,8 +59,8 @@ export function CancelOrderDialog({
<DialogHeader>
<DialogTitle>주문을 취소할까요?</DialogTitle>
<DialogDescription>
{orderNumber} 주문을 취소하면 구매자에게 취소 알림을 보냅니다. 사유는 상태 이력에
"[관리자]"로 시작하는 메모로 남고, 취소한 주문은 되돌릴 수 없습니다.
{orderNumber} 주문을 취소하면 구매자에게 취소 알림을 보냅니다. 사유는 상태 이력과 감사
로그에 남고, 취소한 주문은 되돌릴 수 없습니다.
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-1.5">
Expand Down
Loading
Loading