Exemplo n.º 1
0
        public Collection<AccountTransaction> AccountTransactionsGet(DateTime? StartDate, DateTime? EndDate)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("AccountTransactionsGet", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@StartDate", StartDate);
            cmd.Parameters.AddWithValue("@EndDate", EndDate);

            try
            {
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default);
                AccountTransaction currentitem;
                Collection<AccountTransaction> items = new Collection<AccountTransaction>();
                while (reader.Read())
                {
                    currentitem = new AccountTransaction(
                        int.Parse(reader["AccountTransactionId"].ToString()),
                        DateTime.Parse(reader["TransactionDate"].ToString()),
                        int.Parse(reader["AccountId"].ToString()),
                        int.Parse(reader["AccountTransactionTaxCategoryId"].ToString()),
                        decimal.Parse(reader["Amount"].ToString())
                        );
                    items.Add(currentitem);
                }
                return items;
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }
 static internal DataOperation GetWriteAccountTransaction(AccountTransaction o) {
   return DataOperation.Parse("writeFSMTransaction", o.Id,
                             o.Account.Id, o.FinancialConcept.Id, o.Organization.Id, o.AppliedToId,
                             o.CollectedBy.Id, o.PostedBy.Id, o.ReferenceId, o.Summary, o.Notes, o.AuthorizationId,
                             o.TransactionDate, o.PostingDate, o.CancelationDate, o.CanceledById,
                             o.CurrencyId, o.Amount, 0.16m, o.Taxes, o.Credit, o.Debit,
                             o.CreditBalance, o.CRTransactionId, o.Status);
 }
Exemplo n.º 3
0
        public void TestGetTransactions_RecordExistsInDb_DoesNotGetAdded()
        {
            var accountRepo       = new Mock <IAccountRepository>();
            var transactionRepo   = new Mock <ITransactionRepository>();
            var fakeToken         = "fake";
            var fakeAccountId     = "123";
            var fakeTransactionId = "456";
            var fakeAccount       = new Account {
                account_id = fakeAccountId
            };
            var fakeTransaction = new Transaction {
                transaction_id = fakeTransactionId
            };
            var fakeAccountResponse = new AccountRootObject {
                results = new List <Account> {
                    fakeAccount
                }
            };
            var fakeTransactionResponse = new TransactionRootObject {
                results = new List <Transaction> {
                    fakeTransaction
                }
            };
            var fakeAccountTransaction = new AccountTransaction
            {
                Id            = new System.Guid(),
                AccountId     = fakeAccountId,
                TransactionId = fakeTransactionId
            };

            var mockResponse = new RestResponse
            {
                StatusCode = System.Net.HttpStatusCode.OK,
                Content    = JsonConvert.SerializeObject(fakeAccountResponse)
            };

            var mockTransactionResponse = new RestResponse
            {
                StatusCode = System.Net.HttpStatusCode.OK,
                Content    = JsonConvert.SerializeObject(fakeTransactionResponse)
            };

            accountRepo.Setup(a => a.GetAllAccounts(fakeToken)).Returns(mockResponse);
            transactionRepo.Setup(a => a.GetAllTransactions(fakeAccountId, fakeToken)).Returns(mockTransactionResponse);
            transactionRepo.Setup(a => a.GetAccountTransaction(fakeAccountId, fakeTransactionId)).Returns(fakeAccountTransaction);

            var controller = new TransactionController(accountRepo.Object, transactionRepo.Object);

            controller.Get(fakeToken);
            transactionRepo.Verify(a => a.AddAccountTransaction(It.IsAny <AccountTransaction>()), Times.Never);
        }
        public bool AddAccountTransaction(AccountTransaction transaction)
        {
            bool isTransactionDuplicate = accountTransactions.Any(at => at.AccountId == transaction.AccountId &&
                                                                  at.Date.Date == transaction.Date.Date && at.Total == transaction.Total);

            if (isTransactionDuplicate)
            {
                return(false);
            }

            transaction.PropertyChanged += OnTransactionPropertyChanged;
            accountTransactions.Add(transaction);
            return(true);
        }
        public async Task <bool> Handle(InvestInvestmentToolToAccountCommand request, CancellationToken cancellationToken)
        {
            //Notify for reporting
            var accountBalanceChangedIntegrationEvent = new AccountBalanceChangedIntegrationEvent();

            accountBalanceChangedIntegrationEvent.EffectedAccountIds.Add(Guid.Parse(request.AccountId));
            await _imsIntegrationEventService.AddAndSaveEventAsync(accountBalanceChangedIntegrationEvent);

            var transaction = new AccountTransaction(Guid.Parse(request.AccountId), request.TransactionTypeId, request.TransactionDate, request.Amount, request.Rate ?? 1);

            _logger.LogInformation("----- Creating Transaction - Transaction: {@Transaction}", transaction);
            _accountTransactionRepository.Add(transaction);
            return(await _accountTransactionRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken));
        }
Exemplo n.º 6
0
        public async Task <ActionResult <CustomerAccount> > OpenAccount(
            [SwaggerParameter("New account request parameters", Required = true)] CustomerAccountCreateRequest customerAccountCreateRequest)
        {
            if (customerAccountCreateRequest.CustomerId <= 0)
            {
                return(BadRequest(new ProblemDetails
                {
                    Detail = "Invalid customer Id"
                }));
            }

            if (customerAccountCreateRequest.InitialCredit < 0)
            {
                return(BadRequest(new ProblemDetails
                {
                    Detail = "Initial credit could not be negative"
                }));
            }

            try
            {
                var customer = _customerAccountRepository.GetCustomer(customerAccountCreateRequest.CustomerId);
                if (customer == null)
                {
                    return(BadRequest($"Customer with id {customerAccountCreateRequest.CustomerId} does not exist"));
                }

                var newAccount = _customerAccountRepository.CreateCustomerAccount(customerAccountCreateRequest.CustomerId, customerAccountCreateRequest.InitialCredit);

                if (customerAccountCreateRequest.InitialCredit != 0)
                {
                    var newTransaction = new AccountTransaction
                    {
                        AccountId  = newAccount.CustomerAccountId,
                        Amount     = customerAccountCreateRequest.InitialCredit,
                        CreateDate = DateTime.UtcNow,
                        CustomerId = customerAccountCreateRequest.CustomerId
                    };

                    await _transactionProxyService.CreateTransaction(newTransaction);
                }

                return(Ok(_mapper.Map <CustomerAccount>(newAccount)));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error in {nameof(OpenAccount)} with customerId {customerAccountCreateRequest?.CustomerId}. Details: {ex}");
                return(StatusCode(500));
            }
        }
    static internal int WriteAccountTransaction(AccountTransaction o) {
      DataOperation operation = DataOperation.Parse("writeFSMTransaction", o.Id,
                                o.Account.Id, o.FinancialConcept.Id, o.Organization.Id, o.AppliedToId,
                                o.CollectedBy.Id, o.PostedBy.Id, o.ReferenceId, o.Summary, o.Notes, o.AuthorizationId,
                                o.TransactionDate, o.PostingDate, o.CancelationDate, o.CanceledById,
                                o.CurrencyId, o.Amount, 0.16m, o.Taxes, o.Credit, o.Debit,
                                o.CreditBalance, o.CRTransactionId, o.Status);

      int i = DataWriter.Execute(operation);

      FinancialAccountData.UpdateAccountsTable(o.Account.Id);

      return i;
    }
        public static List <AccountTransaction> GetAccountTransactionListByDate(string transactionDate, bool allOffices = false, bool showDeleted = false)
        {
            List <AccountTransaction> AccountTransactionList = new List <AccountTransaction>();

            DataTable GetAccountTransactionTable = AccountTransactionDataAccess.GetInstance.GetAccountTransactionListByDate(transactionDate, allOffices, showDeleted);

            foreach (DataRow dr in GetAccountTransactionTable.Rows)
            {
                AccountTransaction TheAccountTransaction = DataRowToObject(dr);
                AccountTransactionList.Add(TheAccountTransaction);
            }

            return(AccountTransactionList);
        }
Exemplo n.º 9
0
        public AccountTransaction SaveAccountTransaction(AccountTransaction accountTransaction, int tenantId, int userId)
        {
            var trans = _currentDbContext.AccountTransactions.Find(accountTransaction.AccountTransactionId);

            if (trans == null)
            {
                var accountBalance = Financials.CalcAccountBalance(accountTransaction.AccountId ?? 0);

                if (accountTransaction.AccountTransactionTypeId == (int)AccountTransactionTypeEnum.PaidByAccount || accountTransaction.AccountTransactionTypeId == (int)AccountTransactionTypeEnum.Refund ||
                    accountTransaction.AccountTransactionTypeId == (int)AccountTransactionTypeEnum.CreditNote || accountTransaction.AccountTransactionTypeId == (int)AccountTransactionTypeEnum.Discount)
                {
                    accountBalance = accountBalance - accountTransaction.Amount;
                }
                else
                {
                    accountBalance = accountBalance + accountTransaction.Amount;
                }

                trans = new AccountTransaction();
                _currentDbContext.Entry(trans).State = EntityState.Added;
                trans.Amount = accountTransaction.Amount;
                trans.AccountTransactionTypeId = accountTransaction.AccountTransactionTypeId;
                trans.FinalBalance             = accountBalance;
                trans.AccountId   = accountTransaction.AccountId;
                trans.DateCreated = DateTime.UtcNow;
                trans.CreatedBy   = userId;
                trans.TenantId    = tenantId;

                var account = _currentDbContext.Account.Find(trans.AccountId);
                account.FinalBalance = accountBalance;
                account.DateUpdated  = DateTime.UtcNow;
                _currentDbContext.Entry(account).State = EntityState.Modified;
            }
            else
            {
                // _currentDbContext.Entry(trans).State = EntityState.Modified;
                trans.DateUpdated = DateTime.UtcNow;
                trans.UpdatedBy   = userId;
                // AMOUNT CANNOT BE UPDATED AT ALL
                //trans.Amount = amount;
                //trans.AccountTransactionTypeId = accountTransaction.AccountTransactionTypeId;
                //trans.FinalBalance = accountBalance;
            }

            trans.Notes = accountTransaction.Notes;

            _currentDbContext.SaveChanges();
            accountTransaction = trans;
            return(accountTransaction);
        }
        public IActionResult PickupCompleted(int id)
        {
            //var completedPickupInDb = _context.OneTimePickups.Where(o => o.Id == completedPickup.Id).Single();


            var completedPickupInDb = _context.OneTimePickups.Where(o => o.Id == id).Single();

            try
            {
                //var completedPickupInDb = _context.OneTimePickups.Find(completedPickup);

                var customer = _context.Customers.Where(c => c.Id == completedPickupInDb.CustomerId).FirstOrDefault();
                customer.SpecialtyPickupCompleted = true;


                double pickupFee = TrashPrices.GetOneTimePickupCost(customer);
                customer.OutstandingBalance += pickupFee;

                AccountTransaction serviceFee = new AccountTransaction();
                serviceFee.CustomerId      = customer.Id;
                serviceFee.Fee             = pickupFee;
                serviceFee.TransactionDate = DateTime.Today;
                serviceFee.TransactionType = "Specialty Pickup";

                customer.SpecialtyPickupDay         = DateTime.MinValue;
                completedPickupInDb.HasBeenPickedup = true;
                _context.AccountTransactions.Add(serviceFee);
                _context.SaveChanges();

                var employee  = _context.Employees.Where(e => e.Id == completedPickupInDb.EmployeeId).SingleOrDefault();
                var addresses = _context.Customers.Where(c => c.ZipCode == employee.AssignedZipCode).ToDictionary(c => c.StreetAddress, c => c.WeeklyPickupDay);
                employee.Addresses = addresses;

                EmployeesIndexViewModel employeesIndexView = new EmployeesIndexViewModel(employee, _context, "Pickup Confirmation Recieved.");

                //return View("Index", employeesIndexView);
                return(Index("Pickup Confirmation Recieved."));
            }
            catch
            {
                //completedPickupInDb = _context.OneTimePickups.Where(o => o == (OneTimePickup)completedPickup).Single();
                var employee  = _context.Employees.Where(e => e.Id == completedPickupInDb.EmployeeId).SingleOrDefault();
                var addresses = _context.Customers.Where(c => c.ZipCode == employee.AssignedZipCode).ToDictionary(c => c.StreetAddress, c => c.WeeklyPickupDay);
                employee.Addresses = addresses;

                EmployeesIndexViewModel employeesIndexView = new EmployeesIndexViewModel(employee, _context, "Pickup Confirmation Failed!");

                return(View("Index", employeesIndexView));
            }
        }
Exemplo n.º 11
0
        // GET: AccountTransactions/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            AccountTransaction accountTransaction = db.accountTransactions.Find(id);

            if (accountTransaction == null)
            {
                return(HttpNotFound());
            }
            return(View(accountTransaction));
        }
        private async Task <TransactionResult> CreateTransactionAndUpdateSummary(AccountTransaction accountTransaction, AccountSummary accountSummary)
        {
            var accountTransactionEntity = _mapper.Map <AccountTransactionEntity>(accountTransaction);
            var accountSummaryEntity     = _mapper.Map <AccountSummaryEntity>(accountSummary);

            await _accountTransactionRepository.Create(accountTransactionEntity, accountSummaryEntity);

            var currentSummary = await _accountSummaryRepository.Read(accountTransaction.AccountNumber);

            var result = _mapper.Map <TransactionResult>(accountTransactionEntity);

            result.Balance = new Money(currentSummary.Balance, currentSummary.Currency.TryParseEnum <Currency>());
            return(result);
        }
Exemplo n.º 13
0
        public AccountTransactionsForUser GetModelAccountTransactionsForUser(AccountTransaction transaction, User payee, User recipient, int userId)
        {
            AccountTransactionsForUser transactionsModel = new AccountTransactionsForUser();

            transactionsModel.Amount            = transaction.Amount;
            transactionsModel.TimeOfTransaction = transaction.TimeOfTransaction.ToString("g");
            transactionsModel.PayeeId           = payee.Id;
            transactionsModel.PayeeName         = payee.UserName;
            transactionsModel.RecipientId       = recipient.Id;
            transactionsModel.RecipientName     = recipient.UserName;
            transactionsModel.Balance           = (userId == payee.Id) ? transaction.PayeeBalance : transaction.RecipientBalance;
            transactionsModel.Repeat            = (userId == payee.Id) ? true : false;

            return(transactionsModel);
        }
Exemplo n.º 14
0
        /// <summary>
        /// This method is called when the grid's UserDeletedRow event has been fired.
        /// </summary>
        /// <param name="sender">The <see cref="object"/> that fired the event.</param>
        /// <param name="e">The <see cref="DataGridViewRowEventArgs"/> of the event.</param>
        private void grid_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            AccountTransaction t = e.Row.Tag as AccountTransaction;

            if (t == null)
            {
                return;
            }
            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork             += BWDeleteRow;
            bw.RunWorkerCompleted += BwOnRunWorkerCompleted;
            TE(false);
            bw.RunWorkerAsync(t);
        }
Exemplo n.º 15
0
 private AccountConfig(
     string name,
     Address address,
     string bic,
     string number,
     Balance balance,
     AccountTransaction transaction)
 {
     this.Name        = name;
     this.Address     = address;
     this.Bic         = bic;
     this.Number      = number;
     this.Balance     = balance;
     this.Transaction = transaction;
 }
Exemplo n.º 16
0
        public AccountTransaction Add(Account payee, Account recipient, decimal amount)
        {
            AccountTransaction accountTransaction = new AccountTransaction();

            accountTransaction.PayeeId           = payee.Id;
            accountTransaction.RecipientId       = recipient.Id;
            accountTransaction.PayeeBalance      = payee.Balance;
            accountTransaction.RecipientBalance  = recipient.Balance;
            accountTransaction.TimeOfTransaction = DateTime.Now;
            accountTransaction.Amount            = amount;

            db.AccountTransactions.Add(accountTransaction);
            db.SaveChanges();
            return(accountTransaction);
        }
        public void Should_Fail_For_NotFound_AccountNumber()
        {
            // do some setup for constructor DI:
            var          dataStoreMock = new Mock <IDataStore>();
            const string accountNumber = "100";

            dataStoreMock.Setup(ds => ds.AccountNumberExists(accountNumber)).Returns(false);

            var atv = new AccountTransactionValidator(dataStoreMock.Object);
            var accountTransaction = new AccountTransaction {
                AccountNumber = accountNumber
            };

            atv.ShouldHaveValidationErrorFor(a => a.AccountNumber, accountTransaction);
        }
Exemplo n.º 18
0
        public void TestGetUserMetrics_MetricsForSingleTransactionSameAsTransaction()
        {
            var accountRepo       = new Mock <IAccountRepository>();
            var transactionRepo   = new Mock <ITransactionRepository>();
            var fakeToken         = "fake";
            var fakeAccountId     = "123";
            var fakeTransactionId = "456";
            var fakeCategory      = "cat1";
            var fakeAccount       = new Account {
                account_id = fakeAccountId
            };
            var fakeAccountResponse = new AccountRootObject {
                results = new List <Account> {
                    fakeAccount
                }
            };
            var accountTransactionObject = new AccountTransaction
            {
                AccountId     = fakeAccountId,
                TransactionId = fakeTransactionId,
                Amount        = 10,
                Category      = fakeCategory
            };
            var listOfAccountTransactions = new List <AccountTransaction> {
                accountTransactionObject
            };

            var mockResponse = new RestResponse
            {
                StatusCode = System.Net.HttpStatusCode.OK,
                Content    = JsonConvert.SerializeObject(fakeAccountResponse)
            };

            accountRepo.Setup(a => a.GetAllAccounts(fakeToken)).Returns(mockResponse);
            transactionRepo.Setup(t => t.GetAccountTransactionsByAccounts(new List <string> {
                fakeAccountId
            })).Returns(listOfAccountTransactions);

            var controller  = new TransactionController(accountRepo.Object, transactionRepo.Object);
            var result      = controller.UserMetrics(fakeToken);
            var metricsList = result.Result as OkObjectResult;
            var final       = (List <UserTransactionMetrics>)metricsList.Value;

            Assert.AreEqual(1, final.Count);
            Assert.AreEqual(10, final[0].MaximumTransaction);
            Assert.AreEqual(10, final[0].MinimumTransaction);
            Assert.AreEqual(10, final[0].AverageTransaction);
        }
Exemplo n.º 19
0
        public void CheckTransactionHistory()
        {
            // Arrange
            CurrentAccount account;
            var            expectedValueForDeposit  = new AccountTransaction(TransactionType.Deposit, 100.00);
            var            expectedValueForWithdraw = new AccountTransaction(TransactionType.Withdrawal, 50.00);

            // Act
            account = new CurrentAccount(25.00, "P-96");
            account.transactions.Add(expectedValueForDeposit);
            account.transactions.Add(expectedValueForWithdraw);

            // Assert
            Assert.IsTrue(account.transactions.Contains(expectedValueForDeposit));
            Assert.IsTrue(account.transactions.Contains(expectedValueForWithdraw));
        }
Exemplo n.º 20
0
        public ActionResult <AccountTransaction> Transaction([FromBody] AccountTransaction accountTransaction)
        {
            try
            {
                if (accountTransaction.TransactionType == TransactionType.Debit)
                {
                    return(_dataStore.Debit(accountTransaction));
                }

                return(_dataStore.Credit(accountTransaction));
            }
            catch (InsufficientFundsException)
            {
                return(BadRequest());
            }
        }
        public static AccountTransaction GetAccountTransactionByID(int transactionID)
        {
            AccountTransaction TheAccountTransaction;
            DataRow            AccountTransactionRow = AccountTransactionDataAccess.GetInstance.GetAccountTransactionByID(transactionID);

            if (AccountTransactionRow != null)
            {
                TheAccountTransaction = DataRowToObject(AccountTransactionRow);
            }
            else
            {
                TheAccountTransaction = new AccountTransaction();
            }

            return(TheAccountTransaction);
        }
Exemplo n.º 22
0
        public AccountTransaction PostAccountTransaction(AccountTransaction accountTransaction)
        {
            var item = AccountTransactions.FirstOrDefault(c => c.AccountTransactionId == accountTransaction.AccountTransactionId);

            if (item != null)
            {
                item = accountTransaction;
                return(item);
            }
            else
            {
                accountTransaction.AccountTransactionId = GenerateAccontTransactionId();
                AccountTransactions.Add(accountTransaction);
                return(accountTransaction);
            }
        }
Exemplo n.º 23
0
        public async Task <AccountTransaction> InsertAsync(AccountTransaction accountTransaction)
        {
            using (IDbConnection con = _factory.CreateConnection())
            {
                accountTransaction.DateTime = DateTime.Now;

                var id = await con.ExecuteScalarAsync <int>(InsertQuery(), accountTransaction);

                if (id > 0)
                {
                    accountTransaction.Id = id;
                }

                return(accountTransaction);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        ///
        /// </summary>
        private void FilterItems()
        {
            foreach (DataGridViewRow row in grid.Rows)
            {
                AccountTransaction trans = row.Tag as AccountTransaction;
                if (trans == null)
                {
                    continue;
                }
                row.Visible = checkBox1.Checked || (trans.Date.Year == dateTimePicker1.Value.Year && trans.Date.Month == dateTimePicker1.Value.Month);
            }
            NameValueList settings = ctx.Settings.Get(this);

            settings["ShowAll"]    = checkBox1.Checked ? "true" : "false";
            settings["FilterDate"] = dateTimePicker1.Value.Ticks.ToString();
        }
        //Lấy KeyName cho entity
        public static string GetKeyName(string entityName)
        {
            string keyName = entityName + "Id";

            try
            {
                #region Trường hợp key đặc biệt viết tại đây
                if (entityName == ConfigApprovalTransaction.EntityName())
                {
                    keyName = ConfigApprovalTransaction.ConfigApprovalTransactionFields.ConfigType.ToString();
                }
                if (entityName == MemberInfo.EntityName())
                {
                    keyName = MemberInfo.MemberInfoFields.MemberId.ToString();
                }
                if (entityName == UserInfo.EntityName())
                {
                    keyName = UserInfo.UserInfoFields.UserId.ToString();
                }
                if (entityName == SessionHistory.EntityName())
                {
                    keyName = SessionHistory.SessionHistoryFields.SessionId.ToString();
                }
                if (entityName == AccountTransaction.EntityName())
                {
                    keyName = AccountTransaction.AccountTransactionFields.TransactionId.ToString();
                }
                if (entityName == AccountTransactionView.EntityName())
                {
                    keyName = AccountTransactionView.AccountTransactionViewFields.TransactionViewId.ToString();
                }
                if (entityName == ChangedPasswordHist.EntityName())
                {
                    keyName = ChangedPasswordHist.ChangedPasswordHistFields.Id.ToString();
                }
                if (entityName == MemberTradingLimit.EntityName())
                {
                    keyName = MemberTradingLimit.MemberTradingLimitFields.Id.ToString();
                }
                #endregion
            }
            catch (Exception ex)
            {
                LogTo.Error(ex.ToString());
            }
            return(keyName);
        }
Exemplo n.º 26
0
        public async Task Execute(AccountDepositModel model)
        {
            var entity = new AccountTransaction
            {
                AcctId            = model.AcctId,
                TransactionType   = model.TransactionType,
                TransactionAmount = model.TransactionAmount,
                DateCreated       = DateTime.UtcNow
            };

            _context.AccountTransactions.Add(entity);

            await _context.SaveChangesAsync();

            //return auto-generated transaction id
            model.TranId = entity.TranId;
        }
Exemplo n.º 27
0
        public AccountTransfer Transfer(AccountTransfer transfer)
        {
            // get customer details
            var fromAccount = GetAccount(transfer.FromAccount);
            var toAccount   = GetAccount(transfer.ToAccount);

            if (!fromAccount.IsActive)
            {
                throw new AccountException("From account inactive");
            }

            if (!toAccount.IsActive)
            {
                throw new AccountException("To account inactive");
            }

            var fromCustomer = GetCustomer(fromAccount.CustomerID);
            var toCustomer   = GetCustomer(toAccount.CustomerID);

            // does from account have enough funds for the transaction?
            if (fromAccount.Balance - transfer.Amount < -fromAccount.OverdraftLimit)
            {
                throw new InsufficientFundsException("From account has insufficient funds for transfer");
            }

            // create two transactions based on the transfer:
            var fromTransaction = new AccountTransaction
            {
                AccountNumber   = transfer.FromAccount,
                Amount          = transfer.Amount,
                Description     = $"{transfer.Description}. Transfer to {toCustomer.Name}",
                TransactionType = TransactionType.Transfer
            };
            var toTransaction = new AccountTransaction
            {
                AccountNumber   = transfer.ToAccount,
                Amount          = transfer.Amount,
                Description     = $"{transfer.Description}. Transfer from {fromCustomer.Name}",
                TransactionType = TransactionType.Transfer
            };

            Debit(fromTransaction);
            Credit(toTransaction);

            return(transfer);
        }
Exemplo n.º 28
0
        private void InsertData(DataTable dt, DataTable errorsdt)
        {
            int count = 0;

            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    AccountTransaction at = new AccountTransaction();

                    try
                    {
                        at.Account      = dt.Rows[i]["Account"].ToString().Trim();
                        at.Description  = dt.Rows[i]["Description"].ToString().Trim();
                        at.CurrencyCode = dt.Rows[i]["CurrencyCode"].ToString().Trim();
                        at.Amount       = Convert.ToDecimal(dt.Rows[i]["Amount"].ToString().Trim());
                        if (ModelState.IsValid)
                        {
                            //Get currency symbol by currency code
                            var results = Utility.CultureInfoFromCurrencyISO(at.CurrencyCode);
                            if (results.Count > 0)
                            {
                                db.accountTransactions.Add(at);
                                count = count + 1;
                                db.SaveChanges();
                            }
                        }
                        else
                        {
                            // insert row values
                            errorsdt.Rows.Add(new Object[] { at.Account, at.Description, at.CurrencyCode, at.Amount });
                        }
                    }
                    catch (Exception e)
                    {
                        // insert row values
                        errorsdt.Rows.Add(new Object[] { at.Account, at.Description, at.CurrencyCode, at.Amount });
                    }
                }
                ViewBag.Data = errorsdt;
                if (count > 0)
                {
                    ViewBag.Count = count + " records inserted successfully!";
                }
            }
        }
Exemplo n.º 29
0
        private async Task CancelBetAndAccountTransaction(Bet bet)
        {
            bet.State = await AppDbContext.FindGenericElementByIdAsync <BetState>((long)BetStates.Canceled);

            AccountTransaction accountTransaction = bet.AccountTransaction;

            accountTransaction.State = await AppDbContext
                                       .FindGenericElementByIdAsync <AccountTransactionState>((long)AccountTransactionStates.Cancelled);

            await AppDbContext.BeginTransactionAsync();

            AppDbContext.Entry(bet).State = EntityState.Modified;
            AppDbContext.Entry(accountTransaction).State = EntityState.Modified;

            await AppDbContext.SaveChangesAsync();

            await AppDbContext.CommitTransactionAsync();
        }
        public AccountTransaction CreateTransaction(AccountTransaction transaction)
        {
            var maxTransactionId = _accountTransactions.SelectMany(c => c.Value).Select(c => c.Id).Max();

            transaction.Id = maxTransactionId;
            if (_accountTransactions.ContainsKey(transaction.AccountId))
            {
                _accountTransactions[transaction.AccountId].Add(transaction);
            }
            else
            {
                _accountTransactions[transaction.AccountId] = new List <AccountTransaction> {
                    transaction
                };
            }

            return(transaction);
        }
Exemplo n.º 31
0
        private static void SetTransactionAmount(AccountTransaction transaction, string amountAsString, bool isMinusOutflow)
        {
            decimal.TryParse(new string(amountAsString.Where(c => char.IsDigit(c) || char.IsPunctuation(c)).ToArray()), out decimal amount);

            if (isMinusOutflow)
            {
                amount = -amount;
            }

            if (amount >= 0)
            {
                transaction.Outflow = amount;
            }
            else
            {
                transaction.Inflow = -amount;
            }
        }
        public async Task <IActionResult> AddTransactionAsync([FromBody] AccountTransaction model)
        {
            try
            {
                if (model?.Type == null)
                {
                    return(BadRequest());
                }

                var result = await _transactionService.AddTransactionAsync(model);

                return(Ok(result));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
        protected void btn_Delete_CheckedItem_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow EachRow in gview_AccountTransaction.Rows)
            {
                CheckBox EachCheckBox = (CheckBox)EachRow.FindControl("chk_TransactionID");

                if (EachCheckBox.Checked)
                {
                    int RecordID = int.Parse(((Label)EachRow.FindControl("lbl_TransactionID")).Text);

                    AccountTransaction TheAccountTransaction = new AccountTransaction();
                    TheAccountTransaction.TransactionID = RecordID;

                    int ProcReturnValue = AccountTransactionManagement.GetInstance.DeleteAccountTransaction(TheAccountTransaction, RecordID);
                }
                BindGridView();
            }
        }
Exemplo n.º 34
0
 static internal DataOperation CancelAccountTransaction(AccountTransaction transaction, int currentUserId,
                                                        DateTime date) {
   return DataOperation.Parse("setFSMAccountTransactionStatus", transaction.Id, currentUserId, date, 'X');
 }
Exemplo n.º 35
0
 public void Add(AccountTransaction transaction)
 {
     this.Value += transaction.Value;
 }
        public static Report ParseReport(string selector, StreamReader content)
        {
            var htmlDocument = new HtmlDocument();
            htmlDocument.Load(content);
            var html = htmlDocument.DocumentNode;

            var report = new Report();
            var trans = new List<AccountTransaction>();
            // <td width=\"55\" colspan=\"3\" rowspan=\"2\"> <td width=361 colspan=26 rowspan=2>
            var reportPeriodRows = html.CssSelect("tr")
                .Where(r => (r.InnerHtml.Contains("<td width=\"361\" colspan=\"26\" rowspan=\"2\">") && r.InnerHtml.Contains("<td height=\"9\" colspan=\"22\">"))
                || (r.InnerHtml.Contains("<td width=\"361\" colspan=\"16\" rowspan=\"2\">") && r.InnerHtml.Contains("<td height=\"9\" colspan=\"15\">"))
                || (r.InnerHtml.Contains("<td width=\"361\" colspan=\"31\" rowspan=\"2\">") && r.InnerHtml.Contains("<td height=\"9\" colspan=\"29\">")));
            var reportPeriodCells = reportPeriodRows.Select(record => record.CssSelect("tt"));
            var period = new ReportPeriod();

            foreach (var reportPeriodCell in reportPeriodCells)
            {
                if (reportPeriodCell == null) continue;
                var local = reportPeriodCell.ToList();
                if (!local.Any()) continue;
                var count = local.Count();
                if (count == 4)
                {
                    if (local[0].InnerHtml == "Отчетный&nbsp;период:&nbsp;")
                    {
                        period.StartDate = DateTime.Parse(local[1].InnerText.Trim(), CultureInfo.CreateSpecificCulture("ru-RU"));
                        period.EndDate = DateTime.Parse(local[3].InnerText.Trim(), CultureInfo.CreateSpecificCulture("ru-RU"));
                        report.ReportPeriod = period;
                    }
                }
            }

            var cardRows = html.CssSelect("tr")
                .Where(r => r.InnerHtml.Contains("<td width=\"284\" colspan=\"10\" rowspan=\"2\">"));
            var cardCells = cardRows.Select(record => record.CssSelect("tt"));
            foreach (var cardCell in cardCells)
            {
                if (cardCell == null) continue;
                var local = cardCell.ToList();
                if (!local.Any()) continue;
                var count = local.Count();
                if (count == 2)
                {
                    if (local[0].InnerHtml == "Контракт&nbsp;#&nbsp;")
                        report.CardNumber = local[1].InnerHtml.Replace("&nbsp;", " ").Trim();
                }
            }

            var stateRows = html.CssSelect("tr")
                .Where(r => r.InnerHtml.Contains("<td height=\"9\"></td>") &&
                    (r.InnerHtml.Contains("<td width=\"100\" colspan=\"10\">") || (r.InnerHtml.Contains("<td width=\"100\" colspan=\"4\">"))));
            var stateCells = stateRows.Select(record => record.CssSelect("tt"));
            var stateOnDate = new StateOnDate();
            foreach (var stateCell in stateCells)
            {
                if (stateCell == null) continue;
                var local = stateCell.ToList();
                if (!local.Any()) continue;
                var count = local.Count();
                if (count == 4)
                {
                    if (local[0].InnerHtml != "На&nbsp;Дату")
                    {
                        stateOnDate.Date = DateTime.Parse(local[0].InnerText.Trim(), CultureInfo.CreateSpecificCulture("ru-RU"));
                        stateOnDate.Available = Decimal.Parse(local[1].InnerText.Replace("&nbsp;", "").Trim());
                        stateOnDate.BlockedAmount = Decimal.Parse(local[2].InnerText.Replace("&nbsp;", "").Trim());
                        stateOnDate.CreditLimit = Decimal.Parse(local[3].InnerText.Replace("&nbsp;", "").Trim());
                        report.StateOnDate = stateOnDate;
                    }
                }
            }

            var transcationRows = html.CssSelect("tr")
                .Where(r => r.InnerHtml.Contains("<td height=\"9\" colspan=\"2\"></td>")
                    || r.InnerHtml.Contains("<td height=\"9\" colspan=\"28\">")
                    || r.InnerHtml.Contains("<td width=\"69\" colspan=\"2\" rowspan=\"2\">"));
            var transactionCells = transcationRows.Select(record => record.CssSelect("tt"));

            var transactionDate = DateTime.MinValue; // fixed bug with html report from sbsibank (the transaction date is on another row)

            foreach (var values in transactionCells)
            {
                if (values == null) continue;
                var local = values.ToList();
                if (!local.Any()) continue;
                var count = local.Count();
                switch (count)
                {
                    case 1:
                        transactionDate = DateTime.Parse(local[0].InnerText.Trim(), CultureInfo.CreateSpecificCulture("ru-RU"));
                        break;
                    case 2:
                        if (local[0].InnerHtml == "Валюта&nbsp;Контракта:&nbsp;")
                            report.Currency = local[1].InnerText.Replace("&nbsp;", " ").Trim();
                        if (local[0].InnerHtml == "BYR" || local[0].InnerHtml == "USD" || local[0].InnerHtml == "EUR")
                            report.StartBalance = Decimal.Parse(local[1].InnerText.Replace("&nbsp;", " ").Replace(" ", "").Trim());
                        break;
                    case 3:
                        if (local[0].InnerHtml == "Операции&nbsp;по&nbsp;Card&nbsp;#&nbsp;")
                            report.CardNumber = local[1].InnerHtml.Replace("&nbsp;", " ").Trim();
                        break;
                    case 6:
                        if (local[0].InnerText.Trim() == "Дата") continue;
                        var transaction1 = new AccountTransaction
                        {
                            OperationDate = DateTime.Parse(local[0].InnerText.Trim(), CultureInfo.CreateSpecificCulture("ru-RU")),
                            OperationDescription = HttpUtility.HtmlDecode(local[1].InnerText.Replace("&nbsp;", " ").Trim()),
                            OperationAmount = Decimal.Parse(local[2].InnerText.Replace("&nbsp;", "").Trim()),
                            Currency = local[3].InnerText.Trim(),
                            TransactionDate = transactionDate,
                            Commission = Decimal.Parse(local[4].InnerText.Replace("&nbsp;", "").Trim()),
                            TransactionAmount = Decimal.Parse(local[5].InnerText.Replace("&nbsp;", "").Trim()),
                            Status = "F"
                        };
                        Log.Info(transaction1);
                        trans.Add(transaction1);
                        break;
                    case 7:
                        if (local[0].InnerText.Trim() == "Дата") continue;
                        DateTime date;
                        if (DateTime.TryParse(local[1].InnerText.Trim(), out date))
                        {
                            // operations waiting authorization
                            var transaction3 = new AccountTransaction
                            {
                                OperationDate = DateTime.Parse(local[0].InnerText.Trim(), CultureInfo.CreateSpecificCulture("ru-RU")),
                                OperationDescription = HttpUtility.HtmlDecode(local[2].InnerText.Replace("&nbsp;", " ").Trim()),
                                OperationAmount = Decimal.Parse(local[3].InnerText.Replace("&nbsp;", "").Trim()),
                                Currency = local[4].InnerText.Trim(),
                                //TransactionDate = DateTime.Parse(local[4].InnerText.Trim(), CultureInfo.CreateSpecificCulture("ru-RU")),
                                //Commission = Decimal.Parse(local[5].InnerText.Replace("&nbsp;", "").Trim()),
                                TransactionAmount = Decimal.Parse(local[5].InnerText.Replace("&nbsp;", "").Trim()),
                                Status = "A"
                            };
                            Log.Info(transaction3);
                            trans.Add(transaction3);
                            break;
                        }
                        var transaction2 = new AccountTransaction
                        {
                            OperationDate = DateTime.Parse(local[0].InnerText.Trim(), CultureInfo.CreateSpecificCulture("ru-RU")),
                            OperationDescription = HttpUtility.HtmlDecode(local[1].InnerText.Replace("&nbsp;", " ").Trim()),
                            OperationAmount = Decimal.Parse(local[2].InnerText.Replace("&nbsp;", "").Trim()),
                            Currency = local.ElementAt(3).InnerText.Trim(),
                            TransactionDate = DateTime.Parse(local[4].InnerText.Trim(), CultureInfo.CreateSpecificCulture("ru-RU")),
                            Commission = Decimal.Parse(local[5].InnerText.Replace("&nbsp;", "").Trim()),
                            TransactionAmount = Decimal.Parse(local[6].InnerText.Replace("&nbsp;", "").Trim()),
                            Status = "F"
                        };
                        Log.Info(transaction2);
                        trans.Add(transaction2);
                        break;
                }
            }
            report.Transactions = trans;
            return report;
        }
Exemplo n.º 37
0
 public AccountPosition(AccountTransaction transaction)
 {
     this.CurrencyId = transaction.CurrencyId;
     this.Value = transaction.Value;
 }