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
8 changes: 8 additions & 0 deletions src/common/errors/error-catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,14 @@ export const ERROR_CATALOG = {
status: HttpStatus.BAD_REQUEST,
message: '노쇼는 픽업 시각부터 24시간 안에만 처리할 수 있습니다.',
},
PICKUP_RESCHEDULE_NOT_ALLOWED: {
status: HttpStatus.BAD_REQUEST,
message: '접수·확정·제작 완료 주문만 픽업 일시를 바꿀 수 있습니다.',
},
PICKUP_UNCHANGED: {
status: HttpStatus.BAD_REQUEST,
message: '지금과 같은 픽업 일시입니다.',
},
ORDER_AMOUNT_OUT_OF_RANGE: {
status: HttpStatus.BAD_REQUEST,
message: '주문 금액이 처리 가능한 범위를 벗어났습니다.',
Expand Down
2 changes: 2 additions & 0 deletions src/features/notification/constants/notification-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ export const ORDER_PAYMENT_EXPIRED_NOTIFICATION = {
body: '입금이 확인되지 않아 주문이 취소되었어요.',
} as const;

export const ORDER_PICKUP_RESCHEDULED_TITLE = '픽업변경';

export const REFUND_ACCOUNT_REQUESTED_TITLE = '환불계좌입력';

export const REFUND_COMPLETED_TITLE = '환불완료';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,40 @@ describe('NotificationOutboxConsumer (real DB)', () => {
});
});

it('order.pickup_rescheduled는 구매자에게 바뀐 픽업 일시(KST) 알림을 만들고, 재전달은 중복을 만들지 않는다', async () => {
const buyer = await createAccount(prisma, { account_type: 'USER' });
const order = await createOrder(prisma, { account_id: buyer.id });
const item = await createOrderItem(prisma, { order_id: order.id });
const rescheduled = event('order.pickup_rescheduled', {
orderId: order.id.toString(),
orderNumber: 'ORD-5',
buyerAccountId: buyer.id.toString(),
storeId: item.store_id.toString(),
storeName: '케이크샵',
productId: item.product_id.toString(),
productName: '레터링 케이크',
fromPickupAt: '2026-09-20T05:00:00.000Z',
toPickupAt: '2026-09-21T06:30:00.000Z',
});

await consumer.handle(rescheduled);
await consumer.handle(rescheduled);

const rows = await prisma.notification.findMany();
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({
account_id: buyer.id,
type: 'ORDER_STATUS',
event: 'ORDER_PICKUP_RESCHEDULED',
title: '픽업변경',
body: 'ORD-5 픽업 일시가 9/21 15:30로 변경되었어요.',
order_id: order.id,
store_id: item.store_id,
product_id: item.product_id,
created_at: OCCURRED_AT,
});
});

it('review.liked는 작성자에게 좋아요 알림을 만든다', async () => {
const review = await createReview(prisma);
await consumer.handle(
Expand Down
26 changes: 26 additions & 0 deletions src/features/notification/services/notification-outbox.consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@ import {
NotificationRepository,
} from '@/features/notification/repositories/notification.repository';
import {
buildOrderPickupRescheduledNotification,
buildOrderStatusNotification,
buildRefundAccountRequestedNotification,
buildRefundCompletedNotification,
buildReviewLikedNotification,
type NotificationPayload,
} from '@/features/notification/services/notification-payloads.helper';
import {
ORDER_PICKUP_RESCHEDULED,
ORDER_STATUS_CHANGED,
parseOrderPickupRescheduledPayload,
parseOrderStatusChangedPayload,
parseRefundCompletedPayload,
parseRefundRequestedPayload,
Expand All @@ -42,6 +45,7 @@ import { parseReviewLikedPayload, REVIEW_LIKED } from '@/features/review';
@Injectable()
@SubscribeOutbox(
ORDER_STATUS_CHANGED,
ORDER_PICKUP_RESCHEDULED,
REFUND_REQUESTED,
REFUND_COMPLETED,
REVIEW_LIKED,
Expand All @@ -60,6 +64,8 @@ export class NotificationOutboxConsumer implements OutboxConsumer {
switch (event.eventType) {
case ORDER_STATUS_CHANGED:
return this.onOrderStatusChanged(event);
case ORDER_PICKUP_RESCHEDULED:
return this.onPickupRescheduled(event);
case REFUND_REQUESTED:
return this.onRefundRequested(event);
case REFUND_COMPLETED:
Expand Down Expand Up @@ -93,6 +99,26 @@ export class NotificationOutboxConsumer implements OutboxConsumer {
]);
}

private async onPickupRescheduled(event: OutboxEvent): Promise<void> {
const p = parseOrderPickupRescheduledPayload(event.payload);
await this.repo.createFromEvent(event.eventId, [
{
account_id: parseId(p.buyerAccountId),
...buildOrderPickupRescheduledNotification(
p.orderNumber,
new Date(p.toPickupAt),
),
order_id: parseId(p.orderId),
store_id: p.storeId === null ? null : parseId(p.storeId),
product_id: p.productId === null ? null : parseId(p.productId),
order_number: p.orderNumber,
store_name: p.storeName,
product_name: p.productName,
created_at: event.occurredAt,
},
]);
}

private async onRefundRequested(event: OutboxEvent): Promise<void> {
const p = parseRefundRequestedPayload(event.payload);
// 취소와 함께 계좌를 넣었으면 요청할 게 없다(관리자 송금 알림만 간다)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
buildOrderPickupRescheduledNotification,
buildOrderStatusNotification,
buildRefundAccountRequestedNotification,
buildRefundCompletedNotification,
Expand Down Expand Up @@ -123,6 +124,22 @@ describe('notification-payloads.helper', () => {
});
});

describe('buildOrderPickupRescheduledNotification', () => {
it('바뀐 픽업 일시를 KST M/d HH:mm로 적는다', () => {
expect(
buildOrderPickupRescheduledNotification(
'ORD-3',
new Date('2026-10-05T15:30:00.000Z'),
),
).toEqual({
type: NotificationType.ORDER_STATUS,
event: NotificationEvent.ORDER_PICKUP_RESCHEDULED,
title: '픽업변경',
body: 'ORD-3 픽업 일시가 10/6 00:30로 변경되었어요.',
});
});
});

describe('buildRefundAccountRequestedNotification', () => {
it('금액을 천 단위로 적어 계좌 입력을 요청한다', () => {
expect(buildRefundAccountRequestedNotification('ORD-2', 30_000)).toEqual({
Expand Down
15 changes: 15 additions & 0 deletions src/features/notification/services/notification-payloads.helper.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import {
ORDER_CANCELED_NOTIFICATION,
ORDER_PAYMENT_EXPIRED_NOTIFICATION,
ORDER_PICKUP_RESCHEDULED_TITLE,
ORDER_STATUS_NOTIFICATION_BODIES,
ORDER_STATUS_NOTIFICATION_TITLES,
REFUND_ACCOUNT_REQUESTED_TITLE,
REFUND_COMPLETED_TITLE,
REVIEW_LIKED_NOTIFICATION,
} from '@/features/notification/constants/notification-messages';
import { formatKstPickupAt } from '@/features/notification/services/seller-push-messages.helper';
import {
ORDER_CANCEL_REASON_LABELS,
type OrderStatusChangedPayload,
Expand Down Expand Up @@ -86,6 +88,19 @@ function buildOrderCanceled(
};
}

/** 판매자가 픽업 일시를 바꿨을 때. */
export function buildOrderPickupRescheduledNotification(
orderNumber: string,
toPickupAt: Date,
): NotificationPayload {
return {
type: NotificationType.ORDER_STATUS,
event: NotificationEvent.ORDER_PICKUP_RESCHEDULED,
title: ORDER_PICKUP_RESCHEDULED_TITLE,
body: `${orderNumber} 픽업 일시가 ${formatKstPickupAt(toPickupAt)}로 변경되었어요.`,
};
}

/** 돌려줄 돈이 생겼을 때 계좌 입력을 요청한다. */
export function buildRefundAccountRequestedNotification(
orderNumber: string,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { IsDate, IsOptional, IsString } from 'class-validator';

export class SellerRescheduleOrderPickupInput {
@IsString()
orderId!: string;

// 영업일·슬롯·수량은 매장 픽업 판정과 capacity 재검사가 본다
@IsDate()
pickupAt!: Date;

@IsOptional()
@IsString()
note?: string | null;
}
72 changes: 72 additions & 0 deletions src/features/order/events/order-pickup-rescheduled.event.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import {
ORDER_PICKUP_RESCHEDULED,
orderPickupRescheduledEvent,
parseOrderPickupRescheduledPayload,
} from '@/features/order/events/order-pickup-rescheduled.event';
import type { Prisma } from '@/generated/prisma/client';

const VALID = {
orderId: '7',
orderNumber: 'ORD-20261119-ABC234',
buyerAccountId: '3',
storeId: '5',
storeName: '해즈 케이크',
productId: '9',
productName: '딸기 케이크',
fromPickupAt: '2026-11-20T05:00:00.000Z',
toPickupAt: '2026-11-21T06:30:00.000Z',
};

describe('order.pickup_rescheduled 이벤트', () => {
it('bigint·Date를 문자열로 싣고 order aggregate에 묶고 행위자는 판매자다', () => {
const occurredAt = new Date('2026-11-19T07:00:00.000Z');
const event = orderPickupRescheduledEvent({
orderId: 7n,
orderNumber: VALID.orderNumber,
buyerAccountId: 3n,
storeId: 5n,
storeName: VALID.storeName,
productId: 9n,
productName: VALID.productName,
fromPickupAt: new Date(VALID.fromPickupAt),
toPickupAt: new Date(VALID.toPickupAt),
occurredAt,
actorAccountId: 11n,
});

expect(event).toEqual({
aggregateType: 'order',
aggregateId: '7',
eventType: ORDER_PICKUP_RESCHEDULED,
payload: VALID,
occurredAt,
actorAccountId: 11n,
});
expect(
parseOrderPickupRescheduledPayload(event.payload as Prisma.JsonValue),
).toEqual(VALID);
});

it('품목이 없던 주문의 매장·상품은 null로 읽는다', () => {
expect(
parseOrderPickupRescheduledPayload({
...VALID,
storeId: null,
storeName: null,
productId: null,
productName: null,
}),
).toMatchObject({ storeId: null, productName: null });
});

it.each([
['배열', []],
['구매자 누락', { ...VALID, buyerAccountId: undefined }],
['변경 후 시각 비ISO', { ...VALID, toPickupAt: 'not-a-date' }],
['변경 전 시각 숫자', { ...VALID, fromPickupAt: 1_700_000_000 }],
])('%s payload는 던진다', (_label, value) => {
expect(() =>
parseOrderPickupRescheduledPayload(value as Prisma.JsonValue),
).toThrow('order.pickup_rescheduled payload 형식 오류');
});
});
90 changes: 90 additions & 0 deletions src/features/order/events/order-pickup-rescheduled.event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import type { OutboxEventInput } from '@/features/outbox';
import type { Prisma } from '@/generated/prisma/client';

/** 판매자 픽업 일시 변경(구매자 알림 원천). payload는 생산 시점 스냅샷이다. */
export const ORDER_PICKUP_RESCHEDULED = 'order.pickup_rescheduled';

export interface OrderPickupRescheduledPayload {
orderId: string;
orderNumber: string;
buyerAccountId: string;
storeId: string | null;
storeName: string | null;
productId: string | null;
productName: string | null;
/** ISO 8601 */
fromPickupAt: string;
/** ISO 8601 */
toPickupAt: string;
}

export function orderPickupRescheduledEvent(args: {
orderId: bigint;
orderNumber: string;
buyerAccountId: bigint;
storeId: bigint | null;
storeName: string | null;
productId: bigint | null;
productName: string | null;
fromPickupAt: Date;
toPickupAt: Date;
occurredAt: Date;
actorAccountId: bigint;
}): OutboxEventInput {
const payload: OrderPickupRescheduledPayload = {
orderId: args.orderId.toString(),
orderNumber: args.orderNumber,
buyerAccountId: args.buyerAccountId.toString(),
storeId: args.storeId?.toString() ?? null,
storeName: args.storeName,
productId: args.productId?.toString() ?? null,
productName: args.productName,
fromPickupAt: args.fromPickupAt.toISOString(),
toPickupAt: args.toPickupAt.toISOString(),
};
return {
aggregateType: 'order',
aggregateId: payload.orderId,
eventType: ORDER_PICKUP_RESCHEDULED,
payload: { ...payload },
occurredAt: args.occurredAt,
actorAccountId: args.actorAccountId,
};
}

const isIsoString = (v: unknown): v is string =>
typeof v === 'string' && !Number.isNaN(Date.parse(v));
const stringOrNull = (v: unknown): string | null =>
typeof v === 'string' ? v : null;

/** 소비자용 방어적 파싱 — 형태가 어긋난 payload는 던져서 재시도·FAILED로 드러낸다. */
export function parseOrderPickupRescheduledPayload(
value: Prisma.JsonValue,
): OrderPickupRescheduledPayload {
const p = value as Partial<
Record<keyof OrderPickupRescheduledPayload, unknown>
>;
if (
typeof value !== 'object' ||
value === null ||
Array.isArray(value) ||
typeof p.orderId !== 'string' ||
typeof p.orderNumber !== 'string' ||
typeof p.buyerAccountId !== 'string' ||
!isIsoString(p.fromPickupAt) ||
!isIsoString(p.toPickupAt)
) {
throw new Error(`${ORDER_PICKUP_RESCHEDULED} payload 형식 오류`);
}
return {
orderId: p.orderId,
orderNumber: p.orderNumber,
buyerAccountId: p.buyerAccountId,
storeId: stringOrNull(p.storeId),
storeName: stringOrNull(p.storeName),
productId: stringOrNull(p.productId),
productName: stringOrNull(p.productName),
fromPickupAt: p.fromPickupAt,
toPickupAt: p.toPickupAt,
};
}
6 changes: 6 additions & 0 deletions src/features/order/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,9 @@ export {
type OrderConfirmReminderDuePayload,
parseOrderConfirmReminderDuePayload,
} from '@/features/order/events/order-confirm-reminder-due.event';
// 판매자 픽업 변경 이벤트 계약(outbox). 구매자 알림 소비자(notification)가 읽는다.
export {
ORDER_PICKUP_RESCHEDULED,
type OrderPickupRescheduledPayload,
parseOrderPickupRescheduledPayload,
} from '@/features/order/events/order-pickup-rescheduled.event';
4 changes: 4 additions & 0 deletions src/features/order/order-admin.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,10 @@ type AdminOrderDetail {
노쇼 처리 시각. 노쇼가 아니면 null.
"""
noShowAt: DateTime
"""
판매자 픽업 일시 변경 이력. 오래된 순, 없으면 빈 배열.
"""
pickupChanges: [OrderPickupChange!]!
}

"""
Expand Down
Loading
Loading