From 21cc29a8a39769d5797cd4519a51de271c7a703c Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Thu, 19 Nov 2026 05:56:35 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=ED=99=98=EB=B6=88=20=EA=B3=84=EC=A2=8C?= =?UTF-8?q?=20=EC=9E=85=EB=A0=A5=C2=B7=ED=99=98=EB=B6=88=20=EC=99=84?= =?UTF-8?q?=EB=A3=8C=EC=99=80=20=EC=9E=85=EA=B8=88=20=EB=B0=98=ED=99=98?= =?UTF-8?q?=C2=B7=EC=A2=85=EA=B2=B0=20=EA=B8=B0=EB=A1=9D,=20=ED=83=88?= =?UTF-8?q?=ED=87=B4=20=EC=B0=A8=EB=8B=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ① 무엇·왜 - 환불이 생기면 구매자가 돌려받을 계좌를 넣고(취소와 함께 넣을 수도 있다) 관리자가 송금한 뒤 완료로 기록한다. 계좌번호는 암호화해 두고 원문은 관리자 환불 상세에서만 푼다. - 결제로 확인하지 않은 입금은 주문의 반환 대상으로 연결해 입금액 전액 환불을 만든다. 주문 상태와 관계없이 그 주문의 구매자에게 돌려주며 주문·결제·정산은 건드리지 않는다. 주인 모를 입금은 메모와 함께 종결 기록하고, 나중에 주인을 찾으면 같은 기록을 반환으로 바꿔 같은 돈이 두 번 기록되지 않게 한다. - 진행 주문(입금 대기~제작 완료)이나 송금이 끝나지 않은 환불(종류 무관)이 있으면 구매자 탈퇴를 막는다. 탈퇴하면 환불 계좌를 받을 수 없다. - 명세에 없던 결정: 종결 기록을 반환으로 바꾸는 mutation 이름은 adminLinkUnidentifiedDeposit, 오류는 DEPOSIT_RECORD_NOT_FOUND(404)·DEPOSIT_RECORD_ALREADY_LINKED(409). 환불 목록은 처리 순서(오래된 것부터), 입금 기록 목록은 최근 기록부터. 입금 기록 금액 하한(1원)을 기존 DEPOSIT_AMOUNT_INVALID로 거절하도록 메시지를 두 경로에 맞게 바꿨다. ② 변경점 - SDL: submitMyRefundAccount, CancelMyOrderInput.refundAccount(RefundAccountInput), MyOrderDetail.refunds, adminRefunds·adminRefund·adminDepositRecords, adminCompleteRefund·adminCreateDepositReturn·adminRecordUnidentifiedDeposit·adminLinkUnidentifiedDeposit, DepositRecordKindType, AdminTaskCounts.refundsAwaitingAccount·refundsAwaitingTransfer, deleteMyAccount 설명 - RefundRepository: 계좌 입력·덮어쓰기(환불 행 잠금, 송금 완료면 거절) → 송금 대기 + outbox refund.account_submitted, 송금 완료(송금 대기만) + 감사 REFUND + outbox refund.completed, 관리자 목록·상세 - DepositRecordRepository: 반환 연결(주문 잠금 → 입금 기록 → 환불 → refund.requested), 종결 기록, 종결 → 반환 전환(주문 → 입금 기록 잠금), 감사 DEPOSIT_RECORD - OrderTransitionRepository.cancelLocked: 취소와 함께 받은 계좌로 환불을 바로 송금 대기로 만든다(환불이 없으면 버린다) - 이벤트: refund.requested에 accountSubmitted(없던 이벤트는 false), refund.account_submitted·refund.completed 신설(공통 payload) - 알림: 계좌가 이미 있는 refund.requested는 구매자 계좌 요청 대신 관리자 경보, refund.account_submitted도 관리자 경보(key refund-ready:{refundId}, info, /tasks/refunds 딥링크), refund.completed는 구매자 REFUND_COMPLETED 알림 - 탈퇴 차단: common 포트 WithdrawalBlockingOrderQuery(abstract class), order 구현 OrderWithdrawalBlockingRepository, auth는 첫 호출 때 ModuleRef(strict: false)로 찾고 ACCOUNT_HAS_ACTIVE_ORDERS(409, 건수)로 거절. guide §1(c)에 포트 추가 - 에러 7종(REFUND_NOT_FOUND·REFUND_NOT_READY·REFUND_ALREADY_COMPLETED·ACCOUNT_HAS_ACTIVE_ORDERS·DEPOSIT_NOTE_REQUIRED·DEPOSIT_RECORD_NOT_FOUND·DEPOSIT_RECORD_ALREADY_LINKED), 게이트: ADMIN_QUERY_COUNT 20, roles-coverage admin 74, enum-sdl-sync DepositRecordKind, module-wiring 탈퇴 차단 포트 resolve(api·ws·worker), 팩토리 createRefund ③ 테스트 - 관리자 환불: null 필터 = 전체·상태×종류 AND·키셋, 상세 원문 복호화·입금 기록, 송금 완료(처리자·메모·감사·구매자 알림), 계좌 입력 전·완료 뒤 거절과 무변경 - 입금 반환: 취소 환불과 공존·주문·결제·정산 불변, 주문 상태 6종 연결, 처리자 라벨 null 관리자, 입력 오류 6경우, 삭제된 주문 - 종결·전환: 메모 필수(빈 문자열·공백), 환불·이벤트 없음, 같은 기록 전환·감사 UPDATE, 이미 반환·없는 기록·없는 주문 - 구매자: 취소와 함께 계좌(송금 대기·암호문 복호화·accountSubmitted), 환불 없는 취소는 계좌를 버림, 계좌 형식 오류면 취소 안 함, 입력·덮어쓰기, 완료 뒤 거절, 남의·삭제된 주문 환불, 상세 refunds 순서 - 탈퇴: 상태 7종 표, 미완료 반환(계좌 입력 대기·송금 대기)·진행 주문 합산, 완료 뒤 허용·다른 구매자·삭제 주문 제외 - 소비자: 관리자 경보 key·문구·딥링크·계좌 없는 생성 미전송·억제 창, 구매자 완료 알림·계좌 있는 생성 미알림·재전달 멱등, 이벤트 파서 반증 - 반증: 탈퇴 차단 조건·OrderModule 포트 제공·계좌 있는 생성 건너뛰기를 지우면 해당 테스트 11건이 실패하는 것을 확인 --- docs/guide/architecture-conventions.md | 2 +- src/common/errors/error-catalog.spec.ts | 1 + src/common/errors/error-catalog.ts | 31 +- .../ports/withdrawal-blocking-order.port.ts | 9 + src/features/auth/auth-user-profile.graphql | 3 +- .../auth-user-profile.resolver.spec.ts | 6 + .../auth-user-profile.service.spec.ts | 96 ++- .../services/auth-user-profile.service.ts | 21 + .../constants/notification-messages.ts | 2 + .../notification-outbox.consumer.spec.ts | 62 ++ .../services/notification-outbox.consumer.ts | 33 +- .../notification-payloads.helper.spec.ts | 12 + .../services/notification-payloads.helper.ts | 14 + .../dto/inputs/admin-complete-refund.input.ts | 10 + .../admin-create-deposit-return.input.ts | 21 + .../inputs/admin-deposit-record-list.input.ts | 10 + .../admin-link-unidentified-deposit.input.ts | 9 + ...admin-record-unidentified-deposit.input.ts | 17 + .../dto/inputs/admin-refund-list.input.ts | 14 + .../order/dto/inputs/cancel-my-order.input.ts | 10 +- .../order/dto/inputs/refund-account.input.ts | 13 + .../inputs/submit-my-refund-account.input.ts | 8 + .../events/refund-account-submitted.event.ts | 23 + .../order/events/refund-completed.event.ts | 21 + .../events/refund-requested.event.spec.ts | 101 ++- .../order/events/refund-requested.event.ts | 53 +- src/features/order/index.ts | 7 +- .../order/order-deposit-admin.graphql | 8 + src/features/order/order-my.graphql | 57 +- src/features/order/order-refund-admin.graphql | 353 ++++++++++ src/features/order/order.module.ts | 20 +- .../repositories/deposit-record.repository.ts | 230 ++++++ .../order-transition.repository.ts | 10 + .../order-withdrawal-blocking.repository.ts | 32 + .../order/repositories/refund.repository.ts | 248 +++++++ .../order-deposit-admin.resolver.spec.ts | 4 + .../resolvers/order-my-mutation.resolver.ts | 9 + .../order/resolvers/order-my.resolver.spec.ts | 34 + .../order-refund-admin-mutation.resolver.ts | 68 ++ .../order-refund-admin-query.resolver.ts | 55 ++ .../order-refund-admin.resolver.spec.ts | 106 +++ .../order-admin-alert-messages.helper.ts | 27 + .../order-admin-alert.consumer.spec.ts | 83 +++ .../services/order-admin-alert.consumer.ts | 31 +- .../order-deposit-admin.service.spec.ts | 11 +- .../services/order-deposit-admin.service.ts | 20 +- .../order/services/order-my.service.spec.ts | 268 +++++++ .../order/services/order-my.service.ts | 56 +- .../order-refund-admin.service.spec.ts | 659 ++++++++++++++++++ .../services/order-refund-admin.service.ts | 230 ++++++ .../services/order-refund-mappers.helper.ts | 57 ++ .../order/types/order-my-output.type.ts | 2 + .../order/types/order-payment-output.type.ts | 2 + .../order/types/order-refund-output.type.ts | 38 + src/test/admin-query-null-inputs.spec.ts | 2 +- src/test/enum-sdl-sync.spec.ts | 7 + src/test/factories/order.factory.ts | 67 ++ src/test/module-wiring.spec.ts | 3 + src/test/roles-coverage.spec.ts | 2 +- 59 files changed, 3349 insertions(+), 59 deletions(-) create mode 100644 src/common/ports/withdrawal-blocking-order.port.ts create mode 100644 src/features/order/dto/inputs/admin-complete-refund.input.ts create mode 100644 src/features/order/dto/inputs/admin-create-deposit-return.input.ts create mode 100644 src/features/order/dto/inputs/admin-deposit-record-list.input.ts create mode 100644 src/features/order/dto/inputs/admin-link-unidentified-deposit.input.ts create mode 100644 src/features/order/dto/inputs/admin-record-unidentified-deposit.input.ts create mode 100644 src/features/order/dto/inputs/admin-refund-list.input.ts create mode 100644 src/features/order/dto/inputs/refund-account.input.ts create mode 100644 src/features/order/dto/inputs/submit-my-refund-account.input.ts create mode 100644 src/features/order/events/refund-account-submitted.event.ts create mode 100644 src/features/order/events/refund-completed.event.ts create mode 100644 src/features/order/order-refund-admin.graphql create mode 100644 src/features/order/repositories/deposit-record.repository.ts create mode 100644 src/features/order/repositories/order-withdrawal-blocking.repository.ts create mode 100644 src/features/order/repositories/refund.repository.ts create mode 100644 src/features/order/resolvers/order-refund-admin-mutation.resolver.ts create mode 100644 src/features/order/resolvers/order-refund-admin-query.resolver.ts create mode 100644 src/features/order/resolvers/order-refund-admin.resolver.spec.ts create mode 100644 src/features/order/services/order-refund-admin.service.spec.ts create mode 100644 src/features/order/services/order-refund-admin.service.ts create mode 100644 src/features/order/services/order-refund-mappers.helper.ts create mode 100644 src/features/order/types/order-refund-output.type.ts diff --git a/docs/guide/architecture-conventions.md b/docs/guide/architecture-conventions.md index 6e29036e..051cd3cc 100644 --- a/docs/guide/architecture-conventions.md +++ b/docs/guide/architecture-conventions.md @@ -12,7 +12,7 @@ - (a) 2번째 구현이 현실적으로 예상됨 - (b) 외부 부수효과 어댑터(OIDC 클라이언트, 경보 전송 함수, 시계, ID 생성기)라 테스트에서 stub이 필요 -- (c) 여러 feature가 광범위하게 주입하는 cross-cutting 포트 — `audit-log`(`AUDIT_LOG_REPOSITORY`), `store`의 `CatalogQuery`(conversation이 묻는 읽기 포트), `order`의 예약 수량 포트 +- (c) 여러 feature가 광범위하게 주입하는 cross-cutting 포트 — `audit-log`(`AUDIT_LOG_REPOSITORY`), `store`의 `CatalogQuery`(conversation이 묻는 읽기 포트), `order`의 예약 수량 포트, `order`의 탈퇴 차단 포트(`WithdrawalBlockingOrderQuery`, auth가 첫 호출 때 `ModuleRef`로 찾는 읽기 포트, `module-wiring.spec`이 역할별 resolve를 본다) **왜.** NestJS DI는 클래스 토큰도 `Test.overrideProvider(Class)`로 바꿀 수 있어 **테스트 용이성은 토큰 도입 근거가 아니다**. 전 repository에 1:1 인터페이스를 강제하면 lockstep 유지 비용만 늘고 얻는 게 없다(YAGNI, speculative generality). diff --git a/src/common/errors/error-catalog.spec.ts b/src/common/errors/error-catalog.spec.ts index cac760d7..a359aaf1 100644 --- a/src/common/errors/error-catalog.spec.ts +++ b/src/common/errors/error-catalog.spec.ts @@ -33,6 +33,7 @@ const RENDER_PARAMS: Partial< INVALID_LIMIT: { max: 50 }, FIELD_OUT_OF_RANGE: { field: 'capacity', min: 1, max: 100 }, REFUND_AMOUNT_OUT_OF_RANGE: { max: '30,000' }, + ACCOUNT_HAS_ACTIVE_ORDERS: { count: 2 }, CUSTOM_TEXT_DEFAULT_TOO_LONG: { label: '이름', max: 20 }, CUSTOM_3D_ITEM_LIMIT_EXCEEDED: { max: 10 }, CUSTOM_3D_DESIGN_INVALID: { field: 'top[0].size' }, diff --git a/src/common/errors/error-catalog.ts b/src/common/errors/error-catalog.ts index 1083f0d7..d9bc2c24 100644 --- a/src/common/errors/error-catalog.ts +++ b/src/common/errors/error-catalog.ts @@ -225,6 +225,11 @@ export const ERROR_CATALOG = { status: HttpStatus.BAD_REQUEST, message: '푸시 토큰 형식이 올바르지 않습니다.', }, + ACCOUNT_HAS_ACTIVE_ORDERS: { + status: HttpStatus.CONFLICT, + message: ({ count }) => + `진행 중인 주문 또는 환불 ${count}건이 있어 탈퇴할 수 없습니다.`, + }, // ── 카탈로그(매장·상품·지역) STORE_NOT_FOUND: { @@ -340,6 +345,18 @@ export const ERROR_CATALOG = { status: HttpStatus.BAD_REQUEST, message: ({ max }) => `환불 금액은 0원 이상 ${max}원 이하로 입력해 주세요.`, }, + REFUND_NOT_FOUND: { + status: HttpStatus.NOT_FOUND, + message: '환불을 찾을 수 없습니다.', + }, + REFUND_NOT_READY: { + status: HttpStatus.BAD_REQUEST, + message: '환불 계좌가 입력되지 않아 송금 완료로 처리할 수 없어요.', + }, + REFUND_ALREADY_COMPLETED: { + status: HttpStatus.CONFLICT, + message: '이미 송금이 끝난 환불입니다.', + }, DUPLICATE_OPTION_ITEM: { status: HttpStatus.BAD_REQUEST, message: '중복된 옵션 선택입니다.', @@ -437,13 +454,25 @@ export const ERROR_CATALOG = { }, DEPOSIT_AMOUNT_INVALID: { status: HttpStatus.BAD_REQUEST, - message: '입금액은 0원 이상의 정수로 입력해 주세요.', + message: '입금액이 올바르지 않아요. 원 단위 정수로 입력해 주세요.', }, DEPOSIT_AMOUNT_MISMATCH: { status: HttpStatus.BAD_REQUEST, message: '입금액이 결제 금액과 달라 입금 확인할 수 없어요. 반환 대상으로 연결해 주세요.', }, + DEPOSIT_NOTE_REQUIRED: { + status: HttpStatus.BAD_REQUEST, + message: '주인 모를 입금은 메모를 남겨야 기록할 수 있어요.', + }, + DEPOSIT_RECORD_NOT_FOUND: { + status: HttpStatus.NOT_FOUND, + message: '입금 기록을 찾을 수 없습니다.', + }, + DEPOSIT_RECORD_ALREADY_LINKED: { + status: HttpStatus.CONFLICT, + message: '이미 반환 대상으로 연결된 입금 기록입니다.', + }, // ── 판매자 SELLER_ONLY: { status: HttpStatus.FORBIDDEN, diff --git a/src/common/ports/withdrawal-blocking-order.port.ts b/src/common/ports/withdrawal-blocking-order.port.ts new file mode 100644 index 00000000..bc6fe496 --- /dev/null +++ b/src/common/ports/withdrawal-blocking-order.port.ts @@ -0,0 +1,9 @@ +/** + * auth(구매자 탈퇴)가 order에 묻는 "탈퇴를 막는 주문·환불 수" 읽기 포트. + * order → auth 의존(관리자 컨텍스트)이 이미 있어 auth가 OrderModule을 import하면 순환이라, 계약은 무의존 common에 두고 + * order가 구현을 제공한다. auth는 첫 호출 때 ModuleRef(strict: false)로 찾는다. + */ +export abstract class WithdrawalBlockingOrderQuery { + /** 진행 중 주문(입금 대기~제작 완료)과 송금이 끝나지 않은 환불(종류 무관) 수의 합. */ + abstract countByBuyer(accountId: bigint): Promise; +} diff --git a/src/features/auth/auth-user-profile.graphql b/src/features/auth/auth-user-profile.graphql index c1191fc7..6348206b 100644 --- a/src/features/auth/auth-user-profile.graphql +++ b/src/features/auth/auth-user-profile.graphql @@ -29,7 +29,8 @@ extend type Mutation { """ updateMyProfileImage(input: UpdateMyProfileImageInput!): MePayload! """ - 회원 탈퇴(soft delete). 로그인 필수. 본인 데이터만 대상이 된다. + 회원 탈퇴(soft delete). 진행 중인 주문(입금 대기~제작 완료)이나 송금이 끝나지 않은 환불(계좌 입력 대기·송금 대기)이 있으면 + ACCOUNT_HAS_ACTIVE_ORDERS(CONFLICT, 메시지에 건수). 로그인 필수. 본인 데이터만 대상이 된다. """ deleteMyAccount: Boolean! """ diff --git a/src/features/auth/resolvers/auth-user-profile.resolver.spec.ts b/src/features/auth/resolvers/auth-user-profile.resolver.spec.ts index 57cefdc5..621760a8 100644 --- a/src/features/auth/resolvers/auth-user-profile.resolver.spec.ts +++ b/src/features/auth/resolvers/auth-user-profile.resolver.spec.ts @@ -1,7 +1,9 @@ +import { WithdrawalBlockingOrderQuery } from '@/common/ports/withdrawal-blocking-order.port'; import { AccountUserRepository } from '@/features/auth/repositories/account-user.repository'; import { UserProfileMutationResolver } from '@/features/auth/resolvers/auth-user-profile-mutation.resolver'; import { UserProfileQueryResolver } from '@/features/auth/resolvers/auth-user-profile-query.resolver'; import { UserProfileService } from '@/features/auth/services/auth-user-profile.service'; +import { OrderWithdrawalBlockingRepository } from '@/features/order/repositories/order-withdrawal-blocking.repository'; import type { PrismaClient } from '@/generated/prisma/client'; import { S3Service } from '@/global/storage/s3.service'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; @@ -34,6 +36,10 @@ describe('User Profile Resolvers (real DB)', () => { NOOP_BLACKLIST_PROVIDER, AccountUserRepository, { provide: S3Service, useValue: s3Service }, + { + provide: WithdrawalBlockingOrderQuery, + useClass: OrderWithdrawalBlockingRepository, + }, ], }); diff --git a/src/features/auth/services/auth-user-profile.service.spec.ts b/src/features/auth/services/auth-user-profile.service.spec.ts index 6716be8b..9c4eed94 100644 --- a/src/features/auth/services/auth-user-profile.service.spec.ts +++ b/src/features/auth/services/auth-user-profile.service.spec.ts @@ -1,6 +1,8 @@ +import { WithdrawalBlockingOrderQuery } from '@/common/ports/withdrawal-blocking-order.port'; import { AccountUserRepository } from '@/features/auth/repositories/account-user.repository'; import { UserProfileService } from '@/features/auth/services/auth-user-profile.service'; -import type { PrismaClient } from '@/generated/prisma/client'; +import { OrderWithdrawalBlockingRepository } from '@/features/order/repositories/order-withdrawal-blocking.repository'; +import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; import { TokenBlacklistService } from '@/global/auth'; import { S3Service } from '@/global/storage/s3.service'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; @@ -8,6 +10,8 @@ import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { createAccount, createAccountIdentity, + createOrder, + createRefund, createUserProfile, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; @@ -35,6 +39,11 @@ describe('UserProfileService (real DB)', () => { { provide: TokenBlacklistService, useValue: blacklist }, AccountUserRepository, { provide: S3Service, useValue: s3Service }, + // 앱에서는 OrderModule이 제공하고 서비스가 ModuleRef로 찾는다 + { + provide: WithdrawalBlockingOrderQuery, + useClass: OrderWithdrawalBlockingRepository, + }, ], }); @@ -580,5 +589,90 @@ describe('UserProfileService (real DB)', () => { await expect(service.me(account.id)).rejects.toThrowDomain(401); }); + + async function buyer() { + const account = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { account_id: account.id }); + return account; + } + + async function expectBlocked(accountId: bigint, count: number) { + await expect(service.deleteMyAccount(accountId)).rejects.toThrowDomain( + 'ACCOUNT_HAS_ACTIVE_ORDERS', + ); + await expect(service.deleteMyAccount(accountId)).rejects.toThrow( + `진행 중인 주문 또는 환불 ${count}건이 있어 탈퇴할 수 없습니다.`, + ); + await expect( + prisma.account.findUniqueOrThrow({ where: { id: accountId } }), + ).resolves.toMatchObject({ deleted_at: null }); + expect(blacklist.blockStatus).not.toHaveBeenCalled(); + } + + it.each<[OrderStatus, boolean]>([ + ['PENDING_PAYMENT', true], + ['SUBMITTED', true], + ['CONFIRMED', true], + ['MADE', true], + ['PICKED_UP', false], + ['NO_SHOW', false], + ['CANCELED', false], + ])('%s 주문이 있으면 탈퇴 차단 = %s', async (status, blocked) => { + const account = await buyer(); + await createOrder(prisma, { account_id: account.id, status }); + + if (blocked) { + await expectBlocked(account.id, 1); + } else { + await expect(service.deleteMyAccount(account.id)).resolves.toBe(true); + } + }); + + it.each(['AWAITING_ACCOUNT', 'AWAITING_TRANSFER'] as const)( + '끝난 주문이라도 송금이 끝나지 않은 입금 반환(%s)이 있으면 막고, 진행 주문과 합쳐 센다', + async (status) => { + const account = await buyer(); + const canceled = await createOrder(prisma, { + account_id: account.id, + status: 'CANCELED', + }); + await createRefund(prisma, { + order_id: canceled.id, + kind: 'DEPOSIT_RETURN', + status, + }); + await expectBlocked(account.id, 1); + + await createOrder(prisma, { account_id: account.id, status: 'MADE' }); + await expectBlocked(account.id, 2); + }, + ); + + it('환불 송금이 끝나면 탈퇴할 수 있고, 다른 구매자·삭제된 주문의 건은 세지 않는다', async () => { + const account = await buyer(); + const canceled = await createOrder(prisma, { + account_id: account.id, + status: 'CANCELED', + }); + const refund = await createRefund(prisma, { + order_id: canceled.id, + status: 'AWAITING_TRANSFER', + }); + await createRefund(prisma); + await createOrder(prisma, { status: 'SUBMITTED' }); + await createOrder(prisma, { + account_id: account.id, + status: 'SUBMITTED', + deleted_at: new Date(), + }); + await expectBlocked(account.id, 1); + + await prisma.refund.update({ + where: { id: refund.id }, + data: { status: 'COMPLETED', completed_at: new Date() }, + }); + + await expect(service.deleteMyAccount(account.id)).resolves.toBe(true); + }); }); }); diff --git a/src/features/auth/services/auth-user-profile.service.ts b/src/features/auth/services/auth-user-profile.service.ts index a585f02f..b62e1b62 100644 --- a/src/features/auth/services/auth-user-profile.service.ts +++ b/src/features/auth/services/auth-user-profile.service.ts @@ -1,6 +1,8 @@ import { Injectable } from '@nestjs/common'; +import { ModuleRef } from '@nestjs/core'; import { DomainException } from '@/common/errors/error-catalog'; +import { WithdrawalBlockingOrderQuery } from '@/common/ports/withdrawal-blocking-order.port'; import { MAX_NICKNAME_LENGTH, MIN_NICKNAME_LENGTH, @@ -20,10 +22,13 @@ import type { CreateUploadUrlOutput } from '@/global/storage/types/storage.types @Injectable() export class UserProfileService extends UserBaseService { + private blockingOrders: WithdrawalBlockingOrderQuery | undefined; + constructor( accounts: AccountUserRepository, private readonly s3Service: S3Service, private readonly blacklist: TokenBlacklistService, + private readonly moduleRef: ModuleRef, ) { super(accounts); } @@ -190,8 +195,15 @@ export class UserProfileService extends UserBaseService { }); } + /** 진행 중 주문이나 송금이 끝나지 않은 환불이 있으면 거절한다 — 탈퇴하면 환불 계좌를 받을 수 없다. */ async deleteMyAccount(accountId: bigint): Promise { await this.requireActiveUser(accountId); + const blocking = await this.withdrawalBlocking().countByBuyer(accountId); + if (blocking > 0) { + throw new DomainException('ACCOUNT_HAS_ACTIVE_ORDERS', { + count: blocking, + }); + } const now = new Date(); const deletedNickname = `deleted_${accountId.toString()}`; @@ -206,4 +218,13 @@ export class UserProfileService extends UserBaseService { return true; } + + /** OrderModule이 auth를 import해 반대 방향 import는 순환이다 — 첫 호출 때 컨테이너 전체에서 찾는다. */ + private withdrawalBlocking(): WithdrawalBlockingOrderQuery { + this.blockingOrders ??= this.moduleRef.get( + WithdrawalBlockingOrderQuery, + { strict: false }, + ); + return this.blockingOrders; + } } diff --git a/src/features/notification/constants/notification-messages.ts b/src/features/notification/constants/notification-messages.ts index 92ff1513..6283a0b1 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 = { export const REFUND_ACCOUNT_REQUESTED_TITLE = '환불계좌입력'; +export const REFUND_COMPLETED_TITLE = '환불완료'; + export const REVIEW_LIKED_NOTIFICATION = { title: '리뷰 좋아요', body: '다른 사람이 내가 남긴 리뷰를 좋아했어요.', diff --git a/src/features/notification/services/notification-outbox.consumer.spec.ts b/src/features/notification/services/notification-outbox.consumer.spec.ts index 55c1a316..ebba1f9d 100644 --- a/src/features/notification/services/notification-outbox.consumer.spec.ts +++ b/src/features/notification/services/notification-outbox.consumer.spec.ts @@ -239,6 +239,68 @@ describe('NotificationOutboxConsumer (real DB)', () => { consumer.handle(event('refund.requested', { refundId: 5 })), ).rejects.toThrow('payload 형식 오류'); }); + + async function refundPayload(orderNumber: string) { + 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 }); + return { + buyer, + order, + item, + payload: { + refundId: '6', + orderId: order.id.toString(), + orderNumber, + buyerAccountId: buyer.id.toString(), + kind: 'DEPOSIT_RETURN', + amount: 30_000, + storeId: item.store_id.toString(), + storeName: '케이크샵', + productId: item.product_id.toString(), + productName: '레터링 케이크', + }, + }; + } + + it('취소와 함께 계좌가 들어온 refund.requested는 계좌 요청 알림을 만들지 않는다', async () => { + const { payload } = await refundPayload('ORD-5'); + + await consumer.handle( + event('refund.requested', { ...payload, accountSubmitted: true }), + ); + + expect(await prisma.notification.count()).toBe(0); + }); + + it('refund.completed는 구매자에게 환불 완료 알림을 만들고, 재전달은 중복을 만들지 않는다', async () => { + const { buyer, order, item, payload } = await refundPayload('ORD-6'); + const completed = event('refund.completed', payload); + + await consumer.handle(completed); + await consumer.handle(completed); + + const rows = await prisma.notification.findMany(); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ + account_id: buyer.id, + type: 'ORDER_STATUS', + event: 'REFUND_COMPLETED', + title: '환불완료', + body: 'ORD-6 30,000원 환불이 완료되었어요.', + order_id: order.id, + store_id: item.store_id, + product_id: item.product_id, + order_number: 'ORD-6', + created_at: OCCURRED_AT, + }); + }); + + it('반증: 형식이 어긋난 refund.completed는 던진다', async () => { + await expect( + consumer.handle(event('refund.completed', { refundId: 6 })), + ).rejects.toThrow('refund.completed payload 형식 오류'); + }); }); it('review.liked는 작성자에게 좋아요 알림을 만든다', async () => { diff --git a/src/features/notification/services/notification-outbox.consumer.ts b/src/features/notification/services/notification-outbox.consumer.ts index fdf8cfc2..853208c4 100644 --- a/src/features/notification/services/notification-outbox.consumer.ts +++ b/src/features/notification/services/notification-outbox.consumer.ts @@ -15,13 +15,18 @@ import { import { buildOrderStatusNotification, buildRefundAccountRequestedNotification, + buildRefundCompletedNotification, buildReviewLikedNotification, + type NotificationPayload, } from '@/features/notification/services/notification-payloads.helper'; import { ORDER_STATUS_CHANGED, parseOrderStatusChangedPayload, + parseRefundCompletedPayload, parseRefundRequestedPayload, + REFUND_COMPLETED, REFUND_REQUESTED, + type RefundEventPayload, } from '@/features/order'; import { type OutboxConsumer, @@ -38,6 +43,7 @@ import { parseReviewLikedPayload, REVIEW_LIKED } from '@/features/review'; @SubscribeOutbox( ORDER_STATUS_CHANGED, REFUND_REQUESTED, + REFUND_COMPLETED, REVIEW_LIKED, NOTIFICATION_BROADCAST_REQUESTED, ) @@ -56,6 +62,8 @@ export class NotificationOutboxConsumer implements OutboxConsumer { return this.onOrderStatusChanged(event); case REFUND_REQUESTED: return this.onRefundRequested(event); + case REFUND_COMPLETED: + return this.onRefundCompleted(event); case REVIEW_LIKED: return this.onReviewLiked(event); case NOTIFICATION_BROADCAST_REQUESTED: @@ -87,10 +95,33 @@ export class NotificationOutboxConsumer implements OutboxConsumer { private async onRefundRequested(event: OutboxEvent): Promise { const p = parseRefundRequestedPayload(event.payload); + // 취소와 함께 계좌를 넣었으면 요청할 게 없다(관리자 송금 알림만 간다) + if (p.accountSubmitted) return; + await this.saveRefundNotification( + event, + p, + buildRefundAccountRequestedNotification(p.orderNumber, p.amount), + ); + } + + private async onRefundCompleted(event: OutboxEvent): Promise { + const p = parseRefundCompletedPayload(event.payload); + await this.saveRefundNotification( + event, + p, + buildRefundCompletedNotification(p.orderNumber, p.amount), + ); + } + + private async saveRefundNotification( + event: OutboxEvent, + p: RefundEventPayload, + payload: NotificationPayload, + ): Promise { await this.repo.createFromEvent(event.eventId, [ { account_id: parseId(p.buyerAccountId), - ...buildRefundAccountRequestedNotification(p.orderNumber, p.amount), + ...payload, order_id: parseId(p.orderId), store_id: p.storeId === null ? null : parseId(p.storeId), product_id: p.productId === null ? null : parseId(p.productId), diff --git a/src/features/notification/services/notification-payloads.helper.spec.ts b/src/features/notification/services/notification-payloads.helper.spec.ts index c419316c..016f006e 100644 --- a/src/features/notification/services/notification-payloads.helper.spec.ts +++ b/src/features/notification/services/notification-payloads.helper.spec.ts @@ -1,6 +1,7 @@ import { buildOrderStatusNotification, buildRefundAccountRequestedNotification, + buildRefundCompletedNotification, buildReviewLikedNotification, } from '@/features/notification/services/notification-payloads.helper'; import { ORDER_CANCEL_REASON_LABELS } from '@/features/order'; @@ -124,6 +125,17 @@ describe('notification-payloads.helper', () => { }); }); + describe('buildRefundCompletedNotification', () => { + it('주문번호와 천 단위 금액으로 환불 완료를 알린다', () => { + expect(buildRefundCompletedNotification('ORD-3', 1_234_567)).toEqual({ + type: NotificationType.ORDER_STATUS, + event: NotificationEvent.REFUND_COMPLETED, + title: '환불완료', + body: 'ORD-3 1,234,567원 환불이 완료되었어요.', + }); + }); + }); + describe('buildReviewLikedNotification', () => { it('리뷰 좋아요 알림 payload를 만든다', () => { expect(buildReviewLikedNotification()).toEqual({ diff --git a/src/features/notification/services/notification-payloads.helper.ts b/src/features/notification/services/notification-payloads.helper.ts index 6d398953..f5819a8c 100644 --- a/src/features/notification/services/notification-payloads.helper.ts +++ b/src/features/notification/services/notification-payloads.helper.ts @@ -4,6 +4,7 @@ import { 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 { @@ -97,6 +98,19 @@ export function buildRefundAccountRequestedNotification( }; } +/** 환불 송금이 끝났다. */ +export function buildRefundCompletedNotification( + orderNumber: string, + amount: number, +): NotificationPayload { + return { + type: NotificationType.ORDER_STATUS, + event: NotificationEvent.REFUND_COMPLETED, + title: REFUND_COMPLETED_TITLE, + body: `${orderNumber} ${amount.toLocaleString('ko-KR')}원 환불이 완료되었어요.`, + }; +} + /** 복원 좋아요는 호출부에서 알림 생략. */ export function buildReviewLikedNotification(): NotificationPayload { return { diff --git a/src/features/order/dto/inputs/admin-complete-refund.input.ts b/src/features/order/dto/inputs/admin-complete-refund.input.ts new file mode 100644 index 00000000..fc5a42d4 --- /dev/null +++ b/src/features/order/dto/inputs/admin-complete-refund.input.ts @@ -0,0 +1,10 @@ +import { IsOptional, IsString } from 'class-validator'; + +export class AdminCompleteRefundInput { + @IsString() + refundId!: string; + + @IsOptional() + @IsString() + note?: string | null; +} diff --git a/src/features/order/dto/inputs/admin-create-deposit-return.input.ts b/src/features/order/dto/inputs/admin-create-deposit-return.input.ts new file mode 100644 index 00000000..a43ed2c6 --- /dev/null +++ b/src/features/order/dto/inputs/admin-create-deposit-return.input.ts @@ -0,0 +1,21 @@ +import { IsDate, IsInt, IsOptional, IsString } from 'class-validator'; + +// 금액 하한·입금자명 길이는 서비스가 도메인 오류 코드로 거절한다 +export class AdminCreateDepositReturnInput { + @IsString() + orderId!: string; + + @IsInt() + amount!: number; + + @IsString() + depositorName!: string; + + @IsOptional() + @IsDate() + depositedAt?: Date | null; + + @IsOptional() + @IsString() + note?: string | null; +} diff --git a/src/features/order/dto/inputs/admin-deposit-record-list.input.ts b/src/features/order/dto/inputs/admin-deposit-record-list.input.ts new file mode 100644 index 00000000..5fdccf45 --- /dev/null +++ b/src/features/order/dto/inputs/admin-deposit-record-list.input.ts @@ -0,0 +1,10 @@ +import { IsEnum, IsOptional } from 'class-validator'; + +import { CursorInput } from '@/common/dto/inputs/cursor.input'; +import { DepositRecordKind } from '@/generated/prisma/client'; + +export class AdminDepositRecordListInput extends CursorInput { + @IsOptional() + @IsEnum(DepositRecordKind) + kind?: DepositRecordKind | null; +} diff --git a/src/features/order/dto/inputs/admin-link-unidentified-deposit.input.ts b/src/features/order/dto/inputs/admin-link-unidentified-deposit.input.ts new file mode 100644 index 00000000..bc6afcdd --- /dev/null +++ b/src/features/order/dto/inputs/admin-link-unidentified-deposit.input.ts @@ -0,0 +1,9 @@ +import { IsString } from 'class-validator'; + +export class AdminLinkUnidentifiedDepositInput { + @IsString() + depositRecordId!: string; + + @IsString() + orderId!: string; +} diff --git a/src/features/order/dto/inputs/admin-record-unidentified-deposit.input.ts b/src/features/order/dto/inputs/admin-record-unidentified-deposit.input.ts new file mode 100644 index 00000000..2799bfa6 --- /dev/null +++ b/src/features/order/dto/inputs/admin-record-unidentified-deposit.input.ts @@ -0,0 +1,17 @@ +import { IsDate, IsInt, IsOptional, IsString } from 'class-validator'; + +// 메모가 비면 서비스가 DEPOSIT_NOTE_REQUIRED로 거절한다 +export class AdminRecordUnidentifiedDepositInput { + @IsInt() + amount!: number; + + @IsString() + depositorName!: string; + + @IsOptional() + @IsDate() + depositedAt?: Date | null; + + @IsString() + note!: string; +} diff --git a/src/features/order/dto/inputs/admin-refund-list.input.ts b/src/features/order/dto/inputs/admin-refund-list.input.ts new file mode 100644 index 00000000..ad998d29 --- /dev/null +++ b/src/features/order/dto/inputs/admin-refund-list.input.ts @@ -0,0 +1,14 @@ +import { IsEnum, IsOptional } from 'class-validator'; + +import { CursorInput } from '@/common/dto/inputs/cursor.input'; +import { RefundKind, RefundStatus } from '@/generated/prisma/client'; + +export class AdminRefundListInput extends CursorInput { + @IsOptional() + @IsEnum(RefundStatus) + status?: RefundStatus | null; + + @IsOptional() + @IsEnum(RefundKind) + kind?: RefundKind | null; +} diff --git a/src/features/order/dto/inputs/cancel-my-order.input.ts b/src/features/order/dto/inputs/cancel-my-order.input.ts index 636866db..e17150dc 100644 --- a/src/features/order/dto/inputs/cancel-my-order.input.ts +++ b/src/features/order/dto/inputs/cancel-my-order.input.ts @@ -1,4 +1,7 @@ -import { IsOptional, IsString } from 'class-validator'; +import { Type } from 'class-transformer'; +import { IsOptional, IsString, ValidateNested } from 'class-validator'; + +import { RefundAccountInput } from '@/features/order/dto/inputs/refund-account.input'; export class CancelMyOrderInput { @IsString() @@ -7,4 +10,9 @@ export class CancelMyOrderInput { @IsOptional() @IsString() note?: string | null; + + @IsOptional() + @ValidateNested() + @Type(() => RefundAccountInput) + refundAccount?: RefundAccountInput | null; } diff --git a/src/features/order/dto/inputs/refund-account.input.ts b/src/features/order/dto/inputs/refund-account.input.ts new file mode 100644 index 00000000..cbd25e57 --- /dev/null +++ b/src/features/order/dto/inputs/refund-account.input.ts @@ -0,0 +1,13 @@ +import { IsString } from 'class-validator'; + +// 은행·계좌번호·예금주 형식은 서비스가 도메인 오류 코드로 거절한다 +export class RefundAccountInput { + @IsString() + bankCode!: string; + + @IsString() + accountHolder!: string; + + @IsString() + accountNumber!: string; +} diff --git a/src/features/order/dto/inputs/submit-my-refund-account.input.ts b/src/features/order/dto/inputs/submit-my-refund-account.input.ts new file mode 100644 index 00000000..13ae9b39 --- /dev/null +++ b/src/features/order/dto/inputs/submit-my-refund-account.input.ts @@ -0,0 +1,8 @@ +import { IsString } from 'class-validator'; + +import { RefundAccountInput } from '@/features/order/dto/inputs/refund-account.input'; + +export class SubmitMyRefundAccountInput extends RefundAccountInput { + @IsString() + refundId!: string; +} diff --git a/src/features/order/events/refund-account-submitted.event.ts b/src/features/order/events/refund-account-submitted.event.ts new file mode 100644 index 00000000..9de57e20 --- /dev/null +++ b/src/features/order/events/refund-account-submitted.event.ts @@ -0,0 +1,23 @@ +import { + parseRefundEventPayload, + type RefundEventArgs, + refundEventInput, + type RefundEventPayload, +} from '@/features/order/events/refund-requested.event'; +import type { OutboxEventInput } from '@/features/outbox'; +import type { Prisma } from '@/generated/prisma/client'; + +/** 구매자 환불 계좌 입력(덮어쓰기 포함). 관리자 송금 대기 알림의 원천이다. */ +export const REFUND_ACCOUNT_SUBMITTED = 'refund.account_submitted'; + +export function refundAccountSubmittedEvent( + args: RefundEventArgs, +): OutboxEventInput { + return refundEventInput(REFUND_ACCOUNT_SUBMITTED, args); +} + +export function parseRefundAccountSubmittedPayload( + value: Prisma.JsonValue, +): RefundEventPayload { + return parseRefundEventPayload(REFUND_ACCOUNT_SUBMITTED, value); +} diff --git a/src/features/order/events/refund-completed.event.ts b/src/features/order/events/refund-completed.event.ts new file mode 100644 index 00000000..41d405c4 --- /dev/null +++ b/src/features/order/events/refund-completed.event.ts @@ -0,0 +1,21 @@ +import { + parseRefundEventPayload, + type RefundEventArgs, + refundEventInput, + type RefundEventPayload, +} from '@/features/order/events/refund-requested.event'; +import type { OutboxEventInput } from '@/features/outbox'; +import type { Prisma } from '@/generated/prisma/client'; + +/** 관리자 환불 송금 완료. 구매자 환불 완료 알림의 원천이다. */ +export const REFUND_COMPLETED = 'refund.completed'; + +export function refundCompletedEvent(args: RefundEventArgs): OutboxEventInput { + return refundEventInput(REFUND_COMPLETED, args); +} + +export function parseRefundCompletedPayload( + value: Prisma.JsonValue, +): RefundEventPayload { + return parseRefundEventPayload(REFUND_COMPLETED, value); +} diff --git a/src/features/order/events/refund-requested.event.spec.ts b/src/features/order/events/refund-requested.event.spec.ts index 7e7e99d3..33ab0ae3 100644 --- a/src/features/order/events/refund-requested.event.spec.ts +++ b/src/features/order/events/refund-requested.event.spec.ts @@ -1,3 +1,13 @@ +import { + parseRefundAccountSubmittedPayload, + REFUND_ACCOUNT_SUBMITTED, + refundAccountSubmittedEvent, +} from '@/features/order/events/refund-account-submitted.event'; +import { + parseRefundCompletedPayload, + REFUND_COMPLETED, + refundCompletedEvent, +} from '@/features/order/events/refund-completed.event'; import { parseRefundRequestedPayload, REFUND_REQUESTED, @@ -17,36 +27,44 @@ const VALID = { productId: '5', productName: '레터링 케이크', }; +const occurredAt = new Date('2026-09-16T07:30:00.000Z'); +const ARGS = { + refundId: 11n, + orderId: 7n, + orderNumber: 'ORD-1', + buyerAccountId: 3n, + kind: 'CANCEL' as const, + amount: 30_000, + storeId: 2n, + storeName: '케이크샵', + productId: 5n, + productName: '레터링 케이크', + occurredAt, + actorAccountId: 9n, +}; describe('refund.requested 이벤트', () => { - it('주문과 같은 aggregate(파티션)에 묶고 파서가 그대로 읽는다', () => { - const occurredAt = new Date('2026-09-16T07:30:00.000Z'); - const event = refundRequestedEvent({ - refundId: 11n, - orderId: 7n, - orderNumber: 'ORD-1', - buyerAccountId: 3n, - kind: 'CANCEL', - amount: 30_000, - storeId: 2n, - storeName: '케이크샵', - productId: 5n, - productName: '레터링 케이크', - occurredAt, - actorAccountId: 9n, - }); + it.each([true, false])( + '주문과 같은 aggregate(파티션)에 묶고 파서가 그대로 읽는다(계좌 입력 %s)', + (accountSubmitted) => { + const event = refundRequestedEvent({ ...ARGS, accountSubmitted }); - expect(event).toEqual({ - aggregateType: 'order', - aggregateId: '7', - eventType: REFUND_REQUESTED, - payload: VALID, - occurredAt, - actorAccountId: 9n, - }); - expect( - parseRefundRequestedPayload(event.payload as Prisma.JsonValue), - ).toEqual(VALID); + expect(event).toEqual({ + aggregateType: 'order', + aggregateId: '7', + eventType: REFUND_REQUESTED, + payload: { ...VALID, accountSubmitted }, + occurredAt, + actorAccountId: 9n, + }); + expect( + parseRefundRequestedPayload(event.payload as Prisma.JsonValue), + ).toEqual({ ...VALID, accountSubmitted }); + }, + ); + + it('계좌 입력 여부가 없던 이벤트는 false로 읽는다', () => { + expect(parseRefundRequestedPayload(VALID).accountSubmitted).toBe(false); }); it('매장·상품 스냅샷이 없으면 null로 읽는다', () => { @@ -76,6 +94,33 @@ describe('refund.requested 이벤트', () => { ])('반증: %s payload는 던진다', (_label, payload) => { expect(() => parseRefundRequestedPayload(payload as Prisma.JsonValue), - ).toThrow('payload 형식 오류'); + ).toThrow('refund.requested payload 형식 오류'); + }); +}); + +describe.each([ + [ + REFUND_ACCOUNT_SUBMITTED, + refundAccountSubmittedEvent, + parseRefundAccountSubmittedPayload, + ], + [REFUND_COMPLETED, refundCompletedEvent, parseRefundCompletedPayload], +] as const)('%s 이벤트', (eventType, build, parse) => { + it('같은 공통 payload로 주문 파티션에 싣고 파서가 그대로 읽는다', () => { + const event = build(ARGS); + + expect(event).toMatchObject({ + aggregateType: 'order', + aggregateId: '7', + eventType, + payload: VALID, + }); + expect(parse(event.payload as Prisma.JsonValue)).toEqual(VALID); + }); + + it('반증: 형식이 틀리면 이벤트 이름과 함께 던진다', () => { + expect(() => parse({ ...VALID, amount: '1' })).toThrow( + `${eventType} payload 형식 오류`, + ); }); }); diff --git a/src/features/order/events/refund-requested.event.ts b/src/features/order/events/refund-requested.event.ts index b7485e2d..8ecf30fe 100644 --- a/src/features/order/events/refund-requested.event.ts +++ b/src/features/order/events/refund-requested.event.ts @@ -1,10 +1,14 @@ import type { OutboxEventInput } from '@/features/outbox'; import { RefundKind, type Prisma } from '@/generated/prisma/client'; -/** 환불 생성(취소 환불·입금 반환). 구매자에게 돌려받을 계좌 입력을 요청하는 알림의 원천이다. */ +/** + * 환불 생성(취소 환불·입금 반환). 계좌가 없으면 구매자 계좌 요청 알림, 취소와 함께 계좌가 들어왔으면 + * 관리자 송금 대기 알림의 원천이다. + */ export const REFUND_REQUESTED = 'refund.requested'; -export interface RefundRequestedPayload { +/** 환불 이벤트(생성·계좌 입력·송금 완료) 공통 payload. 알림 행이 매장·상품 스냅샷을 그대로 싣는다. */ +export interface RefundEventPayload { refundId: string; orderId: string; orderNumber: string; @@ -17,7 +21,7 @@ export interface RefundRequestedPayload { productName: string | null; } -export function refundRequestedEvent(args: { +export interface RefundEventArgs { refundId: bigint; orderId: bigint; orderNumber: string; @@ -30,8 +34,19 @@ export function refundRequestedEvent(args: { productName: string | null; occurredAt: Date; actorAccountId: bigint | null; -}): OutboxEventInput { - const payload: RefundRequestedPayload = { +} + +export interface RefundRequestedPayload extends RefundEventPayload { + /** 생성과 함께 계좌가 들어왔는지. 이 필드가 없던 이벤트는 false다. */ + accountSubmitted: boolean; +} + +export function refundEventInput( + eventType: string, + args: RefundEventArgs, + extra: Record = {}, +): OutboxEventInput { + const payload: RefundEventPayload = { refundId: args.refundId.toString(), orderId: args.orderId.toString(), orderNumber: args.orderNumber, @@ -47,8 +62,8 @@ export function refundRequestedEvent(args: { // 같은 주문의 상태 전이와 같은 파티션 순서를 탄다 aggregateType: 'order', aggregateId: payload.orderId, - eventType: REFUND_REQUESTED, - payload: { ...payload }, + eventType, + payload: { ...payload, ...extra }, occurredAt: args.occurredAt, actorAccountId: args.actorAccountId, }; @@ -58,10 +73,11 @@ const REFUND_KINDS = new Set(Object.values(RefundKind)); const nullableString = (v: unknown): string | null => typeof v === 'string' ? v : null; -export function parseRefundRequestedPayload( +export function parseRefundEventPayload( + eventType: string, value: Prisma.JsonValue, -): RefundRequestedPayload { - const p = value as Partial>; +): RefundEventPayload { + const p = value as Partial>; if ( typeof value !== 'object' || value === null || @@ -74,7 +90,7 @@ export function parseRefundRequestedPayload( !REFUND_KINDS.has(p.kind) || !Number.isSafeInteger(p.amount) ) { - throw new Error(`${REFUND_REQUESTED} payload 형식 오류`); + throw new Error(`${eventType} payload 형식 오류`); } return { refundId: p.refundId, @@ -89,3 +105,18 @@ export function parseRefundRequestedPayload( productName: nullableString(p.productName), }; } + +export function refundRequestedEvent( + args: RefundEventArgs & { accountSubmitted: boolean }, +): OutboxEventInput { + const { accountSubmitted, ...rest } = args; + return refundEventInput(REFUND_REQUESTED, rest, { accountSubmitted }); +} + +export function parseRefundRequestedPayload( + value: Prisma.JsonValue, +): RefundRequestedPayload { + const base = parseRefundEventPayload(REFUND_REQUESTED, value); + const { accountSubmitted } = value as { accountSubmitted?: unknown }; + return { ...base, accountSubmitted: accountSubmitted === true }; +} diff --git a/src/features/order/index.ts b/src/features/order/index.ts index 185781a3..51dd02d5 100644 --- a/src/features/order/index.ts +++ b/src/features/order/index.ts @@ -18,9 +18,14 @@ export { ORDER_CANCEL_REASON_LABELS } from '@/features/order/constants/order-can // 환불 생성 이벤트 계약(outbox). 구매자 환불 계좌 요청 알림(notification)이 읽는다. export { REFUND_REQUESTED, - type RefundRequestedPayload, + type RefundEventPayload, parseRefundRequestedPayload, } from '@/features/order/events/refund-requested.event'; +// 환불 송금 완료 이벤트 계약(outbox). 구매자 환불 완료 알림(notification)이 읽는다. +export { + REFUND_COMPLETED, + parseRefundCompletedPayload, +} from '@/features/order/events/refund-completed.event'; // 주문 접수 이벤트 계약(outbox). 판매자 푸시 소비자(notification)가 읽는다. export { ORDER_SUBMITTED, diff --git a/src/features/order/order-deposit-admin.graphql b/src/features/order/order-deposit-admin.graphql index 2470a68f..fed915d9 100644 --- a/src/features/order/order-deposit-admin.graphql +++ b/src/features/order/order-deposit-admin.graphql @@ -132,6 +132,14 @@ type AdminTaskCounts { 입금 확인을 기다리는 전체 주문 수(adminPendingPayments의 totalCount, '입금했어요' 포함). """ pendingPayments: Int! + """ + 구매자의 환불 계좌 입력을 기다리는 환불 수(adminRefunds status=AWAITING_ACCOUNT의 totalCount). + """ + refundsAwaitingAccount: Int! + """ + 계좌가 들어와 송금을 기다리는 환불 수(adminRefunds status=AWAITING_TRANSFER의 totalCount). + """ + refundsAwaitingTransfer: Int! } """ diff --git a/src/features/order/order-my.graphql b/src/features/order/order-my.graphql index 4d744a28..c640bb7b 100644 --- a/src/features/order/order-my.graphql +++ b/src/features/order/order-my.graphql @@ -19,10 +19,19 @@ extend type Mutation { """ 내 주문을 취소한다. 판매자 확정 전(입금 대기·접수)까지만 되고 사유는 구매자 요청으로 기록된다. 입금 대기는 환불 없이, 접수는 결제액 전액 환불로 취소되고 환불이 생기면 환불 계좌 입력 요청 알림이 간다. + refundAccount를 함께 보내면 환불이 바로 송금 대기가 되고 계좌 요청 알림은 가지 않는다(환불이 없으면 계좌는 버린다). '입금했어요'를 누른 주문도 취소할 수 있다. 그 밖의 상태면 ORDER_NOT_CANCELLABLE(BAD_USER_INPUT). - 로그인 필수. 본인 주문이 아니면 NOT_FOUND. + 계좌 형식 오류는 submitMyRefundAccount와 같은 코드다. 로그인 필수. 본인 주문이 아니면 NOT_FOUND. """ cancelMyOrder(input: CancelMyOrderInput!): MyOrderDetail! + """ + 돌려받을 환불 계좌를 입력한다(MyOrderDetail.refunds의 id). 송금 완료 전이면 다시 보내 덮어쓸 수 있고, 입력하면 송금 대기가 된다. + 계좌번호는 암호화해 저장하고 응답에는 끝 4자리만 나간다. 은행 코드가 paymentBanks에 없으면 INVALID_BANK_CODE, + 계좌번호가 하이픈을 뺀 숫자 8~20자리가 아니면 INVALID_ACCOUNT_NUMBER, 예금주가 비었거나 50자를 넘으면 + TEXT_REQUIRED·TEXT_TOO_LONG(모두 BAD_USER_INPUT), 송금이 끝났으면 REFUND_ALREADY_COMPLETED(CONFLICT). + 로그인 필수. 본인 환불이 아니면 REFUND_NOT_FOUND(NOT_FOUND). + """ + submitMyRefundAccount(input: SubmitMyRefundAccountInput!): MyOrderDetail! } """ @@ -34,6 +43,47 @@ input CancelMyOrderInput { 취소 메모. 선택, 최대 500자. 상태 이력에 남고 판매자도 본다. """ note: String + """ + 환불받을 계좌. 선택. 접수 주문처럼 환불이 생기는 취소에서 계좌 입력을 한 번에 끝낸다. + """ + refundAccount: RefundAccountInput +} + +""" +환불받을 계좌. +""" +input RefundAccountInput { + """ + 은행 코드(paymentBanks의 code). + """ + bankCode: String! + """ + 예금주(1~50자). + """ + accountHolder: String! + """ + 계좌번호. 하이픈을 빼고 숫자 8~20자리여야 하며 숫자만 저장한다. + """ + accountNumber: String! +} + +""" +환불 계좌 입력. +""" +input SubmitMyRefundAccountInput { + refundId: ID! + """ + 은행 코드(paymentBanks의 code). + """ + bankCode: String! + """ + 예금주(1~50자). + """ + accountHolder: String! + """ + 계좌번호. 하이픈을 빼고 숫자 8~20자리여야 하며 숫자만 저장한다. + """ + accountNumber: String! } """ @@ -212,6 +262,11 @@ type MyOrderDetail { 지금 cancelMyOrder로 취소할 수 있는지. 입금 대기·접수 상태일 때 true. """ canCancel: Boolean! + """ + 이 주문에서 돌려받을 돈(취소 환불·입금 반환). 오래된 순, 없으면 빈 배열. + status가 AWAITING_ACCOUNT면 submitMyRefundAccount로 계좌를 입력받는다. + """ + refunds: [OrderRefund!]! """ 상태 변경 이력. 오래된 순이다(판매자 주문 상세는 최신순 — 방향이 반대다). diff --git a/src/features/order/order-refund-admin.graphql b/src/features/order/order-refund-admin.graphql new file mode 100644 index 00000000..622f3823 --- /dev/null +++ b/src/features/order/order-refund-admin.graphql @@ -0,0 +1,353 @@ +extend type Query { + """ + 환불(취소 환불·입금 반환) 목록. 처리 순서대로 오래된 환불부터 온다. 계좌번호는 끝 4자리만 나간다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminRefunds(input: AdminRefundListInput): AdminRefundConnection! + """ + 환불 상세. 송금에 쓸 계좌번호 원문과 입금 반환이면 그 입금 기록이 함께 온다. 없으면 REFUND_NOT_FOUND(NOT_FOUND). + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminRefund(refundId: ID!): AdminRefundDetail! + """ + 결제로 확인하지 않은 입금 기록(반환·종결) 목록. 최근 기록부터 온다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminDepositRecords( + input: AdminDepositRecordListInput + ): AdminDepositRecordConnection! +} + +extend type Mutation { + """ + 환불 송금을 마쳤다고 기록한다. 계좌가 들어온(송금 대기) 환불만 되고, 계좌 입력 전이면 REFUND_NOT_READY(BAD_USER_INPUT), + 이미 끝났으면 REFUND_ALREADY_COMPLETED(CONFLICT), 없으면 REFUND_NOT_FOUND(NOT_FOUND). 메모가 500자를 넘으면 TEXT_TOO_LONG. + 구매자에게 REFUND_COMPLETED 알림이 가고 감사 로그(REFUND)를 남긴다. 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminCompleteRefund(input: AdminCompleteRefundInput!): AdminRefund! + """ + 은행 앱에서 본 입금을 주문의 반환 대상으로 연결한다. 입금 기록(RETURN)과 입금액 전액의 환불(계좌 입력 대기)이 생기고 + 구매자에게 환불 계좌 입력 요청 알림이 간다. 주문 상태·결제·정산은 바꾸지 않으며 주문 상태와 관계없이 연결할 수 있다 + (미입금 취소 뒤 늦은 입금, 취소 뒤 입금, 금액이 틀린 입금, 이중 입금). 입금액이 1 미만이면 DEPOSIT_AMOUNT_INVALID, + 입금자명이 비었거나 50자를 넘으면 TEXT_REQUIRED·TEXT_TOO_LONG, 메모가 500자를 넘으면 TEXT_TOO_LONG(모두 BAD_USER_INPUT), + 없는 주문이면 ORDER_NOT_FOUND(NOT_FOUND). 감사 로그(DEPOSIT_RECORD)를 남긴다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminCreateDepositReturn( + input: AdminCreateDepositReturnInput! + ): AdminDepositRecord! + """ + 주인을 알 수 없는 입금을 메모와 함께 종결 기록(UNIDENTIFIED)으로 남긴다. 메모가 비면 DEPOSIT_NOTE_REQUIRED, + 입금액·입금자명·메모 길이 오류는 adminCreateDepositReturn과 같다(모두 BAD_USER_INPUT). 감사 로그(DEPOSIT_RECORD)를 남긴다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminRecordUnidentifiedDeposit( + input: AdminRecordUnidentifiedDepositInput! + ): AdminDepositRecord! + """ + 종결 기록한 입금의 주인을 찾았을 때 그 기록을 주문의 반환 대상으로 바꾼다. 같은 입금을 새로 기록하지 않고 기록 종류가 + RETURN으로 바뀌며, 입금액 전액의 환불이 생겨 구매자에게 계좌 입력 요청 알림이 간다(주문 상태·결제·정산은 그대로). + 이미 반환으로 연결된 기록이면 DEPOSIT_RECORD_ALREADY_LINKED(CONFLICT), 없는 기록이면 DEPOSIT_RECORD_NOT_FOUND, + 없는 주문이면 ORDER_NOT_FOUND(모두 NOT_FOUND). 감사 로그(DEPOSIT_RECORD)를 남긴다. + 관리자 로그인 필수. ADMIN 계정이 아니면 FORBIDDEN. + """ + adminLinkUnidentifiedDeposit( + input: AdminLinkUnidentifiedDepositInput! + ): AdminDepositRecord! +} + +""" +입금 기록 종류. 값은 늘어날 수 있으니 모르는 값을 받아도 화면이 죽지 않게 처리한다. +""" +enum DepositRecordKindType { + """주문에 연결해 돌려주는 입금. 같은 금액의 입금 반환 환불이 함께 있다.""" + RETURN + """주인을 알 수 없어 메모로 종결한 입금.""" + UNIDENTIFIED +} + +""" +환불 목록 조회 조건. 모든 필터는 AND로 결합된다. +""" +input AdminRefundListInput { + """ + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 + """ + 이전 응답의 nextCursor. 첫 페이지는 생략한다. + """ + cursor: String + """ + 진행 상태 필터. null이면 전체. + """ + status: RefundStatusType + """ + 종류 필터. null이면 전체. + """ + kind: RefundKindType +} + +""" +환불(관리자 시점). 계좌번호는 끝 4자리만 담는다. +""" +type AdminRefund { + id: ID! + """ + 환불 종류. + """ + kind: RefundKindType! + """ + 돌려줄 금액(원). + """ + amount: Int! + """ + 진행 상태. + """ + status: RefundStatusType! + """ + 환불받을 은행. 계좌 입력 전이면 null. + """ + bank: Bank + """ + 환불 계좌 예금주. 계좌 입력 전이면 null. + """ + accountHolder: String + """ + 환불 계좌번호 끝 4자리만 보이는 값(예: ****1234). 계좌 입력 전이면 null. + """ + accountNumberMasked: String + """ + 환불이 생긴 시각. + """ + requestedAt: DateTime! + """ + 구매자가 계좌를 입력한 시각(덮어쓰면 마지막 입력). 입력 전이면 null. + """ + accountSubmittedAt: DateTime + """ + 송금 완료 시각. 완료 전이면 null. + """ + completedAt: DateTime + orderId: ID! + """ + 주문번호. + """ + orderNumber: String! + """ + 주문자 이름. 계좌 입력을 기다릴 때 연락에 쓴다. + """ + buyerName: String! + """ + 주문자 연락처. + """ + buyerPhone: String! + """ + 매장명(주문 시점 스냅샷). 품목이 없으면 null. + """ + storeName: String + """ + 상품명(주문 시점 스냅샷). 품목이 없으면 null. + """ + productName: String + """ + 송금 완료를 기록한 관리자 표시 이름(처리 시점 스냅샷). 완료 전이거나 이름이 없으면 null. + """ + completedByLabel: String + """ + 송금 완료 메모. 없으면 null. + """ + completeNote: String +} + +""" +환불 상세. 계좌번호 원문이 들어 있으니 화면 밖(로그·분석 이벤트)에 남기지 않는다. +""" +type AdminRefundDetail { + """ + 환불. + """ + refund: AdminRefund! + """ + 환불 계좌번호 원문(숫자만). 송금에 쓴다. 계좌 입력 전이면 null. + """ + accountNumber: String + """ + 입금 반환이면 그 입금 기록, 취소 환불이면 null. + """ + depositRecord: AdminDepositRecord +} + +""" +환불 목록 페이지. +""" +type AdminRefundConnection { + """ + 환불. 오래된 것부터 온다. + """ + items: [AdminRefund!]! + """ + 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. + """ + nextCursor: String +} + +""" +입금 기록 목록 조회 조건. +""" +input AdminDepositRecordListInput { + """ + 한 번에 가져올 개수. 기본 20, 1~100만 허용하며 벗어나면 BAD_USER_INPUT. + """ + limit: Int = 20 + """ + 이전 응답의 nextCursor. 첫 페이지는 생략한다. + """ + cursor: String + """ + 종류 필터. null이면 전체. + """ + kind: DepositRecordKindType +} + +""" +결제로 확인하지 않은 입금 기록 1건. +""" +type AdminDepositRecord { + id: ID! + """ + 기록 종류. + """ + kind: DepositRecordKindType! + """ + 연결한 주문 ID. 반환(RETURN)만 있고 종결이면 null. + """ + orderId: ID + """ + 연결한 주문번호. 반환(RETURN)만 있고 종결이면 null. + """ + orderNumber: String + """ + 입금액(원). + """ + amount: Int! + """ + 은행 앱에 보인 입금자명. + """ + depositorName: String! + """ + 은행 앱에 보인 입금 일시. 입력하지 않았으면 null. + """ + depositedAt: DateTime + """ + 처리 메모. 없으면 null(종결 기록은 항상 있다). + """ + note: String + """ + 기록한 관리자 표시 이름(기록 시점 스냅샷). 이름이 없으면 null. + """ + recordedByLabel: String + """ + 반환으로 생긴 환불 ID(adminRefund로 연다). 종결이면 null. + """ + refundId: ID + """ + 반환으로 생긴 환불의 진행 상태. 종결이면 null. + """ + refundStatus: RefundStatusType + createdAt: DateTime! +} + +""" +입금 기록 목록 페이지. +""" +type AdminDepositRecordConnection { + """ + 입금 기록. 최근 것부터 온다. + """ + items: [AdminDepositRecord!]! + """ + 조건에 맞는 전체 건수(현재 페이지와 무관). 커서 필터는 제외하고 센다. + """ + totalCount: Int! + """ + 다음 페이지 존재 여부. + """ + hasMore: Boolean! + """ + 다음 페이지 커서. null이면 마지막 페이지다. + """ + nextCursor: String +} + +""" +환불 송금 완료 입력. +""" +input AdminCompleteRefundInput { + refundId: ID! + """ + 처리 메모(선택, 500자 이하). 환불 기록에 남는다. + """ + note: String +} + +""" +입금 반환 연결 입력. +""" +input AdminCreateDepositReturnInput { + orderId: ID! + """ + 은행 앱에서 본 입금액(원, 1 이상). 이 금액 전액을 돌려준다. + """ + amount: Int! + """ + 은행 앱에 보인 입금자명(1~50자). + """ + depositorName: String! + """ + 은행 앱에 보인 입금 일시(선택). + """ + depositedAt: DateTime + """ + 처리 메모(선택, 500자 이하). + """ + note: String +} + +""" +주인 모를 입금 종결 기록 입력. +""" +input AdminRecordUnidentifiedDepositInput { + """ + 은행 앱에서 본 입금액(원, 1 이상). + """ + amount: Int! + """ + 은행 앱에 보인 입금자명(1~50자). + """ + depositorName: String! + """ + 은행 앱에 보인 입금 일시(선택). + """ + depositedAt: DateTime + """ + 종결 사유 메모(필수, 500자 이하). + """ + note: String! +} + +""" +종결 기록을 반환 대상으로 바꾸는 입력. +""" +input AdminLinkUnidentifiedDepositInput { + depositRecordId: ID! + orderId: ID! +} diff --git a/src/features/order/order.module.ts b/src/features/order/order.module.ts index a2e61da7..ba7d5265 100644 --- a/src/features/order/order.module.ts +++ b/src/features/order/order.module.ts @@ -1,18 +1,22 @@ import { Module } from '@nestjs/common'; import { BOOKED_QUANTITY_QUERY } from '@/common/ports/booked-quantity.port'; +import { WithdrawalBlockingOrderQuery } from '@/common/ports/withdrawal-blocking-order.port'; import { AuditLogModule } from '@/features/audit-log'; import { AuthModule } from '@/features/auth'; import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; import { OrderStatusTransitionPolicy } from '@/features/order/policies/order-status-transition.policy'; +import { DepositRecordRepository } from '@/features/order/repositories/deposit-record.repository'; import { OrderBookedRepository } from '@/features/order/repositories/order-booked.repository'; import { OrderCustomUploadRepository } from '@/features/order/repositories/order-custom-upload.repository'; import { OrderInquiryRepository } from '@/features/order/repositories/order-inquiry.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'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentSettingRepository } from '@/features/order/repositories/payment-setting.repository'; import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { RefundRepository } from '@/features/order/repositories/refund.repository'; import { StoreSettlementAccountRepository } from '@/features/order/repositories/store-settlement-account.repository'; import { AdminOrderMutationResolver } from '@/features/order/resolvers/order-admin-mutation.resolver'; import { AdminOrderQueryResolver } from '@/features/order/resolvers/order-admin-query.resolver'; @@ -24,6 +28,8 @@ import { UserOrderQueryResolver } from '@/features/order/resolvers/order-my-quer import { AdminPaymentMutationResolver } from '@/features/order/resolvers/order-payment-admin-mutation.resolver'; import { AdminPaymentQueryResolver } from '@/features/order/resolvers/order-payment-admin-query.resolver'; import { PaymentQueryResolver } from '@/features/order/resolvers/order-payment-query.resolver'; +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 { SellerOrderQueryResolver } from '@/features/order/resolvers/order-seller-query.resolver'; import { SellerSettlementMutationResolver } from '@/features/order/resolvers/order-settlement-seller-mutation.resolver'; @@ -38,6 +44,7 @@ import { AdminDepositService } from '@/features/order/services/order-deposit-adm import { OrderEventsService } from '@/features/order/services/order-events.service'; 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 { 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'; @@ -95,7 +102,18 @@ import { StoreModule } from '@/features/store'; AdminDepositService, AdminDepositQueryResolver, AdminDepositMutationResolver, - // 입금 대기·'입금했어요' 관리자 디스코드 알림(worker 소비자) + // 환불 계좌 입력·송금 완료, 입금 반환·종결 기록 + RefundRepository, + DepositRecordRepository, + AdminRefundService, + AdminRefundQueryResolver, + AdminRefundMutationResolver, + // auth(구매자 탈퇴)가 ModuleRef로 찾는 탈퇴 차단 포트 구현 + { + provide: WithdrawalBlockingOrderQuery, + useClass: OrderWithdrawalBlockingRepository, + }, + // 입금 대기·'입금했어요'·환불 송금 대기 관리자 디스코드 알림(worker 소비자) OrderAdminAlertConsumer, // 결제 설정·매장 정산 계좌(계좌번호는 global AccountCipher로 암호화) PaymentSettingRepository, diff --git a/src/features/order/repositories/deposit-record.repository.ts b/src/features/order/repositories/deposit-record.repository.ts new file mode 100644 index 00000000..ae144c48 --- /dev/null +++ b/src/features/order/repositories/deposit-record.repository.ts @@ -0,0 +1,230 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import type { TimestampIdCursor } from '@/common/utils/keyset-cursor'; +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { refundRequestedEvent } from '@/features/order/events/refund-requested.event'; +import { + adminDepositRecordInclude, + type AdminDepositRecordRow, + loadRefundEventArgs, +} from '@/features/order/repositories/refund.repository'; +import { OutboxPublisher } from '@/features/outbox'; +import { + AuditActionType, + AuditTargetType, + type DepositRecord, + DepositRecordKind, + type Prisma, + RefundKind, +} from '@/generated/prisma/client'; +import { PrismaService } from '@/prisma'; + +export interface DepositRecordInput { + amount: number; + depositorName: string; + depositedAt: Date | null; + note: string | null; + actorAccountId: bigint; + actorLabel: string | null; + now: Date; +} + +export type LinkDepositRecordResult = + | AdminDepositRecordRow + | 'order-not-found' + | 'record-not-found' + | 'already-linked'; + +function recordSnapshot(row: DepositRecord) { + return { + kind: row.kind, + orderId: row.order_id?.toString() ?? null, + amount: row.amount, + depositorName: row.depositor_name, + depositedAt: row.deposited_at?.toISOString() ?? null, + note: row.note, + }; +} + +/** + * 결제로 확인하지 않은 입금 기록. 돌려줄 입금(RETURN)은 주문에 연결하고 입금액 전액 환불을 만든다 — 주문 상태·결제·정산은 + * 건드리지 않는다. 주인 모를 입금(UNIDENTIFIED)은 메모로 종결하고, 나중에 주인을 찾으면 같은 기록을 반환으로 바꾼다. + */ +@Injectable() +export class DepositRecordRepository { + constructor( + private readonly prisma: PrismaService, + private readonly outbox: OutboxPublisher, + @Inject(AUDIT_LOG_REPOSITORY) + private readonly auditLogs: IAuditLogRepository, + ) {} + + /** 최근 기록부터. */ + async listDepositRecords(args: { + kind?: DepositRecordKind; + limit: number; + cursor?: TimestampIdCursor; + }): Promise { + const after: Prisma.DepositRecordWhereInput = args.cursor + ? { + OR: [ + { created_at: { lt: args.cursor.timestamp } }, + { created_at: args.cursor.timestamp, id: { lt: args.cursor.id } }, + ], + } + : {}; + return this.prisma.depositRecord.findMany({ + where: { ...(args.kind ? { kind: args.kind } : {}), ...after }, + include: adminDepositRecordInclude, + orderBy: [{ created_at: 'desc' }, { id: 'desc' }], + take: args.limit + 1, + }); + } + + async countDepositRecords(kind?: DepositRecordKind): Promise { + return this.prisma.depositRecord.count({ + where: kind ? { kind } : {}, + }); + } + + /** 없는 주문이면 null. */ + async createReturn( + args: DepositRecordInput & { orderId: bigint }, + ): Promise { + return this.prisma.$transaction(async (tx) => { + if (!(await this.lockOrder(tx, args.orderId))) return null; + const record = await tx.depositRecord.create({ + data: { + ...this.recordData(args), + kind: DepositRecordKind.RETURN, + order_id: args.orderId, + }, + }); + await this.requestReturnRefund(tx, record, args); + await this.audit(tx, args.actorAccountId, record, null); + return this.findAdminRow(tx, record.id); + }); + } + + async recordUnidentified( + args: DepositRecordInput, + ): Promise { + return this.prisma.$transaction(async (tx) => { + const record = await tx.depositRecord.create({ + data: { + ...this.recordData(args), + kind: DepositRecordKind.UNIDENTIFIED, + }, + }); + await this.audit(tx, args.actorAccountId, record, null); + return this.findAdminRow(tx, record.id); + }); + } + + /** 종결한 입금의 주인을 찾았을 때: 같은 기록을 반환으로 바꿔 주문에 잇는다(같은 돈을 두 번 기록하지 않는다). */ + async linkToOrder(args: { + depositRecordId: bigint; + orderId: bigint; + actorAccountId: bigint; + now: Date; + }): Promise { + return this.prisma.$transaction(async (tx) => { + // 잠금 순서 order → deposit_record + if (!(await this.lockOrder(tx, args.orderId))) return 'order-not-found'; + const [locked] = await tx.$queryRaw<{ id: bigint }[]>` + SELECT id FROM deposit_record WHERE id = ${args.depositRecordId} FOR UPDATE`; + if (!locked) return 'record-not-found'; + const before = await tx.depositRecord.findUniqueOrThrow({ + where: { id: locked.id }, + }); + if (before.kind !== DepositRecordKind.UNIDENTIFIED) { + return 'already-linked'; + } + const record = await tx.depositRecord.update({ + where: { id: before.id }, + data: { kind: DepositRecordKind.RETURN, order_id: args.orderId }, + }); + await this.requestReturnRefund(tx, record, args); + await this.audit(tx, args.actorAccountId, record, before); + return this.findAdminRow(tx, record.id); + }); + } + + private async lockOrder( + tx: Prisma.TransactionClient, + orderId: bigint, + ): Promise { + const [row] = await tx.$queryRaw<{ id: bigint }[]>` + SELECT id FROM \`order\` WHERE id = ${orderId} AND deleted_at IS NULL FOR UPDATE`; + return Boolean(row); + } + + private recordData(args: DepositRecordInput) { + return { + amount: args.amount, + depositor_name: args.depositorName, + deposited_at: args.depositedAt, + note: args.note, + recorded_by_account_id: args.actorAccountId, + recorded_by_label_snapshot: args.actorLabel, + }; + } + + /** 입금액 전액을 계좌 입력 대기 환불로 만들고 구매자 계좌 요청 이벤트를 남긴다. */ + private async requestReturnRefund( + tx: Prisma.TransactionClient, + record: DepositRecord, + args: { actorAccountId: bigint; now: Date }, + ): Promise { + const refund = await tx.refund.create({ + data: { + order_id: record.order_id!, + kind: RefundKind.DEPOSIT_RETURN, + deposit_record_id: record.id, + amount: record.amount, + requested_at: args.now, + }, + }); + await this.outbox.publish( + tx, + refundRequestedEvent({ + ...(await loadRefundEventArgs( + tx, + refund, + args.now, + args.actorAccountId, + )), + accountSubmitted: false, + }), + ); + } + + private async audit( + tx: Prisma.TransactionClient, + actorAccountId: bigint, + after: DepositRecord, + before: DepositRecord | null, + ): Promise { + await this.auditLogs.recordAudit(tx, { + actorAccountId, + targetType: AuditTargetType.DEPOSIT_RECORD, + targetId: after.id, + action: before ? AuditActionType.UPDATE : AuditActionType.CREATE, + beforeJson: before ? recordSnapshot(before) : null, + afterJson: recordSnapshot(after), + }); + } + + private findAdminRow( + tx: Prisma.TransactionClient, + id: bigint, + ): Promise { + return tx.depositRecord.findUniqueOrThrow({ + where: { id }, + include: adminDepositRecordInclude, + }); + } +} diff --git a/src/features/order/repositories/order-transition.repository.ts b/src/features/order/repositories/order-transition.repository.ts index 38305604..357793b2 100644 --- a/src/features/order/repositories/order-transition.repository.ts +++ b/src/features/order/repositories/order-transition.repository.ts @@ -21,6 +21,10 @@ import { adminOrderInclude, type AdminOrderRow, } from '@/features/order/repositories/order.repository'; +import { + refundAccountColumns, + type RefundAccountData, +} from '@/features/order/repositories/refund.repository'; import { OutboxPublisher } from '@/features/outbox'; import { AuditActionType, @@ -69,6 +73,8 @@ export interface CancelOrderArgs { actorAccountId: bigint | null; scope: OrderCancelScope; note: string | null; + /** 취소와 함께 받은 환불 계좌. 환불이 생기면 바로 송금 대기로 만들고, 환불이 없으면 버린다. */ + refundAccount?: RefundAccountData | null; now: Date; /** 잠금 시점 재료로 사유·사정·환불액을 정한다. 던지면 tx가 롤백되고 예외가 그대로 나간다. */ decide: (state: OrderCancelState) => OrderCancelDecision; @@ -317,6 +323,9 @@ export class OrderTransitionRepository { cancel_order_id: locked.id, amount: decision.refundAmount, requested_at: args.now, + ...(args.refundAccount + ? refundAccountColumns(args.refundAccount, args.now) + : {}), }, }) : null; @@ -362,6 +371,7 @@ export class OrderTransitionRepository { refundId: refund.id, kind: refund.kind, amount: refund.amount, + accountSubmitted: refund.account_submitted_at !== null, }), ); } diff --git a/src/features/order/repositories/order-withdrawal-blocking.repository.ts b/src/features/order/repositories/order-withdrawal-blocking.repository.ts new file mode 100644 index 00000000..967f3cf9 --- /dev/null +++ b/src/features/order/repositories/order-withdrawal-blocking.repository.ts @@ -0,0 +1,32 @@ +import { Injectable } from '@nestjs/common'; + +import { WithdrawalBlockingOrderQuery } from '@/common/ports/withdrawal-blocking-order.port'; +import { IN_PROGRESS_ORDER_STATUSES } from '@/features/order/constants/order-status-traits'; +import { RefundStatus } from '@/generated/prisma/client'; +import { activeWhere, PrismaService } from '@/prisma'; + +/** 탈퇴 차단 포트 구현. 돌려줄 돈이 남은 구매자가 탈퇴하면 환불 계좌를 받을 수 없어 막는다. */ +@Injectable() +export class OrderWithdrawalBlockingRepository extends WithdrawalBlockingOrderQuery { + constructor(private readonly prisma: PrismaService) { + super(); + } + + async countByBuyer(accountId: bigint): Promise { + const [orders, refunds] = await Promise.all([ + this.prisma.order.count({ + where: { + account_id: accountId, + status: { in: [...IN_PROGRESS_ORDER_STATUSES] }, + }, + }), + this.prisma.refund.count({ + where: { + status: { not: RefundStatus.COMPLETED }, + order: { account_id: accountId, ...activeWhere }, + }, + }), + ]); + return orders + refunds; + } +} diff --git a/src/features/order/repositories/refund.repository.ts b/src/features/order/repositories/refund.repository.ts new file mode 100644 index 00000000..866b3c87 --- /dev/null +++ b/src/features/order/repositories/refund.repository.ts @@ -0,0 +1,248 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { refundAccountSubmittedEvent } from '@/features/order/events/refund-account-submitted.event'; +import { refundCompletedEvent } from '@/features/order/events/refund-completed.event'; +import type { RefundEventArgs } from '@/features/order/events/refund-requested.event'; +import { OutboxPublisher } from '@/features/outbox'; +import { + AuditActionType, + AuditTargetType, + type Prisma, + type Refund, + type RefundKind, + RefundStatus, +} from '@/generated/prisma/client'; +import { activeWhere, PrismaService } from '@/prisma'; + +export const adminDepositRecordInclude = { + order: { select: { order_number: true } }, + refund: { select: { id: true, status: true } }, +} satisfies Prisma.DepositRecordInclude; + +export type AdminDepositRecordRow = Prisma.DepositRecordGetPayload<{ + include: typeof adminDepositRecordInclude; +}>; + +/** 관리자 목록·상세: 주문 식별·연락처, 첫 품목 스냅샷, 입금 반환이면 입금 기록. */ +const adminRefundInclude = { + order: { + select: { + order_number: true, + buyer_name: true, + buyer_phone: true, + items: { + where: activeWhere, + select: { store_name_snapshot: true, product_name_snapshot: true }, + orderBy: { id: 'asc' }, + take: 1, + }, + }, + }, + deposit_record: { include: adminDepositRecordInclude }, +} satisfies Prisma.RefundInclude; + +export type AdminRefundRow = Prisma.RefundGetPayload<{ + include: typeof adminRefundInclude; +}>; + +export interface RefundFilter { + status?: RefundStatus; + kind?: RefundKind; +} + +/** 서비스가 정규화·암호화한 환불 계좌. 원문 계좌번호는 repository로 내려오지 않는다. */ +export interface RefundAccountData { + bankCode: string; + accountHolder: string; + accountNumberEnc: string; + accountNumberLast4: string; +} + +/** 계좌가 들어오면 송금 대기다. 덮어쓰기도 같은 값으로 바꾼다. */ +export function refundAccountColumns(account: RefundAccountData, now: Date) { + return { + status: RefundStatus.AWAITING_TRANSFER, + bank_code: account.bankCode, + account_holder: account.accountHolder, + account_number_enc: account.accountNumberEnc, + account_number_last4: account.accountNumberLast4, + account_submitted_at: now, + } satisfies Prisma.RefundUncheckedUpdateInput; +} + +/** 환불 이벤트 스냅샷: 주문번호·구매자와 첫 품목의 매장·상품. */ +export async function loadRefundEventArgs( + tx: Prisma.TransactionClient, + refund: Pick, + now: Date, + actorAccountId: bigint | null, +): Promise { + const order = await tx.order.findUniqueOrThrow({ + where: { id: refund.order_id }, + select: { + order_number: true, + account_id: true, + items: { + where: activeWhere, + orderBy: { id: 'asc' }, + take: 1, + select: { + store_id: true, + store_name_snapshot: true, + product_id: true, + product_name_snapshot: true, + }, + }, + }, + }); + const [item] = order.items; + return { + refundId: refund.id, + orderId: refund.order_id, + orderNumber: order.order_number, + buyerAccountId: order.account_id, + kind: refund.kind, + amount: refund.amount, + storeId: item?.store_id ?? null, + storeName: item?.store_name_snapshot ?? null, + productId: item?.product_id ?? null, + productName: item?.product_name_snapshot ?? null, + occurredAt: now, + actorAccountId, + }; +} + +export type SubmitRefundAccountResult = + { orderId: bigint } | 'not-found' | 'completed'; + +export type CompleteRefundResult = + AdminRefundRow | 'not-found' | 'completed' | 'not-ready'; + +/** 환불(취소 환불·입금 반환)의 계좌 입력·송금 완료와 관리자 조회. 잠금은 환불 행 하나만 잡는다. */ +@Injectable() +export class RefundRepository { + constructor( + private readonly prisma: PrismaService, + private readonly outbox: OutboxPublisher, + @Inject(AUDIT_LOG_REPOSITORY) + private readonly auditLogs: IAuditLogRepository, + ) {} + + private filterWhere(filter: RefundFilter): Prisma.RefundWhereInput { + return { + ...(filter.status ? { status: filter.status } : {}), + ...(filter.kind ? { kind: filter.kind } : {}), + }; + } + + /** 처리 순서대로(오래된 환불부터). */ + async listRefunds( + filter: RefundFilter & { limit: number; cursor?: bigint }, + ): Promise { + return this.prisma.refund.findMany({ + where: { + ...this.filterWhere(filter), + ...(filter.cursor !== undefined ? { id: { gt: filter.cursor } } : {}), + }, + include: adminRefundInclude, + orderBy: { id: 'asc' }, + take: filter.limit + 1, + }); + } + + async countRefunds(filter: RefundFilter): Promise { + return this.prisma.refund.count({ where: this.filterWhere(filter) }); + } + + async findAdminRefund(refundId: bigint): Promise { + return this.prisma.refund.findUnique({ + where: { id: refundId }, + include: adminRefundInclude, + }); + } + + /** 구매자 본인 환불의 계좌를 넣거나 바꾼다(송금 완료 전까지). */ + async submitAccount(args: { + refundId: bigint; + accountId: bigint; + account: RefundAccountData; + now: Date; + }): Promise { + return this.prisma.$transaction(async (tx) => { + const [locked] = await tx.$queryRaw[]>` + SELECT r.id, r.status FROM refund r + JOIN \`order\` o ON o.id = r.order_id + WHERE r.id = ${args.refundId} AND o.account_id = ${args.accountId} AND o.deleted_at IS NULL + FOR UPDATE OF r`; + if (!locked) return 'not-found'; + if (locked.status === RefundStatus.COMPLETED) return 'completed'; + + const updated = await tx.refund.update({ + where: { id: locked.id }, + data: refundAccountColumns(args.account, args.now), + }); + await this.outbox.publish( + tx, + refundAccountSubmittedEvent( + await loadRefundEventArgs(tx, updated, args.now, args.accountId), + ), + ); + return { orderId: updated.order_id }; + }); + } + + /** 송금 완료. 계좌가 들어온(송금 대기) 환불만 된다. */ + async complete(args: { + refundId: bigint; + actorAccountId: bigint; + actorLabel: string | null; + note: string | null; + now: Date; + }): Promise { + return this.prisma.$transaction(async (tx) => { + const [locked] = await tx.$queryRaw[]>` + SELECT id, status FROM refund WHERE id = ${args.refundId} FOR UPDATE`; + if (!locked) return 'not-found'; + if (locked.status === RefundStatus.COMPLETED) return 'completed'; + if (locked.status === RefundStatus.AWAITING_ACCOUNT) return 'not-ready'; + + const updated = await tx.refund.update({ + where: { id: locked.id }, + data: { + status: RefundStatus.COMPLETED, + completed_at: args.now, + completed_by_account_id: args.actorAccountId, + completed_by_label_snapshot: args.actorLabel, + complete_note: args.note, + }, + include: adminRefundInclude, + }); + await this.outbox.publish( + tx, + refundCompletedEvent( + await loadRefundEventArgs(tx, updated, args.now, args.actorAccountId), + ), + ); + await this.auditLogs.recordAudit(tx, { + actorAccountId: args.actorAccountId, + targetType: AuditTargetType.REFUND, + targetId: updated.id, + action: AuditActionType.STATUS_CHANGE, + beforeJson: { status: locked.status }, + afterJson: { + status: RefundStatus.COMPLETED, + orderId: updated.order_id.toString(), + kind: updated.kind, + amount: updated.amount, + accountNumberLast4: updated.account_number_last4, + note: args.note, + }, + }); + return updated; + }); + } +} diff --git a/src/features/order/resolvers/order-deposit-admin.resolver.spec.ts b/src/features/order/resolvers/order-deposit-admin.resolver.spec.ts index ec3866b0..fccc3110 100644 --- a/src/features/order/resolvers/order-deposit-admin.resolver.spec.ts +++ b/src/features/order/resolvers/order-deposit-admin.resolver.spec.ts @@ -7,6 +7,7 @@ import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log. import { AccountAdminRepository } from '@/features/auth/repositories/account-admin.repository'; import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { RefundRepository } from '@/features/order/repositories/refund.repository'; import { AdminDepositMutationResolver } from '@/features/order/resolvers/order-deposit-admin-mutation.resolver'; import { AdminDepositQueryResolver } from '@/features/order/resolvers/order-deposit-admin-query.resolver'; import { AdminDepositService } from '@/features/order/services/order-deposit-admin.service'; @@ -39,6 +40,7 @@ describe('Admin Deposit Resolvers (real DB)', () => { AccountAdminRepository, PaymentRepository, OrderTransitionRepository, + RefundRepository, OrderEventsService, { provide: PUB_SUB, useValue: new PubSub() }, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, @@ -74,6 +76,8 @@ describe('Admin Deposit Resolvers (real DB)', () => { await expect(queryResolver.adminTaskCounts(user)).resolves.toEqual({ claimedPayments: 0, pendingPayments: 1, + refundsAwaitingAccount: 0, + refundsAwaitingTransfer: 0, }); const confirmed = await mutationResolver.adminConfirmPayment(user, { diff --git a/src/features/order/resolvers/order-my-mutation.resolver.ts b/src/features/order/resolvers/order-my-mutation.resolver.ts index a52cbd1e..e89bb102 100644 --- a/src/features/order/resolvers/order-my-mutation.resolver.ts +++ b/src/features/order/resolvers/order-my-mutation.resolver.ts @@ -3,6 +3,7 @@ import { Args, Mutation, Resolver } from '@nestjs/graphql'; import { parseId } from '@/common/utils/id-parser'; import { CancelMyOrderInput } from '@/features/order/dto/inputs/cancel-my-order.input'; +import { SubmitMyRefundAccountInput } from '@/features/order/dto/inputs/submit-my-refund-account.input'; import { UserOrderService } from '@/features/order/services/order-my.service'; import type { MyOrderDetail } from '@/features/order/types/order-my-output.type'; import { @@ -35,4 +36,12 @@ export class UserOrderMutationResolver { ): Promise { return this.orderService.cancelMyOrder(parseAccountId(user), input); } + + @Mutation('submitMyRefundAccount') + submitMyRefundAccount( + @CurrentUser() user: JwtUser, + @Args('input') input: SubmitMyRefundAccountInput, + ): Promise { + return this.orderService.submitMyRefundAccount(parseAccountId(user), input); + } } diff --git a/src/features/order/resolvers/order-my.resolver.spec.ts b/src/features/order/resolvers/order-my.resolver.spec.ts index 3f054a48..4e743fd8 100644 --- a/src/features/order/resolvers/order-my.resolver.spec.ts +++ b/src/features/order/resolvers/order-my.resolver.spec.ts @@ -6,12 +6,15 @@ import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { RefundRepository } from '@/features/order/repositories/refund.repository'; import { UserOrderMutationResolver } from '@/features/order/resolvers/order-my-mutation.resolver'; import { UserOrderQueryResolver } from '@/features/order/resolvers/order-my-query.resolver'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { UserOrderService } from '@/features/order/services/order-my.service'; import type { PrismaClient } from '@/generated/prisma/client'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; import { PUB_SUB } from '@/global/pubsub'; +import { createTestAccountCipher } from '@/test/account-cipher'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { @@ -20,6 +23,7 @@ import { createOrderItem, createPayment, createProduct, + createRefund, createStore, createUserProfile, } from '@/test/factories'; @@ -42,6 +46,8 @@ describe('User Order Resolver (real DB)', () => { OrderTransitionRepository, OrderCancelPolicy, OrderEventsService, + RefundRepository, + { provide: AccountCipher, useValue: createTestAccountCipher() }, { provide: PUB_SUB, useValue: new PubSub() }, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, // 발행 repository가 OutboxPublisher를 주입받는다(08b) @@ -160,4 +166,32 @@ describe('User Order Resolver (real DB)', () => { }, }); }); + + it('Mutation.submitMyRefundAccount: ID를 파싱해 계좌를 넣고 상세(송금 대기·마스킹)를 반환한다', async () => { + const account = await createAccount(prisma, { account_type: 'USER' }); + await createUserProfile(prisma, { account_id: account.id }); + const order = await createOrder(prisma, { + account_id: account.id, + status: 'CANCELED', + }); + const refund = await createRefund(prisma, { order_id: order.id }); + + const result = await mutationResolver.submitMyRefundAccount( + { accountId: account.id.toString() }, + { + refundId: refund.id.toString(), + bankCode: '004', + accountHolder: '홍길동', + accountNumber: '12345678901', + }, + ); + + expect(result.refunds).toEqual([ + expect.objectContaining({ + id: refund.id.toString(), + status: 'AWAITING_TRANSFER', + accountNumberMasked: '****8901', + }), + ]); + }); }); diff --git a/src/features/order/resolvers/order-refund-admin-mutation.resolver.ts b/src/features/order/resolvers/order-refund-admin-mutation.resolver.ts new file mode 100644 index 00000000..94a752fe --- /dev/null +++ b/src/features/order/resolvers/order-refund-admin-mutation.resolver.ts @@ -0,0 +1,68 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Mutation, Resolver } from '@nestjs/graphql'; + +import { AdminCompleteRefundInput } from '@/features/order/dto/inputs/admin-complete-refund.input'; +import { AdminCreateDepositReturnInput } from '@/features/order/dto/inputs/admin-create-deposit-return.input'; +import { AdminLinkUnidentifiedDepositInput } from '@/features/order/dto/inputs/admin-link-unidentified-deposit.input'; +import { AdminRecordUnidentifiedDepositInput } from '@/features/order/dto/inputs/admin-record-unidentified-deposit.input'; +import { AdminRefundService } from '@/features/order/services/order-refund-admin.service'; +import type { + AdminDepositRecordOutput, + AdminRefundOutput, +} from '@/features/order/types/order-refund-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Mutation') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('ADMIN') +export class AdminRefundMutationResolver { + constructor(private readonly refundService: AdminRefundService) {} + + @Mutation('adminCompleteRefund') + adminCompleteRefund( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminCompleteRefundInput, + ): Promise { + return this.refundService.adminCompleteRefund(parseAccountId(user), input); + } + + @Mutation('adminCreateDepositReturn') + adminCreateDepositReturn( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminCreateDepositReturnInput, + ): Promise { + return this.refundService.adminCreateDepositReturn( + parseAccountId(user), + input, + ); + } + + @Mutation('adminRecordUnidentifiedDeposit') + adminRecordUnidentifiedDeposit( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminRecordUnidentifiedDepositInput, + ): Promise { + return this.refundService.adminRecordUnidentifiedDeposit( + parseAccountId(user), + input, + ); + } + + @Mutation('adminLinkUnidentifiedDeposit') + adminLinkUnidentifiedDeposit( + @CurrentUser() user: JwtUser, + @Args('input') input: AdminLinkUnidentifiedDepositInput, + ): Promise { + return this.refundService.adminLinkUnidentifiedDeposit( + parseAccountId(user), + input, + ); + } +} diff --git a/src/features/order/resolvers/order-refund-admin-query.resolver.ts b/src/features/order/resolvers/order-refund-admin-query.resolver.ts new file mode 100644 index 00000000..c7fbf236 --- /dev/null +++ b/src/features/order/resolvers/order-refund-admin-query.resolver.ts @@ -0,0 +1,55 @@ +import { UseGuards } from '@nestjs/common'; +import { Args, Query, Resolver } from '@nestjs/graphql'; + +import type { CursorConnection } from '@/common/types/cursor-connection.type'; +import { parseId } from '@/common/utils/id-parser'; +import { AdminDepositRecordListInput } from '@/features/order/dto/inputs/admin-deposit-record-list.input'; +import { AdminRefundListInput } from '@/features/order/dto/inputs/admin-refund-list.input'; +import { AdminRefundService } from '@/features/order/services/order-refund-admin.service'; +import type { + AdminDepositRecordOutput, + AdminRefundDetailOutput, + AdminRefundOutput, +} from '@/features/order/types/order-refund-output.type'; +import { + CurrentUser, + JwtAuthGuard, + Roles, + RolesGuard, + parseAccountId, + type JwtUser, +} from '@/global/auth'; + +@Resolver('Query') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('ADMIN') +export class AdminRefundQueryResolver { + constructor(private readonly refundService: AdminRefundService) {} + + @Query('adminRefunds') + adminRefunds( + @CurrentUser() user: JwtUser, + @Args('input', { nullable: true }) input?: AdminRefundListInput, + ): Promise> { + return this.refundService.adminRefunds(parseAccountId(user), input); + } + + @Query('adminRefund') + adminRefund( + @CurrentUser() user: JwtUser, + @Args('refundId') refundId: string, + ): Promise { + return this.refundService.adminRefund( + parseAccountId(user), + parseId(refundId), + ); + } + + @Query('adminDepositRecords') + adminDepositRecords( + @CurrentUser() user: JwtUser, + @Args('input', { nullable: true }) input?: AdminDepositRecordListInput, + ): Promise> { + return this.refundService.adminDepositRecords(parseAccountId(user), input); + } +} diff --git a/src/features/order/resolvers/order-refund-admin.resolver.spec.ts b/src/features/order/resolvers/order-refund-admin.resolver.spec.ts new file mode 100644 index 00000000..762e2e0e --- /dev/null +++ b/src/features/order/resolvers/order-refund-admin.resolver.spec.ts @@ -0,0 +1,106 @@ +import { AUDIT_LOG_REPOSITORY } from '@/features/audit-log'; +import { AuditLogRepository } from '@/features/audit-log/repositories/audit-log.repository'; +import { AccountAdminRepository } from '@/features/auth/repositories/account-admin.repository'; +import { DepositRecordRepository } from '@/features/order/repositories/deposit-record.repository'; +import { RefundRepository } from '@/features/order/repositories/refund.repository'; +import { AdminRefundMutationResolver } from '@/features/order/resolvers/order-refund-admin-mutation.resolver'; +import { AdminRefundQueryResolver } from '@/features/order/resolvers/order-refund-admin-query.resolver'; +import { AdminRefundService } from '@/features/order/services/order-refund-admin.service'; +import type { PrismaClient } from '@/generated/prisma/client'; +import type { JwtUser } from '@/global/auth'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; +import { createTestAccountCipher } from '@/test/account-cipher'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { createAccount, createOrder, createRefund } from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { outboxPublisherProviders } from '@/test/outbox'; + +// 상세 분기는 order-refund-admin.service.spec. 여기서는 리졸버 → 서비스 → DB 배선과 ID 파싱만 본다. +describe('Admin Refund Resolvers (real DB)', () => { + let queryResolver: AdminRefundQueryResolver; + let mutationResolver: AdminRefundMutationResolver; + let cipher: AccountCipher; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + providers: [ + AdminRefundQueryResolver, + AdminRefundMutationResolver, + AdminRefundService, + AccountAdminRepository, + RefundRepository, + DepositRecordRepository, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + { provide: AccountCipher, useValue: createTestAccountCipher() }, + ...outboxPublisherProviders(), + ], + }); + queryResolver = module.get(AdminRefundQueryResolver); + mutationResolver = module.get(AdminRefundMutationResolver); + cipher = module.get(AccountCipher); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + }); + + it('환불 목록·상세를 조회하고 ID 문자열로 송금 완료한다', async () => { + const admin = await createAccount(prisma, { account_type: 'ADMIN' }); + const user = { accountId: admin.id.toString() } as JwtUser; + const refund = await createRefund(prisma, { + status: 'AWAITING_TRANSFER', + account_number_enc: cipher.encrypt('12345678', 'refund-account'), + }); + + const list = await queryResolver.adminRefunds(user, {}); + expect(list.items.map((i) => i.id)).toEqual([refund.id.toString()]); + await expect( + queryResolver.adminRefund(user, refund.id.toString()), + ).resolves.toMatchObject({ + refund: { id: refund.id.toString() }, + accountNumber: '12345678', + }); + + await expect( + mutationResolver.adminCompleteRefund(user, { + refundId: refund.id.toString(), + }), + ).resolves.toMatchObject({ status: 'COMPLETED' }); + }); + + it('입금 반환·종결·연결 mutation과 입금 기록 목록이 이어진다', async () => { + const admin = await createAccount(prisma, { account_type: 'ADMIN' }); + const user = { accountId: admin.id.toString() } as JwtUser; + const order = await createOrder(prisma, { status: 'CANCELED' }); + + const returned = await mutationResolver.adminCreateDepositReturn(user, { + orderId: order.id.toString(), + amount: 10_000, + depositorName: '차차', + }); + const closed = await mutationResolver.adminRecordUnidentifiedDeposit(user, { + amount: 20_000, + depositorName: '모르는분', + note: '주문 없음', + }); + const linked = await mutationResolver.adminLinkUnidentifiedDeposit(user, { + depositRecordId: closed.id, + orderId: order.id.toString(), + }); + + expect(returned.kind).toBe('RETURN'); + expect(linked).toMatchObject({ id: closed.id, kind: 'RETURN' }); + const records = await queryResolver.adminDepositRecords(user, { + kind: 'RETURN', + }); + expect(records.totalCount).toBe(2); + }); +}); diff --git a/src/features/order/services/order-admin-alert-messages.helper.ts b/src/features/order/services/order-admin-alert-messages.helper.ts index 431275e8..10b82d26 100644 --- a/src/features/order/services/order-admin-alert-messages.helper.ts +++ b/src/features/order/services/order-admin-alert-messages.helper.ts @@ -5,8 +5,15 @@ import { } from '@/common/utils/kst-time'; import type { OrderPaymentPendingPayload } from '@/features/order/events/order-payment-pending.event'; import type { PaymentDepositClaimedPayload } from '@/features/order/events/payment-deposit-claimed.event'; +import type { RefundEventPayload } from '@/features/order/events/refund-requested.event'; +import { RefundKind } from '@/generated/prisma/client'; import type { AlertMessage } from '@/global/alerting'; +const REFUND_KIND_LABELS: Record = { + [RefundKind.CANCEL]: '취소 환불', + [RefundKind.DEPOSIT_RETURN]: '입금 반환', +}; + /** 관리자 웹 처리 화면 링크. 주소가 설정되지 않았으면 null(링크 없이 보낸다). */ export function adminTaskLink( baseUrl: string | null, @@ -65,3 +72,23 @@ export function buildDepositClaimedAlert( detail: depositLines(p, depositLink(baseUrl, p.orderId)), }; } + +/** 환불 계좌가 들어와 송금할 차례(취소와 함께 입력·나중에 입력·덮어쓰기). 계좌번호는 싣지 않는다. */ +export function buildRefundReadyAlert( + p: RefundEventPayload, + baseUrl: string | null, +): AlertMessage { + const link = adminTaskLink(baseUrl, '/tasks/refunds', { + refundId: p.refundId, + }); + return { + level: 'info', + title: '환불 송금 대기', + key: `refund-ready:${p.refundId}`, + detail: [ + `주문 ${p.orderNumber}`, + `${p.amount.toLocaleString('ko-KR')}원 · ${REFUND_KIND_LABELS[p.kind]}`, + ...(link ? [link] : []), + ].join('\n'), + }; +} diff --git a/src/features/order/services/order-admin-alert.consumer.spec.ts b/src/features/order/services/order-admin-alert.consumer.spec.ts index 55d4d2e8..b928618c 100644 --- a/src/features/order/services/order-admin-alert.consumer.spec.ts +++ b/src/features/order/services/order-admin-alert.consumer.spec.ts @@ -5,6 +5,8 @@ import type { AdminWebConfig } from '@/config/admin-web.config'; import type { AlertingConfig } from '@/config/alerting.config'; import { ORDER_PAYMENT_PENDING } from '@/features/order/events/order-payment-pending.event'; import { PAYMENT_DEPOSIT_CLAIMED } from '@/features/order/events/payment-deposit-claimed.event'; +import { REFUND_ACCOUNT_SUBMITTED } from '@/features/order/events/refund-account-submitted.event'; +import { REFUND_REQUESTED } from '@/features/order/events/refund-requested.event'; import { OrderAdminAlertConsumer } from '@/features/order/services/order-admin-alert.consumer'; import type { OutboxEvent } from '@/features/outbox'; import { AlertService } from '@/global/alerting'; @@ -24,6 +26,18 @@ const CLAIMED = { amount: 1234567, depositorName: '홍길동', }; +const REFUND = { + refundId: '9', + orderId: '42', + orderNumber: 'ORD-20260916-ABC234', + buyerAccountId: '3', + kind: 'CANCEL', + amount: 30000, + storeId: '2', + storeName: '케이크샵', + productId: '5', + productName: '레터링 케이크', +}; function event( eventType: string, @@ -151,6 +165,75 @@ describe('OrderAdminAlertConsumer', () => { }); it.each([ + [ + '취소와 함께 계좌 입력', + REFUND_REQUESTED, + { ...REFUND, accountSubmitted: true }, + ], + ['나중에 계좌 입력', REFUND_ACCOUNT_SUBMITTED, REFUND], + ])( + '환불 송금 대기(%s): info, 환불별 key, 금액·종류·처리 화면 링크(계좌번호 없음)', + async (_label, type, payload) => { + const consumer = build({ baseUrl: 'https://admin.caquick.com' }); + + await consumer.handle(event(type, payload)); + + expect(transport).toHaveBeenCalledWith( + expect.any(String), + { + level: 'info', + title: '환불 송금 대기', + key: 'refund-ready:9', + detail: [ + '주문 ORD-20260916-ABC234', + '30,000원 · 취소 환불', + 'https://admin.caquick.com/tasks/refunds?refundId=9', + ].join('\n'), + }, + expect.any(Object), + ); + }, + ); + + it('계좌가 없는 환불 생성은 관리자에게 보내지 않는다(구매자 계좌 요청 알림만 간다)', async () => { + const consumer = build({ baseUrl: null }); + + await consumer.handle(event(REFUND_REQUESTED, REFUND)); + await consumer.handle( + event(REFUND_REQUESTED, { ...REFUND, accountSubmitted: false }), + ); + + expect(transport).not.toHaveBeenCalled(); + }); + + it('같은 환불의 계좌 덮어쓰기는 억제 창 안에서 한 번만, 입금 반환은 종류를 다르게 적는다', async () => { + const consumer = build({ baseUrl: null }); + + await consumer.handle(event(REFUND_ACCOUNT_SUBMITTED, REFUND)); + await consumer.handle(event(REFUND_ACCOUNT_SUBMITTED, REFUND)); + await consumer.handle( + event(REFUND_ACCOUNT_SUBMITTED, { + ...REFUND, + refundId: '10', + kind: 'DEPOSIT_RETURN', + }), + ); + + const messages = transport.mock.calls.map( + ([, m]) => m as { key: string; detail: string }, + ); + expect(messages.map((m) => m.key)).toEqual([ + 'refund-ready:9', + 'refund-ready:10', + ]); + expect(messages[1].detail).toBe( + ['주문 ORD-20260916-ABC234', '30,000원 · 입금 반환'].join('\n'), + ); + }); + + it.each([ + [REFUND_REQUESTED, { ...REFUND, kind: 'CHARGEBACK' }], + [REFUND_ACCOUNT_SUBMITTED, { ...REFUND, amount: '30000' }], [ORDER_PAYMENT_PENDING, { ...PENDING, amount: '56000' }], [ORDER_PAYMENT_PENDING, { ...PENDING, expiresAt: 'not-a-date' }], [PAYMENT_DEPOSIT_CLAIMED, { ...CLAIMED, orderId: 43 }], diff --git a/src/features/order/services/order-admin-alert.consumer.ts b/src/features/order/services/order-admin-alert.consumer.ts index ff80ca72..957d4a79 100644 --- a/src/features/order/services/order-admin-alert.consumer.ts +++ b/src/features/order/services/order-admin-alert.consumer.ts @@ -10,9 +10,18 @@ import { parsePaymentDepositClaimedPayload, PAYMENT_DEPOSIT_CLAIMED, } from '@/features/order/events/payment-deposit-claimed.event'; +import { + parseRefundAccountSubmittedPayload, + REFUND_ACCOUNT_SUBMITTED, +} from '@/features/order/events/refund-account-submitted.event'; +import { + parseRefundRequestedPayload, + REFUND_REQUESTED, +} from '@/features/order/events/refund-requested.event'; import { buildDepositClaimedAlert, buildDepositPendingAlert, + buildRefundReadyAlert, } from '@/features/order/services/order-admin-alert-messages.helper'; import { type OutboxConsumer, @@ -26,7 +35,12 @@ import { AlertService, type AlertMessage } from '@/global/alerting'; * 막고, 창이 지난 재전달은 같은 알림이 다시 갈 수 있다(진실은 adminTaskCounts·처리 대기 목록). */ @Injectable() -@SubscribeOutbox(ORDER_PAYMENT_PENDING, PAYMENT_DEPOSIT_CLAIMED) +@SubscribeOutbox( + ORDER_PAYMENT_PENDING, + PAYMENT_DEPOSIT_CLAIMED, + REFUND_REQUESTED, + REFUND_ACCOUNT_SUBMITTED, +) export class OrderAdminAlertConsumer implements OutboxConsumer { constructor( private readonly alerts: AlertService, @@ -34,10 +48,11 @@ export class OrderAdminAlertConsumer implements OutboxConsumer { ) {} async handle(event: OutboxEvent): Promise { - await this.alerts.notify(this.messageOf(event)); + const message = this.messageOf(event); + if (message) await this.alerts.notify(message); } - private messageOf(event: OutboxEvent): AlertMessage { + private messageOf(event: OutboxEvent): AlertMessage | null { const { baseUrl } = this.config.getOrThrow('adminWeb'); switch (event.eventType) { case ORDER_PAYMENT_PENDING: @@ -50,6 +65,16 @@ export class OrderAdminAlertConsumer implements OutboxConsumer { parsePaymentDepositClaimedPayload(event.payload), baseUrl, ); + case REFUND_REQUESTED: { + const p = parseRefundRequestedPayload(event.payload); + // 계좌가 아직 없으면 구매자 계좌 요청 알림만 간다(알림 소비자) + return p.accountSubmitted ? buildRefundReadyAlert(p, baseUrl) : null; + } + case REFUND_ACCOUNT_SUBMITTED: + return buildRefundReadyAlert( + parseRefundAccountSubmittedPayload(event.payload), + baseUrl, + ); default: throw new Error(`구독하지 않은 outbox 이벤트: ${event.eventType}`); } diff --git a/src/features/order/services/order-deposit-admin.service.spec.ts b/src/features/order/services/order-deposit-admin.service.spec.ts index 8b460c15..46f84c36 100644 --- a/src/features/order/services/order-deposit-admin.service.spec.ts +++ b/src/features/order/services/order-deposit-admin.service.spec.ts @@ -15,6 +15,7 @@ import { import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { RefundRepository } from '@/features/order/repositories/refund.repository'; import { AdminDepositService } from '@/features/order/services/order-deposit-admin.service'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { OutboxDispatcherService } from '@/features/outbox'; @@ -27,6 +28,7 @@ import { createOrder, createOrderItem, createPayment, + createRefund, createStore, } from '@/test/factories'; import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; @@ -58,6 +60,7 @@ describe('AdminDepositService (real DB)', () => { PaymentRepository, OrderTransitionRepository, OrderRepository, + RefundRepository, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, OrderEventsService, { provide: PUB_SUB, useValue: new PubSub() }, @@ -573,15 +576,21 @@ describe('AdminDepositService (real DB)', () => { }, ); - it("처리 대기 건수는 '입금했어요'와 전체 입금 대기를 센다", async () => { + it("처리 대기 건수는 '입금했어요'·전체 입금 대기와 환불 상태별(종류 무관)을 센다", async () => { const adminId = await admin(); await pendingOrder({ claimedAt: NOW }); await pendingOrder(); await pendingOrder({ status: 'SUBMITTED', paymentStatus: 'CONFIRMED' }); + await createRefund(prisma); + await createRefund(prisma, { kind: 'DEPOSIT_RETURN' }); + await createRefund(prisma, { status: 'AWAITING_TRANSFER' }); + await createRefund(prisma, { status: 'COMPLETED' }); await expect(service.adminTaskCounts(adminId)).resolves.toEqual({ claimedPayments: 1, pendingPayments: 2, + refundsAwaitingAccount: 2, + refundsAwaitingTransfer: 1, }); }); }); diff --git a/src/features/order/services/order-deposit-admin.service.ts b/src/features/order/services/order-deposit-admin.service.ts index 33f1eeb2..d1ff6210 100644 --- a/src/features/order/services/order-deposit-admin.service.ts +++ b/src/features/order/services/order-deposit-admin.service.ts @@ -25,6 +25,7 @@ import type { AdminPendingPaymentListInput } from '@/features/order/dto/inputs/a import { assertPaymentConfirmable } from '@/features/order/policies/payment-confirm.policy'; import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { RefundRepository } from '@/features/order/repositories/refund.repository'; import { toAdminOrderSummaryOutput } from '@/features/order/services/order-admin-mappers.helper'; import { toSellerOrderUpdateEvent } from '@/features/order/services/order-events-mappers.helper'; import { OrderEventsService } from '@/features/order/services/order-events.service'; @@ -34,7 +35,7 @@ import type { AdminPendingPaymentOutput, AdminTaskCountsOutput, } from '@/features/order/types/order-payment-output.type'; -import { PaymentConfirmSource } from '@/generated/prisma/client'; +import { PaymentConfirmSource, RefundStatus } from '@/generated/prisma/client'; const MAX_CONFIRM_NOTE_LENGTH = 500; @@ -49,6 +50,7 @@ export class AdminDepositService extends AdminBaseService { private readonly transitions: OrderTransitionRepository, private readonly clock: ClockService, private readonly events: OrderEventsService, + private readonly refunds: RefundRepository, ) { super(accounts, auditLogs); } @@ -89,11 +91,23 @@ export class AdminDepositService extends AdminBaseService { async adminTaskCounts(accountId: bigint): Promise { await this.requireAdminContext(accountId); - const [claimedPayments, pendingPayments] = await Promise.all([ + const [ + claimedPayments, + pendingPayments, + refundsAwaitingAccount, + refundsAwaitingTransfer, + ] = await Promise.all([ this.payments.countPendingPayments({ claimedOnly: true }), this.payments.countPendingPayments({ claimedOnly: false }), + this.refunds.countRefunds({ status: RefundStatus.AWAITING_ACCOUNT }), + this.refunds.countRefunds({ status: RefundStatus.AWAITING_TRANSFER }), ]); - return { claimedPayments, pendingPayments }; + return { + claimedPayments, + pendingPayments, + refundsAwaitingAccount, + refundsAwaitingTransfer, + }; } async adminConfirmPayment( diff --git a/src/features/order/services/order-my.service.spec.ts b/src/features/order/services/order-my.service.spec.ts index 3287767e..c8da9718 100644 --- a/src/features/order/services/order-my.service.spec.ts +++ b/src/features/order/services/order-my.service.spec.ts @@ -9,15 +9,19 @@ import { parsePaymentDepositClaimedPayload, PAYMENT_DEPOSIT_CLAIMED, } from '@/features/order/events/payment-deposit-claimed.event'; +import { REFUND_ACCOUNT_SUBMITTED } from '@/features/order/events/refund-account-submitted.event'; import { REFUND_REQUESTED } from '@/features/order/events/refund-requested.event'; import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { RefundRepository } from '@/features/order/repositories/refund.repository'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { UserOrderService } from '@/features/order/services/order-my.service'; import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; import { PUB_SUB } from '@/global/pubsub'; +import { createTestAccountCipher } from '@/test/account-cipher'; import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; import { @@ -26,6 +30,7 @@ import { createOrderItem, createPayment, createProduct, + createRefund, createReview, createStore, createThreeDOrderItemCustom, @@ -41,6 +46,7 @@ describe('UserOrderService (real DB)', () => { let clock: ClockService; let prisma: PrismaClient; let pubSub: PubSub; + let cipher: AccountCipher; beforeAll(async () => { const { module, prisma: p } = await createTestingModuleWithRealDb({ @@ -51,6 +57,8 @@ describe('UserOrderService (real DB)', () => { OrderTransitionRepository, OrderCancelPolicy, OrderEventsService, + RefundRepository, + { provide: AccountCipher, useValue: createTestAccountCipher() }, { provide: PUB_SUB, useValue: new PubSub() }, { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, // 발행 repository가 OutboxPublisher를 주입받는다(08b) @@ -60,6 +68,7 @@ describe('UserOrderService (real DB)', () => { service = module.get(UserOrderService); clock = module.get(ClockService); pubSub = module.get(PUB_SUB); + cipher = module.get(AccountCipher); prisma = p; }); @@ -1032,4 +1041,263 @@ describe('UserOrderService (real DB)', () => { expect(detail.cancellation).toBeNull(); }); }); + + describe('환불 계좌', () => { + const NOW = new Date('2026-09-16T07:30:00.000Z'); + const ACCOUNT = { + bankCode: '088', + accountHolder: ' 홍길동 ', + accountNumber: '110-123-456789', + }; + + async function submittedOrder(accountId: bigint) { + const order = await createOrder(prisma, { + account_id: accountId, + status: 'SUBMITTED', + }); + await createOrderItem(prisma, { order_id: order.id }); + await createPayment(prisma, { + order_id: order.id, + status: 'CONFIRMED', + confirmed_at: NOW, + }); + return order; + } + + async function expectAccount(refundId: bigint, accountNumber: string) { + const row = await prisma.refund.findUniqueOrThrow({ + where: { id: refundId }, + }); + expect(cipher.decrypt(row.account_number_enc!, 'refund-account')).toBe( + accountNumber, + ); + return row; + } + + beforeEach(() => { + jest.spyOn(clock, 'now').mockReturnValue(NOW); + }); + + it('취소와 함께 계좌를 받으면 환불이 바로 송금 대기가 되고 이벤트에 계좌 입력을 싣는다', async () => { + const account = await setupUser(); + const order = await submittedOrder(account.id); + + const result = await service.cancelMyOrder(account.id, { + orderId: order.id.toString(), + refundAccount: ACCOUNT, + }); + + expect(result.cancellation).toMatchObject({ + refundStatus: 'AWAITING_TRANSFER', + }); + expect(result.refunds).toEqual([ + expect.objectContaining({ + kind: 'CANCEL', + status: 'AWAITING_TRANSFER', + bank: { code: '088', name: expect.any(String) }, + accountHolder: '홍길동', + accountNumberMasked: '****6789', + accountSubmittedAt: NOW, + }), + ]); + const refund = await expectAccount( + BigInt(result.refunds[0].id), + '110123456789', + ); + expect(refund.account_number_last4).toBe('6789'); + const requested = await prisma.outbox.findFirstOrThrow({ + where: { event_type: REFUND_REQUESTED }, + }); + expect(requested.payload_json).toMatchObject({ accountSubmitted: true }); + }); + + it('환불이 없는 취소(입금 대기)에 보낸 계좌는 버린다', async () => { + const account = await setupUser(); + const order = await createOrder(prisma, { + account_id: account.id, + status: 'PENDING_PAYMENT', + }); + await createPayment(prisma, { order_id: order.id }); + + const result = await service.cancelMyOrder(account.id, { + orderId: order.id.toString(), + refundAccount: ACCOUNT, + }); + + expect(result).toMatchObject({ status: 'CANCELED', refunds: [] }); + expect(await prisma.refund.count()).toBe(0); + }); + + it('계좌 형식이 틀리면 취소하지 않는다', async () => { + const account = await setupUser(); + const order = await submittedOrder(account.id); + + await expect( + service.cancelMyOrder(account.id, { + orderId: order.id.toString(), + refundAccount: { ...ACCOUNT, bankCode: '999' }, + }), + ).rejects.toThrowDomain('INVALID_BANK_CODE'); + expect( + (await prisma.order.findUniqueOrThrow({ where: { id: order.id } })) + .status, + ).toBe('SUBMITTED'); + }); + + it('계좌 입력 대기 환불에 계좌를 넣으면 송금 대기가 되고, 완료 전에는 덮어쓸 수 있다', async () => { + const account = await setupUser(); + const order = await createOrder(prisma, { + account_id: account.id, + status: 'CANCELED', + }); + const refund = await createRefund(prisma, { order_id: order.id }); + + const first = await service.submitMyRefundAccount(account.id, { + refundId: refund.id.toString(), + ...ACCOUNT, + }); + expect(first.refunds).toEqual([ + expect.objectContaining({ + id: refund.id.toString(), + status: 'AWAITING_TRANSFER', + accountNumberMasked: '****6789', + accountSubmittedAt: NOW, + }), + ]); + + const later = new Date(NOW.getTime() + 60_000); + jest.spyOn(clock, 'now').mockReturnValue(later); + const second = await service.submitMyRefundAccount(account.id, { + refundId: refund.id.toString(), + bankCode: '004', + accountHolder: '김철수', + accountNumber: '12345678', + }); + + expect(second.refunds[0]).toMatchObject({ + status: 'AWAITING_TRANSFER', + bank: { code: '004' }, + accountHolder: '김철수', + accountNumberMasked: '****5678', + accountSubmittedAt: later, + }); + await expectAccount(refund.id, '12345678'); + const events = await prisma.outbox.findMany({ orderBy: { id: 'asc' } }); + expect(events.map((e) => e.event_type)).toEqual([ + REFUND_ACCOUNT_SUBMITTED, + REFUND_ACCOUNT_SUBMITTED, + ]); + expect(events[1].payload_json).toMatchObject({ + refundId: refund.id.toString(), + orderNumber: order.order_number, + buyerAccountId: account.id.toString(), + amount: refund.amount, + }); + }); + + it('송금이 끝난 환불은 REFUND_ALREADY_COMPLETED로 거절하고 계좌를 바꾸지 않는다', async () => { + const account = await setupUser(); + const order = await createOrder(prisma, { + account_id: account.id, + status: 'CANCELED', + }); + const refund = await createRefund(prisma, { + order_id: order.id, + status: 'COMPLETED', + }); + + await expect( + service.submitMyRefundAccount(account.id, { + refundId: refund.id.toString(), + ...ACCOUNT, + }), + ).rejects.toThrowDomain('REFUND_ALREADY_COMPLETED'); + await expect( + prisma.refund.findUniqueOrThrow({ where: { id: refund.id } }), + ).resolves.toMatchObject({ account_number_last4: '5678' }); + expect(await prisma.outbox.count()).toBe(0); + }); + + it('다른 계정·삭제된 주문의 환불과 없는 환불은 REFUND_NOT_FOUND, 계좌번호 형식 오류는 INVALID_ACCOUNT_NUMBER다', async () => { + const account = await setupUser(); + const other = await setupUser(); + const othersRefund = await createRefund(prisma, { + order_id: ( + await createOrder(prisma, { + account_id: other.id, + status: 'CANCELED', + }) + ).id, + }); + const deletedRefund = await createRefund(prisma, { + order_id: ( + await createOrder(prisma, { + account_id: account.id, + status: 'CANCELED', + deleted_at: NOW, + }) + ).id, + }); + const mine = await createRefund(prisma, { + order_id: ( + await createOrder(prisma, { + account_id: account.id, + status: 'CANCELED', + }) + ).id, + }); + + for (const id of [othersRefund.id, deletedRefund.id, 999_999n]) { + await expect( + service.submitMyRefundAccount(account.id, { + refundId: id.toString(), + ...ACCOUNT, + }), + ).rejects.toThrowDomain('REFUND_NOT_FOUND'); + } + await expect( + service.submitMyRefundAccount(account.id, { + refundId: mine.id.toString(), + ...ACCOUNT, + accountNumber: '1234-567', + }), + ).rejects.toThrowDomain('INVALID_ACCOUNT_NUMBER'); + expect( + await prisma.refund.count({ where: { status: 'AWAITING_ACCOUNT' } }), + ).toBe(3); + }); + + it('상세 refunds는 취소 환불과 입금 반환을 생긴 순서대로 싣는다', async () => { + const account = await setupUser(); + const order = await createOrder(prisma, { + account_id: account.id, + status: 'CANCELED', + }); + const cancel = await createRefund(prisma, { order_id: order.id }); + const deposit = await createRefund(prisma, { + order_id: order.id, + kind: 'DEPOSIT_RETURN', + amount: 5_000, + status: 'COMPLETED', + }); + + const detail = await service.getMyOrder(account.id, order.id); + + expect(detail.refunds).toEqual([ + expect.objectContaining({ + id: cancel.id.toString(), + kind: 'CANCEL', + status: 'AWAITING_ACCOUNT', + bank: null, + accountNumberMasked: null, + }), + expect.objectContaining({ + id: deposit.id.toString(), + kind: 'DEPOSIT_RETURN', + amount: 5_000, + status: 'COMPLETED', + }), + ]); + }); + }); }); diff --git a/src/features/order/services/order-my.service.ts b/src/features/order/services/order-my.service.ts index 2b0e1568..a70f8d7e 100644 --- a/src/features/order/services/order-my.service.ts +++ b/src/features/order/services/order-my.service.ts @@ -9,14 +9,22 @@ import { sliceOverfetched } from '@/common/utils/pagination'; import { cleanNullableText } from '@/common/utils/text-cleaner'; import type { CancelMyOrderInput } from '@/features/order/dto/inputs/cancel-my-order.input'; import type { MyOrdersInput } from '@/features/order/dto/inputs/my-orders.input'; +import type { RefundAccountInput } from '@/features/order/dto/inputs/refund-account.input'; +import type { SubmitMyRefundAccountInput } from '@/features/order/dto/inputs/submit-my-refund-account.input'; import { OrderCancelPolicy } from '@/features/order/policies/order-cancel.policy'; import { OrderTransitionRepository } from '@/features/order/repositories/order-transition.repository'; import { OrderRepository } from '@/features/order/repositories/order.repository'; import { PaymentRepository } from '@/features/order/repositories/payment.repository'; +import { + type RefundAccountData, + RefundRepository, +} from '@/features/order/repositories/refund.repository'; +import { normalizeBankAccount } from '@/features/order/services/order-bank-account.helper'; import { OrderEventsService } from '@/features/order/services/order-events.service'; import { toOrderCancellation, toOrderItemDetail, + toOrderRefund, toOrderStatusHistory, } from '@/features/order/services/order-output-mappers.helper'; import { toOrderPaymentOutput } from '@/features/order/services/order-payment-mappers.helper'; @@ -31,6 +39,7 @@ import { OrderStatus, PaymentStatus, } from '@/generated/prisma/client'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; @Injectable() export class UserOrderService { @@ -41,20 +50,30 @@ export class UserOrderService { private readonly cancelPolicy: OrderCancelPolicy, private readonly events: OrderEventsService, private readonly clock: ClockService, + private readonly refunds: RefundRepository, + private readonly cipher: AccountCipher, ) {} - /** 판매자 확정 전까지만. 입금 대기면 환불 없이, 접수면 전액 환불로 취소한다('입금했어요'를 눌렀어도 허용). */ + /** + * 판매자 확정 전까지만. 입금 대기면 환불 없이, 접수면 전액 환불로 취소한다('입금했어요'를 눌렀어도 허용). + * 환불 계좌를 함께 받으면 환불이 바로 송금 대기가 된다. + */ async cancelMyOrder( accountId: bigint, input: CancelMyOrderInput, ): Promise { const orderId = parseId(input.orderId); + const note = cleanNullableText(input.note, MAX_REASON_LENGTH); + const refundAccount = input.refundAccount + ? this.encryptRefundAccount(input.refundAccount) + : null; const updated = await this.transitions.cancel({ orderId, actor: OrderActor.BUYER, actorAccountId: accountId, scope: { kind: 'buyer', accountId }, - note: cleanNullableText(input.note, MAX_REASON_LENGTH), + note, + refundAccount, now: this.clock.now(), decide: (state) => this.cancelPolicy.decide( @@ -70,6 +89,38 @@ export class UserOrderService { return this.getMyOrder(accountId, orderId); } + /** 돌려받을 계좌 입력. 송금 완료 전이면 덮어쓸 수 있고, 입력하면 송금 대기가 된다. */ + async submitMyRefundAccount( + accountId: bigint, + input: SubmitMyRefundAccountInput, + ): Promise { + const refundId = parseId(input.refundId); + const result = await this.refunds.submitAccount({ + refundId, + accountId, + account: this.encryptRefundAccount(input), + now: this.clock.now(), + }); + if (result === 'not-found') throw new DomainException('REFUND_NOT_FOUND'); + if (result === 'completed') { + throw new DomainException('REFUND_ALREADY_COMPLETED'); + } + return this.getMyOrder(accountId, result.orderId); + } + + private encryptRefundAccount(input: RefundAccountInput): RefundAccountData { + const account = normalizeBankAccount(input); + return { + bankCode: account.bankCode, + accountHolder: account.accountHolder, + accountNumberEnc: this.cipher.encrypt( + account.accountNumber, + 'refund-account', + ), + accountNumberLast4: account.accountNumber.slice(-4), + }; + } + /** '입금했어요'. 마감 전 첫 누름만 기록해 미입금 자동 취소에서 빼고, 다시 누르면 그대로 돌려준다. */ async markMyOrderDepositSent( accountId: bigint, @@ -190,6 +241,7 @@ export class UserOrderService { canceledAt: order.canceled_at, cancellation: toOrderCancellation(order), canCancel: this.cancelPolicy.canCancel(OrderActor.BUYER, order.status), + refunds: order.refunds.map(toOrderRefund), statusHistories: order.status_histories.map(toOrderStatusHistory), items: order.items.map((item) => ({ item: toOrderItemDetail(item), diff --git a/src/features/order/services/order-refund-admin.service.spec.ts b/src/features/order/services/order-refund-admin.service.spec.ts new file mode 100644 index 00000000..1445e9e6 --- /dev/null +++ b/src/features/order/services/order-refund-admin.service.spec.ts @@ -0,0 +1,659 @@ +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 { AccountAdminRepository } from '@/features/auth/repositories/account-admin.repository'; +import { NotificationAdminRepository } from '@/features/notification/repositories/notification-admin.repository'; +import { NotificationRepository } from '@/features/notification/repositories/notification.repository'; +import { NotificationOutboxConsumer } from '@/features/notification/services/notification-outbox.consumer'; +import { REFUND_COMPLETED } from '@/features/order/events/refund-completed.event'; +import { REFUND_REQUESTED } from '@/features/order/events/refund-requested.event'; +import { DepositRecordRepository } from '@/features/order/repositories/deposit-record.repository'; +import { RefundRepository } from '@/features/order/repositories/refund.repository'; +import { AdminRefundService } from '@/features/order/services/order-refund-admin.service'; +import { OutboxDispatcherService } from '@/features/outbox'; +import type { OrderStatus, PrismaClient } from '@/generated/prisma/client'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; +import { createTestAccountCipher } from '@/test/account-cipher'; +import { disconnectTestPrismaClient } from '@/test/db/prisma-test-client'; +import { closeTruncateConnection, truncateAll } from '@/test/db/truncate'; +import { + createAccount, + createOrder, + createOrderItem, + createPayment, + createRefund, + createStore, +} from '@/test/factories'; +import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder'; +import { + drainOutbox, + OUTBOX_TEST_IMPORTS, + outboxTestProviders, +} from '@/test/outbox'; + +// 2026-09-16(수) 16:00 KST +const NOW = new Date('2026-09-16T07:00:00.000Z'); + +describe('AdminRefundService (real DB)', () => { + let service: AdminRefundService; + let clock: ClockService; + let cipher: AccountCipher; + let dispatcher: OutboxDispatcherService; + let prisma: PrismaClient; + + beforeAll(async () => { + const { module, prisma: p } = await createTestingModuleWithRealDb({ + imports: OUTBOX_TEST_IMPORTS, + providers: [ + AdminRefundService, + AccountAdminRepository, + RefundRepository, + DepositRecordRepository, + { provide: AUDIT_LOG_REPOSITORY, useClass: AuditLogRepository }, + { provide: AccountCipher, useValue: createTestAccountCipher() }, + ...outboxTestProviders(), + NotificationOutboxConsumer, + NotificationRepository, + NotificationAdminRepository, + ], + }); + service = module.get(AdminRefundService); + clock = module.get(ClockService); + cipher = module.get(AccountCipher); + dispatcher = module.get(OutboxDispatcherService); + prisma = p; + }); + + afterAll(async () => { + await closeTruncateConnection(); + await disconnectTestPrismaClient(); + }); + + beforeEach(async () => { + await truncateAll(); + jest.spyOn(clock, 'now').mockReturnValue(NOW); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + async function admin(name: string | null = '김운영'): Promise { + return (await createAccount(prisma, { account_type: 'ADMIN', name })).id; + } + + /** 품목이 있는 주문(매장·상품 스냅샷). */ + async function order(status: OrderStatus = 'CANCELED', totalPrice = 30_000) { + const store = await createStore(prisma, { store_name: '해즈 케이크' }); + const row = await createOrder(prisma, { + status, + total_price: totalPrice, + buyer_name: '차차', + buyer_phone: '010-1234-5678', + }); + await createOrderItem(prisma, { + order_id: row.id, + store_id: store.id, + product_name_snapshot: '딸기 케이크', + }); + return row; + } + + describe('adminRefunds·adminRefund', () => { + it('필터를 null로 보내면 전체를 오래된 환불부터 주문·연락처·첫 품목 스냅샷과 함께 준다', async () => { + const adminId = await admin(); + const o = await order(); + const r1 = await createRefund(prisma, { order_id: o.id }); + const r2 = await createRefund(prisma, { + order_id: o.id, + kind: 'DEPOSIT_RETURN', + status: 'AWAITING_TRANSFER', + amount: 5_000, + }); + const r3 = await createRefund(prisma, { status: 'COMPLETED' }); + + const result = await service.adminRefunds(adminId, { + status: null, + kind: null, + }); + + expect(result.totalCount).toBe(3); + expect(result.items.map((i) => i.id)).toEqual( + [r1, r2, r3].map((r) => r.id.toString()), + ); + expect(result.items[1]).toMatchObject({ + orderId: o.id.toString(), + orderNumber: o.order_number, + buyerName: '차차', + buyerPhone: '010-1234-5678', + storeName: '해즈 케이크', + productName: '딸기 케이크', + kind: 'DEPOSIT_RETURN', + amount: 5_000, + status: 'AWAITING_TRANSFER', + accountNumberMasked: '****5678', + completedByLabel: null, + }); + }); + + it('상태·종류 필터는 AND로 걸고 키셋으로 넘긴다', async () => { + const adminId = await admin(); + const ids: bigint[] = []; + for (let i = 0; i < 3; i++) { + ids.push((await createRefund(prisma)).id); + } + await createRefund(prisma, { kind: 'DEPOSIT_RETURN' }); + await createRefund(prisma, { status: 'AWAITING_TRANSFER' }); + + const first = await service.adminRefunds(adminId, { + status: 'AWAITING_ACCOUNT', + kind: 'CANCEL', + limit: 2, + }); + expect(first).toMatchObject({ + totalCount: 3, + hasMore: true, + nextCursor: ids[1].toString(), + }); + const second = await service.adminRefunds(adminId, { + status: 'AWAITING_ACCOUNT', + kind: 'CANCEL', + limit: 2, + cursor: first.nextCursor!, + }); + expect(second.items.map((i) => i.id)).toEqual([ids[2].toString()]); + expect(second).toMatchObject({ hasMore: false, nextCursor: null }); + await expect( + service.adminRefunds(adminId, { cursor: 'abc' }), + ).rejects.toThrowDomain('INVALID_CURSOR'); + }); + + it('상세는 계좌번호 원문과 입금 반환이면 입금 기록을 함께 준다', async () => { + const adminId = await admin(); + const o = await order(); + const refund = await createRefund(prisma, { + order_id: o.id, + kind: 'DEPOSIT_RETURN', + status: 'AWAITING_TRANSFER', + account_number_enc: cipher.encrypt('110123455678', 'refund-account'), + }); + + const detail = await service.adminRefund(adminId, refund.id); + + expect(detail).toMatchObject({ + refund: { id: refund.id.toString(), accountNumberMasked: '****5678' }, + accountNumber: '110123455678', + depositRecord: { + kind: 'RETURN', + orderId: o.id.toString(), + orderNumber: o.order_number, + refundId: refund.id.toString(), + refundStatus: 'AWAITING_TRANSFER', + }, + }); + }); + + it('계좌 입력 전 취소 환불은 원문·입금 기록이 null이고, 없는 환불은 REFUND_NOT_FOUND다', async () => { + const adminId = await admin(); + const refund = await createRefund(prisma); + + await expect( + service.adminRefund(adminId, refund.id), + ).resolves.toMatchObject({ accountNumber: null, depositRecord: null }); + await expect( + service.adminRefund(adminId, refund.id + 1n), + ).rejects.toThrowDomain('REFUND_NOT_FOUND'); + }); + }); + + describe('adminCompleteRefund', () => { + it('송금 대기 환불을 완료로 바꾸고 처리자·메모·감사·구매자 완료 알림을 남긴다', async () => { + const adminId = await admin('김운영'); + const o = await order(); + const refund = await createRefund(prisma, { + order_id: o.id, + status: 'AWAITING_TRANSFER', + }); + + const result = await service.adminCompleteRefund(adminId, { + refundId: refund.id.toString(), + note: ' 국민 16:05 송금 ', + }); + + expect(result).toMatchObject({ + status: 'COMPLETED', + completedAt: NOW, + completedByLabel: '김운영', + completeNote: '국민 16:05 송금', + }); + await expect( + prisma.refund.findUniqueOrThrow({ where: { id: refund.id } }), + ).resolves.toMatchObject({ completed_by_account_id: adminId }); + const [audit] = await prisma.auditLog.findMany(); + expect(audit).toMatchObject({ + actor_account_id: adminId, + store_id: null, + target_type: 'REFUND', + target_id: refund.id, + action: 'STATUS_CHANGE', + before_json: { status: 'AWAITING_TRANSFER' }, + after_json: { + status: 'COMPLETED', + amount: refund.amount, + accountNumberLast4: '5678', + note: '국민 16:05 송금', + }, + }); + const events = await prisma.outbox.findMany(); + expect(events.map((e) => e.event_type)).toEqual([REFUND_COMPLETED]); + + await drainOutbox(dispatcher); + await expect(prisma.notification.findMany()).resolves.toEqual([ + expect.objectContaining({ + account_id: o.account_id, + event: 'REFUND_COMPLETED', + body: `${o.order_number} 30,000원 환불이 완료되었어요.`, + store_name: '해즈 케이크', + }), + ]); + }); + + it.each([ + ['AWAITING_ACCOUNT', 'REFUND_NOT_READY'], + ['COMPLETED', 'REFUND_ALREADY_COMPLETED'], + ] as const)( + '%s 환불은 %s로 거절하고 아무것도 남기지 않는다', + async (status, code) => { + const adminId = await admin(); + const refund = await createRefund(prisma, { status }); + + await expect( + service.adminCompleteRefund(adminId, { + refundId: refund.id.toString(), + }), + ).rejects.toThrowDomain(code); + await expect( + prisma.refund.findUniqueOrThrow({ where: { id: refund.id } }), + ).resolves.toMatchObject({ status, completed_by_account_id: null }); + expect(await prisma.auditLog.count()).toBe(0); + expect(await prisma.outbox.count()).toBe(0); + }, + ); + + it('없는 환불은 REFUND_NOT_FOUND, 메모 501자는 TEXT_TOO_LONG이다', async () => { + const adminId = await admin(); + const refund = await createRefund(prisma, { + status: 'AWAITING_TRANSFER', + }); + + await expect( + service.adminCompleteRefund(adminId, { refundId: '999999' }), + ).rejects.toThrowDomain('REFUND_NOT_FOUND'); + await expect( + service.adminCompleteRefund(adminId, { + refundId: refund.id.toString(), + note: 'x'.repeat(501), + }), + ).rejects.toThrowDomain('TEXT_TOO_LONG'); + }); + }); + + describe('adminCreateDepositReturn', () => { + it('취소 환불이 있는 주문에 연결하면 반환 환불이 공존하고 주문·결제·정산은 그대로다', async () => { + const adminId = await admin('김운영'); + const o = await order('CANCELED'); + await createPayment(prisma, { + order_id: o.id, + status: 'CONFIRMED', + confirmed_at: NOW, + }); + await prisma.order.update({ + where: { id: o.id }, + data: { + canceled_at: NOW, + settlement_base_amount: 10_000, + commission_amount: 500, + settlement_finalized_at: NOW, + }, + }); + const cancelRefund = await createRefund(prisma, { + order_id: o.id, + amount: 20_000, + }); + const orderBefore = await prisma.order.findUniqueOrThrow({ + where: { id: o.id }, + include: { payment: true }, + }); + + const result = await service.adminCreateDepositReturn(adminId, { + orderId: o.id.toString(), + amount: 30_000, + depositorName: ' 차차 ', + depositedAt: new Date('2026-09-16T06:50:00.000Z'), + note: '취소 뒤 입금', + }); + + expect(result).toMatchObject({ + kind: 'RETURN', + orderId: o.id.toString(), + orderNumber: o.order_number, + amount: 30_000, + depositorName: '차차', + depositedAt: new Date('2026-09-16T06:50:00.000Z'), + note: '취소 뒤 입금', + recordedByLabel: '김운영', + refundStatus: 'AWAITING_ACCOUNT', + createdAt: expect.any(Date), + }); + const refunds = await prisma.refund.findMany({ + where: { order_id: o.id }, + orderBy: { id: 'asc' }, + }); + expect(refunds).toEqual([ + expect.objectContaining({ id: cancelRefund.id, kind: 'CANCEL' }), + expect.objectContaining({ + id: BigInt(result.refundId!), + kind: 'DEPOSIT_RETURN', + amount: 30_000, + status: 'AWAITING_ACCOUNT', + deposit_record_id: BigInt(result.id), + requested_at: NOW, + }), + ]); + await expect( + prisma.order.findUniqueOrThrow({ + where: { id: o.id }, + include: { payment: true }, + }), + ).resolves.toEqual(orderBefore); + const [audit] = await prisma.auditLog.findMany(); + expect(audit).toMatchObject({ + target_type: 'DEPOSIT_RECORD', + target_id: BigInt(result.id), + action: 'CREATE', + store_id: null, + after_json: { + kind: 'RETURN', + orderId: o.id.toString(), + amount: 30_000, + }, + }); + const [requested] = await prisma.outbox.findMany(); + expect(requested).toMatchObject({ + event_type: REFUND_REQUESTED, + payload_json: { + refundId: result.refundId, + kind: 'DEPOSIT_RETURN', + amount: 30_000, + accountSubmitted: false, + }, + }); + + await drainOutbox(dispatcher); + await expect(prisma.notification.findMany()).resolves.toEqual([ + expect.objectContaining({ + account_id: o.account_id, + event: 'REFUND_ACCOUNT_REQUESTED', + body: `${o.order_number} 30,000원을 돌려받을 계좌를 입력해 주세요.`, + }), + ]); + }); + + it.each([ + 'PENDING_PAYMENT', + 'SUBMITTED', + 'CONFIRMED', + 'MADE', + 'PICKED_UP', + 'NO_SHOW', + ])('%s 주문에도 연결하고 상태는 바꾸지 않는다', async (status) => { + const adminId = await admin(); + const o = await order(status); + + await service.adminCreateDepositReturn(adminId, { + orderId: o.id.toString(), + amount: 1, + depositorName: '차차', + }); + + await expect( + prisma.order.findUniqueOrThrow({ where: { id: o.id } }), + ).resolves.toMatchObject({ status }); + expect(await prisma.refund.count()).toBe(1); + }); + + it('라벨을 만들 수 없는 관리자(이름·아이디 없음)도 기록하고 처리자 라벨은 null이다', async () => { + const adminId = await admin(null); + const o = await order(); + + const result = await service.adminCreateDepositReturn(adminId, { + orderId: o.id.toString(), + amount: 30_000, + depositorName: '차차', + }); + + expect(result).toMatchObject({ + recordedByLabel: null, + depositedAt: null, + }); + await expect( + prisma.depositRecord.findFirstOrThrow(), + ).resolves.toMatchObject({ + recorded_by_account_id: adminId, + recorded_by_label_snapshot: null, + }); + }); + + it.each([ + ['입금액 0', { amount: 0 }, 'DEPOSIT_AMOUNT_INVALID'], + ['입금액 음수', { amount: -1 }, 'DEPOSIT_AMOUNT_INVALID'], + ['입금자명 공백', { depositorName: ' ' }, 'TEXT_REQUIRED'], + ['입금자명 51자', { depositorName: '가'.repeat(51) }, 'TEXT_TOO_LONG'], + ['메모 501자', { note: 'x'.repeat(501) }, 'TEXT_TOO_LONG'], + ['없는 주문', { orderId: '999999' }, 'ORDER_NOT_FOUND'], + ] as const)('%s는 %s다', async (_label, override, code) => { + const adminId = await admin(); + const o = await order(); + + await expect( + service.adminCreateDepositReturn(adminId, { + orderId: o.id.toString(), + amount: 30_000, + depositorName: '차차', + ...override, + }), + ).rejects.toThrowDomain(code); + expect(await prisma.depositRecord.count()).toBe(0); + expect(await prisma.refund.count()).toBe(0); + }); + + it('삭제된 주문은 ORDER_NOT_FOUND다', async () => { + const adminId = await admin(); + const deleted = await createOrder(prisma, { deleted_at: NOW }); + + await expect( + service.adminCreateDepositReturn(adminId, { + orderId: deleted.id.toString(), + amount: 30_000, + depositorName: '차차', + }), + ).rejects.toThrowDomain('ORDER_NOT_FOUND'); + }); + }); + + describe('adminRecordUnidentifiedDeposit·adminLinkUnidentifiedDeposit', () => { + async function unidentified(adminId: bigint) { + return service.adminRecordUnidentifiedDeposit(adminId, { + amount: 45_000, + depositorName: '모르는분', + note: '입금자명·금액 일치 주문 없음', + }); + } + + it('주인 모를 입금은 환불·이벤트 없이 메모와 함께 종결 기록하고 감사를 남긴다', async () => { + const adminId = await admin('김운영'); + + const result = await unidentified(adminId); + + expect(result).toMatchObject({ + kind: 'UNIDENTIFIED', + orderId: null, + orderNumber: null, + amount: 45_000, + note: '입금자명·금액 일치 주문 없음', + recordedByLabel: '김운영', + refundId: null, + refundStatus: null, + }); + expect(await prisma.refund.count()).toBe(0); + expect(await prisma.outbox.count()).toBe(0); + await expect(prisma.auditLog.findFirstOrThrow()).resolves.toMatchObject({ + target_type: 'DEPOSIT_RECORD', + action: 'CREATE', + after_json: { kind: 'UNIDENTIFIED', orderId: null }, + }); + }); + + it.each([ + ['빈 문자열', ''], + ['공백', ' '], + ])('종결 메모가 %s면 DEPOSIT_NOTE_REQUIRED다', async (_label, note) => { + const adminId = await admin(); + + await expect( + service.adminRecordUnidentifiedDeposit(adminId, { + amount: 45_000, + depositorName: '모르는분', + note, + }), + ).rejects.toThrowDomain('DEPOSIT_NOTE_REQUIRED'); + expect(await prisma.depositRecord.count()).toBe(0); + }); + + it('주인을 찾으면 같은 기록을 반환으로 바꿔 주문에 잇고 입금액 전액 환불을 만든다', async () => { + const adminId = await admin(); + const o = await order('CANCELED'); + const record = await unidentified(adminId); + await prisma.auditLog.deleteMany(); + + const linked = await service.adminLinkUnidentifiedDeposit(adminId, { + depositRecordId: record.id, + orderId: o.id.toString(), + }); + + expect(linked).toMatchObject({ + id: record.id, + kind: 'RETURN', + orderId: o.id.toString(), + orderNumber: o.order_number, + amount: 45_000, + note: '입금자명·금액 일치 주문 없음', + refundStatus: 'AWAITING_ACCOUNT', + }); + expect(await prisma.depositRecord.count()).toBe(1); + await expect(prisma.refund.findFirstOrThrow()).resolves.toMatchObject({ + id: BigInt(linked.refundId!), + order_id: o.id, + kind: 'DEPOSIT_RETURN', + amount: 45_000, + deposit_record_id: BigInt(record.id), + }); + await expect(prisma.auditLog.findFirstOrThrow()).resolves.toMatchObject({ + action: 'UPDATE', + before_json: { kind: 'UNIDENTIFIED', orderId: null }, + after_json: { kind: 'RETURN', orderId: o.id.toString() }, + }); + await expect(prisma.outbox.findFirstOrThrow()).resolves.toMatchObject({ + event_type: REFUND_REQUESTED, + payload_json: { refundId: linked.refundId, kind: 'DEPOSIT_RETURN' }, + }); + }); + + it('이미 반환인 기록은 DEPOSIT_RECORD_ALREADY_LINKED, 없는 기록·주문은 NOT_FOUND다', async () => { + const adminId = await admin(); + const o = await order(); + const returned = await service.adminCreateDepositReturn(adminId, { + orderId: o.id.toString(), + amount: 30_000, + depositorName: '차차', + }); + const record = await unidentified(adminId); + + await expect( + service.adminLinkUnidentifiedDeposit(adminId, { + depositRecordId: returned.id, + orderId: o.id.toString(), + }), + ).rejects.toThrowDomain('DEPOSIT_RECORD_ALREADY_LINKED'); + await expect( + service.adminLinkUnidentifiedDeposit(adminId, { + depositRecordId: '999999', + orderId: o.id.toString(), + }), + ).rejects.toThrowDomain('DEPOSIT_RECORD_NOT_FOUND'); + await expect( + service.adminLinkUnidentifiedDeposit(adminId, { + depositRecordId: record.id, + orderId: '999999', + }), + ).rejects.toThrowDomain('ORDER_NOT_FOUND'); + expect(await prisma.refund.count()).toBe(1); + }); + }); + + describe('adminDepositRecords', () => { + it('kind를 null로 보내면 전체를 최근 기록부터, 같은 시각은 id 역순으로 넘긴다', async () => { + const adminId = await admin(); + const o = await order(); + const a = await service.adminCreateDepositReturn(adminId, { + orderId: o.id.toString(), + amount: 1_000, + depositorName: '가', + }); + const b = await service.adminRecordUnidentifiedDeposit(adminId, { + amount: 2_000, + depositorName: '나', + note: '메모', + }); + const c = await service.adminRecordUnidentifiedDeposit(adminId, { + amount: 3_000, + depositorName: '다', + note: '메모', + }); + // 같은 시각 둘 + 더 이른 하나 + await prisma.depositRecord.updateMany({ + where: { id: { in: [BigInt(b.id), BigInt(c.id)] } }, + data: { created_at: NOW }, + }); + await prisma.depositRecord.update({ + where: { id: BigInt(a.id) }, + data: { created_at: new Date(NOW.getTime() - 1) }, + }); + + const first = await service.adminDepositRecords(adminId, { + kind: null, + limit: 2, + }); + expect(first.items.map((i) => i.id)).toEqual([c.id, b.id]); + expect(first).toMatchObject({ totalCount: 3, hasMore: true }); + const second = await service.adminDepositRecords(adminId, { + limit: 2, + cursor: first.nextCursor!, + }); + expect(second.items.map((i) => i.id)).toEqual([a.id]); + expect(second.hasMore).toBe(false); + + const returns = await service.adminDepositRecords(adminId, { + kind: 'RETURN', + }); + expect(returns).toMatchObject({ totalCount: 1 }); + expect(returns.items[0]).toMatchObject({ + id: a.id, + refundId: expect.any(String), + }); + await expect( + service.adminDepositRecords(adminId, { cursor: '1' }), + ).rejects.toThrowDomain('INVALID_CURSOR'); + }); + }); +}); diff --git a/src/features/order/services/order-refund-admin.service.ts b/src/features/order/services/order-refund-admin.service.ts new file mode 100644 index 00000000..712dcace --- /dev/null +++ b/src/features/order/services/order-refund-admin.service.ts @@ -0,0 +1,230 @@ +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 type { CursorConnection } from '@/common/types/cursor-connection.type'; +import { parseId } from '@/common/utils/id-parser'; +import { + buildTimestampIdCursor, + parseIdCursor, + parseTimestampIdCursor, +} from '@/common/utils/keyset-cursor'; +import { + normalizeCursorInput, + sliceCursorPage, + sliceIdCursorPage, + toCursorConnection, +} from '@/common/utils/pagination'; +import { + cleanNullableText, + cleanRequiredText, +} from '@/common/utils/text-cleaner'; +import { + AUDIT_LOG_REPOSITORY, + type IAuditLogRepository, +} from '@/features/audit-log'; +import { AccountAdminRepository, AdminBaseService } from '@/features/auth'; +import type { AdminCompleteRefundInput } from '@/features/order/dto/inputs/admin-complete-refund.input'; +import type { AdminCreateDepositReturnInput } from '@/features/order/dto/inputs/admin-create-deposit-return.input'; +import type { AdminDepositRecordListInput } from '@/features/order/dto/inputs/admin-deposit-record-list.input'; +import type { AdminLinkUnidentifiedDepositInput } from '@/features/order/dto/inputs/admin-link-unidentified-deposit.input'; +import type { AdminRecordUnidentifiedDepositInput } from '@/features/order/dto/inputs/admin-record-unidentified-deposit.input'; +import type { AdminRefundListInput } from '@/features/order/dto/inputs/admin-refund-list.input'; +import { + DepositRecordRepository, + type DepositRecordInput, +} from '@/features/order/repositories/deposit-record.repository'; +import { RefundRepository } from '@/features/order/repositories/refund.repository'; +import { + toAdminDepositRecordOutput, + toAdminRefundDetailOutput, + toAdminRefundOutput, +} from '@/features/order/services/order-refund-mappers.helper'; +import type { + AdminDepositRecordOutput, + AdminRefundDetailOutput, + AdminRefundOutput, +} from '@/features/order/types/order-refund-output.type'; +import { AccountCipher } from '@/global/crypto/account-cipher.service'; + +/** 입금 기록의 입금자명은 은행 앱 표기 그대로라 결제 입금자명(20자)보다 길게 받는다. */ +const MAX_DEPOSITOR_NAME_LENGTH = 50; + +/** + * 관리자 환불 송금·입금 기록. 돌려줄 입금은 주문에 연결해 환불을 만들고, 주인 모를 입금은 메모로 종결한다. + * 환불 계좌번호 원문 복호화는 환불 상세(adminRefund)에서만 한다. + */ +@Injectable() +export class AdminRefundService extends AdminBaseService { + constructor( + accounts: AccountAdminRepository, + @Inject(AUDIT_LOG_REPOSITORY) + auditLogs: IAuditLogRepository, + private readonly refunds: RefundRepository, + private readonly depositRecords: DepositRecordRepository, + private readonly cipher: AccountCipher, + private readonly clock: ClockService, + ) { + super(accounts, auditLogs); + } + + async adminRefunds( + accountId: bigint, + input?: AdminRefundListInput, + ): Promise> { + await this.requireAdminContext(accountId); + // 관리자 FE는 '전체'를 null로 보낸다 — 생략과 같다 + const filter = { + status: input?.status ?? undefined, + kind: input?.kind ?? undefined, + }; + const { limit } = normalizeCursorInput({ limit: input?.limit }); + const cursor = input?.cursor; + const [rows, totalCount] = await Promise.all([ + this.refunds.listRefunds({ + ...filter, + limit, + ...(cursor == null ? {} : { cursor: parseIdCursor(cursor) }), + }), + this.refunds.countRefunds(filter), + ]); + return toCursorConnection( + sliceIdCursorPage(rows, limit), + totalCount, + toAdminRefundOutput, + ); + } + + async adminRefund( + accountId: bigint, + refundId: bigint, + ): Promise { + await this.requireAdminContext(accountId); + const row = await this.refunds.findAdminRefund(refundId); + if (!row) throw new DomainException('REFUND_NOT_FOUND'); + return toAdminRefundDetailOutput( + row, + row.account_number_enc + ? this.cipher.decrypt(row.account_number_enc, 'refund-account') + : null, + ); + } + + async adminCompleteRefund( + accountId: bigint, + input: AdminCompleteRefundInput, + ): Promise { + const ctx = await this.requireAdminContext(accountId); + const result = await this.refunds.complete({ + refundId: parseId(input.refundId), + actorAccountId: ctx.accountId, + actorLabel: ctx.displayLabel, + note: cleanNullableText(input.note, MAX_REASON_LENGTH), + now: this.clock.now(), + }); + if (result === 'not-found') throw new DomainException('REFUND_NOT_FOUND'); + if (result === 'completed') { + throw new DomainException('REFUND_ALREADY_COMPLETED'); + } + if (result === 'not-ready') throw new DomainException('REFUND_NOT_READY'); + return toAdminRefundOutput(result); + } + + async adminDepositRecords( + accountId: bigint, + input?: AdminDepositRecordListInput, + ): Promise> { + await this.requireAdminContext(accountId); + const kind = input?.kind ?? undefined; + const { limit } = normalizeCursorInput({ limit: input?.limit }); + const cursor = input?.cursor; + const [rows, totalCount] = await Promise.all([ + this.depositRecords.listDepositRecords({ + kind, + limit, + ...(cursor == null ? {} : { cursor: parseTimestampIdCursor(cursor) }), + }), + this.depositRecords.countDepositRecords(kind), + ]); + const page = sliceCursorPage(rows, limit, (last) => + buildTimestampIdCursor(last.created_at, last.id), + ); + return toCursorConnection(page, totalCount, toAdminDepositRecordOutput); + } + + /** 주문 상태와 관계없이 그 주문의 구매자에게 입금액 전액을 돌려준다(주문·결제·정산은 그대로). */ + async adminCreateDepositReturn( + accountId: bigint, + input: AdminCreateDepositReturnInput, + ): Promise { + const deposit = await this.depositInput(accountId, input); + const record = await this.depositRecords.createReturn({ + ...deposit, + orderId: parseId(input.orderId), + }); + if (!record) throw new DomainException('ORDER_NOT_FOUND'); + return toAdminDepositRecordOutput(record); + } + + async adminRecordUnidentifiedDeposit( + accountId: bigint, + input: AdminRecordUnidentifiedDepositInput, + ): Promise { + const deposit = await this.depositInput(accountId, input); + if (!deposit.note) throw new DomainException('DEPOSIT_NOTE_REQUIRED'); + return toAdminDepositRecordOutput( + await this.depositRecords.recordUnidentified(deposit), + ); + } + + async adminLinkUnidentifiedDeposit( + accountId: bigint, + input: AdminLinkUnidentifiedDepositInput, + ): Promise { + const ctx = await this.requireAdminContext(accountId); + const result = await this.depositRecords.linkToOrder({ + depositRecordId: parseId(input.depositRecordId), + orderId: parseId(input.orderId), + actorAccountId: ctx.accountId, + now: this.clock.now(), + }); + if (result === 'order-not-found') { + throw new DomainException('ORDER_NOT_FOUND'); + } + if (result === 'record-not-found') { + throw new DomainException('DEPOSIT_RECORD_NOT_FOUND'); + } + if (result === 'already-linked') { + throw new DomainException('DEPOSIT_RECORD_ALREADY_LINKED'); + } + return toAdminDepositRecordOutput(result); + } + + private async depositInput( + accountId: bigint, + input: { + amount: number; + depositorName: string; + depositedAt?: Date | null; + note?: string | null; + }, + ): Promise { + const ctx = await this.requireAdminContext(accountId); + if (!Number.isSafeInteger(input.amount) || input.amount < 1) { + throw new DomainException('DEPOSIT_AMOUNT_INVALID'); + } + return { + amount: input.amount, + depositorName: cleanRequiredText( + input.depositorName, + MAX_DEPOSITOR_NAME_LENGTH, + ), + depositedAt: input.depositedAt ?? null, + note: cleanNullableText(input.note, MAX_REASON_LENGTH), + actorAccountId: ctx.accountId, + actorLabel: ctx.displayLabel, + now: this.clock.now(), + }; + } +} diff --git a/src/features/order/services/order-refund-mappers.helper.ts b/src/features/order/services/order-refund-mappers.helper.ts new file mode 100644 index 00000000..a80726ea --- /dev/null +++ b/src/features/order/services/order-refund-mappers.helper.ts @@ -0,0 +1,57 @@ +import type { + AdminDepositRecordRow, + AdminRefundRow, +} from '@/features/order/repositories/refund.repository'; +import { toOrderRefund } from '@/features/order/services/order-output-mappers.helper'; +import type { + AdminDepositRecordOutput, + AdminRefundDetailOutput, + AdminRefundOutput, +} from '@/features/order/types/order-refund-output.type'; + +export function toAdminRefundOutput(row: AdminRefundRow): AdminRefundOutput { + const [firstItem] = row.order.items; + return { + ...toOrderRefund(row), + orderId: row.order_id.toString(), + orderNumber: row.order.order_number, + buyerName: row.order.buyer_name, + buyerPhone: row.order.buyer_phone, + storeName: firstItem?.store_name_snapshot ?? null, + productName: firstItem?.product_name_snapshot ?? null, + completedByLabel: row.completed_by_label_snapshot, + completeNote: row.complete_note, + }; +} + +export function toAdminRefundDetailOutput( + row: AdminRefundRow, + accountNumber: string | null, +): AdminRefundDetailOutput { + return { + refund: toAdminRefundOutput(row), + accountNumber, + depositRecord: row.deposit_record + ? toAdminDepositRecordOutput(row.deposit_record) + : null, + }; +} + +export function toAdminDepositRecordOutput( + row: AdminDepositRecordRow, +): AdminDepositRecordOutput { + return { + id: row.id.toString(), + kind: row.kind, + orderId: row.order_id?.toString() ?? null, + orderNumber: row.order?.order_number ?? null, + amount: row.amount, + depositorName: row.depositor_name, + depositedAt: row.deposited_at, + note: row.note, + recordedByLabel: row.recorded_by_label_snapshot, + refundId: row.refund?.id.toString() ?? null, + refundStatus: row.refund?.status ?? null, + createdAt: row.created_at, + }; +} diff --git a/src/features/order/types/order-my-output.type.ts b/src/features/order/types/order-my-output.type.ts index 15947eac..f85061cc 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, + OrderRefundOutput, OrderStatusHistoryOutput, } from '@/features/order/types/order-output.type'; import type { OrderPaymentOutput } from '@/features/order/types/order-payment-output.type'; @@ -67,6 +68,7 @@ export interface MyOrderDetail { canceledAt: Date | null; cancellation: OrderCancellationOutput | null; canCancel: boolean; + refunds: OrderRefundOutput[]; statusHistories: OrderStatusHistoryOutput[]; items: MyOrderItem[]; store: MyOrderStoreInfo; diff --git a/src/features/order/types/order-payment-output.type.ts b/src/features/order/types/order-payment-output.type.ts index cb8cfb26..f22e5fa7 100644 --- a/src/features/order/types/order-payment-output.type.ts +++ b/src/features/order/types/order-payment-output.type.ts @@ -69,4 +69,6 @@ export interface AdminPendingPaymentOutput { export interface AdminTaskCountsOutput { claimedPayments: number; pendingPayments: number; + refundsAwaitingAccount: number; + refundsAwaitingTransfer: number; } diff --git a/src/features/order/types/order-refund-output.type.ts b/src/features/order/types/order-refund-output.type.ts new file mode 100644 index 00000000..1c0a6d6c --- /dev/null +++ b/src/features/order/types/order-refund-output.type.ts @@ -0,0 +1,38 @@ +import type { OrderRefundOutput } from '@/features/order/types/order-output.type'; +import type { + DepositRecordKind, + RefundStatus, +} from '@/generated/prisma/client'; + +export interface AdminRefundOutput extends OrderRefundOutput { + orderId: string; + orderNumber: string; + buyerName: string; + buyerPhone: string; + storeName: string | null; + productName: string | null; + completedByLabel: string | null; + completeNote: string | null; +} + +export interface AdminDepositRecordOutput { + id: string; + kind: DepositRecordKind; + orderId: string | null; + orderNumber: string | null; + amount: number; + depositorName: string; + depositedAt: Date | null; + note: string | null; + recordedByLabel: string | null; + refundId: string | null; + refundStatus: RefundStatus | null; + createdAt: Date; +} + +export interface AdminRefundDetailOutput { + refund: AdminRefundOutput; + /** 원문. 관리자 상세에서만 복호화해 내려준다. 계좌 입력 전이면 null. */ + accountNumber: string | null; + depositRecord: AdminDepositRecordOutput | null; +} diff --git a/src/test/admin-query-null-inputs.spec.ts b/src/test/admin-query-null-inputs.spec.ts index 82f7c234..18ac484e 100644 --- a/src/test/admin-query-null-inputs.spec.ts +++ b/src/test/admin-query-null-inputs.spec.ts @@ -44,7 +44,7 @@ import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.bui // admin 접두 Query 전수에 nullable 필드를 전부 null로 채워 실제 앱(파이프·필터·가드·실DB)으로 보낸다. const FEATURES_DIR = join(__dirname, '..', 'features'); -const ADMIN_QUERY_COUNT = 18; +const ADMIN_QUERY_COUNT = 20; /** 필수 스칼라의 최소 유효값. 새 스칼라가 필수 필드로 오면 표에 없다고 던져 결정을 강제한다 */ const MINIMAL_SCALARS: Record = { diff --git a/src/test/enum-sdl-sync.spec.ts b/src/test/enum-sdl-sync.spec.ts index dbbf9cff..ea4e0df7 100644 --- a/src/test/enum-sdl-sync.spec.ts +++ b/src/test/enum-sdl-sync.spec.ts @@ -8,6 +8,7 @@ import { THREE_D_OPTION_CATEGORIES } from '@/features/product/constants/custom-3 import { ConversationBodyFormat, CustomImageKind, + DepositRecordKind, CustomMode, CustomTextAlign, NotificationEvent, @@ -82,6 +83,12 @@ const PAIRS: Array< 'src/features/order/order.types.graphql', 'RefundStatusType', ], + [ + 'DepositRecordKind', + Object.values(DepositRecordKind), + 'src/features/order/order-refund-admin.graphql', + 'DepositRecordKindType', + ], [ 'CustomMode', Object.values(CustomMode), diff --git a/src/test/factories/order.factory.ts b/src/test/factories/order.factory.ts index 89c91530..cc14a821 100644 --- a/src/test/factories/order.factory.ts +++ b/src/test/factories/order.factory.ts @@ -12,6 +12,9 @@ import type { PaymentStatus, Prisma, PrismaClient, + Refund, + RefundKind, + RefundStatus, } from '@/generated/prisma/client'; import { activeWhere } from '@/prisma'; import { createAccount } from '@/test/factories/account.factory'; @@ -145,6 +148,70 @@ export async function createPayment( }); } +export interface RefundOverrides { + /** 미지정 시 취소된 주문을 새로 만든다 */ + order_id?: bigint; + kind?: RefundKind; + status?: RefundStatus; + amount?: number; + requested_at?: Date; + /** 계좌가 있는 상태(송금 대기·완료)의 암호문. 미지정 시 복호화할 수 없는 자리표시 값 */ + account_number_enc?: string; +} + +/** + * 환불. 취소 환불은 cancel_order_id를, 입금 반환은 입금 기록(RETURN)을 함께 만든다. + * 송금 대기·완료면 계좌 칸을 채운다. + */ +export async function createRefund( + prisma: PrismaClient, + overrides: RefundOverrides = {}, +): Promise { + const order = overrides.order_id + ? await prisma.order.findUniqueOrThrow({ + where: { id: overrides.order_id }, + }) + : await createOrder(prisma, { status: 'CANCELED' }); + const kind = overrides.kind ?? 'CANCEL'; + const status = overrides.status ?? 'AWAITING_ACCOUNT'; + const amount = overrides.amount ?? order.total_price; + const requestedAt = overrides.requested_at ?? new Date(); + const record = + kind === 'DEPOSIT_RETURN' + ? await prisma.depositRecord.create({ + data: { + kind: 'RETURN', + order_id: order.id, + amount, + depositor_name: order.buyer_name.slice(0, 50), + recorded_by_account_id: order.account_id, + }, + }) + : null; + return prisma.refund.create({ + data: { + order_id: order.id, + kind, + cancel_order_id: kind === 'CANCEL' ? order.id : null, + deposit_record_id: record?.id ?? null, + amount, + status, + requested_at: requestedAt, + ...(status === 'AWAITING_ACCOUNT' + ? {} + : { + bank_code: '004', + account_holder: '환불받는이', + account_number_enc: + overrides.account_number_enc ?? 'v1.test.iv.tag.ct', + account_number_last4: '5678', + account_submitted_at: requestedAt, + }), + ...(status === 'COMPLETED' ? { completed_at: requestedAt } : {}), + }, + }); +} + export interface OrderItemOverrides { order_id?: bigint; store_id?: bigint; diff --git a/src/test/module-wiring.spec.ts b/src/test/module-wiring.spec.ts index 0be614ae..29c18305 100644 --- a/src/test/module-wiring.spec.ts +++ b/src/test/module-wiring.spec.ts @@ -5,6 +5,7 @@ import { Test } from '@nestjs/testing'; import { PubSub } from 'graphql-subscriptions'; import { AppModule } from '@/app.module'; +import { WithdrawalBlockingOrderQuery } from '@/common/ports/withdrawal-blocking-order.port'; import { PUB_SUB } from '@/global/pubsub'; import { PrismaService } from '@/prisma'; @@ -55,6 +56,7 @@ describe('모듈 배선 (AppModule compile)', () => { } // 역할 전수 — 어느 역할이든 모든 provider가 resolve되고, 역할에 없는 책임(GraphQL·크론)은 실리지 않는다. + // 지연 바인딩 포트(탈퇴 차단)는 compile이 잡지 못해 토큰이 실제로 resolve되는지 따로 본다. it.each([ ['api', true, false], ['ws', true, false], @@ -73,6 +75,7 @@ describe('모듈 배선 (AppModule compile)', () => { }; expect(has(GraphQLModule)).toBe(graphql); expect(has(SchedulerRegistry)).toBe(schedule); + expect(has(WithdrawalBlockingOrderQuery)).toBe(true); await module.close(); }, ); diff --git a/src/test/roles-coverage.spec.ts b/src/test/roles-coverage.spec.ts index 17c91e7b..32c93561 100644 --- a/src/test/roles-coverage.spec.ts +++ b/src/test/roles-coverage.spec.ts @@ -14,7 +14,7 @@ describe('접두 루트 필드 인가 커버리지', () => { describe.each([ ['seller', 'SELLER', 60], - ['admin', 'ADMIN', 67], + ['admin', 'ADMIN', 74], ] as const)('%s 접두 → @Roles(%s)', (prefix, role, count) => { const fields = collectRootFieldsWithPrefix(prefix);