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
13 changes: 13 additions & 0 deletions src/common/errors/error-catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,19 @@ export const ERROR_CATALOG = {
status: HttpStatus.CONFLICT,
message: '이미 반환 대상으로 연결된 입금 기록입니다.',
},
SETTLEMENT_NOT_FOUND: {
status: HttpStatus.NOT_FOUND,
message: '정산 내역을 찾을 수 없어요.',
},
SETTLEMENT_ALREADY_PAID: {
status: HttpStatus.CONFLICT,
message: '이미 송금 완료로 처리된 정산이에요.',
},
SETTLEMENT_ACCOUNT_REQUIRED: {
status: HttpStatus.BAD_REQUEST,
message:
'매장 정산 계좌가 등록되지 않아 송금 완료로 처리할 수 없어요. 정산 계좌를 먼저 등록해 주세요.',
},
// ── 판매자
SELLER_ONLY: {
status: HttpStatus.FORBIDDEN,
Expand Down
37 changes: 37 additions & 0 deletions src/common/utils/kst-time.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import {
daysInMonth,
formatDateOnly,
formatKstDate,
formatMinutesOfDay,
kstDayBoundaries,
kstDayDiff,
kstMidnightUtc,
kstMinutesOfDay,
kstWeekStart,
parseKstDate,
parseKstYearMonth,
toKstYmd,
Expand Down Expand Up @@ -105,6 +107,41 @@ describe('kst-time', () => {
});
});

describe('kstWeekStart', () => {
it.each([
[
'월 00:00 KST는 그 주의 시작이다',
'2026-11-15T15:00:00.000Z',
'2026-11-15T15:00:00.000Z',
],
[
'일 23:59:59.999 KST는 앞 주에 속한다',
'2026-11-15T14:59:59.999Z',
'2026-11-08T15:00:00.000Z',
],
[
'UTC로는 수요일인 목 00:30 KST',
'2026-11-18T15:30:00.000Z',
'2026-11-15T15:00:00.000Z',
],
[
'연말 금요일은 전년 12월 월요일로 간다',
'2027-01-01T01:00:00.000Z',
'2026-12-27T15:00:00.000Z',
],
])('%s', (_label, at, expected) => {
expect(kstWeekStart(new Date(at)).toISOString()).toBe(expected);
});
});

describe('formatDateOnly', () => {
it('@db.Date 값을 YYYY-MM-DD로 쓴다', () => {
expect(formatDateOnly(new Date('2026-11-09T00:00:00.000Z'))).toBe(
'2026-11-09',
);
});
});

describe('daysInMonth', () => {
it('말일을 계산한다(윤년 포함)', () => {
expect(daysInMonth(2026, 9)).toBe(30);
Expand Down
11 changes: 11 additions & 0 deletions src/common/utils/kst-time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@ export function kstDayBoundaries(at: Date): KstDayBoundaries {
};
}

/** 그 시각이 속한 KST 주(월~일)의 월요일 00:00 KST(UTC 시각). */
export function kstWeekStart(at: Date): Date {
const { dayStartUtc, weekday } = kstDayBoundaries(at);
return new Date(dayStartUtc.getTime() - ((weekday + 6) % 7) * DAY_MS);
}

/** `@db.Date` 값(KST 달력일의 UTC 자정 표현)을 YYYY-MM-DD로. */
export function formatDateOnly(dateOnlyUtc: Date): string {
return dateOnlyUtc.toISOString().slice(0, 10);
}

export function daysInMonth(year: number, month: number): number {
return new Date(Date.UTC(year, month, 0)).getUTCDate();
}
Expand Down
10 changes: 10 additions & 0 deletions src/features/order/dto/inputs/admin-mark-settlement-paid.input.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { IsOptional, IsString } from 'class-validator';

export class AdminMarkSettlementPaidInput {
@IsString()
settlementId!: string;

@IsOptional()
@IsString()
note?: string;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { IsString } from 'class-validator';

export class AdminMonthlyCommissionInput {
// 형식(YYYY-MM)은 서비스가 INVALID_YEAR_MONTH로 거절한다
@IsString()
month!: string;
}
19 changes: 19 additions & 0 deletions src/features/order/dto/inputs/admin-settlement-list.input.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { IsEnum, IsOptional, IsString } from 'class-validator';

import { CursorInput } from '@/common/dto/inputs/cursor.input';
import { SettlementStatus } from '@/generated/prisma/client';

export class AdminSettlementListInput extends CursorInput {
@IsOptional()
@IsEnum(SettlementStatus)
status?: SettlementStatus;

@IsOptional()
@IsString()
storeId?: string;

// 형식(YYYY-MM-DD)은 서비스가 INVALID_DATE로 거절한다
@IsOptional()
@IsString()
periodStart?: string;
}
3 changes: 3 additions & 0 deletions src/features/order/dto/inputs/seller-settlement-list.input.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { CursorInput } from '@/common/dto/inputs/cursor.input';

export class SellerSettlementListInput extends CursorInput {}
55 changes: 55 additions & 0 deletions src/features/order/events/settlement-created.event.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import {
parseSettlementCreatedPayload,
SETTLEMENT_CREATED,
settlementCreatedEvent,
} from '@/features/order/events/settlement-created.event';
import type { Prisma } from '@/generated/prisma/client';

const VALID = {
settlementId: '5',
storeId: '9',
storeName: '해즈 케이크',
periodStart: '2026-11-09',
periodEnd: '2026-11-15',
orderCount: 3,
settlementBaseAmount: 90_000,
commissionAmount: 4_995,
payoutAmount: 85_005,
};

describe('settlement.created 이벤트', () => {
it('정산 단위 aggregate에 묶고 시스템 행위(행위자 없음)다', () => {
const occurredAt = new Date('2026-11-15T20:00:00.000Z');
const event = settlementCreatedEvent(VALID, occurredAt);

expect(event).toEqual({
aggregateType: 'settlement',
aggregateId: '5',
eventType: SETTLEMENT_CREATED,
payload: VALID,
occurredAt,
actorAccountId: null,
});
expect(
parseSettlementCreatedPayload(event.payload as Prisma.JsonValue),
).toEqual(VALID);
});

it.each([
['null', null],
['배열', [VALID]],
['settlementId 숫자', { ...VALID, settlementId: 5 }],
['storeName 누락', { ...VALID, storeName: undefined }],
[
'periodStart 시각 형식',
{ ...VALID, periodStart: '2026-11-09T00:00:00Z' },
],
['periodEnd 누락', { ...VALID, periodEnd: undefined }],
['orderCount 문자열', { ...VALID, orderCount: '3' }],
['payoutAmount 소수', { ...VALID, payoutAmount: 1.5 }],
])('반증: %s payload는 던진다', (_label, payload) => {
expect(() =>
parseSettlementCreatedPayload(payload as Prisma.JsonValue),
).toThrow('payload 형식 오류');
});
});
72 changes: 72 additions & 0 deletions src/features/order/events/settlement-created.event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import type { OutboxEventInput } from '@/features/outbox';
import type { Prisma } from '@/generated/prisma/client';

/** 주간 정산 생성(매장별). 관리자 '정산 송금' 알림의 원천이다. */
export const SETTLEMENT_CREATED = 'settlement.created';

export interface SettlementCreatedPayload {
settlementId: string;
storeId: string;
storeName: string;
/** 정산 기간(KST 월~일), YYYY-MM-DD */
periodStart: string;
periodEnd: string;
orderCount: number;
settlementBaseAmount: number;
commissionAmount: number;
payoutAmount: number;
}

export function settlementCreatedEvent(
payload: SettlementCreatedPayload,
occurredAt: Date,
): OutboxEventInput {
return {
aggregateType: 'settlement',
aggregateId: payload.settlementId,
eventType: SETTLEMENT_CREATED,
payload: { ...payload },
occurredAt,
actorAccountId: null,
};
}

const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
const AMOUNT_KEYS = [
'orderCount',
'settlementBaseAmount',
'commissionAmount',
'payoutAmount',
] as const;

export function parseSettlementCreatedPayload(
value: Prisma.JsonValue,
): SettlementCreatedPayload {
const p = value as Partial<Record<keyof SettlementCreatedPayload, unknown>>;
if (
typeof value !== 'object' ||
value === null ||
Array.isArray(value) ||
typeof p.settlementId !== 'string' ||
typeof p.storeId !== 'string' ||
typeof p.storeName !== 'string' ||
typeof p.periodStart !== 'string' ||
!DATE_ONLY.test(p.periodStart) ||
typeof p.periodEnd !== 'string' ||
!DATE_ONLY.test(p.periodEnd) ||
AMOUNT_KEYS.some((key) => !Number.isSafeInteger(p[key]))
) {
throw new Error(`${SETTLEMENT_CREATED} payload 형식 오류`);
}
return {
settlementId: p.settlementId,
storeId: p.storeId,
storeName: p.storeName,
periodStart: p.periodStart,
periodEnd: p.periodEnd,
orderCount: p.orderCount as number,
settlementBaseAmount: p.settlementBaseAmount as number,
commissionAmount: p.commissionAmount as number,
payoutAmount: p.payoutAmount as number,
};
}
25 changes: 25 additions & 0 deletions src/features/order/order-admin.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,31 @@ type AdminOrderDetail {
판매자 픽업 일시 변경 이력. 오래된 순, 없으면 빈 배열.
"""
pickupChanges: [OrderPickupChange!]!
"""
주문 생성 시점의 수수료율(bp, 1bp = 0.01%). 바뀐 설정은 그 뒤 주문부터 적용된다.
"""
commissionRateBps: Int!
"""
정산 예정 금액(원). 정산 확정 뒤에는 실제 지급액(기준액 − 수수료), 확정 전에는 결제 금액에서 수수료(원 미만 버림)를 뺀
예상값이다. 입금이 확인되지 않았거나 결제 도입 전 주문이면 null, 확정 없이 취소된 주문(전액 환불)은 0.
"""
expectedPayoutAmount: Int
"""
확정된 수수료 기준액(원). 픽업 완료·노쇼는 결제 금액, 구매자 사정 취소는 결제 금액 − 환불 금액. 확정 전이면 null.
"""
settlementBaseAmount: Int
"""
확정된 수수료(원). 기준액 × 수수료율, 원 미만 버림. 확정 전이면 null.
"""
commissionAmount: Int
"""
정산 확정 시각. 확정 전이면 null.
"""
settlementFinalizedAt: DateTime
"""
이 주문이 묶인 주간 정산(adminSettlement). 아직 묶이지 않았으면 null.
"""
settlementId: ID
}

"""
Expand Down
4 changes: 4 additions & 0 deletions src/features/order/order-deposit-admin.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,10 @@ type AdminTaskCounts {
계좌가 들어와 송금을 기다리는 환불 수(adminRefunds status=AWAITING_TRANSFER의 totalCount).
"""
refundsAwaitingTransfer: Int!
"""
송금을 기다리는 주간 정산 수(adminSettlements status=PENDING의 totalCount).
"""
pendingSettlements: Int!
}

"""
Expand Down
17 changes: 17 additions & 0 deletions src/features/order/order-seller.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,23 @@ type SellerOrderDetail {
픽업 일시 변경 이력. 오래된 순, 없으면 빈 배열.
"""
pickupChanges: [OrderPickupChange!]!
"""
주문 생성 시점의 수수료율(bp, 1bp = 0.01%). 바뀐 설정은 그 뒤 주문부터 적용된다.
"""
commissionRateBps: Int!
"""
정산 예정 금액(원). 정산 확정 뒤에는 실제 지급액(기준액 − 수수료), 확정 전에는 결제 금액에서 수수료(원 미만 버림)를 뺀
예상값이다. 입금이 확인되지 않았거나 결제 도입 전 주문이면 null, 확정 없이 취소된 주문(전액 환불)은 0.
"""
expectedPayoutAmount: Int
"""
확정된 수수료 기준액(원). 픽업 완료·노쇼는 결제 금액, 구매자 사정 취소는 결제 금액 − 환불 금액. 확정 전이면 null.
"""
settlementBaseAmount: Int
"""
확정된 수수료(원). 기준액 × 수수료율, 원 미만 버림. 확정 전이면 null.
"""
commissionAmount: Int
}

"""
Expand Down
Loading
Loading