public BalanceChangeTests()
        {
            this.address  = TestAddress.Mainnet1;
            this.amount   = new PropertyAmount(10);
            this.property = new PropertyId(2);

            this.subject = new BalanceChange(address, amount, property);
        }
Example #2
0
 public void WithdrawMoney(decimal amount)
 {
     if (amount <= Money)
     {
         Money -= amount;
         BalanceChange?.Invoke(this, new BalanceChangedArg(Action.Withdraw, amount));
     }
 }
 public string SerializeTransaction(BalanceChange trans)
 {
     return(string.Format("INSERT INTO BALANCE_CHANGE (AccountID, ChangeType, Amount, ValueDate, Description)" +
                          "VALUES ({0}, {1}, {2}, '{3}', '{4}')",
                          trans.AccountID,
                          (int)trans.ChangeType,
                          trans.Amount,
                          trans.ValueDate.ToString("yyyyMMdd HH:mm"),
                          trans.Description));
 }
Example #4
0
        public RequestStatus ChangeBalance(int accountId, decimal summ, string comment, DateTime date, BalanceChangeType changeType)
        {
            if (summ == 0)
            {
                return(RequestStatus.BadRequest);
            }
            // корректировать знак
            summ = BalanceChange.CorrectSign(summ, changeType);

            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    ACCOUNT acc;
                    try
                    {
                        acc = (from a in ctx.ACCOUNT
                               where a.ID == accountId
                               select a).First();
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("Ошибка получения счета для редактирования {0}: {1}", accountId, ex);
                        return(RequestStatus.ServerError);
                    }

                    var bc = new BALANCE_CHANGE
                    {
                        AccountID   = accountId,
                        ValueDate   = date,
                        Amount      = summ,
                        ChangeType  = (int)changeType,
                        Description = comment
                    };
                    try
                    {
                        acc.Balance = acc.Balance + summ;
                        ctx.BALANCE_CHANGE.Add(bc);
                        ctx.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("Ошибка изменения баланса счета {0}: {1}", accountId, ex);
                        return(RequestStatus.ServerError);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в ChangeBalance", ex);
                return(RequestStatus.ServerError);
            }
            return(RequestStatus.OK);
        }
        public void Construct_WithValidArgs_ShouldSuccess()
        {
            // Arrange.
            var address  = TestAddress.Mainnet1;
            var amount   = new PropertyAmount(10);
            var property = new PropertyId(2);

            // Act.
            var c = new BalanceChange(address, amount, property);

            // Assert.
            Assert.Equal(address, c.Address);
            Assert.Equal(amount, c.Amount);
            Assert.Equal(property, c.Property);
        }
Example #6
0
        public async Task <int> Handle(UserUpdateBalanceCommand request, CancellationToken cancellationToken)
        {
            if (request.Amount <= 0)
            {
                throw new Exception("Amount must be greater than 0.");
            }

            var user = await _db.Users.FirstOrDefaultAsync(w => w.Id == request.UserId, cancellationToken);

            if (user == null)
            {
                throw new UserNotFoundException(request.UserId);
            }

            var balanceChange = new BalanceChange
            {
                OldBalance = user.Balance
            };

            switch (request.Type)
            {
            case AddRemove.Add:
                user.Balance += request.Amount;
                break;

            case AddRemove.Remove:
                user.Balance -= request.Amount;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            balanceChange.NewBalance  = user.Balance;
            balanceChange.UserId      = user.Id;
            balanceChange.Timestamp   = DateTimeOffset.UtcNow;
            balanceChange.AdminUserId = request.AdminUserId;
            balanceChange.OrderId     = request.OrderId;
            balanceChange.Reason      = request.Reason;

            _db.Users.Update(user);
            _db.BalanceChanges.Add(balanceChange);
            await _db.SaveChangesAsync(cancellationToken);

            await _mediator.Send(new UpdateUserCacheCommand(user.Username), cancellationToken);

            return(user.Balance);
        }
        private async Task OnBatch(List <MongoBalanceChange> list)
        {
            var legacyIds = list.Select(w => w._id.ToString()).ToList();

            var legacyUserIds  = list.Select(w => Guid.Parse(w.UserId)).ToList();
            var legacyAdminIds = list.Where(w => w.AdminUserId != null).Select(w => Guid.Parse(w.AdminUserId)).ToList();

            var users = await _db.Users.AsQueryable().Where(w => legacyUserIds.Contains(w.LegacyId)).ToListAsync();

            var usersDict = users.ToDictionary(w => w.LegacyId, w => w);

            var admins = await _db.Users.AsQueryable().Where(w => legacyAdminIds.Contains(w.LegacyId)).ToListAsync();

            var adminsDict = admins.ToDictionary(w => w.LegacyId, w => w);

            var existing = await _db.BalanceChanges.AsQueryable().Where(w => legacyIds.Contains(w.LegacyId)).Select(w => w.LegacyId)
                           .ToListAsync();

            var existingSet = existing.ToHashSet();

            list = list.Where(w => !existingSet.Contains(w._id.ToString())).ToList();

            foreach (var change in list)
            {
                if (!usersDict.ContainsKey(Guid.Parse(change.UserId)))
                {
                    await _db.Data.AddAsync(new Data
                    {
                        Key   = "import:balanceChanges:userNotExist",
                        Value = change.UserId
                    });

                    continue;
                }

                var record = new BalanceChange
                {
                    LegacyId    = change._id.ToString(),
                    OldBalance  = change.OldBalance,
                    NewBalance  = change.NewBalance,
                    AdminUserId = change.AdminUserId == null ? (int?)null : adminsDict[Guid.Parse(change.AdminUserId)].Id,
                    UserId      = usersDict[Guid.Parse(change.UserId)].Id,
                    Timestamp   = change.Date
                };

                await _db.BalanceChanges.AddAsync(record);
            }
        }
Example #8
0
        public WalletError GetTransferExtendedInfo(ProtectedOperationContext secCtx,
                                                   int transferId, out BalanceChange balanceChange, out PlatformUser user)
        {
            balanceChange = null;
            user          = null;

            if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false))
            {
                return(WalletError.InsufficientRights);
            }

            var error = WalletError.ServerError;

            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var trans = ctx.TRANSFER.FirstOrDefault(t => t.ID == transferId);
                    if (trans == null)
                    {
                        return(WalletError.InvalidData);
                    }
                    if (trans.BalanceChange.HasValue)
                    {
                        balanceChange = LinqToEntity.DecorateBalanceChange(trans.BALANCE_CHANGE);
                        return(WalletError.OK);
                    }
                    if (trans.RefWallet.HasValue)
                    {
                        var us = ctx.PLATFORM_USER.FirstOrDefault(u => u.ID == trans.RefWallet.Value);
                        if (us != null)
                        {
                            user          = LinqToEntity.DecoratePlatformUser(us);
                            user.Password = string.Empty;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("GetTransferExtendedInfo({0}) error: {1}", transferId, ex);
                error = WalletError.ServerError;
            }
            return(error);
        }
Example #9
0
 public ActionResult DecreasePointBalance(BalanceChange change)
 {
     _PointService.DecreaseBalance(change.customerId, change.amount);
     return(Ok());
 }
Example #10
0
        private void GridPaymentOnUserHitCell(object sender, MouseEventArgs e, int rowIndex, FastColumn col)
        {
            var gridPayment = sender as FastGrid.FastGrid;

            if (gridPayment == null)
            {
                return;
            }
            if (e.Button != MouseButtons.Left)
            {
                return;
            }
            var transfer = (Transfer)gridPayment.rows[rowIndex].ValueObject;

            // показать подсказку по платежу - перевод на счет, платеж за услугу...
            // if (col.PropertyName == "Comment")
            if (col.PropertyName == transfer.Property(t => t.Comment))
            {
                // подписка?
                if (transfer.Subscription.HasValue)
                {
                    new ServiceDetailForm(transfer.Subscription.Value).ShowDialog();
                    return;
                }
                // перевод на торг. счет?
                // платеж в пользу кошелька?
                if (transfer.BalanceChange.HasValue || transfer.RefWallet.HasValue)
                {
                    BalanceChange bc = null;
                    PlatformUser  us = null;
                    try
                    {
                        TradeSharpWalletManager.Instance.proxy.GetTransferExtendedInfo(
                            CurrentProtectedContext.Instance.MakeProtectedContext(), transfer.Id, out bc, out us);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("GetTransferExtendedInfo()", ex);
                    }
                    if (bc == null && us == null)
                    {
                        return;
                    }
                    if (UserSettings.Instance.GetAccountEventAction(AccountEventCode.WalletModified) == AccountEventAction.DoNothing)
                    {
                        return;
                    }

                    var text = bc != null
                        ? string.Format("{0} счета {1}, {2} {3}",
                                        BalanceChange.GetSign(bc.ChangeType) > 0? "Пополнение" : "Списание со",
                                        bc.AccountID,
                                        bc.AmountDepo.ToStringUniformMoneyFormat(),
                                        walletCurrency /*bc.Currency*/)
                        : string.Format("Платеж на кошелек пользователя, {0}", us.MakeFullName());

                    bool repeatNotification;
                    NotificationBox.Show(text, "Операция выполнена", out repeatNotification);

                    if (!repeatNotification)
                    {
                        UserSettings.Instance.SwitchAccountEventAction(AccountEventCode.WalletModified);
                        UserSettings.Instance.SaveSettings();
                    }
                }
            }
        }
Example #11
0
 public BalanceChangeTests()
 {
     this.context = new object();
     this.subject = new BalanceChange <object, int>(this.context, 10);
 }
Example #12
0
        public OperationResult <BalanceChange> ProcessInvestmentRequests(Guid investmentProgramId)
        {
            return(InvokeOperations.InvokeOperation(() =>
            {
                var result = new BalanceChange();
                decimal brokerBalanceChange = 0;

                //Todo: manager's threshold amount
                var managerThresholdAmount = 1000;

                var GVTUSDRate = rateService.GetRate(Currency.GVT, Currency.USD);
                if (!GVTUSDRate.IsSuccess)
                {
                    throw new Exception("Error at GetRate: " + string.Join(", ", GVTUSDRate.Errors));
                }

                var nextPeriod = context.Periods
                                 .Include(x => x.InvestmentRequests)
                                 .First(x => x.InvestmentProgramId == investmentProgramId && x.Status == PeriodStatus.Planned);

                var investmentProgram = context.InvestmentPrograms
                                        .Include(x => x.Token)
                                        .Include(x => x.ManagerAccount)
                                        .ThenInclude(x => x.BrokerTradeServer)
                                        .ThenInclude(x => x.Broker)
                                        .ThenInclude(x => x.User)
                                        .ThenInclude(x => x.Wallets)
                                        .First(x => x.Id == investmentProgramId);

                var brokerWalletId = investmentProgram.ManagerAccount.BrokerTradeServer.Broker.User.Id;
                var GVTToManagerTokenRate = GVTUSDRate.Data / investmentProgram.Token.InitialPrice;

                foreach (var request in nextPeriod.InvestmentRequests
                         .OrderByDescending(x => x.Type)
                         .ThenBy(x => x.Date)
                         .Where(x => x.Status == InvestmentRequestStatus.New && x.UserId != investmentProgram.ManagerAccount.UserId))
                {
                    request.Status = InvestmentRequestStatus.Executed;

                    var investor = context.InvestorAccounts
                                   .Include(x => x.InvestorTokens)
                                   .Include(x => x.User)
                                   .ThenInclude(x => x.Wallets)
                                   .First(x => x.UserId == request.UserId);

                    var investorTokens = investor.InvestorTokens.FirstOrDefault(x => x.ManagerTokenId == investmentProgram.Token.Id);

                    if (request.Type == InvestmentRequestType.Invest)
                    {
                        //ToDo: Actual value in manager's currency to request

                        var tokensAmount = request.Amount * GVTToManagerTokenRate;
                        var gvtAmount = request.Amount;

                        if (investmentProgram.Token.FreeTokens == 0)
                        {
                            //ToDo: separate refund transaction?
                            CancelInvestmentRequest(request.Id);
                            continue;
                        }
                        if (tokensAmount > investmentProgram.Token.FreeTokens)
                        {
                            gvtAmount = investmentProgram.Token.FreeTokens * investmentProgram.Token.InitialPrice / GVTUSDRate.Data;
                            tokensAmount = investmentProgram.Token.FreeTokens;

                            var wallet = investor.User.Wallets.First(x => x.Currency == Currency.GVT);
                            wallet.Amount += request.Amount - gvtAmount;

                            var tx = new WalletTransactions
                            {
                                Id = Guid.NewGuid(),
                                Type = WalletTransactionsType.PartialInvestmentExecutionRefund,
                                WalletId = wallet.Id,
                                Amount = request.Amount - gvtAmount,
                                Date = DateTime.UtcNow,
                                InvestmentProgramtId = investmentProgramId
                            };

                            context.Add(tx);
                        }

                        brokerBalanceChange += gvtAmount;
                        result.AccountBalanceChange += gvtAmount * GVTUSDRate.Data;

                        if (investorTokens == null)
                        {
                            var newPortfolio = new InvestorTokens
                            {
                                Id = Guid.NewGuid(),
                                InvestorAccountId = request.UserId,
                                ManagerTokenId = investmentProgram.Token.Id,
                                Amount = tokensAmount
                            };
                            context.Add(newPortfolio);
                        }
                        else
                        {
                            investorTokens.Amount += tokensAmount;
                        }

                        investmentProgram.Token.FreeTokens -= tokensAmount;
                    }
                    else
                    {
                        var investorTokensValue = investorTokens.Amount * investmentProgram.Token.InitialPrice;

                        //ToDo: Actual amount to request
                        var amount = investorTokensValue > request.Amount ? request.Amount : investorTokensValue;

                        var amountInGVT = amount / GVTUSDRate.Data;

                        brokerBalanceChange -= amountInGVT;
                        result.AccountBalanceChange -= amount;

                        var tokensAmount = amount / investmentProgram.Token.InitialPrice;
                        investorTokens.Amount -= tokensAmount;
                        investmentProgram.Token.FreeTokens += tokensAmount;


                        var wallet = investor.User.Wallets.First(x => x.Currency == Currency.GVT);
                        wallet.Amount += amountInGVT;

                        var investorTx = new WalletTransactions
                        {
                            Id = Guid.NewGuid(),
                            Type = WalletTransactionsType.WithdrawFromProgram,
                            WalletId = wallet.Id,
                            Amount = amountInGVT,
                            Date = DateTime.UtcNow,
                            InvestmentProgramtId = investmentProgramId
                        };

                        context.Add(investorTx);
                    }
                }

                foreach (var request in nextPeriod.InvestmentRequests
                         .Where(i => i.Status == InvestmentRequestStatus.New && i.UserId == investmentProgram.ManagerAccount.UserId))
                {
                    request.Status = InvestmentRequestStatus.Executed;

                    if (request.Type == InvestmentRequestType.Invest)
                    {
                        brokerBalanceChange += request.Amount;

                        result.AccountBalanceChange += request.Amount * GVTUSDRate.Data;
                        result.ManagerBalanceChange += request.Amount * GVTUSDRate.Data;
                    }
                    else
                    {
                        var amount = nextPeriod.ManagerStartBalance > request.Amount + managerThresholdAmount
                            ? request.Amount
                            : nextPeriod.ManagerStartBalance - managerThresholdAmount;

                        var amountInGVT = amount / GVTUSDRate.Data;

                        brokerBalanceChange -= amountInGVT;

                        result.AccountBalanceChange -= amount;
                        result.ManagerBalanceChange -= amount;

                        var manager = context.Users
                                      .Include(x => x.Wallets)
                                      .First(x => x.Id == investmentProgram.ManagerAccount.UserId);

                        var wallet = manager.Wallets.First(x => x.Currency == Currency.GVT);
                        wallet.Amount += amountInGVT;

                        var managerTx = new WalletTransactions
                        {
                            Id = Guid.NewGuid(),
                            Type = WalletTransactionsType.WithdrawFromProgram,
                            Amount = amountInGVT,
                            Date = DateTime.UtcNow,
                            WalletId = wallet.Id,
                            InvestmentProgramtId = investmentProgramId
                        };

                        context.Add(managerTx);
                    }
                }

                //ToDo: Transaction record?
                investmentProgram.ManagerAccount.BrokerTradeServer.Broker.User.Wallets.First(x => x.Currency == Currency.GVT).Amount += brokerBalanceChange;

                context.SaveChanges();

                return result;
            }));
        }
Example #13
0
 public void DepositMoney(decimal amount)
 {
     Money += amount;
     BalanceChange?.Invoke(this, new BalanceChangedArg(Action.Deposit, amount));
 }