Skip to content

Commit

Permalink
Merge pull request #61 from plus-tdd/hotfix/alarm
Browse files Browse the repository at this point in the history
Hotfix/alarm
  • Loading branch information
codesejin authored Jul 26, 2023
2 parents ec985a4 + a2b5426 commit 2585580
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 20 deletions.
17 changes: 13 additions & 4 deletions src/module/payment/api/payment.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
import { Body, Controller, Get, Post, Param, UseGuards } from '@nestjs/common';
import { PaymentService } from '../domain/payment.service';
import { PaymentInfo, PaymentInfoForRefund } from '../domain/payment.model';
import { ApiOperation } from '@nestjs/swagger';
Expand All @@ -8,7 +8,7 @@ import { Payment } from '../domain/payment.model';
import { RefundPaymentInfo } from '../domain/payment.model';
import { JwtAuthGuard } from "../../auth/auth.jwtAuthGuard";
import Logger from 'src/logger';
//@UseGuards(AuthGuard)
@UseGuards(JwtAuthGuard)
@Controller('/payment')
export class PaymentController {

Expand All @@ -18,7 +18,6 @@ export class PaymentController {
this.logger = new Logger('PaymentController')
}

@UseGuards(JwtAuthGuard)
@ApiOperation({summary : '결제하기'})
@Post()
async makePayment(@Body() paymentData: PaymentRequestDto): Promise<Payment> {
Expand All @@ -44,12 +43,22 @@ export class PaymentController {
return await this.paymentService.makePayment(paymentInfo)
}

@UseGuards(JwtAuthGuard)
@ApiOperation({summary : '유저별 결제 목록 조회하기(환불된 것 제외)'})
@Get(':userId')
async getPaymenList(@Param('userId') userId: number): Promise<Payment[]> {

this.logger.info('request userId', userId)
return await this.paymentService.getPaymenList(userId)
}


@ApiOperation({summary : '결제 취소하기'})
@Post('/refund')
refundPayment(@Body() refundData: RefundPaymentRequestDto): Promise<PaymentInfoForRefund> {
const { paymentId, userId} = refundData;

this.logger.info('request userId', refundData.userId)
this.logger.info('request paymentId',refundData.paymentId)
// dto - > model
const refundInfo: RefundPaymentInfo = {
paymentId: paymentId,
Expand Down
54 changes: 43 additions & 11 deletions src/module/payment/data/payment.db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
import { PaymentInfo, Payment } from '../domain/payment.model';
import { PaymentEntity } from './payment.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Repository, FindOperator } from 'typeorm';
import { InvalidPaymentInfoException } from '../payment.error';
import { UserEntity } from 'src/module/user/data/user.entity';
import { AlarmService } from 'src/module/alarm/alarm.service';
Expand All @@ -28,6 +28,9 @@ export class PaymentRepositoryImpl implements PaymentRepository {
) {
this.logger = new Logger('PaymentRepositoryImpl');
}


// 결제 저장하기
async savePayment(paymentInfo: PaymentInfo): Promise<Payment> {
try {
// user가 db에 존재하는지??
Expand Down Expand Up @@ -83,19 +86,46 @@ export class PaymentRepositoryImpl implements PaymentRepository {
throw error; // 예외를 다시 던져서 호출한 쪽에서 처리할 수 있도록 함
}
}
async refundPayment(
refundInfo: RefundPaymentInfo,
): Promise<PaymentInfoForRefund> {

// 유저pk로 결제 목록 조회
async findPaymentsByUserId(userId: number): Promise<Payment[]> {
const payments = await this.PaymentDB
.createQueryBuilder('payment')
.innerJoinAndSelect('payment.User', 'user')
.where('user.id = :userId', { userId })
.andWhere('payment.is_refund <> :isRefund', { isRefund: true }) // is_refund가 1이 아닌 조건 추가
.getMany();

// PaymentEntity와 매핑된 Payment 객체를 생성하여 배열로 변환
const paymentList: Payment[] = payments.map((paymentEntity) => ({
paymentId: paymentEntity.id,
userId: paymentEntity.User.id,
cardNum: paymentEntity.cardNum,
endDate: paymentEntity.endDate,
cvc: paymentEntity.cvc,
cardCompany: paymentEntity.cardCompany,
price: paymentEntity.price,
}));

return paymentList;
}

// 환불하기
async refundPayment(refundInfo: RefundPaymentInfo): Promise<PaymentInfoForRefund> {

// 요청에 들어온 paymentId가 db에 존재하는지?
const payment = await this.PaymentDB.findOne({
where: { id: refundInfo.paymentId },
});
if (payment === null) throw new InvalidPaymentInfoException('결제 PK');
// user가 db에 존재하는지??
const user = await this.UserDB.findOne({
where: { id: refundInfo.userId },
where: { id: refundInfo.paymentId, User: { id: refundInfo.userId } },
relations: ['User'],
});
if (user === null) throw new InvalidPaymentInfoException('유저');

if (payment === null) throw new InvalidPaymentInfoException('결제PK와 유저PK');

// 이미 환불 처리된 결제인지 확인
if (payment.isRefund) {
throw new InvalidPaymentInfoException('요청이며, 이미 환불 처리된 결제');
}

// 소프트 딜리트 - 환불 처리됨
payment.isRefund = true; // 원하는 칼럼을 true로 변경
await this.PaymentDB.save(payment); // 변경 내용을 저장
Expand All @@ -110,11 +140,13 @@ export class PaymentRepositoryImpl implements PaymentRepository {
};
return refundPaymentDomain;
}

async findUserPhoneNumber(userId: number): Promise<string> {
// user가 db에 존재하는지??
const user = await this.UserDB.findOne({
where: { id: userId },
});

if (user === null) throw new InvalidPaymentInfoException('유저');
return user.phoneNumber;
}
Expand Down
2 changes: 1 addition & 1 deletion src/module/payment/data/payment.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class PaymentEntity {
User: UserEntity | null; // nullable로 변경
//@JoinColumn([{ name: 'userId', referencedColumnName: 'id' }])

@Column('int', { name: 'card_num', nullable: true })
@Column('bigint', { name: 'card_num', nullable: true })
cardNum: number;

@Column('varchar', { name: 'end_date', length: 45, nullable: true })
Expand Down
27 changes: 27 additions & 0 deletions src/module/payment/domain/payment.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export interface PaymentRepository {
savePayment(paymentInfo: PaymentInfo): Promise<Payment>;
refundPayment(paymentInfo: RefundPaymentInfo): Promise<PaymentInfoForRefund>;
findUserPhoneNumber(userId: number): Promise<string>;
findPaymentsByUserId(userId: number): Promise<Payment[]>;
}

// 테스트용
Expand All @@ -27,6 +28,32 @@ export class TestPaymentRepository implements PaymentRepository {
};
}

async findPaymentsByUserId(userId: number): Promise<Payment[]> {
// 테스트용 가짜 데이터 생성
const fakeData: Payment[] = [
{
paymentId: 1,
userId: userId,
cardNum: 1234,
endDate: '2307',
cvc: 567,
cardCompany: 'hyundai',
price: 1000,
},
{
paymentId: 2,
userId: userId,
cardNum: 5678,
endDate: '2308',
cvc: 789,
cardCompany: 'shinhan',
price: 2000,
}
];

return fakeData;
}

async refundPayment(
paymentInfo: RefundPaymentInfo,
): Promise<PaymentInfoForRefund> {
Expand Down
14 changes: 10 additions & 4 deletions src/module/payment/domain/payment.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class PaymentService {
}

public async makePayment(paymentInfo: PaymentInfo): Promise<Payment> {
this.validatePaymentInfo(paymentInfo);
await this.validatePaymentInfo(paymentInfo);
// DB작업 - 결제 정보 저장
const savePaymentInfo = await this.repository.savePayment(paymentInfo);

Expand All @@ -39,7 +39,7 @@ export class PaymentService {
const userPhoneNumber = await this.repository.findUserPhoneNumber(
paymentInfo.userId,
);
const message = '결제가 완료되었습니다';
let message = '결제가 완료되었습니다';

const alarmData: AlarmData = {
recipient: userPhoneNumber,
Expand All @@ -51,6 +51,12 @@ export class PaymentService {
return savePaymentInfo;
}

public async getPaymenList(userId: number): Promise<Payment[]> {

const paymentList: Payment[] = await this.repository.findPaymentsByUserId(userId);
return paymentList;
}

public async refundPayment(
refundInfo: RefundPaymentInfo,
): Promise<PaymentInfoForRefund> {
Expand All @@ -65,7 +71,7 @@ export class PaymentService {
refundInfo.userId,
);

const message = '결제가 취소되었습니다';
let message = '결제가 취소되었습니다';

const alarmData: AlarmData = {
recipient: userPhoneNumber,
Expand Down Expand Up @@ -145,4 +151,4 @@ export class PaymentService {
}
return true;
}
}
}

0 comments on commit 2585580

Please sign in to comment.