Implemented user transactions
This commit is contained in:
@ -1,4 +1,5 @@
|
||||
using IO.Swagger.Models.db;
|
||||
using IO.Swagger.Models.dto;
|
||||
using IO.Swagger.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
@ -8,6 +9,7 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace IO.Swagger.Repositories
|
||||
{
|
||||
|
||||
public class TransactionRepository : ITransactionRepository
|
||||
{
|
||||
BankDbContext context;
|
||||
@ -31,5 +33,48 @@ namespace IO.Swagger.Repositories
|
||||
t.Amount *= -1;
|
||||
return transactions;
|
||||
}
|
||||
|
||||
public async Task<List<Tuple<Currency, float>>> GetBalancesForUser(int userId)
|
||||
{
|
||||
var transactions = await context.Transactions.Where(t => t.ToUserId == userId || t.FromUserId == userId)
|
||||
.Include(t => t.Currency)
|
||||
.GroupBy(t => t.Currency)
|
||||
.Select(g => Tuple.Create(
|
||||
g.Key,
|
||||
g.Sum(t =>t.ToUserId != t.FromUserId && t.FromUserId == userId
|
||||
? -t.Amount
|
||||
: t.Amount
|
||||
)
|
||||
)
|
||||
)
|
||||
.ToListAsync();
|
||||
|
||||
return transactions;
|
||||
}
|
||||
|
||||
public async Task<TransactionReturnCode> TransferPhysical(WalletTransferPhysicalBody request, int fromUserId)
|
||||
{
|
||||
var trimmedDest = request.DestUserEmail.Trim().ToLower();
|
||||
var destUser = await context.Users.FirstOrDefaultAsync(u => u.Email == trimmedDest);
|
||||
if (destUser == null)
|
||||
return TransactionReturnCode.UnknownDestinationUser;
|
||||
|
||||
var balances = await GetBalancesForUser(fromUserId);
|
||||
var balance = balances.FirstOrDefault(b => b.Item1.CurrencyId == request.CurrencyId);
|
||||
if (balance == null || balance.Item2 < request.Amount)
|
||||
return TransactionReturnCode.InsufficientFunds;
|
||||
|
||||
|
||||
await context.Transactions.AddAsync(new Transaction
|
||||
{
|
||||
Amount = request.Amount,
|
||||
CurrencyId = request.CurrencyId,
|
||||
ToUserId = destUser.Id,
|
||||
FromUserId = fromUserId,
|
||||
Memo = request.Memo
|
||||
});
|
||||
return await context.SaveChangesAsync() > 0 ? TransactionReturnCode.Success : TransactionReturnCode.DbError;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user