From bbde4a2ec5824ef920943c5732bf9ec0440f2233 Mon Sep 17 00:00:00 2001 From: Kevsl Date: Fri, 14 Jun 2024 12:07:26 +0200 Subject: [PATCH] added token sell to bank --- src/crypto/crypto.service.ts | 43 ++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/crypto/crypto.service.ts b/src/crypto/crypto.service.ts index 07baabe..62ae643 100644 --- a/src/crypto/crypto.service.ts +++ b/src/crypto/crypto.service.ts @@ -51,6 +51,48 @@ export class CryptoService { } } + async sellCryto(userId: string, dto: BuyCryptoDto) { + await checkUserHasAccount(userId); + + const crypto = await this.prisma.crypto.findFirst({ + where: { + id: dto.id_crypto, + }, + }); + + if (!crypto || !crypto.id) { + throw new ForbiddenException('Crypto doesnt exist'); + } + + const userAsset = await this.prisma.userHasCrypto.findFirst({ + where: { + id_user: userId, + id_crypto: dto.id_crypto, + }, + }); + if (!userAsset || userAsset.amount < dto.amount) { + throw new ForbiddenException(`Seller dont have enough asset`); + } else { + const newBalance = userAsset.amount - dto.amount; + if (newBalance > 0) { + await this.prisma.userHasCrypto.update({ + where: { + id: userAsset.id, + }, + data: { + amount: newBalance, + }, + }); + } else { + await this.prisma.userHasCrypto.delete({ + where: { + id: userAsset.id, + }, + }); + } + } + } + async createCrypto(userId: string, dto: CryptoDto) { await checkuserIsAdmin(userId); @@ -151,6 +193,7 @@ export class CryptoService { }, }); } + async editCryptoById(userId: string, cryptoId: string, dto: CryptoDto) { await checkuserIsAdmin(userId);