Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BE] account 스키마 변경, user data 초기화 api #150

Merged
merged 2 commits into from
Nov 28, 2024
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: 2 additions & 0 deletions packages/server/src/account/account.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,6 @@ export class AccountController {
throw error;
}
}


}
3 changes: 3 additions & 0 deletions packages/server/src/account/account.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ export class Account {
@Column('double')
KRW: number;

@Column('double')
availableKRW: number;

@Column('double')
USDT: number;

Expand Down
7 changes: 4 additions & 3 deletions packages/server/src/account/account.module.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { Module } from '@nestjs/common';
import { Module, forwardRef } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Account } from './account.entity';
import { AccountRepository } from './account.repository';
import { User } from 'src/auth/user.entity';
import { AccountController } from './account.controller';
import { AccountService } from './account.service';
import { AssetRepository } from '@src/asset/asset.repository';

@Module({
imports: [TypeOrmModule.forFeature([Account, User])],
imports: [TypeOrmModule.forFeature([Account, User]),],
controllers: [AccountController],
providers: [AccountRepository, AccountService, AssetRepository],
})
export class AccountModule {}
export class AccountModule { }
4 changes: 4 additions & 0 deletions packages/server/src/account/account.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
HttpStatus,
Injectable,
Logger,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import { AssetRepository } from '@src/asset/asset.repository';
Expand All @@ -11,6 +12,7 @@ import { CURRENCY_CONSTANTS } from './constants/currency.constants';
import { AccountResponseDto, MyAccountResponseDto, UserDto } from './dtos/my-account.response.dto';
import { AccountRepository } from './account.repository';
import { Asset } from '@src/asset/asset.entity';
import { UserRepository } from '@src/auth/user.repository';

@Injectable()
export class AccountService {
Expand Down Expand Up @@ -47,13 +49,15 @@ export class AccountService {
totalPrice = this.calculateTotalPrice(coins);

accountData.KRW = account.KRW;
accountData.availableKRW = account.availableKRW;
accountData.total_bid = totalPrice;
accountData.coins = coins;

this.logger.log(`계정 데이터 조회 완료: ${user.userId}`);

return {
KRW: accountData.KRW,
availableKRW: accountData.availableKRW,
total_bid: accountData.total_bid,
coins: accountData.coins
};
Expand Down
3 changes: 3 additions & 0 deletions packages/server/src/account/dtos/my-account.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ export class MyAccountDto {
@IsNumber()
KRW: number;

@IsNumber()
availableKRW: number;

@IsNumber()
total_bid: number;

Expand Down
6 changes: 6 additions & 0 deletions packages/server/src/account/dtos/my-account.response.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ export class AccountResponseDto {
description: '계좌 잔액',
})
KRW: number;

@ApiProperty({
example: 2000000,
description: '매수가능한 계좌 잔액',
})
availableKRW: number;

@ApiProperty({
type: MyAccountDto,
Expand Down
11 changes: 6 additions & 5 deletions packages/server/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
Get,
HttpCode,
HttpStatus,
Logger,
Post,
Request,
Res,
Expand All @@ -25,7 +26,9 @@ import { FRONTEND_URL } from './constants';

@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}

private readonly logger = new Logger(AuthController.name);
constructor(private authService: AuthService) { }

@ApiBody({ type: SignInDto })
@HttpCode(HttpStatus.OK)
Expand All @@ -42,7 +45,7 @@ export class AuthController {

@Get('google')
@UseGuards(PassportAuthGuard('google'))
async googleLogin() {}
async googleLogin() { }

@Get('google/callback')
@UseGuards(PassportAuthGuard('google'))
Expand All @@ -53,7 +56,7 @@ export class AuthController {

@Get('kakao')
@UseGuards(PassportAuthGuard('kakao'))
async kakaoLogin() {}
async kakaoLogin() { }

@Get('kakao/callback')
@UseGuards(PassportAuthGuard('kakao'))
Expand Down Expand Up @@ -122,7 +125,6 @@ export class AuthController {
return this.authService.validateOAuthLogin(signUpDto);
}

// Helper method to redirect with tokens
private redirectWithTokens(res: any, tokens: any): void {
const redirectURL = new URL('/auth/callback', FRONTEND_URL);

Expand All @@ -131,5 +133,4 @@ export class AuthController {
res.redirect(redirectURL.toString());
}


}
17 changes: 13 additions & 4 deletions packages/server/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Module } from '@nestjs/common';
import { Module, forwardRef } from '@nestjs/common';
import { UserRepository } from './user.repository';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity';
Expand All @@ -11,26 +11,35 @@ import { AccountModule } from 'src/account/account.module';
import { KakaoStrategy } from './strategies/kakao.strategy';
import { GoogleStrategy } from './strategies/google.strategy';
import { PassportModule } from '@nestjs/passport';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { TradeModule } from '@src/trade/trade.module';
import { TradehistoryModule } from '@src/trade-history/trade-history.module';
import { AssetRepository } from '@src/asset/asset.repository';
import { AssetModule } from '@src/asset/asset.module';
@Module({
imports: [
TypeOrmModule.forFeature([User]),
TypeOrmModule.forFeature([User, UserRepository]),
JwtModule.register({
global: true,
secret: jwtConstants.secret,
signOptions: { expiresIn: '6000s' },
}),
AccountModule,
TradeModule,
TradehistoryModule,
PassportModule,
],
providers: [
UserRepository,
AccountRepository,
AuthService,
UserService,
JwtService,
GoogleStrategy,
KakaoStrategy,
],
controllers: [AuthController],
controllers: [AuthController, UserController],
exports: [UserRepository],
})
export class AuthModule {}
export class AuthModule { }
19 changes: 2 additions & 17 deletions packages/server/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ export class AuthService {
private accountRepository: AccountRepository,
private jwtService: JwtService,
private readonly redisRepository: RedisRepository,
) {
this.createAdminUser();
}
) {}

async signIn(
username: string,
Expand Down Expand Up @@ -120,20 +118,6 @@ export class AuthService {
return { message: 'User logged out successfully' };
}

async createAdminUser() {
const user = await this.userRepository.findOneBy({ username: 'admin' });

if (!user) {
const adminUser = new User();
adminUser.username = 'admin';
await this.userRepository.save(adminUser);
await this.accountRepository.createAccountForAdmin(adminUser);
this.logger.log('Admin user created successfully.');
} else {
this.logger.log('Admin user already exists.');
}
}

private async generateTokens(
userId: number,
username: string,
Expand Down Expand Up @@ -223,6 +207,7 @@ export class AuthService {
await this.accountRepository.save({
user,
KRW: DEFAULT_KRW,
availableKRW: DEFAULT_KRW,
USDT: DEFAULT_USDT,
BTC: DEFAULT_BTC,
});
Expand Down
52 changes: 52 additions & 0 deletions packages/server/src/auth/user.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {
Controller,
Delete,
HttpCode,
HttpStatus,
UseGuards,
Logger,
Request,
} from '@nestjs/common';
import { AuthGuard } from './auth.guard';
import { UserService } from './user.service';
import { ApiBearerAuth, ApiSecurity, ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';

@ApiTags('유저 API')
@Controller('user')
export class UserController {
private readonly logger = new Logger(UserController.name);

constructor(
private readonly userService: UserService,
) {}

@ApiOperation({
summary: '유저 데이터 초기화 및 새 계정 생성',
description: '유저의 계정, 에셋, 트레이드, 트레이드 히스토리를 삭제하고 새 계정을 생성합니다.',
})
@ApiResponse({
status: HttpStatus.OK,
description: '유저 데이터 초기화 성공 및 새 계정 생성 완료',
})
@ApiResponse({
status: HttpStatus.NOT_FOUND,
description: '유저를 찾을 수 없음',
})
@HttpCode(HttpStatus.OK)
@ApiBearerAuth('access-token')
@ApiSecurity('access-token')
@UseGuards(AuthGuard)
@Delete('reset')
async resetUserData(@Request() req): Promise<{ message: string }> {
this.logger.log(`유저 데이터 초기화 시작: User ID ${req.user.userId}`);
try {
await this.userService.resetUserData(req.user.userId);
this.logger.log(`유저 데이터 초기화 완료: User ID ${req.user.userId}`);
return { message: '유저 데이터 초기화 및 새 계정 생성이 완료되었습니다.' };
} catch (error) {
this.logger.error(`유저 데이터 초기화 실패: ${error.message}`, error.stack);
throw error;
}
}
}

62 changes: 62 additions & 0 deletions packages/server/src/auth/user.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { UserRepository } from './user.repository';
import { TradeRepository } from '../trade/trade.repository';
import { TradeHistoryRepository } from '../trade-history/trade-history.repository';
import { AccountRepository } from '@src/account/account.repository';
import { DEFAULT_BTC, DEFAULT_KRW, DEFAULT_USDT } from './constants';
import { DataSource } from 'typeorm';

@Injectable()
export class UserService {
private readonly logger = new Logger(UserService.name);

constructor(
private readonly userRepository: UserRepository,
private readonly tradeRepository: TradeRepository,
private readonly accountRepository: AccountRepository,
private readonly tradeHistoryRepository: TradeHistoryRepository,
private readonly dataSource: DataSource,
) { }

async resetUserData(userId: number): Promise<void> {
await this.dataSource.transaction(async (manager) => {
const user = await manager.findOne(this.userRepository.target, {
where: { id: userId },
relations: ['account'], // account 관계를 로드
});

if (!user) {
throw new NotFoundException(`User with ID ${userId} not found`);
}

this.logger.log(`유저 데이터 삭제 시작: User ID ${userId}`);

await manager.delete(this.tradeRepository.target, { user });

await manager.delete(this.tradeHistoryRepository.target, { user });

if (user.account) {
await manager.delete(this.accountRepository.target, { id: user.account.id });
user.account = null;
await manager.save(this.userRepository.target, user);
}
await manager.save(this.userRepository.target, user);

this.logger.log(`유저 데이터 삭제 완료: User ID ${userId}`);

this.logger.log(`새 어카운트 생성 시작: User ID ${userId}`);

const newAccount = manager.create(this.accountRepository.target, {
KRW: DEFAULT_KRW,
USDT: DEFAULT_USDT,
BTC: DEFAULT_BTC,
});

user.account = newAccount;

await manager.save(this.userRepository.target, user);

this.logger.log(`새 어카운트 생성 완료: User ID ${userId}`);
});
}
}
1 change: 1 addition & 0 deletions packages/server/src/trade-history/trade-history.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ import { UpbitModule } from '@src/upbit/upbit.module';
imports: [TypeOrmModule.forFeature([TradeHistory]), HttpModule, UpbitModule],
providers: [TradeHistoryRepository, TradeHistoryService],
controllers: [TradeHistoryController],
exports: [TradeHistoryRepository]
})
export class TradehistoryModule {}
11 changes: 11 additions & 0 deletions packages/server/src/trade/trade-ask.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,12 +291,23 @@ export class AskService extends TradeAskBidService implements OnModuleInit {
account[askDto.typeReceived] + buyData.price * buyData.quantity,
);

const availableChange = formatQuantity(
account.availableKRW + buyData.price * buyData.quantity,
);

await this.accountRepository.updateAccountCurrency(
askDto.typeReceived,
change,
account.id,
queryRunner,
);

await this.accountRepository.updateAccountCurrency(
'availableKRW',
availableChange,
account.id,
queryRunner,
);
}

private async waitForTransaction(
Expand Down
Loading