Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/guide/architecture-conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
1 change: 1 addition & 0 deletions src/common/errors/error-catalog.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
Expand Down
31 changes: 30 additions & 1 deletion src/common/errors/error-catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -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: '중복된 옵션 선택입니다.',
Expand Down Expand Up @@ -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,
Expand Down
9 changes: 9 additions & 0 deletions src/common/ports/withdrawal-blocking-order.port.ts
Original file line number Diff line number Diff line change
@@ -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<number>;
}
3 changes: 2 additions & 1 deletion src/features/auth/auth-user-profile.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ extend type Mutation {
"""
updateMyProfileImage(input: UpdateMyProfileImageInput!): MePayload!
"""
회원 탈퇴(soft delete). 로그인 필수. 본인 데이터만 대상이 된다.
회원 탈퇴(soft delete). 진행 중인 주문(입금 대기~제작 완료)이나 송금이 끝나지 않은 환불(계좌 입력 대기·송금 대기)이 있으면
ACCOUNT_HAS_ACTIVE_ORDERS(CONFLICT, 메시지에 건수). 로그인 필수. 본인 데이터만 대상이 된다.
"""
deleteMyAccount: Boolean!
"""
Expand Down
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -34,6 +36,10 @@ describe('User Profile Resolvers (real DB)', () => {
NOOP_BLACKLIST_PROVIDER,
AccountUserRepository,
{ provide: S3Service, useValue: s3Service },
{
provide: WithdrawalBlockingOrderQuery,
useClass: OrderWithdrawalBlockingRepository,
},
],
});

Expand Down
96 changes: 95 additions & 1 deletion src/features/auth/services/auth-user-profile.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
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';
import { closeTruncateConnection, truncateAll } from '@/test/db/truncate';
import {
createAccount,
createAccountIdentity,
createOrder,
createRefund,
createUserProfile,
} from '@/test/factories';
import { createTestingModuleWithRealDb } from '@/test/modules/testing-module.builder';
Expand Down Expand Up @@ -35,6 +39,11 @@ describe('UserProfileService (real DB)', () => {
{ provide: TokenBlacklistService, useValue: blacklist },
AccountUserRepository,
{ provide: S3Service, useValue: s3Service },
// 앱에서는 OrderModule이 제공하고 서비스가 ModuleRef로 찾는다
{
provide: WithdrawalBlockingOrderQuery,
useClass: OrderWithdrawalBlockingRepository,
},
],
});

Expand Down Expand Up @@ -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);
});
});
});
21 changes: 21 additions & 0 deletions src/features/auth/services/auth-user-profile.service.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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);
}
Expand Down Expand Up @@ -190,8 +195,15 @@ export class UserProfileService extends UserBaseService {
});
}

/** 진행 중 주문이나 송금이 끝나지 않은 환불이 있으면 거절한다 — 탈퇴하면 환불 계좌를 받을 수 없다. */
async deleteMyAccount(accountId: bigint): Promise<boolean> {
await this.requireActiveUser(accountId);
const blocking = await this.withdrawalBlocking().countByBuyer(accountId);
if (blocking > 0) {
Comment on lines +201 to +202

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Serialize the withdrawal check with refund creation

If an administrator creates a deposit return for a canceled order after countByBuyer() returns zero but before softDeleteAccount() commits, withdrawal still succeeds with an unfinished refund. DepositRecordRepository.createReturn() and linkToOrder() lock only the order, while account deletion runs in a separate transaction, so nothing prevents this interleaving. The buyer's sessions are then revoked, leaving an AWAITING_ACCOUNT refund whose account they can no longer submit. Coordinate the check and deletion with refund creation through a shared lock and transaction protocol; merely counting before deletion does not enforce the new withdrawal restriction.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

미반영(기록): 유효함. 막으려면 탈퇴 tx(계정 FOR UPDATE + 잠금 읽기 건수)와 입금 반환 생성(계정 FOR SHARE)이 같은 계정 행을 잠그는 auth·order 공용 잠금 프로토콜이 필요해 이 PR 범위를 넘는 새 장치. 관리자 수동 작업과 구매자 탈퇴가 같은 순간 겹쳐야 생기는 경합이라 후속 #582(탈퇴 검사 직렬화 항목)으로 넘김.

throw new DomainException('ACCOUNT_HAS_ACTIVE_ORDERS', {
count: blocking,
});
}

const now = new Date();
const deletedNickname = `deleted_${accountId.toString()}`;
Expand All @@ -206,4 +218,13 @@ export class UserProfileService extends UserBaseService {

return true;
}

/** OrderModule이 auth를 import해 반대 방향 import는 순환이다 — 첫 호출 때 컨테이너 전체에서 찾는다. */
private withdrawalBlocking(): WithdrawalBlockingOrderQuery {
this.blockingOrders ??= this.moduleRef.get<WithdrawalBlockingOrderQuery>(
WithdrawalBlockingOrderQuery,
{ strict: false },
);
return this.blockingOrders;
}
}
2 changes: 2 additions & 0 deletions src/features/notification/constants/notification-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ export const ORDER_PAYMENT_EXPIRED_NOTIFICATION = {

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

export const REFUND_COMPLETED_TITLE = '환불완료';

export const REVIEW_LIKED_NOTIFICATION = {
title: '리뷰 좋아요',
body: '다른 사람이 내가 남긴 리뷰를 좋아했어요.',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
Loading
Loading