diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index eb2471d7..82af049d 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -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: '주문 금액이 처리 가능한 범위를 벗어났습니다.', diff --git a/src/features/notification/constants/notification-messages.ts b/src/features/notification/constants/notification-messages.ts index c06b3f84..a8774d8d 100644 --- a/src/features/notification/constants/notification-messages.ts +++ b/src/features/notification/constants/notification-messages.ts @@ -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 = '환불완료'; diff --git a/src/features/notification/services/notification-outbox.consumer.spec.ts b/src/features/notification/services/notification-outbox.consumer.spec.ts index ebba1f9d..403e67e3 100644 --- a/src/features/notification/services/notification-outbox.consumer.spec.ts +++ b/src/features/notification/services/notification-outbox.consumer.spec.ts @@ -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( diff --git a/src/features/notification/services/notification-outbox.consumer.ts b/src/features/notification/services/notification-outbox.consumer.ts index 853208c4..5885e46a 100644 --- a/src/features/notification/services/notification-outbox.consumer.ts +++ b/src/features/notification/services/notification-outbox.consumer.ts @@ -13,6 +13,7 @@ import { NotificationRepository, } from '@/features/notification/repositories/notification.repository'; import { + buildOrderPickupRescheduledNotification, buildOrderStatusNotification, buildRefundAccountRequestedNotification, buildRefundCompletedNotification, @@ -20,7 +21,9 @@ import { type NotificationPayload, } from '@/features/notification/services/notification-payloads.helper'; import { + ORDER_PICKUP_RESCHEDULED, ORDER_STATUS_CHANGED, + parseOrderPickupRescheduledPayload, parseOrderStatusChangedPayload, parseRefundCompletedPayload, parseRefundRequestedPayload, @@ -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, @@ -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: @@ -93,6 +99,26 @@ export class NotificationOutboxConsumer implements OutboxConsumer { ]); } + private async onPickupRescheduled(event: OutboxEvent): Promise { + 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 { const p = parseRefundRequestedPayload(event.payload); // 취소와 함께 계좌를 넣었으면 요청할 게 없다(관리자 송금 알림만 간다) diff --git a/src/features/notification/services/notification-payloads.helper.spec.ts b/src/features/notification/services/notification-payloads.helper.spec.ts index d0fa8923..3b58c8f2 100644 --- a/src/features/notification/services/notification-payloads.helper.spec.ts +++ b/src/features/notification/services/notification-payloads.helper.spec.ts @@ -1,4 +1,5 @@ import { + buildOrderPickupRescheduledNotification, buildOrderStatusNotification, buildRefundAccountRequestedNotification, buildRefundCompletedNotification, @@ -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({ diff --git a/src/features/notification/services/notification-payloads.helper.ts b/src/features/notification/services/notification-payloads.helper.ts index 2b543e7c..9e7ee2c7 100644 --- a/src/features/notification/services/notification-payloads.helper.ts +++ b/src/features/notification/services/notification-payloads.helper.ts @@ -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, @@ -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, diff --git a/src/features/order/dto/inputs/seller-reschedule-order-pickup.input.ts b/src/features/order/dto/inputs/seller-reschedule-order-pickup.input.ts new file mode 100644 index 00000000..07144c03 --- /dev/null +++ b/src/features/order/dto/inputs/seller-reschedule-order-pickup.input.ts @@ -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; +} diff --git a/src/features/order/events/order-pickup-rescheduled.event.spec.ts b/src/features/order/events/order-pickup-rescheduled.event.spec.ts new file mode 100644 index 00000000..b69be623 --- /dev/null +++ b/src/features/order/events/order-pickup-rescheduled.event.spec.ts @@ -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 형식 오류'); + }); +}); diff --git a/src/features/order/events/order-pickup-rescheduled.event.ts b/src/features/order/events/order-pickup-rescheduled.event.ts new file mode 100644 index 00000000..c836d902 --- /dev/null +++ b/src/features/order/events/order-pickup-rescheduled.event.ts @@ -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 + >; + 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, + }; +} diff --git a/src/features/order/index.ts b/src/features/order/index.ts index f2fc4f16..73a4d464 100644 --- a/src/features/order/index.ts +++ b/src/features/order/index.ts @@ -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'; diff --git a/src/features/order/order-admin.graphql b/src/features/order/order-admin.graphql index 96d8f17f..69730da3 100644 --- a/src/features/order/order-admin.graphql +++ b/src/features/order/order-admin.graphql @@ -249,6 +249,10 @@ type AdminOrderDetail { 노쇼 처리 시각. 노쇼가 아니면 null. """ noShowAt: DateTime + """ + 판매자 픽업 일시 변경 이력. 오래된 순, 없으면 빈 배열. + """ + pickupChanges: [OrderPickupChange!]! } """ diff --git a/src/features/order/order-my.graphql b/src/features/order/order-my.graphql index c640bb7b..1084611f 100644 --- a/src/features/order/order-my.graphql +++ b/src/features/order/order-my.graphql @@ -267,6 +267,10 @@ type MyOrderDetail { status가 AWAITING_ACCOUNT면 submitMyRefundAccount로 계좌를 입력받는다. """ refunds: [OrderRefund!]! + """ + 판매자가 바꾼 픽업 일시 이력. 오래된 순, 없으면 빈 배열. pickupAt은 마지막 변경 뒤 값이다. + """ + pickupChanges: [OrderPickupChange!]! """ 상태 변경 이력. 오래된 순이다(판매자 주문 상세는 최신순 — 방향이 반대다). diff --git a/src/features/order/order-seller-pickup.graphql b/src/features/order/order-seller-pickup.graphql new file mode 100644 index 00000000..b01870d6 --- /dev/null +++ b/src/features/order/order-seller-pickup.graphql @@ -0,0 +1,50 @@ +extend type Query { + """ + 픽업 일시 변경 시트의 월 달력. 영업일·특별휴무·예약 가능 기간·일일 제작 수량을 보고, 리드타임·상품 제작 시간은 보지 않는다 + (지난 시각만 막는다). 이 주문이 지금 점유한 수량은 빼고 세며, 숨긴 매장도 계산한다. 접수·확정·제작 완료가 아니면 + PICKUP_RESCHEDULE_NOT_ALLOWED, yearMonth 형식이 어긋나면 BAD_USER_INPUT(INVALID_YEAR_MONTH). 입금 확인 전·다른 매장 주문은 NOT_FOUND. + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerOrderPickupCalendar( + orderId: ID! + """대상 연월. "YYYY-MM" 형식(KST 기준).""" + yearMonth: String! + ): PickupCalendar! + """ + 픽업 일시 변경 시트의 그날 슬롯. 규칙은 sellerOrderPickupCalendar와 같다. date 형식이 어긋나면 BAD_USER_INPUT(INVALID_DATE). + 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerOrderPickupTimeSlots( + orderId: ID! + """대상 날짜. "YYYY-MM-DD" 형식(KST 기준).""" + date: String! + ): PickupTimeSlots! +} + +extend type Mutation { + """ + 주문 픽업 일시를 바꾼다(접수·확정·제작 완료만, 그 밖은 PICKUP_RESCHEDULE_NOT_ALLOWED). 지금과 같은 일시면 PICKUP_UNCHANGED, + 영업일·특별휴무·슬롯 시각·지난 시각·예약 가능 기간·일일 제작 수량(이 주문 수량은 빼고 센다)에 맞지 않으면 PICKUP_NOT_AVAILABLE + (모두 BAD_USER_INPUT). 리드타임·상품 제작 시간은 보지 않고, 숨긴 매장의 주문도 바꿀 수 있다. 접수 상태면 확정 마감을 + min(접수 + 24시간, 새 픽업 시각)으로 다시 잰다. 변경 이력(pickupChanges)이 남고 구매자에게 알림이 간다. 커스텀 내용은 바뀌지 않는다. + 입금 확인 전·다른 매장 주문은 NOT_FOUND. 판매자 로그인 필수. SELLER 계정이 아니면 FORBIDDEN, 매장을 보유하지 않으면 NOT_FOUND. + """ + sellerRescheduleOrderPickup( + input: SellerRescheduleOrderPickupInput! + ): SellerOrderSummary! +} + +""" +판매자 픽업 일시 변경 입력. +""" +input SellerRescheduleOrderPickupInput { + orderId: ID! + """ + 새 픽업 일시. sellerOrderPickupTimeSlots의 슬롯 시각이어야 한다(초 이하는 0). + """ + pickupAt: DateTime! + """ + 변경 메모. 선택, 최대 500자. 변경 이력에 남고 구매자도 본다. + """ + note: String +} diff --git a/src/features/order/order-seller.graphql b/src/features/order/order-seller.graphql index 1a994765..7b0965ad 100644 --- a/src/features/order/order-seller.graphql +++ b/src/features/order/order-seller.graphql @@ -252,6 +252,10 @@ type SellerOrderDetail { 노쇼 처리 시각. 노쇼가 아니면 null. """ noShowAt: DateTime + """ + 픽업 일시 변경 이력. 오래된 순, 없으면 빈 배열. + """ + pickupChanges: [OrderPickupChange!]! } """ diff --git a/src/features/order/order.module.ts b/src/features/order/order.module.ts index 5af0468f..28c9692b 100644 --- a/src/features/order/order.module.ts +++ b/src/features/order/order.module.ts @@ -11,6 +11,7 @@ import { OrderBookedRepository } from '@/features/order/repositories/order-booke import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; import { OrderInquiryRepository } from '@/features/order/repositories/order-inquiry.repository'; import { OrderLifecycleRepository } from '@/features/order/repositories/order-lifecycle.repository'; +import { OrderPickupChangeRepository } from '@/features/order/repositories/order-pickup-change.repository'; import { OrderStoreDailyLimitRepository } from '@/features/order/repositories/order-store-daily-limit.repository'; import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderWithdrawalBlockingRepository } from '@/features/order/repositories/order-withdrawal-blocking.repository'; @@ -32,6 +33,8 @@ import { PaymentQueryResolver } from '@/features/order/resolvers/order-payment-q import { AdminRefundMutationResolver } from '@/features/order/resolvers/order-refund-admin-mutation.resolver'; import { AdminRefundQueryResolver } from '@/features/order/resolvers/order-refund-admin-query.resolver'; import { SellerOrderMutationResolver } from '@/features/order/resolvers/order-seller-mutation.resolver'; +import { SellerOrderPickupMutationResolver } from '@/features/order/resolvers/order-seller-pickup-mutation.resolver'; +import { SellerOrderPickupQueryResolver } from '@/features/order/resolvers/order-seller-pickup-query.resolver'; import { SellerOrderQueryResolver } from '@/features/order/resolvers/order-seller-query.resolver'; import { SellerSettlementMutationResolver } from '@/features/order/resolvers/order-settlement-seller-mutation.resolver'; import { SellerSettlementQueryResolver } from '@/features/order/resolvers/order-settlement-seller-query.resolver'; @@ -47,6 +50,7 @@ import { OrderLifecycleScheduler } from '@/features/order/services/order-lifecyc import { UserOrderService } from '@/features/order/services/order-my.service'; import { AdminPaymentService } from '@/features/order/services/order-payment-admin.service'; import { AdminRefundService } from '@/features/order/services/order-refund-admin.service'; +import { SellerOrderPickupService } from '@/features/order/services/order-seller-pickup.service'; import { SellerOrderService } from '@/features/order/services/order-seller.service'; import { SellerSettlementService } from '@/features/order/services/order-settlement-seller.service'; import { OrderStoreDailyLimitConsumer } from '@/features/order/services/order-store-daily-limit.consumer'; @@ -90,6 +94,11 @@ import { StoreModule } from '@/features/store'; SellerOrderService, SellerOrderQueryResolver, SellerOrderMutationResolver, + // 판매자 픽업 일시 변경(변경 시트 달력·슬롯 포함) + OrderPickupChangeRepository, + SellerOrderPickupService, + SellerOrderPickupQueryResolver, + SellerOrderPickupMutationResolver, // 관리자 주문 관리(목록·상세·강제 취소) AdminOrderService, AdminOrderQueryResolver, diff --git a/src/features/order/order.types.graphql b/src/features/order/order.types.graphql index 8efb7472..278e17ba 100644 --- a/src/features/order/order.types.graphql +++ b/src/features/order/order.types.graphql @@ -382,3 +382,18 @@ type OrderItemFreeEditAttachment { """첨부 순서. 오름차순.""" sortOrder: Int! } + +""" +판매자 픽업 일시 변경 이력 1건. 구매자·판매자·관리자 주문 상세가 공용으로 쓴다. +""" +type OrderPickupChange { + id: ID! + """변경 전 픽업 일시.""" + fromPickupAt: DateTime! + """변경 후 픽업 일시.""" + toPickupAt: DateTime! + """변경 시각.""" + changedAt: DateTime! + """판매자가 남긴 변경 메모. 없으면 null.""" + note: String +} diff --git a/src/features/order/policies/order-lifecycle.policy.ts b/src/features/order/policies/order-lifecycle.policy.ts index 4a7ad3b2..924f430e 100644 --- a/src/features/order/policies/order-lifecycle.policy.ts +++ b/src/features/order/policies/order-lifecycle.policy.ts @@ -1,10 +1,15 @@ -import { HOUR_MS } from '@/common/utils/kst-time'; +import { DAY_MS, HOUR_MS } from '@/common/utils/kst-time'; import { OrderStatus, PaymentStatus, type Payment, } from '@/generated/prisma/client'; +/** 판매자 확정 마감: 접수(입금 확인) + 24시간과 픽업 시각 중 이른 쪽. 픽업 변경 때도 다시 잰다. */ +export function confirmDeadlineFor(submittedAt: Date, pickupAt: Date): Date { + return new Date(Math.min(submittedAt.getTime() + DAY_MS, pickupAt.getTime())); +} + /** 확정 마감 이만큼 전에 판매자에게 미리 알린다. */ export const CONFIRM_REMINDER_LEAD_MS = 2 * HOUR_MS; diff --git a/src/features/order/policies/order-status-transition.policy.spec.ts b/src/features/order/policies/order-status-transition.policy.spec.ts index 98f69d3f..1a4fc333 100644 --- a/src/features/order/policies/order-status-transition.policy.spec.ts +++ b/src/features/order/policies/order-status-transition.policy.spec.ts @@ -177,4 +177,39 @@ describe('OrderStatusTransitionPolicy', () => { }, ); }); + + describe('픽업 일시 변경', () => { + const changed = new Date(PICKUP_AT.getTime() + HOUR_MS); + + it.each( + STATUSES.map( + (status) => + [ + status, + ['SUBMITTED', 'CONFIRMED', 'MADE'].includes(status) + ? null + : 'PICKUP_RESCHEDULE_NOT_ALLOWED', + ] as const, + ), + )('%s: %s', (status, code) => { + const run = () => + policy.assertPickupChange({ + status, + fromPickupAt: PICKUP_AT, + toPickupAt: changed, + }); + if (code === null) expect(run).not.toThrow(); + else expect(run).toThrowDomain(code); + }); + + it('같은 일시면 PICKUP_UNCHANGED', () => { + expect(() => + policy.assertPickupChange({ + status: OrderStatus.CONFIRMED, + fromPickupAt: PICKUP_AT, + toPickupAt: new Date(PICKUP_AT.getTime()), + }), + ).toThrowDomain('PICKUP_UNCHANGED'); + }); + }); }); diff --git a/src/features/order/policies/order-status-transition.policy.ts b/src/features/order/policies/order-status-transition.policy.ts index adf26712..b4aff268 100644 --- a/src/features/order/policies/order-status-transition.policy.ts +++ b/src/features/order/policies/order-status-transition.policy.ts @@ -30,6 +30,13 @@ const TRANSITIONS: Partial< }, }; +/** 판매자가 픽업 일시를 바꿀 수 있는 상태. */ +const PICKUP_RESCHEDULABLE: readonly OrderStatus[] = [ + OrderStatus.SUBMITTED, + OrderStatus.CONFIRMED, + OrderStatus.MADE, +]; + /** 픽업 시각에서 이만큼 지나면 자동 픽업 완료되고, 노쇼는 그 전까지만 처리할 수 있다. */ export const AUTO_PICKUP_DELAY_MS = DAY_MS; @@ -90,4 +97,21 @@ export class OrderStatusTransitionPolicy { canTransition(request: OrderTransitionRequest): boolean { return violationOf(request) === null; } + + assertPickupReschedulable(status: OrderStatus): void { + if (!PICKUP_RESCHEDULABLE.includes(status)) { + throw new DomainException('PICKUP_RESCHEDULE_NOT_ALLOWED'); + } + } + + assertPickupChange(args: { + status: OrderStatus; + fromPickupAt: Date; + toPickupAt: Date; + }): void { + this.assertPickupReschedulable(args.status); + if (args.fromPickupAt.getTime() === args.toPickupAt.getTime()) { + throw new DomainException('PICKUP_UNCHANGED'); + } + } } diff --git a/src/features/order/repositories/order-capacity.helper.ts b/src/features/order/repositories/order-capacity.helper.ts new file mode 100644 index 00000000..274ccf6d --- /dev/null +++ b/src/features/order/repositories/order-capacity.helper.ts @@ -0,0 +1,49 @@ +import { Prisma } from '@/generated/prisma/client'; + +/** 트랜잭션 안에서 capacity 행을 잠그고 점유를 재집계해 검사-삽입 race로 capacity가 초과되는 것을 막는다. */ +export interface DailyCapacityGuard { + storeId: bigint; + dateOnlyUtc: Date; + dayStartUtc: Date; + dayEndUtc: Date; +} + +/** + * capacity는 order 소유 복제본(order_store_daily_limit)에서 읽는다 — catalog 행을 잠그지 않는다. + * 복제본이 없거나 capacity가 비어 있으면(tombstone) 무제한: 설정 직후 복제 지연 구간에는 제한 없이 받는다. + * forUpdate는 READ COMMITTED tx에서만 같은 매장·날짜의 동시 주문 생성·픽업 변경을 직렬화한다(REPEATABLE READ면 재집계가 잠금 전 스냅샷을 읽는다). + * excludeOrderId는 픽업을 옮기는 주문 자신의 점유를 뺀다. + */ +export async function isDailyCapacityExceeded( + db: Prisma.TransactionClient, + guard: DailyCapacityGuard, + quantity: number, + options: { forUpdate: boolean; excludeOrderId?: bigint }, +): Promise { + const capacityRows = await db.$queryRaw<{ capacity: number }[]>(Prisma.sql` + SELECT capacity + FROM order_store_daily_limit + WHERE store_id = ${guard.storeId} + AND booking_date = ${guard.dateOnlyUtc} + AND capacity IS NOT NULL + ${options.forUpdate ? Prisma.sql`FOR UPDATE` : Prisma.empty} + `); + const capacity = capacityRows[0]?.capacity; + if (capacity === undefined) return false; + + const bookedRows = await db.$queryRaw<{ booked: bigint }[]>(Prisma.sql` + SELECT CAST(COALESCE(SUM(oi.quantity), 0) AS UNSIGNED) AS booked + FROM order_item oi + JOIN \`order\` o + ON o.id = oi.order_id + AND o.deleted_at IS NULL + AND o.status <> 'CANCELED' + AND o.pickup_at >= ${guard.dayStartUtc} + AND o.pickup_at < ${guard.dayEndUtc} + ${options.excludeOrderId !== undefined ? Prisma.sql`AND o.id <> ${options.excludeOrderId}` : Prisma.empty} + WHERE oi.store_id = ${guard.storeId} + AND oi.deleted_at IS NULL + `); + const booked = Number(bookedRows[0]?.booked ?? 0); + return booked + quantity > capacity; +} diff --git a/src/features/order/repositories/order-pickup-change.repository.ts b/src/features/order/repositories/order-pickup-change.repository.ts new file mode 100644 index 00000000..50e8dd48 --- /dev/null +++ b/src/features/order/repositories/order-pickup-change.repository.ts @@ -0,0 +1,169 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { orderPickupRescheduledEvent } from '@/features/order/events/order-pickup-rescheduled.event'; +import { confirmDeadlineFor } from '@/features/order/policies/order-lifecycle.policy'; +import { + isDailyCapacityExceeded, + type DailyCapacityGuard, +} from '@/features/order/repositories/order-capacity.helper'; +import { + sellerOrderSummaryInclude, + type SellerOrderRow, +} from '@/features/order/repositories/order.repository'; +import { OutboxPublisher } from '@/features/outbox'; +import { + AuditActionType, + AuditTargetType, + OrderStatus, + Prisma, +} from '@/generated/prisma/client'; +import { activeWhere, PrismaService } from '@/prisma'; + +export interface ReschedulePickupArgs { + orderId: bigint; + storeId: bigint; + actorAccountId: bigint; + pickupAt: Date; + note: string | null; + now: Date; + /** 새 픽업일의 capacity 재검사 대상(이 주문 자신의 점유는 빼고 센다) */ + capacityGuard: DailyCapacityGuard; + /** 잠금 뒤 상태·현재 픽업 시각으로 다시 판정한다. 던지면 롤백되고 예외가 그대로 나간다. */ + assertReschedulable: (state: { status: OrderStatus; pickupAt: Date }) => void; +} + +export type ReschedulePickupResult = SellerOrderRow | 'capacity-exceeded'; + +/** 판매자 픽업 일시 변경. 잠금 순서는 order → order_store_daily_limit. */ +@Injectable() +export class OrderPickupChangeRepository { + constructor( + private readonly prisma: PrismaService, + private readonly outbox: OutboxPublisher, + @Inject(AUDIT_LOG_REPOSITORY) + private readonly auditLogs: IAuditLogRepository, + ) {} + + /** + * 판매자에게 보이는 자기 매장 주문만 옮긴다(없으면 null). 새 날짜 capacity는 행을 잠근 뒤 이 주문을 뺀 점유로 다시 센다. + * 접수 상태면 확정 마감을 새 픽업 기준으로 다시 재고 미리 알림 표시를 지운다. 변경 이력·감사·구매자 알림 이벤트를 같은 tx에 남긴다. + * READ COMMITTED: 잠금을 기다린 뒤의 점유 재집계가 그사이 커밋된 주문 생성·픽업 변경을 봐야 한다. + */ + async reschedule( + args: ReschedulePickupArgs, + ): Promise { + return this.prisma.$transaction( + async (tx) => { + const [locked] = await tx.$queryRaw< + { + id: bigint; + status: OrderStatus; + pickup_at: Date; + submitted_at: Date; + confirm_deadline_at: Date | null; + }[] + >` + SELECT o.id, o.status, o.pickup_at, o.submitted_at, o.confirm_deadline_at FROM \`order\` o + WHERE o.id = ${args.orderId} AND o.deleted_at IS NULL + AND o.submitted_at IS NOT NULL + AND EXISTS ( + SELECT 1 FROM order_item i + WHERE i.order_id = o.id AND i.store_id = ${args.storeId} AND i.deleted_at IS NULL + ) + FOR UPDATE OF o`; + if (!locked) return null; + args.assertReschedulable({ + status: locked.status, + pickupAt: locked.pickup_at, + }); + + const items = await tx.orderItem.findMany({ + where: { + order_id: locked.id, + store_id: args.storeId, + ...activeWhere, + }, + orderBy: { id: 'asc' }, + select: { + product_id: true, + product_name_snapshot: true, + store_name_snapshot: true, + quantity: true, + }, + }); + const quantity = items.reduce((sum, item) => sum + item.quantity, 0); + const exceeded = await isDailyCapacityExceeded( + tx, + args.capacityGuard, + quantity, + { forUpdate: true, excludeOrderId: locked.id }, + ); + if (exceeded) return 'capacity-exceeded'; + + // 결제 도입 전 접수는 마감이 없다 — 새로 만들지 않는다 + const resetDeadline = + locked.status === OrderStatus.SUBMITTED && + locked.confirm_deadline_at !== null; + const updated = await tx.order.update({ + where: { id: locked.id }, + data: { + pickup_at: args.pickupAt, + ...(resetDeadline + ? { + confirm_deadline_at: confirmDeadlineFor( + locked.submitted_at, + args.pickupAt, + ), + confirm_reminder_sent_at: null, + } + : {}), + }, + include: sellerOrderSummaryInclude(args.storeId), + }); + await tx.orderPickupChange.create({ + data: { + order_id: locked.id, + from_pickup_at: locked.pickup_at, + to_pickup_at: args.pickupAt, + changed_by_account_id: args.actorAccountId, + note: args.note, + changed_at: args.now, + }, + }); + + const [firstItem] = items; + await this.outbox.publish( + tx, + orderPickupRescheduledEvent({ + orderId: locked.id, + orderNumber: updated.order_number, + buyerAccountId: updated.account_id, + storeId: args.storeId, + storeName: firstItem?.store_name_snapshot ?? null, + productId: firstItem?.product_id ?? null, + productName: firstItem?.product_name_snapshot ?? null, + fromPickupAt: locked.pickup_at, + toPickupAt: args.pickupAt, + occurredAt: args.now, + actorAccountId: args.actorAccountId, + }), + ); + await this.auditLogs.recordAudit(tx, { + actorAccountId: args.actorAccountId, + storeId: args.storeId, + targetType: AuditTargetType.ORDER, + targetId: locked.id, + action: AuditActionType.UPDATE, + beforeJson: { pickupAt: locked.pickup_at.toISOString() }, + afterJson: { pickupAt: args.pickupAt.toISOString(), note: args.note }, + }); + return updated; + }, + { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted }, + ); + } +} diff --git a/src/features/order/repositories/order-transition.repository.ts b/src/features/order/repositories/order-transition.repository.ts index f0e72717..e8abe7e5 100644 --- a/src/features/order/repositories/order-transition.repository.ts +++ b/src/features/order/repositories/order-transition.repository.ts @@ -1,6 +1,5 @@ import { Inject, Injectable } from '@nestjs/common'; -import { DAY_MS } from '@/common/utils/kst-time'; import { AUDIT_LOG_REPOSITORY, type IAuditLogRepository, @@ -12,7 +11,10 @@ import type { OrderCancelDecision, OrderCancelState, } from '@/features/order/policies/order-cancel.policy'; -import type { OrderLockedState } from '@/features/order/policies/order-lifecycle.policy'; +import { + confirmDeadlineFor, + type OrderLockedState, +} from '@/features/order/policies/order-lifecycle.policy'; import { confirmedPaidAmount, finalizeSettlementLocked, @@ -108,9 +110,6 @@ interface PickupActor { now: Date; } -/** 접수 뒤 판매자 확정 마감: 확인 + 24시간과 픽업 시각 중 이른 쪽. */ -const CONFIRM_WINDOW_MS = DAY_MS; - interface LockedOrderRow { id: bigint; status: OrderStatus; @@ -219,12 +218,7 @@ export class OrderTransitionRepository { paymentAmount, pickupAt: locked.pickup_at, }); - const confirmDeadlineAt = new Date( - Math.min( - args.now.getTime() + CONFIRM_WINDOW_MS, - locked.pickup_at.getTime(), - ), - ); + const confirmDeadlineAt = confirmDeadlineFor(args.now, locked.pickup_at); const actorType = args.source === PaymentConfirmSource.ADMIN ? OrderActor.ADMIN diff --git a/src/features/order/repositories/order.repository.ts b/src/features/order/repositories/order.repository.ts index 09d6cb00..767b4ce9 100644 --- a/src/features/order/repositories/order.repository.ts +++ b/src/features/order/repositories/order.repository.ts @@ -7,6 +7,10 @@ import { import { IN_PROGRESS_ORDER_STATUSES } from '@/features/order/constants/order-status-traits'; import { orderPaymentPendingEvent } from '@/features/order/events/order-payment-pending.event'; import { orderStatusChangedEvent } from '@/features/order/events/order-status-changed.event'; +import { + isDailyCapacityExceeded, + type DailyCapacityGuard, +} from '@/features/order/repositories/order-capacity.helper'; import { lockCustomUploadsForAttach, markCustomUploadsAttached, @@ -59,6 +63,11 @@ const sellerVisibleWhere = { submitted_at: { not: null }, } satisfies Prisma.OrderWhereInput; +/** 주문 상세 3곳(구매자·판매자·관리자)의 픽업 변경 이력(오래된 순). */ +const pickupChangesInclude = { + orderBy: [{ changed_at: 'asc' }, { id: 'asc' }], +} satisfies Prisma.Order$pickup_changesArgs; + /** 주문 상세 3곳(구매자·판매자·관리자)의 커스텀 스냅샷. 디자인·이미지는 deleted_at이 없어 부모 품목 가시성을 따른다 */ const orderItemCustomInclude = { custom_design: { select: { schema_version: true, design_json: true } }, @@ -91,7 +100,7 @@ export const adminOrderInclude = { } satisfies Prisma.OrderInclude; /** 목록 카드용 첫 품목 스냅샷 — 매장 필터가 들어가 상수로 둘 수 없다. */ -function sellerOrderSummaryInclude(storeId: bigint) { +export function sellerOrderSummaryInclude(storeId: bigint) { return { items: { where: { store_id: storeId, ...activeWhere }, @@ -118,6 +127,7 @@ const adminOrderDetailInclude = { }, payment: true, refunds: { orderBy: { id: 'asc' } }, + pickup_changes: pickupChangesInclude, status_histories: { where: activeWhere, orderBy: { changed_at: 'desc' } }, items: { where: activeWhere, @@ -181,13 +191,7 @@ export interface OngoingOrderRow { }[]; } -/** 트랜잭션 안에서 capacity 행을 잠그고 점유를 재집계해 검사-삽입 race로 capacity가 초과되는 것을 막는다. */ -export interface DailyCapacityGuard { - storeId: bigint; - dateOnlyUtc: Date; - dayStartUtc: Date; - dayEndUtc: Date; -} +export type { DailyCapacityGuard } from '@/features/order/repositories/order-capacity.helper'; /** 주문 품목 커스텀 스냅샷. 검증·정규화를 마친 값이고, uploads는 같은 tx에서 잠가 ATTACHED로 바꿀 업로드다. */ export interface OrderItemCustomSnapshot { @@ -356,10 +360,11 @@ export class OrderRepository { ); if (pending >= PENDING_PAYMENT_LIMIT) return 'pending-limit'; if (args.capacityGuard) { - const exceeded = await this.isCapacityExceededLocked( + const exceeded = await isDailyCapacityExceeded( tx, args.capacityGuard, args.item.quantity, + { forUpdate: true }, ); if (exceeded) return 'capacity-exceeded'; } @@ -383,53 +388,9 @@ export class OrderRepository { guard: DailyCapacityGuard, quantity: number, ): Promise { - return this.capacityExceeded(this.prisma, guard, quantity, false); - } - - /** FOR UPDATE는 같은 매장·날짜의 동시 주문 생성을 직렬화한다. */ - private isCapacityExceededLocked( - tx: Prisma.TransactionClient, - guard: DailyCapacityGuard, - quantity: number, - ): Promise { - return this.capacityExceeded(tx, guard, quantity, true); - } - - /** - * capacity는 order 소유 복제본(order_store_daily_limit)에서 읽는다 — catalog 행을 잠그지 않는다. - * 복제본이 없거나 capacity가 비어 있으면(tombstone) 무제한: 설정 직후 복제 지연 구간에는 제한 없이 받는다. - */ - private async capacityExceeded( - db: Prisma.TransactionClient, - guard: DailyCapacityGuard, - quantity: number, - forUpdate: boolean, - ): Promise { - const capacityRows = await db.$queryRaw<{ capacity: number }[]>(Prisma.sql` - SELECT capacity - FROM order_store_daily_limit - WHERE store_id = ${guard.storeId} - AND booking_date = ${guard.dateOnlyUtc} - AND capacity IS NOT NULL - ${forUpdate ? Prisma.sql`FOR UPDATE` : Prisma.empty} - `); - const capacity = capacityRows[0]?.capacity; - if (capacity === undefined) return false; - - const bookedRows = await db.$queryRaw<{ booked: bigint }[]>(Prisma.sql` - SELECT CAST(COALESCE(SUM(oi.quantity), 0) AS UNSIGNED) AS booked - FROM order_item oi - JOIN \`order\` o - ON o.id = oi.order_id - AND o.deleted_at IS NULL - AND o.status <> 'CANCELED' - AND o.pickup_at >= ${guard.dayStartUtc} - AND o.pickup_at < ${guard.dayEndUtc} - WHERE oi.store_id = ${guard.storeId} - AND oi.deleted_at IS NULL - `); - const booked = Number(bookedRows[0]?.booked ?? 0); - return booked + quantity > capacity; + return isDailyCapacityExceeded(this.prisma, guard, quantity, { + forUpdate: false, + }); } private async insertPendingPaymentOrder( @@ -706,6 +667,7 @@ export class OrderRepository { include: { payment: { select: orderPaymentSelect }, refunds: { orderBy: { id: 'asc' } }, + pickup_changes: pickupChangesInclude, status_histories: { where: activeWhere, orderBy: { changed_at: 'asc' }, @@ -904,6 +866,7 @@ export class OrderRepository { payment: { select: { method: true } }, // 입금 반환은 구매자와 플랫폼 사이 일이라 취소 환불만 본다 refunds: { where: { kind: RefundKind.CANCEL } }, + pickup_changes: pickupChangesInclude, // 입금 대기 이력은 판매자에게 보이지 않는다 status_histories: { where: { diff --git a/src/features/order/resolvers/order-seller-pickup-mutation.resolver.ts b/src/features/order/resolvers/order-seller-pickup-mutation.resolver.ts new file mode 100644 index 00000000..dd6b44c0 --- /dev/null +++ b/src/features/order/resolvers/order-seller-pickup-mutation.resolver.ts @@ -0,0 +1,32 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Mutation, Resolver } from '@nestjs/graphql'; + +import { SellerRescheduleOrderPickupInput } from '@/features/order/dto/inputs/seller-reschedule-order-pickup.input'; +import { SellerOrderPickupService } from '@/features/order/services/order-seller-pickup.service'; +import type { SellerOrderSummaryOutput } from '@/features/order/types/order-seller-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Mutation') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('SELLER') +export class SellerOrderPickupMutationResolver { + constructor(private readonly pickupService: SellerOrderPickupService) {} + + @Mutation('sellerRescheduleOrderPickup') + sellerRescheduleOrderPickup( + @CurrentUser() user: JwtUser, + @Args('input') input: SellerRescheduleOrderPickupInput, + ): Promise { + return this.pickupService.sellerRescheduleOrderPickup( + parseAccountId(user), + input, + ); + } +} diff --git a/src/features/order/resolvers/order-seller-pickup-query.resolver.ts b/src/features/order/resolvers/order-seller-pickup-query.resolver.ts new file mode 100644 index 00000000..ce7a6ab5 --- /dev/null +++ b/src/features/order/resolvers/order-seller-pickup-query.resolver.ts @@ -0,0 +1,47 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Query, Resolver } from '@nestjs/graphql'; + +import { parseId } from '@/common/utils/id-parser'; +import { SellerOrderPickupService } from '@/features/order/services/order-seller-pickup.service'; +import type { PickupCalendar, PickupTimeSlots } from '@/features/store'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Query') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('SELLER') +export class SellerOrderPickupQueryResolver { + constructor(private readonly pickupService: SellerOrderPickupService) {} + + @Query('sellerOrderPickupCalendar') + sellerOrderPickupCalendar( + @CurrentUser() user: JwtUser, + @Args('orderId') orderId: string, + @Args('yearMonth') yearMonth: string, + ): Promise { + return this.pickupService.sellerOrderPickupCalendar( + parseAccountId(user), + parseId(orderId), + yearMonth, + ); + } + + @Query('sellerOrderPickupTimeSlots') + sellerOrderPickupTimeSlots( + @CurrentUser() user: JwtUser, + @Args('orderId') orderId: string, + @Args('date') date: string, + ): Promise { + return this.pickupService.sellerOrderPickupTimeSlots( + parseAccountId(user), + parseId(orderId), + date, + ); + } +} diff --git a/src/features/order/resolvers/order-seller-pickup.resolver.spec.ts b/src/features/order/resolvers/order-seller-pickup.resolver.spec.ts new file mode 100644 index 00000000..905ea2c9 --- /dev/null +++ b/src/features/order/resolvers/order-seller-pickup.resolver.spec.ts @@ -0,0 +1,126 @@ +import { PubSub } from 'graphql-subscriptions'; + +import { ClockService } from '@/common/providers/clock.service'; +import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; +import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; +import { OrderPickupChangeRepository } from '@/features/order/repositories/order-pickup-change.repository'; +import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { SellerOrderPickupMutationResolver } from '@/features/order/resolvers/order-seller-pickup-mutation.resolver'; +import { SellerOrderPickupQueryResolver } from '@/features/order/resolvers/order-seller-pickup-query.resolver'; +import { OrderEventsService } from '@/features/order/services/order-events.service'; +import { SellerOrderPickupService } from '@/features/order/services/order-seller-pickup.service'; +import { StoreSellerRepository } from '@/features/store/repositories/store-seller.repository'; +import { StoreRepository } from '@/features/store/repositories/store.repository'; +import { StorePickupScheduleService } from '@/features/store/services/store-pickup-schedule.service'; +import type { PrismaClient } from '@/generated/prisma/client'; +import { PUB_SUB } from '@/global/pubsub'; +import { bookedQuantityProviders } from '@/test/booked-quantity'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { + createOrder, + createOrderItem, + setupSellerWithStore, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { outboxPublisherProviders } from '@/test/outbox'; + +// 2026-09-16(수) 16:00 KST +const NOW = new Date('2026-09-16T07:00:00.000Z'); + +describe('Seller Order Pickup Resolvers (real DB)', () => { + let queryResolver: SellerOrderPickupQueryResolver; + let mutationResolver: SellerOrderPickupMutationResolver; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + SellerOrderPickupQueryResolver, + SellerOrderPickupMutationResolver, + SellerOrderPickupService, + StoreSellerRepository, + StoreRepository, + StorePickupScheduleService, + OrderRepository, + OrderPickupChangeRepository, + OrderStatusTransitionPolicy, + OrderEventsService, + { provide: PUB_SUB, useValue: new PubSub() }, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + { provide: ClockService, useValue: { now: () => NOW } }, + ...bookedQuantityProviders(), + ...outboxPublisherProviders({ clock: true }), + ], + }); + queryResolver = module.get(SellerOrderPickupQueryResolver); + mutationResolver = module.get(SellerOrderPickupMutationResolver); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + }); + + async function confirmedOrder() { + const me = await setupSellerWithStore(prisma); + await prisma.storeBusinessHour.createMany({ + data: Array.from({ length: 7 }, (_, dayOfWeek) => ({ + store_id: me.store.id, + day_of_week: dayOfWeek, + is_closed: false, + open_time: new Date(Date.UTC(1970, 0, 1, 10)), + close_time: new Date(Date.UTC(1970, 0, 1, 20)), + })), + }); + const order = await createOrder(prisma, { + status: 'CONFIRMED', + pickup_at: new Date('2026-09-18T05:00:00.000Z'), + }); + await createOrderItem(prisma, { + order_id: order.id, + store_id: me.store.id, + }); + return { user: { accountId: me.account.id.toString() }, order }; + } + + it('Query.sellerOrderPickupCalendar·TimeSlots: ID를 파싱해 변경 시트 달력과 슬롯을 준다', async () => { + const { user, order } = await confirmedOrder(); + + const calendar = await queryResolver.sellerOrderPickupCalendar( + user, + order.id.toString(), + '2026-09', + ); + const slots = await queryResolver.sellerOrderPickupTimeSlots( + user, + order.id.toString(), + '2026-09-17', + ); + + expect(calendar.yearMonth).toBe('2026-09'); + expect(calendar.days.find((d) => d.date === '2026-09-17')?.selectable).toBe( + true, + ); + expect(slots.date).toBe('2026-09-17'); + expect(slots.morning.length).toBeGreaterThan(0); + }); + + it('Mutation.sellerRescheduleOrderPickup: 픽업 일시를 바꾸고 요약을 반환한다', async () => { + const { user, order } = await confirmedOrder(); + const pickupAt = new Date('2026-09-17T06:30:00.000Z'); + + const result = await mutationResolver.sellerRescheduleOrderPickup(user, { + orderId: order.id.toString(), + pickupAt, + }); + + expect(result).toMatchObject({ id: order.id.toString(), pickupAt }); + }); +}); diff --git a/src/features/order/services/order-admin-mappers.helper.ts b/src/features/order/services/order-admin-mappers.helper.ts index ae52e9e0..10212d0f 100644 --- a/src/features/order/services/order-admin-mappers.helper.ts +++ b/src/features/order/services/order-admin-mappers.helper.ts @@ -7,6 +7,7 @@ import { toOrderAutoTransitionTimes, toOrderCancellation, toOrderItemDetail, + toOrderPickupChange, toOrderRefund, toOrderListCustomBadge, toOrderStatusHistory, @@ -77,5 +78,6 @@ export function toAdminOrderDetailOutput( cancellation: toOrderCancellation(row), cancelOptions, ...toOrderAutoTransitionTimes(row), + pickupChanges: row.pickup_changes.map(toOrderPickupChange), }; } diff --git a/src/features/order/services/order-admin.service.spec.ts b/src/features/order/services/order-admin.service.spec.ts index 08183ef4..0ce54844 100644 --- a/src/features/order/services/order-admin.service.spec.ts +++ b/src/features/order/services/order-admin.service.spec.ts @@ -488,6 +488,35 @@ describe('AdminOrderService (real DB)', () => { }, ); + it('판매자 픽업 일시 변경 이력을 준다(없으면 빈 배열)', async () => { + const { order } = await orderWithItem({ status: 'CONFIRMED' }); + const seller = await createAccount(prisma, { account_type: 'SELLER' }); + expect( + (await service.adminOrder(await admin(), order.id)).pickupChanges, + ).toEqual([]); + const change = await prisma.orderPickupChange.create({ + data: { + order_id: order.id, + from_pickup_at: order.pickup_at, + to_pickup_at: new Date('2026-09-21T05:00:00.000Z'), + changed_by_account_id: seller.id, + changed_at: new Date('2026-09-17T00:00:00.000Z'), + }, + }); + + const result = await service.adminOrder(await admin(), order.id); + + expect(result.pickupChanges).toEqual([ + { + id: change.id.toString(), + fromPickupAt: order.pickup_at, + toPickupAt: change.to_pickup_at, + changedAt: change.changed_at, + note: null, + }, + ]); + }); + it('결제와 입금 확인 처리자·메모를 준다', async () => { const { order } = await orderWithItem(); const confirmedAt = new Date('2026-09-16T07:00:00.000Z'); diff --git a/src/features/order/services/order-my.service.spec.ts b/src/features/order/services/order-my.service.spec.ts index c8da9718..43f2e99e 100644 --- a/src/features/order/services/order-my.service.spec.ts +++ b/src/features/order/services/order-my.service.spec.ts @@ -1040,6 +1040,36 @@ describe('UserOrderService (real DB)', () => { expect(detail.canCancel).toBe(canCancel); expect(detail.cancellation).toBeNull(); }); + + it('판매자가 바꾼 픽업 일시 이력을 오래된 순으로 준다', async () => { + const account = await setupUser(); + const { order } = await myOrder(account.id, 'CONFIRMED', null); + const seller = await createAccount(prisma, { account_type: 'SELLER' }); + const first = new Date('2026-09-20T05:00:00.000Z'); + const second = new Date('2026-09-21T05:00:00.000Z'); + for (const [to, changedAt, note] of [ + [second, new Date('2026-09-17T00:00:00.000Z'), null], + [first, new Date('2026-09-16T00:00:00.000Z'), '재료 수급'], + ] as const) { + await prisma.orderPickupChange.create({ + data: { + order_id: order.id, + from_pickup_at: order.pickup_at, + to_pickup_at: to, + changed_by_account_id: seller.id, + note, + changed_at: changedAt, + }, + }); + } + + const detail = await service.getMyOrder(account.id, order.id); + + expect(detail.pickupChanges.map((c) => [c.toPickupAt, c.note])).toEqual([ + [first, '재료 수급'], + [second, null], + ]); + }); }); describe('환불 계좌', () => { diff --git a/src/features/order/services/order-my.service.ts b/src/features/order/services/order-my.service.ts index a70f8d7e..fd168e51 100644 --- a/src/features/order/services/order-my.service.ts +++ b/src/features/order/services/order-my.service.ts @@ -24,6 +24,7 @@ import { OrderEventsService } from '@/features/order/services/order-events.servi import { toOrderCancellation, toOrderItemDetail, + toOrderPickupChange, toOrderRefund, toOrderStatusHistory, } from '@/features/order/services/order-output-mappers.helper'; @@ -242,6 +243,7 @@ export class UserOrderService { cancellation: toOrderCancellation(order), canCancel: this.cancelPolicy.canCancel(OrderActor.BUYER, order.status), refunds: order.refunds.map(toOrderRefund), + pickupChanges: order.pickup_changes.map(toOrderPickupChange), statusHistories: order.status_histories.map(toOrderStatusHistory), items: order.items.map((item) => ({ item: toOrderItemDetail(item), diff --git a/src/features/order/services/order-output-mappers.helper.ts b/src/features/order/services/order-output-mappers.helper.ts index 1fc09405..a282cbe6 100644 --- a/src/features/order/services/order-output-mappers.helper.ts +++ b/src/features/order/services/order-output-mappers.helper.ts @@ -10,6 +10,7 @@ import type { OrderCancellationOutput, OrderItemDetailOutput, OrderItemFreeEditOutput, + OrderPickupChangeOutput, OrderRefundOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; @@ -22,6 +23,7 @@ import { type CustomTextAlign, type OrderActor, type OrderCancelFault, + type OrderPickupChange, type Prisma, type Refund, } from '@/generated/prisma/client'; @@ -252,3 +254,15 @@ export function toOrderRefund(row: Refund): OrderRefundOutput { completedAt: row.completed_at, }; } + +export function toOrderPickupChange( + row: OrderPickupChange, +): OrderPickupChangeOutput { + return { + id: row.id.toString(), + fromPickupAt: row.from_pickup_at, + toPickupAt: row.to_pickup_at, + changedAt: row.changed_at, + note: row.note, + }; +} diff --git a/src/features/order/services/order-seller-mappers.helper.ts b/src/features/order/services/order-seller-mappers.helper.ts new file mode 100644 index 00000000..f58482a8 --- /dev/null +++ b/src/features/order/services/order-seller-mappers.helper.ts @@ -0,0 +1,26 @@ +import type { SellerOrderRow } from '@/features/order/repositories/order.repository'; +import { + toOrderAutoTransitionTimes, + toOrderListCustomBadge, +} from '@/features/order/services/order-output-mappers.helper'; +import type { SellerOrderSummaryOutput } from '@/features/order/types/order-seller-output.type'; + +export function toSellerOrderSummaryOutput( + row: SellerOrderRow, +): SellerOrderSummaryOutput { + return { + id: row.id.toString(), + orderNumber: row.order_number, + status: row.status, + pickupAt: row.pickup_at, + buyerName: row.buyer_name, + buyerPhone: row.buyer_phone, + totalPrice: row.total_price, + createdAt: row.created_at, + // 내 매장 첫 품목의 주문 시점 스냅샷 — 상품이 바뀌어도 카드 값은 유지된다 + firstItemName: row.items[0]?.product_name_snapshot ?? null, + firstItemImageUrl: row.items[0]?.product_thumbnail_url_snapshot ?? null, + ...toOrderListCustomBadge(row.items[0]), + confirmDeadlineAt: toOrderAutoTransitionTimes(row).confirmDeadlineAt, + }; +} diff --git a/src/features/order/services/order-seller-pickup.service.spec.ts b/src/features/order/services/order-seller-pickup.service.spec.ts new file mode 100644 index 00000000..4a973ff0 --- /dev/null +++ b/src/features/order/services/order-seller-pickup.service.spec.ts @@ -0,0 +1,503 @@ +import { PubSub } from 'graphql-subscriptions'; + +import { ClockService } from '@/common/providers/clock.service'; +import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; +import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; +import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; +import { OrderPickupChangeRepository } from '@/features/order/repositories/order-pickup-change.repository'; +import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; +import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { OrderEventsService } from '@/features/order/services/order-events.service'; +import { SellerOrderPickupService } from '@/features/order/services/order-seller-pickup.service'; +import { SellerOrderService } from '@/features/order/services/order-seller.service'; +import { StoreSellerRepository } from '@/features/store/repositories/store-seller.repository'; +import { StoreRepository } from '@/features/store/repositories/store.repository'; +import { StorePickupScheduleService } from '@/features/store/services/store-pickup-schedule.service'; +import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; +import { PUB_SUB } from '@/global/pubsub'; +import { bookedQuantityProviders } from '@/test/booked-quantity'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { + createOrder, + createOrderItem, + createStoreDailyCapacity, + setupSellerWithStore, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { outboxPublisherProviders } from '@/test/outbox'; +import { collectTopic } from '@/test/pubsub'; + +// 2026-09-16(수) 16:00 KST. 매장은 매일 10~20시, 30분 슬롯, 리드타임 3일(픽업 변경은 리드타임을 보지 않는다). +const NOW = new Date('2026-09-16T07:00:00.000Z'); +const PICKUP_AT = new Date('2026-09-18T05:00:00.000Z'); // 9/18 14:00 KST +const NEW_PICKUP_AT = new Date('2026-09-17T06:30:00.000Z'); // 9/17 15:30 KST + +describe('SellerOrderPickupService (real DB)', () => { + let service: SellerOrderPickupService; + let sellerOrders: SellerOrderService; + let prisma: PrismaClient; + let pubSub: PubSub; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + SellerOrderPickupService, + SellerOrderService, + StoreSellerRepository, + StoreRepository, + StorePickupScheduleService, + OrderRepository, + OrderPickupChangeRepository, + OrderTransitionRepository, + OrderStatusTransitionPolicy, + OrderCancelPolicy, + OrderEventsService, + { provide: PUB_SUB, useValue: new PubSub() }, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + { provide: ClockService, useValue: { now: () => NOW } }, + ...bookedQuantityProviders(), + ...outboxPublisherProviders({ clock: true }), + ], + }); + service = module.get(SellerOrderPickupService); + sellerOrders = module.get(SellerOrderService); + pubSub = module.get(PUB_SUB); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + }); + + afterEach(() => jest.restoreAllMocks()); + + async function openStore(opts: { isActive?: boolean } = {}) { + const seller = await setupSellerWithStore(prisma); + await prisma.store.update({ + where: { id: seller.store.id }, + data: { + is_active: opts.isActive ?? true, + pickup_slot_interval_minutes: 30, + min_lead_time_minutes: 3 * 24 * 60, + max_days_ahead: 14, + }, + }); + for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek += 1) { + await prisma.storeBusinessHour.create({ + data: { + store_id: seller.store.id, + day_of_week: dayOfWeek, + is_closed: false, + open_time: new Date(Date.UTC(1970, 0, 1, 10)), + close_time: new Date(Date.UTC(1970, 0, 1, 20)), + }, + }); + } + return seller; + } + + async function storeOrder( + storeId: bigint, + opts: { + status?: OrderStatus; + pickupAt?: Date; + quantity?: number; + submittedAt?: Date; + confirmDeadlineAt?: Date | null; + confirmReminderSentAt?: Date | null; + } = {}, + ) { + const order = await createOrder(prisma, { + status: opts.status ?? 'CONFIRMED', + pickup_at: opts.pickupAt ?? PICKUP_AT, + submitted_at: opts.submittedAt, + confirm_deadline_at: opts.confirmDeadlineAt, + confirm_reminder_sent_at: opts.confirmReminderSentAt, + }); + await createOrderItem(prisma, { + order_id: order.id, + store_id: storeId, + quantity: opts.quantity ?? 1, + product_name_snapshot: '레터링 케이크', + }); + return order; + } + + const reschedule = ( + accountId: bigint, + orderId: bigint, + pickupAt = NEW_PICKUP_AT, + note: string | null = null, + ) => + service.sellerRescheduleOrderPickup(accountId, { + orderId: orderId.toString(), + pickupAt, + note, + }); + const orderRow = (id: bigint) => + prisma.order.findUniqueOrThrow({ where: { id } }); + + describe('sellerRescheduleOrderPickup', () => { + it.each(['SUBMITTED', 'CONFIRMED', 'MADE'] as const)( + '%s 주문은 리드타임 안쪽 슬롯으로도 옮기고 이력·감사·구매자 알림 이벤트·판매자 구독을 남긴다', + async (status) => { + const { account, store } = await openStore(); + const order = await storeOrder(store.id, { status }); + const topic = await collectTopic(pubSub, `order.seller.${store.id}`); + + const result = await reschedule( + account.id, + order.id, + NEW_PICKUP_AT, + '재료 수급', + ); + + expect(result).toMatchObject({ status, pickupAt: NEW_PICKUP_AT }); + expect((await orderRow(order.id)).pickup_at).toEqual(NEW_PICKUP_AT); + expect(await prisma.orderPickupChange.findMany()).toEqual([ + expect.objectContaining({ + order_id: order.id, + from_pickup_at: PICKUP_AT, + to_pickup_at: NEW_PICKUP_AT, + changed_by_account_id: account.id, + note: '재료 수급', + changed_at: NOW, + }), + ]); + expect( + await prisma.auditLog.findFirstOrThrow({ + where: { target_id: order.id }, + }), + ).toMatchObject({ + store_id: store.id, + target_type: 'ORDER', + action: 'UPDATE', + before_json: { pickupAt: PICKUP_AT.toISOString() }, + after_json: { + pickupAt: NEW_PICKUP_AT.toISOString(), + note: '재료 수급', + }, + }); + const [event] = await prisma.outbox.findMany(); + expect(event).toMatchObject({ + event_type: 'order.pickup_rescheduled', + payload_json: expect.objectContaining({ + fromPickupAt: PICKUP_AT.toISOString(), + toPickupAt: NEW_PICKUP_AT.toISOString(), + productName: '레터링 케이크', + }), + }); + expect(topic.received).toEqual([ + expect.objectContaining({ + kind: 'PICKUP_RESCHEDULED', + pickupAt: NEW_PICKUP_AT.toISOString(), + }), + ]); + topic.stop(); + }, + ); + + it.each(['PICKED_UP', 'NO_SHOW', 'CANCELED'] as const)( + '%s 주문은 PICKUP_RESCHEDULE_NOT_ALLOWED', + async (status) => { + const { account, store } = await openStore(); + const order = await storeOrder(store.id, { status }); + + await expect(reschedule(account.id, order.id)).rejects.toThrowDomain( + 'PICKUP_RESCHEDULE_NOT_ALLOWED', + ); + expect(await prisma.orderPickupChange.count()).toBe(0); + }, + ); + + it('입금 대기·다른 매장 주문은 없는 주문이다', async () => { + const { account, store } = await openStore(); + const other = await openStore(); + const pending = await storeOrder(store.id, { status: 'PENDING_PAYMENT' }); + const others = await storeOrder(other.store.id); + + await expect(reschedule(account.id, pending.id)).rejects.toThrowDomain( + 'ORDER_NOT_FOUND', + ); + await expect(reschedule(account.id, others.id)).rejects.toThrowDomain( + 'ORDER_NOT_FOUND', + ); + }); + + it('사전 확인 뒤 주문이 사라지면(잠금 조회에서 빠짐) 없는 주문이다', async () => { + const { account, store } = await openStore(); + const order = await storeOrder(store.id); + const repo = (service as unknown as { orderRepository: OrderRepository }) + .orderRepository; + const original = repo.findOrderDetailByStore.bind(repo); + jest + .spyOn(repo, 'findOrderDetailByStore') + .mockImplementationOnce(async (args) => { + const row = await original(args); + await prisma.order.update({ + where: { id: order.id }, + data: { deleted_at: NOW }, + }); + return row; + }); + + await expect(reschedule(account.id, order.id)).rejects.toThrowDomain( + 'ORDER_NOT_FOUND', + ); + expect(await prisma.orderPickupChange.count()).toBe(0); + }); + + it('같은 일시면 PICKUP_UNCHANGED', async () => { + const { account, store } = await openStore(); + const order = await storeOrder(store.id); + + await expect( + reschedule(account.id, order.id, PICKUP_AT), + ).rejects.toThrowDomain('PICKUP_UNCHANGED'); + }); + + it.each([ + ['지난 시각(오늘 15:30 KST)', '2026-09-16T06:30:00.000Z'], + ['슬롯에 정렬되지 않은 시각', '2026-09-17T06:10:00.000Z'], + ['영업시간 밖(21:00 KST)', '2026-09-17T12:00:00.000Z'], + ['특별휴무일', '2026-09-19T05:00:00.000Z'], + ['예약 가능 기간 밖(15일 뒤)', '2026-10-01T05:00:00.000Z'], + ])('%s는 PICKUP_NOT_AVAILABLE', async (_label, iso) => { + const { account, store } = await openStore(); + await prisma.storeSpecialClosure.create({ + data: { + store_id: store.id, + closure_date: new Date(Date.UTC(2026, 8, 19)), + }, + }); + const order = await storeOrder(store.id); + + await expect( + reschedule(account.id, order.id, new Date(iso)), + ).rejects.toThrowDomain('PICKUP_NOT_AVAILABLE'); + expect((await orderRow(order.id)).pickup_at).toEqual(PICKUP_AT); + }); + + it('오늘 남은 슬롯(16:00 KST 정각)으로는 옮길 수 있다', async () => { + const { account, store } = await openStore(); + const order = await storeOrder(store.id); + + await reschedule(account.id, order.id, NOW); + + expect((await orderRow(order.id)).pickup_at).toEqual(NOW); + }); + + it('같은 날 다른 슬롯으로 옮길 때는 자기 수량을 빼고 센다', async () => { + const { account, store } = await openStore(); + await createStoreDailyCapacity(prisma, { + store_id: store.id, + capacity_date: new Date(Date.UTC(2026, 8, 18)), + capacity: 2, + }); + const order = await storeOrder(store.id, { quantity: 2 }); + const sameDay = new Date('2026-09-18T07:00:00.000Z'); + + await reschedule(account.id, order.id, sameDay); + + expect((await orderRow(order.id)).pickup_at).toEqual(sameDay); + }); + + /** + * 이 워커 DB에서 행 잠금을 기다리는 트랜잭션이 생길 때까지. + * innodb_trx는 직전 읽기 뒤 100ms가 지나야 캐시를 다시 채우므로 그보다 길게 쉬며 읽는다. + */ + async function waitForLockWait(): Promise { + for (let i = 0; i < 50; i++) { + await new Promise((resolve) => setTimeout(resolve, 150)); + const [{ n }] = await prisma.$queryRaw<{ n: bigint }[]>` + SELECT COUNT(*) AS n FROM information_schema.innodb_trx t + JOIN information_schema.processlist p ON p.id = t.trx_mysql_thread_id + WHERE t.trx_state = 'LOCK WAIT' AND p.db = DATABASE()`; + if (n > 0) return; + } + throw new Error('잠금 대기가 관측되지 않았다'); + } + + it('capacity 잠금을 기다린 픽업 변경은 그사이 커밋된 같은 날 점유까지 세어 초과를 거절한다', async () => { + const { account, store } = await openStore(); + const bookingDate = new Date(Date.UTC(2026, 8, 17)); + await createStoreDailyCapacity(prisma, { + store_id: store.id, + capacity_date: bookingDate, + capacity: 2, + }); + await storeOrder(store.id, { pickupAt: NEW_PICKUP_AT }); + const moving = await storeOrder(store.id); + const order = await storeOrder(store.id); + + // 다른 픽업 변경이 9/17 capacity 행을 잡고 주문 하나를 9/17로 옮긴 채(커밋 전) 이 변경이 끼어든다 + let racing: Promise | undefined; + await prisma.$transaction(async (tx) => { + await tx.$queryRaw` + SELECT capacity FROM order_store_daily_limit + WHERE store_id = ${store.id} AND booking_date = ${bookingDate} + FOR UPDATE`; + await tx.order.update({ + where: { id: moving.id }, + data: { pickup_at: NEW_PICKUP_AT }, + }); + racing = reschedule(account.id, order.id); + racing.catch(() => undefined); + await waitForLockWait(); + }); + + await expect(racing).rejects.toThrowDomain('PICKUP_NOT_AVAILABLE'); + expect((await orderRow(order.id)).pickup_at).toEqual(PICKUP_AT); + expect(await prisma.orderPickupChange.count()).toBe(0); + }); + + it('새 날짜의 제작 수량이 모자라면 PICKUP_NOT_AVAILABLE이다(다른 주문 점유 + 내 수량)', async () => { + const { account, store } = await openStore(); + await createStoreDailyCapacity(prisma, { + store_id: store.id, + capacity_date: new Date(Date.UTC(2026, 8, 17)), + capacity: 2, + }); + await storeOrder(store.id, { pickupAt: NEW_PICKUP_AT, quantity: 1 }); + const order = await storeOrder(store.id, { quantity: 2 }); + + await expect(reschedule(account.id, order.id)).rejects.toThrowDomain( + 'PICKUP_NOT_AVAILABLE', + ); + expect(await prisma.orderPickupChange.count()).toBe(0); + + // 반증: 내 수량이 1이면 들어간다 + const small = await storeOrder(store.id, { quantity: 1 }); + await reschedule(account.id, small.id); + expect((await orderRow(small.id)).pickup_at).toEqual(NEW_PICKUP_AT); + }); + + it('숨긴 매장의 주문도 옮길 수 있다', async () => { + const { account, store } = await openStore({ isActive: false }); + const order = await storeOrder(store.id); + + await reschedule(account.id, order.id); + + expect((await orderRow(order.id)).pickup_at).toEqual(NEW_PICKUP_AT); + }); + + it('접수 주문은 확정 마감을 새 픽업 기준으로 다시 재고 미리 알림 표시를 지운다', async () => { + const { account, store } = await openStore(); + const submittedAt = new Date('2026-09-16T06:00:00.000Z'); + const order = await storeOrder(store.id, { + status: 'SUBMITTED', + submittedAt, + confirmDeadlineAt: new Date('2026-09-17T06:00:00.000Z'), + confirmReminderSentAt: new Date('2026-09-16T06:30:00.000Z'), + }); + // 접수 + 24h(9/17 15:00 KST)보다 이른 픽업 → 마감 = 새 픽업 + const earlier = new Date('2026-09-16T08:00:00.000Z'); + + await reschedule(account.id, order.id, earlier); + + expect(await orderRow(order.id)).toMatchObject({ + confirm_deadline_at: earlier, + confirm_reminder_sent_at: null, + }); + // 더 늦은 픽업이면 접수 + 24시간이 마감이다 + await reschedule(account.id, order.id, PICKUP_AT); + expect((await orderRow(order.id)).confirm_deadline_at).toEqual( + new Date('2026-09-17T06:00:00.000Z'), + ); + }); + + it('확정 주문·결제 도입 전 접수 주문은 확정 마감을 건드리지 않는다', async () => { + const { account, store } = await openStore(); + const legacy = await storeOrder(store.id, { + status: 'SUBMITTED', + confirmDeadlineAt: null, + }); + const deadline = new Date('2026-09-17T06:00:00.000Z'); + const confirmed = await storeOrder(store.id, { + status: 'CONFIRMED', + confirmDeadlineAt: deadline, + }); + + await reschedule(account.id, legacy.id); + await reschedule(account.id, confirmed.id); + + expect((await orderRow(legacy.id)).confirm_deadline_at).toBeNull(); + expect((await orderRow(confirmed.id)).confirm_deadline_at).toEqual( + deadline, + ); + }); + + it('변경 이력은 판매자 주문 상세에 오래된 순으로 실린다', async () => { + const { account, store } = await openStore(); + const order = await storeOrder(store.id); + const later = new Date('2026-09-18T07:00:00.000Z'); + + await reschedule(account.id, order.id, NEW_PICKUP_AT, '첫 변경'); + await reschedule(account.id, order.id, later); + + const expected = [ + expect.objectContaining({ + fromPickupAt: PICKUP_AT, + toPickupAt: NEW_PICKUP_AT, + note: '첫 변경', + }), + expect.objectContaining({ + fromPickupAt: NEW_PICKUP_AT, + toPickupAt: later, + note: null, + }), + ]; + const sellerDetail = await sellerOrders.sellerOrder(account.id, order.id); + expect(sellerDetail.pickupChanges).toEqual(expected); + }); + }); + + describe('변경 시트 달력·슬롯', () => { + it('리드타임 안쪽 날도 고를 수 있고 이 주문의 점유는 지금 픽업일에서 뺀다', async () => { + const { account, store } = await openStore(); + await createStoreDailyCapacity(prisma, { + store_id: store.id, + capacity_date: new Date(Date.UTC(2026, 8, 18)), + capacity: 2, + }); + const order = await storeOrder(store.id, { quantity: 2 }); + + const calendar = await service.sellerOrderPickupCalendar( + account.id, + order.id, + '2026-09', + ); + const slots = await service.sellerOrderPickupTimeSlots( + account.id, + order.id, + '2026-09-18', + ); + + const day = (date: string) => calendar.days.find((d) => d.date === date); + expect(day('2026-09-17')?.selectable).toBe(true); + expect(day('2026-09-18')?.selectable).toBe(true); + expect(slots.afternoon.every((slot) => slot.available)).toBe(true); + }); + + it('옮길 수 없는 상태면 PICKUP_RESCHEDULE_NOT_ALLOWED, 남의 주문이면 NOT_FOUND', async () => { + const { account, store } = await openStore(); + const other = await openStore(); + const done = await storeOrder(store.id, { status: 'PICKED_UP' }); + const others = await storeOrder(other.store.id); + + await expect( + service.sellerOrderPickupCalendar(account.id, done.id, '2026-09'), + ).rejects.toThrowDomain('PICKUP_RESCHEDULE_NOT_ALLOWED'); + await expect( + service.sellerOrderPickupTimeSlots(account.id, others.id, '2026-09-18'), + ).rejects.toThrowDomain('ORDER_NOT_FOUND'); + }); + }); +}); diff --git a/src/features/order/services/order-seller-pickup.service.ts b/src/features/order/services/order-seller-pickup.service.ts new file mode 100644 index 00000000..8f67ace2 --- /dev/null +++ b/src/features/order/services/order-seller-pickup.service.ts @@ -0,0 +1,163 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { MAX_REASON_LENGTH } from '@/common/constants/reason.constants'; +import { DomainException } from '@/common/errors/error-catalog'; +import { ClockService } from '@/common/providers/clock.service'; +import { parseId } from '@/common/utils/id-parser'; +import { formatKstDate, kstDayBoundaries } from '@/common/utils/kst-time'; +import { cleanNullableText } from '@/common/utils/text-cleaner'; +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import type { SellerRescheduleOrderPickupInput } from '@/features/order/dto/inputs/seller-reschedule-order-pickup.input'; +import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; +import { OrderPickupChangeRepository } from '@/features/order/repositories/order-pickup-change.repository'; +import { OrderRepository } from '@/features/order/repositories/order.repository'; +import { toSellerOrderUpdateEvent } from '@/features/order/services/order-events-mappers.helper'; +import { OrderEventsService } from '@/features/order/services/order-events.service'; +import { toSellerOrderSummaryOutput } from '@/features/order/services/order-seller-mappers.helper'; +import type { SellerOrderSummaryOutput } from '@/features/order/types/order-seller-output.type'; +import { + SellerBaseService, + StorePickupScheduleService, + StoreSellerRepository, + type BookedAdjustment, + type PickupCalendar, + type PickupTimeSlots, +} from '@/features/store'; +import type { OrderStatus } from '@/generated/prisma/client'; + +/** + * 판매자 픽업 일시 변경(접수·확정·제작 완료). 검사는 영업일·특별휴무·슬롯 시각·과거 금지·예약 가능 기간·제작 수량이고 + * 리드타임·상품 제작 시간은 보지 않는다. 숨긴 매장의 진행 주문도 옮길 수 있다. + */ +@Injectable() +export class SellerOrderPickupService extends SellerBaseService { + constructor( + repo: StoreSellerRepository, + @Inject(AUDIT_LOG_REPOSITORY) + auditLogs: IAuditLogRepository, + private readonly orderRepository: OrderRepository, + private readonly pickupChanges: OrderPickupChangeRepository, + private readonly statusPolicy: OrderStatusTransitionPolicy, + private readonly pickupSchedule: StorePickupScheduleService, + private readonly events: OrderEventsService, + private readonly clock: ClockService, + ) { + super(repo, auditLogs); + } + + async sellerOrderPickupCalendar( + accountId: bigint, + orderId: bigint, + yearMonth: string, + ): Promise { + const { storeId, adjustment } = await this.requireReschedulable( + accountId, + orderId, + ); + return this.pickupSchedule.rescheduleCalendar( + storeId, + yearMonth, + adjustment, + ); + } + + async sellerOrderPickupTimeSlots( + accountId: bigint, + orderId: bigint, + date: string, + ): Promise { + const { storeId, adjustment } = await this.requireReschedulable( + accountId, + orderId, + ); + return this.pickupSchedule.rescheduleTimeSlots(storeId, date, adjustment); + } + + async sellerRescheduleOrderPickup( + accountId: bigint, + input: SellerRescheduleOrderPickupInput, + ): Promise { + const ctx = await this.requireSellerContext(accountId); + const orderId = parseId(input.orderId); + const pickupAt = input.pickupAt; + const current = await this.orderRepository.findOrderDetailByStore({ + orderId, + storeId: ctx.storeId, + }); + if (!current) throw new DomainException('ORDER_NOT_FOUND'); + const assertReschedulable = (state: { + status: OrderStatus; + pickupAt: Date; + }) => + this.statusPolicy.assertPickupChange({ + status: state.status, + fromPickupAt: state.pickupAt, + toPickupAt: pickupAt, + }); + assertReschedulable({ + status: current.status, + pickupAt: current.pickup_at, + }); + + const available = await this.pickupSchedule.isPickupSlotAvailable({ + storeId: ctx.storeId, + pickupAt, + preparationTimeMinutes: 0, + leadTime: 'SKIP', + storeActiveOnly: false, + }); + if (!available) throw new DomainException('PICKUP_NOT_AVAILABLE'); + + const { dateOnlyUtc, dayStartUtc, dayEndUtc } = kstDayBoundaries(pickupAt); + const result = await this.pickupChanges.reschedule({ + orderId, + storeId: ctx.storeId, + actorAccountId: ctx.accountId, + pickupAt, + note: cleanNullableText(input.note, MAX_REASON_LENGTH), + now: this.clock.now(), + capacityGuard: { + storeId: ctx.storeId, + dateOnlyUtc, + dayStartUtc, + dayEndUtc, + }, + // 잠금 뒤 상태·픽업 시각으로 같은 규칙을 다시 적용한다(위 사전 검사는 빠른 거절용) + assertReschedulable, + }); + if (result === null) throw new DomainException('ORDER_NOT_FOUND'); + if (result === 'capacity-exceeded') { + throw new DomainException('PICKUP_NOT_AVAILABLE'); + } + + await this.events.publishSellerOrderUpdate( + ctx.storeId, + toSellerOrderUpdateEvent('PICKUP_RESCHEDULED', result), + ); + return toSellerOrderSummaryOutput(result); + } + + /** 옮길 수 있는 주문인지 보고, 달력 수량에서 뺄 이 주문의 현재 점유(지금 픽업일·수량)를 만든다. */ + private async requireReschedulable( + accountId: bigint, + orderId: bigint, + ): Promise<{ storeId: bigint; adjustment: BookedAdjustment }> { + const ctx = await this.requireSellerContext(accountId); + const order = await this.orderRepository.findOrderDetailByStore({ + orderId, + storeId: ctx.storeId, + }); + if (!order) throw new DomainException('ORDER_NOT_FOUND'); + this.statusPolicy.assertPickupReschedulable(order.status); + return { + storeId: ctx.storeId, + adjustment: { + date: formatKstDate(order.pickup_at), + quantity: order.items.reduce((sum, item) => sum + item.quantity, 0), + }, + }; + } +} diff --git a/src/features/order/services/order-seller.service.ts b/src/features/order/services/order-seller.service.ts index 1e315fe0..e2d6c0f2 100644 --- a/src/features/order/services/order-seller.service.ts +++ b/src/features/order/services/order-seller.service.ts @@ -22,21 +22,19 @@ import type { SellerUpdateOrderStatusInput } from '@/features/order/dto/inputs/s import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; -import { - OrderRepository, - type SellerOrderRow, -} from '@/features/order/repositories/order.repository'; +import { OrderRepository } from '@/features/order/repositories/order.repository'; import { toSellerOrderUpdateEvent } from '@/features/order/services/order-events-mappers.helper'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { + toOrderAutoTransitionTimes, toOrderCancellation, toOrderItemDetail, - toOrderAutoTransitionTimes, - toOrderListCustomBadge, + toOrderPickupChange, toOrderStatusHistory, type OrderItemDetailRow, type OrderStatusHistoryRow, } from '@/features/order/services/order-output-mappers.helper'; +import { toSellerOrderSummaryOutput } from '@/features/order/services/order-seller-mappers.helper'; import type { SellerOrderDetailOutput, SellerOrderSummaryOutput, @@ -45,6 +43,7 @@ import { SellerBaseService, StoreSellerRepository } from '@/features/store'; import { OrderActor, OrderStatus, + type OrderPickupChange, type PaymentMethod, type Refund, } from '@/generated/prisma/client'; @@ -97,7 +96,7 @@ export class SellerOrderService extends SellerBaseService { const paged = sliceIdCursorPage(rows, normalized.limit); return { - items: paged.items.map((row) => this.toOrderSummaryOutput(row)), + items: paged.items.map((row) => toSellerOrderSummaryOutput(row)), nextCursor: paged.nextCursor, hasMore: paged.hasMore, totalCount, @@ -163,7 +162,7 @@ export class SellerOrderService extends SellerBaseService { ctx.storeId, toSellerOrderUpdateEvent('STATUS_CHANGED', updated), ); - return this.toOrderSummaryOutput(updated); + return toSellerOrderSummaryOutput(updated); } /** 접수 단계 거절(전액 환불)과 확정 뒤 취소(사정 선택). 입금 확인 전 주문은 없는 주문과 같다. */ @@ -192,25 +191,7 @@ export class SellerOrderService extends SellerBaseService { }); if (!updated) throw new DomainException('ORDER_NOT_FOUND'); await this.events.publishSellerStatusChanged(updated); - return this.toOrderSummaryOutput(updated); - } - - private toOrderSummaryOutput(row: SellerOrderRow): SellerOrderSummaryOutput { - return { - id: row.id.toString(), - orderNumber: row.order_number, - status: row.status, - pickupAt: row.pickup_at, - buyerName: row.buyer_name, - buyerPhone: row.buyer_phone, - totalPrice: row.total_price, - createdAt: row.created_at, - // 내 매장 첫 품목의 주문 시점 스냅샷 — 상품이 바뀌어도 카드 값은 유지된다 - firstItemName: row.items[0]?.product_name_snapshot ?? null, - firstItemImageUrl: row.items[0]?.product_thumbnail_url_snapshot ?? null, - ...toOrderListCustomBadge(row.items[0]), - confirmDeadlineAt: toOrderAutoTransitionTimes(row).confirmDeadlineAt, - }; + return toSellerOrderSummaryOutput(updated); } private toOrderDetailOutput(row: { @@ -237,6 +218,7 @@ export class SellerOrderService extends SellerBaseService { updated_at: Date; status_histories: OrderStatusHistoryRow[]; refunds: Refund[]; + pickup_changes: OrderPickupChange[]; items: OrderItemDetailRow[]; }): SellerOrderDetailOutput { return { @@ -277,6 +259,7 @@ export class SellerOrderService extends SellerBaseService { now: this.clock.now(), pickupAt: row.pickup_at, }), + pickupChanges: row.pickup_changes.map(toOrderPickupChange), }; } } diff --git a/src/features/order/types/order-admin-output.type.ts b/src/features/order/types/order-admin-output.type.ts index 865ab9ec..93213c05 100644 --- a/src/features/order/types/order-admin-output.type.ts +++ b/src/features/order/types/order-admin-output.type.ts @@ -3,6 +3,7 @@ import type { OrderAutoTransitionTimes, OrderCancellationOutput, OrderItemDetailOutput, + OrderPickupChangeOutput, OrderRefundOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; @@ -67,6 +68,7 @@ export interface AdminOrderDetailOutput extends OrderAutoTransitionTimes { refunds: OrderRefundOutput[]; cancellation: OrderCancellationOutput | null; cancelOptions: AdminOrderCancelOptionsOutput; + pickupChanges: OrderPickupChangeOutput[]; } export interface AdminOrderCancelOptionsOutput { diff --git a/src/features/order/types/order-my-output.type.ts b/src/features/order/types/order-my-output.type.ts index f85061cc..f4c86be0 100644 --- a/src/features/order/types/order-my-output.type.ts +++ b/src/features/order/types/order-my-output.type.ts @@ -2,6 +2,7 @@ import type { OffsetConnection } from '@/common/types/cursor-connection.type'; import type { OrderCancellationOutput, OrderItemDetailOutput, + OrderPickupChangeOutput, OrderRefundOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; @@ -69,6 +70,7 @@ export interface MyOrderDetail { cancellation: OrderCancellationOutput | null; canCancel: boolean; refunds: OrderRefundOutput[]; + pickupChanges: OrderPickupChangeOutput[]; statusHistories: OrderStatusHistoryOutput[]; items: MyOrderItem[]; store: MyOrderStoreInfo; diff --git a/src/features/order/types/order-output.type.ts b/src/features/order/types/order-output.type.ts index 3d4f0a14..49c98f8c 100644 --- a/src/features/order/types/order-output.type.ts +++ b/src/features/order/types/order-output.type.ts @@ -142,3 +142,12 @@ export interface OrderAutoTransitionTimes { autoPickupAt: Date | null; noShowAt: Date | null; } + +/** 판매자 픽업 일시 변경 이력 1건. */ +export interface OrderPickupChangeOutput { + id: string; + fromPickupAt: Date; + toPickupAt: Date; + changedAt: Date; + note: string | null; +} diff --git a/src/features/order/types/order-seller-output.type.ts b/src/features/order/types/order-seller-output.type.ts index 71ab8c7f..917aef0c 100644 --- a/src/features/order/types/order-seller-output.type.ts +++ b/src/features/order/types/order-seller-output.type.ts @@ -2,6 +2,7 @@ import type { OrderAutoTransitionTimes, OrderCancellationOutput, OrderItemDetailOutput, + OrderPickupChangeOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; import type { OrderStatus, PaymentMethod } from '@/generated/prisma/client'; @@ -46,6 +47,7 @@ export interface SellerOrderDetailOutput extends OrderAutoTransitionTimes { statusHistories: OrderStatusHistoryOutput[]; cancellation: OrderCancellationOutput | null; canMarkNoShow: boolean; + pickupChanges: OrderPickupChangeOutput[]; } /** SDL SellerOrderUpdateKind. PICKUP_RESCHEDULED는 판매자 픽업 일시 변경이 발행한다. */ diff --git a/src/features/store/index.ts b/src/features/store/index.ts index bc8e6213..89b8c619 100644 --- a/src/features/store/index.ts +++ b/src/features/store/index.ts @@ -7,7 +7,15 @@ export { } from '@/features/store/constants/store-ranking.constants'; // 매장 픽업 가능 판정. 주문 생성(order feature)이 픽업 일시 재검증에 사용한다 — // 판정 규칙은 store feature에 유지한다(달력·슬롯 조회와 단일 소스). -export { StorePickupScheduleService } from '@/features/store/services/store-pickup-schedule.service'; +export { + StorePickupScheduleService, + type BookedAdjustment, +} from '@/features/store/services/store-pickup-schedule.service'; +// 판매자 픽업 변경 달력·슬롯(order feature)이 같은 출력 타입을 쓴다. +export type { + PickupCalendar, + PickupTimeSlots, +} from '@/features/store/types/pickup-schedule-output.type'; // 픽업 하한(매장 리드타임과 상품 제작 시간 중 긴 쪽). 달력·슬롯·주문 생성이 같은 규칙을 쓴다. export { effectiveLeadTimeMinutes } from '@/features/store/services/store-pickup-policy.helper'; export { scoreAndSortByPopularity } from '@/features/store/services/store-ranking.helper'; diff --git a/src/features/store/repositories/store.repository.ts b/src/features/store/repositories/store.repository.ts index 3887a336..7d0db249 100644 --- a/src/features/store/repositories/store.repository.ts +++ b/src/features/store/repositories/store.repository.ts @@ -177,11 +177,13 @@ export class StoreRepository { return new Map(rows.map((r) => [r.store_id, r.capacity])); } + /** activeOnly=false는 판매자 픽업 변경용 — 숨긴 매장의 진행 주문도 옮길 수 있다. */ async findStoreForPickupSchedule( storeId: bigint, + activeOnly = true, ): Promise { return this.prisma.store.findFirst({ - where: { id: storeId, is_active: true }, + where: { id: storeId, ...(activeOnly ? { is_active: true } : {}) }, select: { id: true, pickup_slot_interval_minutes: true, diff --git a/src/features/store/services/store-pickup-policy.helper.ts b/src/features/store/services/store-pickup-policy.helper.ts index 9b27a657..721cc003 100644 --- a/src/features/store/services/store-pickup-policy.helper.ts +++ b/src/features/store/services/store-pickup-policy.helper.ts @@ -71,6 +71,8 @@ export interface PickupDayInput { /** 레코드가 없으면 undefined = 무제한. */ capacity: number | undefined; booked: number; + /** 이 날짜에 더 들어가야 하는 수량. 기본 1(새 주문 한 건), 픽업 변경은 옮길 주문의 수량. */ + required?: number; now: Date; dayStartUtc: Date; } @@ -111,7 +113,10 @@ export function evaluatePickupDay(input: PickupDayInput): PickupDayResult { } // capacity 레코드가 없으면 무제한으로 간주 - if (input.capacity !== undefined && input.booked >= input.capacity) { + if ( + input.capacity !== undefined && + input.booked + (input.required ?? 1) > input.capacity + ) { return { reason: STORE_PICKUP_DAY_REASON.CAPACITY_FULL, slots }; } diff --git a/src/features/store/services/store-pickup-schedule.service.spec.ts b/src/features/store/services/store-pickup-schedule.service.spec.ts index b691f504..01a543cb 100644 --- a/src/features/store/services/store-pickup-schedule.service.spec.ts +++ b/src/features/store/services/store-pickup-schedule.service.spec.ts @@ -732,4 +732,156 @@ describe('StorePickupScheduleService (real DB)', () => { ).resolves.toBe(false); }); }); + describe('판매자 픽업 변경(리드타임 생략·숨긴 매장 허용·자기 수량 차감)', () => { + const ADJUST_NONE = { date: '2026-09-18', quantity: 0 }; + + it('리드타임·제작 시간 없이 지난 시각만 막는다(isPickupSlotAvailable SKIP)', async () => { + const store = await createStore(prisma, { + min_lead_time_minutes: 3 * 24 * 60, + }); + await openAllWeek(store); + const at = (iso: string) => + service.isPickupSlotAvailable({ + storeId: store.id, + pickupAt: new Date(iso), + preparationTimeMinutes: 26 * 60, + leadTime: 'SKIP', + storeActiveOnly: false, + }); + + // 오늘(9/16) 16:00 KST 정각 슬롯은 가능, 15:30은 지났다 + await expect(at('2026-09-16T07:00:00.000Z')).resolves.toBe(true); + await expect(at('2026-09-16T06:30:00.000Z')).resolves.toBe(false); + // 리드 3일 안쪽(9/17)도 가능 — 반증: APPLY면 불가 + await expect(at('2026-09-17T05:00:00.000Z')).resolves.toBe(true); + await expect( + service.isPickupSlotAvailable({ + storeId: store.id, + pickupAt: new Date('2026-09-17T05:00:00.000Z'), + preparationTimeMinutes: 0, + }), + ).resolves.toBe(false); + }); + + it('숨긴 매장도 storeActiveOnly false면 판정하고, 기본값은 여전히 불가다', async () => { + const store = await createStore(prisma, { is_active: false }); + await openAllWeek(store); + const pickupAt = new Date('2026-09-18T05:00:00.000Z'); + + await expect( + service.isPickupSlotAvailable({ + storeId: store.id, + pickupAt, + preparationTimeMinutes: 0, + leadTime: 'SKIP', + storeActiveOnly: false, + }), + ).resolves.toBe(true); + await expect( + service.isPickupSlotAvailable({ + storeId: store.id, + pickupAt, + preparationTimeMinutes: 0, + leadTime: 'SKIP', + }), + ).resolves.toBe(false); + }); + + it('달력은 숨긴 매장도 계산하고 리드타임에 덮인 날도 고를 수 있다', async () => { + const store = await createStore(prisma, { + is_active: false, + min_lead_time_minutes: 3 * 24 * 60, + }); + await openAllWeek(store); + + const calendar = await service.rescheduleCalendar( + store.id, + '2026-09', + ADJUST_NONE, + ); + + expect(dayOf(calendar, '2026-09-15').reason).toBe('PAST'); + expect(dayOf(calendar, '2026-09-17').selectable).toBe(true); + const slots = await service.rescheduleTimeSlots( + store.id, + '2026-09-16', + ADJUST_NONE, + ); + expect( + slots.afternoon.find((slot) => slot.time === '15:30')?.available, + ).toBe(false); + expect( + slots.afternoon.find((slot) => slot.time === '16:00')?.available, + ).toBe(true); + }); + + it('옮길 주문의 현재 점유는 그 날짜에서 빼고 센다(다른 날짜는 그대로)', async () => { + const store = await createStore(prisma); + await openAllWeek(store); + await setCapacity(store, new Date(Date.UTC(2026, 8, 18)), 2); + await setCapacity(store, new Date(Date.UTC(2026, 8, 19)), 2); + await book(store, new Date('2026-09-18T05:00:00.000Z'), 2); + await book(store, new Date('2026-09-19T05:00:00.000Z'), 2); + const adjustment = { date: '2026-09-18', quantity: 2 }; + + const calendar = await service.rescheduleCalendar( + store.id, + '2026-09', + adjustment, + ); + const slots = await service.rescheduleTimeSlots( + store.id, + '2026-09-18', + adjustment, + ); + + expect(dayOf(calendar, '2026-09-18').selectable).toBe(true); + expect(dayOf(calendar, '2026-09-19').reason).toBe('CAPACITY_FULL'); + expect(slots.afternoon.every((slot) => slot.available)).toBe(true); + // 반증: 차감이 없으면 같은 날도 소진이다 + expect( + dayOf( + await service.rescheduleCalendar(store.id, '2026-09', ADJUST_NONE), + '2026-09-18', + ).reason, + ).toBe('CAPACITY_FULL'); + }); + + it('옮길 주문의 수량 전체가 들어가지 않는 날짜는 소진으로 본다', async () => { + const store = await createStore(prisma); + await openAllWeek(store); + await setCapacity(store, new Date(Date.UTC(2026, 8, 18)), 2); + await setCapacity(store, new Date(Date.UTC(2026, 8, 19)), 3); + await book(store, new Date('2026-09-18T05:00:00.000Z'), 1); + await book(store, new Date('2026-09-19T05:00:00.000Z'), 1); + const adjustment = { date: '2026-09-20', quantity: 2 }; + + const calendar = await service.rescheduleCalendar( + store.id, + '2026-09', + adjustment, + ); + const full = await service.rescheduleTimeSlots( + store.id, + '2026-09-18', + adjustment, + ); + + expect(dayOf(calendar, '2026-09-18').reason).toBe('CAPACITY_FULL'); + expect(dayOf(calendar, '2026-09-19').selectable).toBe(true); + expect(full.afternoon.every((slot) => !slot.available)).toBe(true); + }); + + it('없는 매장과 형식 오류는 거절한다', async () => { + await expect( + service.rescheduleCalendar(999999n, '2026-09', ADJUST_NONE), + ).rejects.toThrowDomain('STORE_NOT_FOUND'); + await expect( + service.rescheduleCalendar(999999n, '2026-13', ADJUST_NONE), + ).rejects.toThrowDomain('INVALID_YEAR_MONTH'); + await expect( + service.rescheduleTimeSlots(999999n, '2026-09-31', ADJUST_NONE), + ).rejects.toThrowDomain('INVALID_DATE'); + }); + }); }); diff --git a/src/features/store/services/store-pickup-schedule.service.ts b/src/features/store/services/store-pickup-schedule.service.ts index 3686d7cf..01f85870 100644 --- a/src/features/store/services/store-pickup-schedule.service.ts +++ b/src/features/store/services/store-pickup-schedule.service.ts @@ -42,6 +42,13 @@ interface ScheduleContext { closureDates: Set; capacities: Map; bookedByDate: Map; + required: number; +} + +/** 픽업 변경 달력에서 옮길 주문이 지금 점유한 수량. 그 날짜(KST 'YYYY-MM-DD') 예약 수량에서 뺀다. */ +export interface BookedAdjustment { + date: string; + quantity: number; } @Injectable() @@ -58,12 +65,28 @@ export class StorePickupScheduleService { yearMonth: string, productId: bigint | null = null, ): Promise { - const ym = parseKstYearMonth(yearMonth); - if (!ym || ym.year < MIN_SCHEDULE_YEAR || ym.year > MAX_SCHEDULE_YEAR) { - throw new DomainException('INVALID_YEAR_MONTH'); - } + const ym = parseScheduleYearMonth(yearMonth); const store = await this.findScheduleStore(storeId, productId); + return this.buildCalendar(store, ym, yearMonth); + } + /** 판매자 픽업 변경 달력: 리드타임·제작 시간 없이(과거만 막는다) 숨긴 매장도 계산하고, 옮길 주문의 수량은 빼고 센다. */ + async rescheduleCalendar( + storeId: bigint, + yearMonth: string, + adjustment: BookedAdjustment, + ): Promise { + const ym = parseScheduleYearMonth(yearMonth); + const store = await this.findRescheduleStore(storeId); + return this.buildCalendar(store, ym, yearMonth, adjustment); + } + + private async buildCalendar( + store: StorePickupPolicyRow, + ym: { year: number; month: number }, + yearMonth: string, + adjustment?: BookedAdjustment, + ): Promise { const now = this.clock.now(); const dayCount = daysInMonth(ym.year, ym.month); // 조회는 월 범위 벌크 4회로 끝내고, 날짜 루프에서는 추가 쿼리를 내지 않는다 @@ -73,6 +96,7 @@ export class StorePickupScheduleService { new Date(Date.UTC(ym.year, ym.month, 1)), kstMidnightUtc(ym.year, ym.month, 1), kstMidnightUtc(ym.year, ym.month + 1, 1), + { withCapacity: true, adjustment }, ); const days: PickupDay[] = Array.from({ length: dayCount }, (_, index) => { @@ -98,16 +122,29 @@ export class StorePickupScheduleService { date: string, productId: bigint | null = null, ): Promise { - const parsed = parseKstDate(date); - if (!parsed) { - throw new DomainException('INVALID_DATE'); - } - const { year, month, day } = toKstYmd(parsed); - if (year < MIN_SCHEDULE_YEAR || year > MAX_SCHEDULE_YEAR) { - throw new DomainException('INVALID_DATE'); - } + const parsed = parseScheduleDate(date); const store = await this.findScheduleStore(storeId, productId); + return this.buildTimeSlots(store, date, parsed); + } + /** 판매자 픽업 변경 슬롯. 규칙은 rescheduleCalendar와 같다. */ + async rescheduleTimeSlots( + storeId: bigint, + date: string, + adjustment: BookedAdjustment, + ): Promise { + const parsed = parseScheduleDate(date); + const store = await this.findRescheduleStore(storeId); + return this.buildTimeSlots(store, date, parsed, adjustment); + } + + private async buildTimeSlots( + store: StorePickupPolicyRow, + date: string, + parsed: Date, + adjustment?: BookedAdjustment, + ): Promise { + const { year, month, day } = toKstYmd(parsed); const now = this.clock.now(); const ctx = await this.loadScheduleContext( store.id, @@ -115,6 +152,7 @@ export class StorePickupScheduleService { new Date(Date.UTC(year, month - 1, day + 1)), parsed, kstMidnightUtc(year, month, day + 1), + { withCapacity: true, adjustment }, ); const input = this.pickupDayInput(store, ctx, now, year, month, day); @@ -147,15 +185,24 @@ export class StorePickupScheduleService { * **capacity는 보지 않는다** — 일일 수량 판정은 order가 자기 복제본으로만 한다. * 여기서 catalog 설정을 함께 보면 복제 지연 구간에 두 소스가 어긋나 "복제본 없으면 무제한"이 깨진다. * 매장이 없거나 비활성이면 false(존재 검증은 호출부 책임). + * 판매자 픽업 변경은 leadTime 'SKIP'(리드타임·제작 시간 없이 과거만 막는다)·storeActiveOnly false(숨긴 매장 허용)로 부른다. */ async isPickupSlotAvailable(args: { storeId: bigint; pickupAt: Date; preparationTimeMinutes: number; + leadTime?: 'APPLY' | 'SKIP'; + storeActiveOnly?: boolean; }): Promise { - const found = await this.repo.findStoreForPickupSchedule(args.storeId); + const found = await this.repo.findStoreForPickupSchedule( + args.storeId, + args.storeActiveOnly ?? true, + ); if (!found) return false; - const store = withPreparationTime(found, args.preparationTimeMinutes); + const store = + args.leadTime === 'SKIP' + ? withoutLeadTime(found) + : withPreparationTime(found, args.preparationTimeMinutes); // 슬롯은 분 단위 시작 시각 포인트 — 초 이하가 남아 있으면 슬롯 정합 실패 if ( @@ -209,6 +256,16 @@ export class StorePickupScheduleService { return withPreparationTime(store, preparation); } + private async findRescheduleStore( + storeId: bigint, + ): Promise { + const store = await this.repo.findStoreForPickupSchedule(storeId, false); + if (!store) { + throw new DomainException('STORE_NOT_FOUND'); + } + return withoutLeadTime(store); + } + /** withCapacity=false면 capacity·예약 수량을 읽지 않는다(주문 생성 재검증 — 수량 판정은 order 몫). */ private async loadScheduleContext( storeId: bigint, @@ -216,7 +273,7 @@ export class StorePickupScheduleService { toDateOnly: Date, rangeStartUtc: Date, rangeEndUtc: Date, - options: { withCapacity: boolean } = { withCapacity: true }, + options: { withCapacity: boolean; adjustment?: BookedAdjustment }, ): Promise { const [hours, closureDates, capacities, bookedByDate] = await Promise.all([ this.repo.findBusinessHoursForStore(storeId), @@ -236,11 +293,21 @@ export class StorePickupScheduleService { ? this.booked.sumByKstDate(storeId, rangeStartUtc, rangeEndUtc) : new Map(), ]); + const { adjustment } = options; + const adjusted = adjustment && bookedByDate.get(adjustment.date); + if (adjustment && adjusted !== undefined) { + bookedByDate.set( + adjustment.date, + Math.max(0, adjusted - adjustment.quantity), + ); + } return { hoursByWeekday: new Map(hours.map((h) => [h.day_of_week, h])), closureDates, capacities, bookedByDate, + // 옮길 주문은 수량 전체가 들어가야 한다 + required: Math.max(1, adjustment?.quantity ?? 1), }; } @@ -261,6 +328,7 @@ export class StorePickupScheduleService { isSpecialClosure: ctx.closureDates.has(dateKey), capacity: ctx.capacities.get(dateKey), booked: ctx.bookedByDate.get(dateKey) ?? 0, + required: ctx.required, now, dayStartUtc: kstMidnightUtc(year, month, day), }; @@ -280,6 +348,34 @@ function withPreparationTime( }; } +/** 판매자 픽업 변경은 리드타임·제작 시간을 보지 않는다 — 하한은 지금(과거 금지)이다. */ +function withoutLeadTime(store: StorePickupPolicyRow): StorePickupPolicyRow { + return { ...store, min_lead_time_minutes: 0 }; +} + +function parseScheduleYearMonth(yearMonth: string): { + year: number; + month: number; +} { + const ym = parseKstYearMonth(yearMonth); + if (!ym || ym.year < MIN_SCHEDULE_YEAR || ym.year > MAX_SCHEDULE_YEAR) { + throw new DomainException('INVALID_YEAR_MONTH'); + } + return ym; +} + +function parseScheduleDate(date: string): Date { + const parsed = parseKstDate(date); + if (!parsed) { + throw new DomainException('INVALID_DATE'); + } + const { year } = toKstYmd(parsed); + if (year < MIN_SCHEDULE_YEAR || year > MAX_SCHEDULE_YEAR) { + throw new DomainException('INVALID_DATE'); + } + return parsed; +} + function slotMinutes(slot: PickupSlot): number { const hours = Number(slot.time.slice(0, 2)); const minutes = Number(slot.time.slice(3, 5)); diff --git a/src/test/roles-coverage.spec.ts b/src/test/roles-coverage.spec.ts index cd0ea0dd..e2a45025 100644 --- a/src/test/roles-coverage.spec.ts +++ b/src/test/roles-coverage.spec.ts @@ -13,7 +13,7 @@ describe('접두 루트 필드 인가 커버리지', () => { const handlerAuth = collectHandlerAuth(collectFeatureResolverClasses()); describe.each([ - ['seller', 'SELLER', 60], + ['seller', 'SELLER', 63], ['admin', 'ADMIN', 75], ] as const)('%s 접두 → @Roles(%s)', (prefix, role, count) => { const fields = collectRootFieldsWithPrefix(prefix);