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] dev merge 및 배포 #123

Merged
merged 13 commits into from
Nov 26, 2024
1 change: 0 additions & 1 deletion .github/workflows/CICD.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ on:
- main
- dev
- dev-be
- feature-be-#105
jobs:
build_and_deploy:
runs-on: ubuntu-latest
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"client": "yarn workspace client"
},
"devDependencies": {
"@types/winston": "^2.4.4",
"eslint": "^8.0.0",
"eslint-config-prettier": "^9.1.0",
"prettier": "^3.3.3",
Expand Down
3 changes: 3 additions & 0 deletions packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"ioredis": "^5.4.1",
"js-yaml": "^4.1.0",
"mysql2": "^3.11.3",
"nest-winston": "1.9.7",
"passport": "^0.7.0",
"passport-google-oauth20": "^2.0.0",
"passport-kakao": "^1.0.1",
Expand All @@ -50,6 +51,8 @@
"tunnel-ssh": "^5.1.2",
"typeorm": "^0.3.20",
"uuid": "^11.0.3",
"winston": "^3.17.0",
"winston-daily-rotate-file": "^5.0.0",
"ws": "^8.18.0"
},
"devDependencies": {
Expand Down
88 changes: 42 additions & 46 deletions packages/server/src/account/account.controller.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,48 @@
import {
Body,
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
Post,
Request,
Res,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '../auth/auth.guard';
import { AuthService } from '@src/auth/auth.service';
import {
ApiBody,
ApiBearerAuth,
ApiSecurity,
ApiResponse,
} from '@nestjs/swagger';
Body,
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
Post,
Request,
Res,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '../auth/auth.guard';
import { AuthService } from '@src/auth/auth.service';
import {
ApiBody,
ApiBearerAuth,
ApiSecurity,
ApiResponse,
} from '@nestjs/swagger';
import { AccountService } from './account.service';
import {Response} from "express";
import { Response } from 'express';

@Controller('account')
export class AccountController {
constructor(private accountService: AccountService) {}

@Controller('account')
export class AccountController {
constructor(private accountService: AccountService) {}

@HttpCode(HttpStatus.OK)
@ApiBearerAuth('access-token')
@ApiSecurity('access-token')
@UseGuards(AuthGuard)
@Get('myaccount')
async signIn(
@Request() req,
@Res() res: Response
) {
try{
const response = await this.accountService.getMyAccountData(req.user);
if (response instanceof UnauthorizedException) {
return res
.status(HttpStatus.UNAUTHORIZED)
.json({ message: response.message }); // UnauthorizedException 처리
}
@HttpCode(HttpStatus.OK)
@ApiBearerAuth('access-token')
@ApiSecurity('access-token')
@UseGuards(AuthGuard)
@Get('myaccount')
async signIn(@Request() req, @Res() res: Response) {
try {
const response = await this.accountService.getMyAccountData(req.user);
if (response instanceof UnauthorizedException) {
return res
.status(HttpStatus.UNAUTHORIZED)
.json({ message: response.message }); // UnauthorizedException 처리
}

return res.status(response.statusCode).json(response.message);
}catch(error){
return res.status(error.statusCode).json(error)
}
return res.status(response.statusCode).json(response.message);
} catch (error) {
return res.status(error.statusCode).json(error);
}
}
}
8 changes: 4 additions & 4 deletions packages/server/src/account/account.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ export class Account {
BTC: number;

@OneToOne(() => User, (user) => user.account, {
nullable: true,
onDelete: 'CASCADE',
})
@JoinColumn()
nullable: true,
onDelete: 'CASCADE',
})
@JoinColumn()
user: User;

@OneToMany(() => Asset, (asset) => asset.account, {
Expand Down
9 changes: 2 additions & 7 deletions packages/server/src/account/account.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,11 @@ import { Account } from './account.entity';
import { AccountRepository } from './account.repository';
import { User } from 'src/auth/user.entity';
import { AccountController } from './account.controller';
import { AuthService } from '@src/auth/auth.service';
import { AccountService } from './account.service';
import { AssetRepository } from '@src/asset/asset.repository';
@Module({
imports: [TypeOrmModule.forFeature([Account, User])],
controllers:[AccountController],
providers: [
AccountRepository,
AccountService,
AssetRepository
],
controllers: [AccountController],
providers: [AccountRepository, AccountService, AssetRepository],
})
export class AccountModule {}
83 changes: 44 additions & 39 deletions packages/server/src/account/account.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,48 +5,53 @@ import { User } from 'src/auth/user.entity';

@Injectable()
export class AccountRepository extends Repository<Account> {
constructor(private dataSource: DataSource) {
super(Account, dataSource.createEntityManager());
}
async createAccountForAdmin(adminUser: User) {
const account = new Account();
account.KRW = 300000000;
account.USDT = 300000;
account.BTC = 0;
account.user = adminUser;
await this.save(account);
console.log('admin 계정에 Account가 성공적으로 생성되었습니다.');
}
async getMyMoney(user, moneyType: string) {
const account = await this.findOne({
where: { user: { id: user.userId } },
});
constructor(private dataSource: DataSource) {
super(Account, dataSource.createEntityManager());
}
async createAccountForAdmin(adminUser: User) {
const account = new Account();
account.KRW = 300000000;
account.USDT = 300000;
account.BTC = 0;
account.user = adminUser;
await this.save(account);
console.log('admin 계정에 Account가 성공적으로 생성되었습니다.');
}
async getMyMoney(user, moneyType: string) {
const account = await this.findOne({
where: { user: { id: user.userId } },
});

if (!account[moneyType]) return 0;
return account[moneyType];
}
async updateAccountCurrency(typeGiven, accountBalance, accountId, queryRunner) {
try{
await queryRunner.manager
.createQueryBuilder()
.update(Account)
.set({
[typeGiven]: accountBalance,
})
.where('id = :id', { id: accountId })
.execute();
}catch(error){
console.log(error)
}
}
async updateAccountBTC(id, quantity, queryRunner){
await queryRunner.manager
if (!account[moneyType]) return 0;
return account[moneyType];
}
async updateAccountCurrency(
typeGiven,
accountBalance,
accountId,
queryRunner,
) {
try {
await queryRunner.manager
.createQueryBuilder()
.update(Account)
.set({
BTC: quantity,
.set({
[typeGiven]: accountBalance,
})
.where('id = :id', { id: id })
.where('id = :id', { id: accountId })
.execute();
}
} catch (error) {
console.log(error);
}
}
async updateAccountBTC(id, quantity, queryRunner) {
await queryRunner.manager
.createQueryBuilder()
.update(Account)
.set({
BTC: quantity,
})
.where('id = :id', { id: id })
.execute();
}
}
97 changes: 50 additions & 47 deletions packages/server/src/account/account.service.ts
Original file line number Diff line number Diff line change
@@ -1,58 +1,61 @@
import { Injectable, OnModuleInit, UnauthorizedException } from '@nestjs/common';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AssetRepository } from '@src/asset/asset.repository';
import { UPBIT_IMAGE_URL } from 'common/upbit';
import { UPBIT_IMAGE_URL } from '@src/upbit/constants';
import { AccountRepository } from 'src/account/account.repository';
import { MyAccountDto } from './dtos/myAccount.dto';
import { CoinDataUpdaterService } from '@src/upbit/coin-data-updater.service';


@Injectable()
export class AccountService {
constructor(
private accountRepository : AccountRepository,
private assetRepository: AssetRepository,
private coinDataUpdaterService : CoinDataUpdaterService
) {}
constructor(
private accountRepository: AccountRepository,
private assetRepository: AssetRepository,
private coinDataUpdaterService: CoinDataUpdaterService,
) {}

async getMyAccountData(user){
const accountData: MyAccountDto = new MyAccountDto();
async getMyAccountData(user) {
const accountData: MyAccountDto = new MyAccountDto();

const account = await this.accountRepository.findOne({
where: {user:{id:user.userId}}
})
if(!account){
return new UnauthorizedException({
statusCode: 401,
message: "등록되지 않은 사용자입니다."
})
}
const KRW = account.KRW;
let total_price = 0;

const myCoins = await this.assetRepository.find({
where: { account: { id : account.id } }
})
const coinNameData = this.coinDataUpdaterService.getCoinNameList();
const coins = [];
myCoins.forEach((myCoin)=>{
const name = myCoin.assetName
const coin = {
img_url : `${UPBIT_IMAGE_URL}${name}.png`,
koreanName: coinNameData.get(`KRW-${name}`)||coinNameData.get(`BTC-${name}`)||coinNameData.get(`USDT-${name}`),
market: name,
quantity: myCoin.quantity,
price : myCoin.price,
averagePrice : myCoin.price / myCoin.quantity
};
coins.push(coin)
total_price+=myCoin.price
})
accountData.KRW = KRW;
accountData.total_bid = total_price;
accountData.coins = coins;
return {
statusCode: 200,
message: accountData
};
const account = await this.accountRepository.findOne({
where: { user: { id: user.userId } },
});
if (!account) {
return new UnauthorizedException({
statusCode: 401,
message: '등록되지 않은 사용자입니다.',
});
}
const KRW = account.KRW;
let total_price = 0;

const myCoins = await this.assetRepository.find({
where: { account: { id: account.id } },
});
const coinNameData = this.coinDataUpdaterService.getCoinNameList();
const coins = [];
myCoins.forEach((myCoin) => {
const name = myCoin.assetName;
const coin = {
img_url: `${UPBIT_IMAGE_URL}${name}.png`,
koreanName:
coinNameData.get(`KRW-${name}`) ||
coinNameData.get(`BTC-${name}`) ||
coinNameData.get(`USDT-${name}`),
market: name,
quantity: myCoin.quantity,
availableQuantity: myCoin.availableQuantity,
price: myCoin.price,
averagePrice: myCoin.price / myCoin.quantity,
};
coins.push(coin);
total_price += myCoin.price;
});
accountData.KRW = KRW;
accountData.total_bid = total_price;
accountData.coins = coins;
return {
statusCode: 200,
message: accountData,
};
}
}
9 changes: 7 additions & 2 deletions packages/server/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@ import { RedisModule } from './redis/redis.module';
import { ScheduleModule as NestScheduleModule } from '@nestjs/schedule';
import { ScheduleModule } from './schedule/schedule.module';
import { TradehistoryModule } from './trade-history/trade-history.module';
import { FavoriteModule } from './favorite/favorite.module';
import { winstonConfig } from './configs/winston.config';
import { WinstonModule } from 'nest-winston';

@Module({
imports: [
AuthModule,
imports: [
AuthModule,
HealthModule,
AccountModule,
TradeModule,
Expand All @@ -29,6 +32,8 @@ import { TradehistoryModule } from './trade-history/trade-history.module';
NestScheduleModule.forRoot(),
ScheduleModule,
TradehistoryModule,
FavoriteModule,
WinstonModule.forRoot(winstonConfig),
],
controllers: [AppController],
providers: [AppService],
Expand Down
3 changes: 3 additions & 0 deletions packages/server/src/asset/asset.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ export class Asset {
@Column('double')
quantity: number;

@Column('double')
availableQuantity: number;

@CreateDateColumn({ type: 'timestamp' })
created: Date;

Expand Down
Loading
Loading