public void it_should_produce_a_statement()
        {
            var henry = new Customer("Henry").
                        openAccount(new Account(AccountType.Checking, "checking")).
                        openAccount(new Account(AccountType.Savings, "savings"));

            henry.deposit("checking", 100.0);
            henry.withdraw("checking", 80.0);
            henry.deposit("savings", 4000.0);
            henry.withdraw("savings", 200.0);

            var result = new AccountStatement().getStatement(henry.getName(), henry.getAccounts());

            Assert.AreEqual("Statement for Henry\n" +
                            "\n" +
                            "Checking Account\n" +
                            "  deposit $100.00\n" +
                            "  withdrawal $80.00\n" +
                            "Total $20.00\n" +
                            "\n" +
                            "Savings Account\n" +
                            "  deposit $4,000.00\n" +
                            "  withdrawal $200.00\n" +
                            "Total $3,800.00\n" +
                            "\n" +
                            "Total In All Accounts $3,820.00", result);
        }
Example #2
0
        public async Task <AccountStatement> Statement(int accountNumber, StatementDate statementDate)
        {
            var accountSummary = await GetAccountSummary(accountNumber);

            await accountSummary.Validate(accountNumber);

            var accountTransactionEntity = await _accountTransactionRepository
                                           .Get(accountNumber, statementDate.StartDate, statementDate.EndDate);

            var currency = accountSummary.Balance.Currency;

            var accountStatement = new AccountStatement()
            {
                AccountNumber      = accountSummary.AccountNumber,
                Currency           = currency,
                Date               = statementDate,
                TransactionDetails = accountTransactionEntity.Select(txn => new StatementTransaction()
                {
                    TransactionType = txn.TransactionType.TryParseEnum <TransactionType>(),
                    Date            = txn.Date,
                    Description     = txn.Description,
                    Amount          = new Money(txn.Amount, currency),
                    CurrentBalance  = new Money(txn.CurrentBalance, currency)
                })
            };

            return(accountStatement);
        }
        public List <InternalTransferDto> GetAsInternalTransfer(FilterAsTableSelected filter)
        {
            List <InternalTransferDto> internalTransferDtos = new List <InternalTransferDto>();

            var date    = Convert.ToDateTime($"01/{filter.MonthYear.Month.Id}/{filter.MonthYear.Year}");
            var dateMin = DateHelper.GetFirstDayOfMonth(date);
            var dateMax = DateHelper.GetLastDayOfMonth(date);

            var accountStatements = _accountStatementRepository.GetAsInternalTransfer(filter.User.IdUserGroup, filter.IdAccount, dateMin, dateMax);
            var asDtos            = _mapper.Map <List <AsForTableDto> >(accountStatements);

            foreach (var asDtoFirst in asDtos)
            {
                AsForTableDto    asDtoSecond = null; // = new AsForTableDto();
                AccountStatement asCouple    = _accountStatementRepository.GetAsInternalTransferCouple(filter.User.IdUserGroup, asDtoFirst.Id);
                if (asCouple != null)
                {
                    var account = _referentialService.AccountService.GetFullById(asCouple.IdAccount);
                    asCouple.Account = account;
                    asDtoSecond      = _mapper.Map <AsForTableDto>(asCouple);
                }

                InternalTransferDto internalTransferDto = new InternalTransferDto()
                {
                    AsFirst  = asDtoFirst,
                    AsSecond = asDtoSecond
                };
                internalTransferDtos.Add(internalTransferDto);
            }

            return(internalTransferDtos);
        }
Example #4
0
        public async Task <IActionResult> Create(AccountStatementViewModel model)
        {
            if (ModelState.IsValid)
            {
                IFileUpload upload;
                try
                {
                    upload = await context.SaveFileUploadAsync(model.Attachment);
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to save uploaded file. Please upload it again later.", ex);
                }
                var statement = new AccountStatement
                {
                    BankAccountId = model.BankAccountId.Value,
                    FileUploadId  = upload.Id,
                    ProcessedAt   = DateTimeOffset.Now
                };
                context.AccountStatements.Add(statement);
                await context.SaveChangesAsync();

                statementProcessor.StartProcessing(statement.Id);

                return(RedirectToAction("Index"));
            }
            ViewData["BankAccountId"] = new SelectList(context.BankAccounts, "Id", "Name", model.BankAccountId);
            return(View(model));
        }
Example #5
0
        public DataSet GetAccountStatementForAccountDetail(AccountStatement prefix1)
        {
            Connect();
            DataSet dsAccountStatementDetails = null;

            try
            {
                SqlCommand cmd = new SqlCommand("GetAccountStatementForAccountDetail", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@HospitalID", HospitalID);
                cmd.Parameters.AddWithValue("@LocationID", LocationID);
                cmd.Parameters.AddWithValue("@FromDate", prefix1.FromDate);
                cmd.Parameters.AddWithValue("@ToDate", prefix1.ToDate);
                cmd.Parameters.AddWithValue("@AccountsID", prefix1.AccountsID);

                con.Open();
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand          = cmd;
                dsAccountStatementDetails = new DataSet();
                da.Fill(dsAccountStatementDetails);
                con.Close();
                return(dsAccountStatementDetails);
            }
            catch (Exception)
            {
                return(dsAccountStatementDetails);
            }
        }
Example #6
0
 public DisplayableAccountStatement(AccountStatement x)
 {
     SerialNumber = x.SerialNumber;
     Description  = x.Description;
     Date         = x.Date;
     Credit       = x.GetCreditValueOrNull();
     Debit        = x.GetDebitValueOrNull();
     Balance      = x.RunningTotaledValue;
 }
Example #7
0
        public async Task <IActionResult> DeleteConfirmed(int id)
        {
            AccountStatement accountStatement = await context.AccountStatements.SingleAsync(m => m.Id == id);

            context.AccountStatements.Remove(accountStatement);
            await context.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
        private async Task UpdateDocument(AccountStatement document)
        {
            await _documentRepository.UpdateAsync(document.Key, document);

            if (_cacheRepository.KeyExistsAsync(document.Key).Result)
            {
                await _cacheRepository.SetAsync(document.Key, document, TimeSpan.FromSeconds(_cacheExpiryInSeconds));
            }
        }
Example #9
0
        public ActionResult DuePayments() // Forfallsoversikt
        {
            //Session["LoggedIn"] = true; // TODO: REMEMBER TO COMMENT OUT. ONLY USED DURING TESTING PHASE
            //Session["UserId"] = "01018912345"; // TODO: REMEMBER TO COMMENT OUT. ONLY USED DURING TESTING PHASE
            if (Session["LoggedIn"] != null)
            {
                bool loggedIn = (bool)Session["LoggedIn"];
                if (!loggedIn)
                {
                    return(RedirectToAction("LoginBirth", "Home", new { area = "" }));
                }

                if (!ModelState.IsValid)
                {
                    return(View());
                }

                string userBirthNo = Session["UserId"] as string;

                // Get accounts to user:
                List <Account> accounts = bankService.getAccountsByBirthNo(userBirthNo);
                var            model    = new AccountStatement();

                var accountViewModels = new List <AccountViewModel>();
                // Populate AccountViewModel list with accounts:
                foreach (var a in accounts)
                {
                    AccountViewModel viewModel = new AccountViewModel()
                    {
                        Type      = a.Type,
                        AccountNo = a.AccountNo,
                        Balance   = a.Balance
                    };
                    accountViewModels.Add(viewModel);
                }

                // Set initial dates for the datepickers:
                DateTime currDatePlusOne = DateTime.Today.AddDays(1);    // Current day plus one
                DateTime oneMonthAgo     = DateTime.Today.AddMonths(-1); // Date one month ago at 0:00am

                var duePayments = new DuePayments()
                {
                    Accounts = accountViewModels,
                    fromDate = oneMonthAgo,
                    toDate   = currDatePlusOne
                };

                return(View(duePayments));
            }
            else
            {
                return(RedirectToAction("LoginBirth", "Home", new { area = "" }));
            }
        }
Example #10
0
        public string GetAccountStatement(Stream Parameterdetails)
        {
            string JsonStringForSerialized = "";

            try
            {
                AccountStatement objAccountStatement = new AccountStatement();
                JsonStringForSerialized = objAccountStatement.GetAccountStatement(Parameterdetails);
            }
            catch { }
            return(JsonStringForSerialized);
        }
Example #11
0
        public async Task <IActionResult> Edit(AccountStatement accountStatement)
        {
            if (ModelState.IsValid)
            {
                context.Update(accountStatement);
                await context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            ViewData["BankAccountId"] = new SelectList(context.BankAccounts, "Id", "BankAccount", accountStatement.BankAccountId);
            ViewData["FileUploadId"]  = new SelectList(context.FileUploads, "Id", "FileUpload", accountStatement.FileUploadId);
            return(View(accountStatement));
        }
        public JsonResult LoadGrid(string sidx, string sord, int rows, int page = 1)
        {
            string getSearchby  = Request["_searchby"];
            string getVal       = Request["_val"];
            string getStartDate = Request["_startDate"];
            string getEndDate   = Request["_endDate"];

            Params param = new Params()
            {
                Parameter = new Dictionary <string, string>()
            };

            param.RequestTransType = "AccountStatement";
            param.Parameter.Add("acctNo", getVal);
            param.Parameter.Add("startDate", getStartDate.Replace("/", "").Trim());
            param.Parameter.Add("endDate", getEndDate.Replace("/", "").Trim());
            AllChannelTransaction data = AccountStatement.Mutasi(param, Session["isSuperAdmin"].ToString());
            var trx = data.Transactions.ToList().Select(x => new
            {
                Number = x.Number,
                displayTransactionDate = x.displayTransactionDate,
                TransactionDate        = x.TransactionDate,
                TransactionType        = x.TransactionType,
                TransactionDescription = x.TransactionDescription,
                Branch = x.Branch,
                Amount = x.Amount
            });

            int pageIndex    = Convert.ToInt32(page) - 1;
            int pageSize     = rows;
            int totalRecords = trx.Count();
            int totalPages   = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            trx = trx.Skip((page - 1) * pageSize).Take(pageSize);
            var       recordCount = trx.Count();
            JSONTable jTable      = new JSONTable();

            jTable.total   = totalPages;
            jTable.page    = page;
            jTable.records = totalRecords;
            jTable.rows    = trx.ToArray();

            string restricted = "Y".Equals(Session["isSuperAdmin"].ToString())? string.Empty : data.RestrictedAccount ? "Restricted Account" : string.Empty;

            jTable.additional = data.Name + "<@z>" + data.Currency + "<@z>" + restricted;

            return(Json(jTable, JsonRequestBehavior.AllowGet));
        }
        /// <exception cref="GPClientException"></exception>
        public byte[] GetStatement(AccountStatement accountStatement)
        {
            var restRequest = CreateRestRequest(@"/accounts/account-statement", "application/json");
            var jsonData    = serializeToJson(accountStatement);

            restRequest.AddParameter("application/json", jsonData, ParameterType.RequestBody);
            var    response = Client.Execute(restRequest);
            string content  = response.Content.ToString();

            if (content.Contains("error_code"))
            {
                Deserialize <APIError>(content);
            }

            return(System.Text.Encoding.UTF8.GetBytes(content));
        }
Example #14
0
        public void BalanceStatementsShouldBeImmutable()
        {
            DateTime today                     = DateTime.Now;
            var      firstStatement            = new AccountStatement(today, 100, 100);
            var      secondStatement           = new AccountStatement(today, 100, 100);
            List <AccountStatement> statements = new List <AccountStatement>
            {
                firstStatement,
                secondStatement
            };
            var balance           = new Balance(statements);
            var currentStatements = balance.GetAccountStatements();

            currentStatements.RemoveAt(0);
            Check.That(statements.Count).IsEqualTo(2);
        }
Example #15
0
        // GET: AccountStatements/Details/5
        public async Task <IActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(HttpNotFound());
            }

            AccountStatement accountStatement = await context.AccountStatements.SingleAsync(m => m.Id == id);

            if (accountStatement == null)
            {
                return(HttpNotFound());
            }

            return(View(accountStatement));
        }
Example #16
0
        public string ValidateAccountStatement(AccountStatement accountStatement)
        {
            if (accountStatement.StartBalance.Currency != accountStatement.EndBalance.Currency)
            {
                return($"Startbalance currency ({accountStatement.StartBalance.Currency}) does not match endbalance currency ({accountStatement.EndBalance.Currency})");
            }

            var transactionSum = Math.Round(accountStatement.Transactions.Sum(t => t.Value), 2);
            var end            = accountStatement.StartBalance.Value + transactionSum;

            if (end != accountStatement.EndBalance.Value)
            {
                return($"Enbalance ({accountStatement.EndBalance.Value}) does not match startbalance ({accountStatement.StartBalance.Value}) + transactions ({transactionSum})");
            }

            return(string.Empty);
        }
Example #17
0
        // GET: AccountStatements/Edit/5
        public async Task <IActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(HttpNotFound());
            }

            AccountStatement accountStatement = await context.AccountStatements.SingleAsync(m => m.Id == id);

            if (accountStatement == null)
            {
                return(HttpNotFound());
            }
            ViewData["BankAccountId"] = new SelectList(context.BankAccounts, "Id", "BankAccount", accountStatement.BankAccountId);
            ViewData["FileUploadId"]  = new SelectList(context.FileUploads, "Id", "FileUpload", accountStatement.FileUploadId);
            return(View(accountStatement));
        }
        public ActionResult AccountName(string prefix)
        {
            BL_AccountStatement     objAcc     = new BL_AccountStatement();
            List <AccountStatement> searchlist = new List <AccountStatement>();
            DataSet ds = objAcc.BindAccountStatement(prefix);
            int     i  = 0;

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                AccountStatement AccStat = new AccountStatement();
                AccStat.AccountsID  = dr["AccountsID"].ToString();
                AccStat.AccountName = dr["AccountName"].ToString();
                searchlist.Add(AccStat);
            }
            return(new JsonResult {
                Data = searchlist, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
Example #19
0
        public static string GetRedboxAccountStatementPayload(AccountStatement accountstatement)
        {
            string channel   = ConfigurationManager.AppSettings["channel"];
            string payload   = "";
            Random reqTranId = new Random();

            try
            {
                payload = "<soapenv:Envelope xmlns: soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns: soap =\"http://soap.request.manager.redbox.stanbic.com/\">" +
                          "<soapenv:Header/>" +
                          "<soapenv:Body>" +
                          "<soap:request>" +
                          "<channel>" + channel + "</channel>" +
                          "<type>ACCOUNT_STATEMENT</type>" +
                          "<customerId>" + accountstatement.CustomerId + "</customerId>" +
                          "<customerIdType>" + accountstatement.CustomerIdType + "</customerIdType>" +
                          "<submissionTime>" + accountstatement.SubmissionTime + "</submissionTime>" +
                          "<reqTranId>" + reqTranId.Next(100000, 999999) + "</reqTranId>" +
                          "<body>" +
                          "<![CDATA[" +
                          "<otherRequestDetails>" +
                          "<sessionId>" + accountstatement.SessionId + "</sessionId>" +
                          "<accountNumber>" + accountstatement.AccountNumber + "</accountNumber>" +
                          "<startDate>" + accountstatement.StartDate + "</startDate>" +
                          "<endDate>" + accountstatement.EndDate + "</endDate>" +
                          "<fileType>" + accountstatement.FileType + "</fileType>" +

                          "<passId>" + accountstatement.PassId + "</passId>" +
                          "<passIdType>" + accountstatement.PassIdType + "</passIdType>" +
                          "<passCodeType>" + accountstatement.PassCodeType + "</passCodeType>" +
                          "<passCode>" + accountstatement.PassCode + "</passCode>" +
                          "</otherRequestDetails>" +
                          "]]>" +
                          "</body>" +
                          "</soap:request>" +
                          "</soapenv:Body>";
            }
            catch
            {
                throw;
            }
            return(payload);
        }
Example #20
0
        public ActionResult Overview() // Total oversikt
        {
            if (Session["LoggedIn"] != null)
            {
                string         birthID  = Session["UserId"] as string;
                List <Account> accounts = bankService.getAccountsByBirthNo(birthID);
                var            model    = new AccountStatement();

                var accountViewModels = new List <AccountViewModel>();
                // Populate AccountViewModel list with accounts:
                foreach (var a in accounts)
                {
                    AccountViewModel viewModel = new AccountViewModel()
                    {
                        Type      = a.Type,
                        AccountNo = a.AccountNo,
                        Balance   = a.Balance,
                        Name      = a.Name
                    };
                    accountViewModels.Add(viewModel);
                }

                var accountStatement = new AccountStatement()
                {
                    Accounts = accountViewModels,
                };

                bool loggedIn = (bool)Session["LoggedIn"];
                if (!loggedIn)
                {
                    return(RedirectToAction("LoginBirth", "Home", new { area = "" }));
                }
                else
                {
                    var            kundeDb   = new BankService();
                    Customer       enKunde   = kundeDb.getCustomerByBirthNo(birthID);
                    List <Account> alleKonto = kundeDb.getAccountsByBirthNo(birthID);
                    return(View(accountStatement));
                }
            }
            return(RedirectToAction("LoginBirth", "Home", new { area = "" }));
        }
        public void GPConnectorTestStatementGenerating()
        {
            var connector = new GPConnector(TestUtils.API_URL, TestUtils.CLIENT_ID, TestUtils.CLIENT_SECRET);

            var accountStatement = new AccountStatement
            {
                DateFrom = new DateTime(2017, 1, 1),
                DateTo   = new DateTime(2017, 2, 27),
                GoID     = TestUtils.GOID,
                Currency = Currency.CZK,
                Format   = StatementGeneratingFormat.CSV_A
            };

            try
            {
                var statement = connector.GetAppToken().GetStatement(accountStatement);
                Assert.NotNull(statement);

                var content = Encoding.UTF8.GetString(statement);

                Console.WriteLine("Content of Array to string: {0}", content);
                Console.WriteLine(
                    "----------------------------------------------------------------------------------------");

                Console.Write("Byte content: ");
                for (var i = 0; i < statement.Length; i++)
                {
                    Console.Write(" {0}", statement[i]);
                }
            }
            catch (GPClientException ex)
            {
                Console.WriteLine("Generating account statement ERROR");
                var err  = ex.Error;
                var date = err.DateIssued;
                foreach (var element in err.ErrorMessages)
                {
                    //
                }
            }
        }
Example #22
0
        static void Main(string[] args)
        {
            ApiExplorer explorer = new ApiExplorer("YOUR_TOKEN_MUST_BE_PRESENT_HERE");

            // get new transactions from last check
            AccountStatement newTransactions = explorer.Last();

            // change last check date
            explorer.SetLastDownloadDate(DateTime.UtcNow.AddMonths(-1));

            // get account statement
            AccountStatement statement = explorer.Periods(TransactionFilter.LastMonth());

            // browse transactions
            foreach (var transaction in statement.TransactionList.Transactions)
            {
                Console.WriteLine(transaction + " - " + transaction.Amount.Value);
            }

            // get data in specific format
            string data = explorer.Periods(TransactionFilter.LastDays(10), Format.Html);
        }
        protected override async Task <AccountStatement> ProcessAsync(ICommand command)
        {
            var qMessage = (StatementMessage)command;

            var monthlyStatement = await _transactionClient.GetStatement(qMessage.AccountNumber, qMessage.Month);

            var statementDate = new StatementDate(qMessage.Month);

            const string DateFormat = "dd/MM/yyyy";

            var accountStatement = new AccountStatement()
            {
                Key           = $"{monthlyStatement.AccountNumber}-{qMessage.Month}",
                Name          = qMessage.Name,
                AccountNumber = monthlyStatement.AccountNumber,
                Currency      = qMessage.Currency,
                StartDate     = statementDate.StartDate.ToString(DateFormat),
                EndDate       = statementDate.EndDate.ToString(DateFormat),
                // Logic used here to calculate opening & closing balance is not accurate and needs improvement
                OpeningBalance = monthlyStatement.TransactionDetails.OrderBy(i => i.Date).Select(i => i.CurrentBalance).FirstOrDefault(),
                ClosingBalance = monthlyStatement.TransactionDetails.OrderByDescending(i => i.Date).Select(i =>
                                                                                                           i.TransactionType == TransactionType.Deposit.ToString() ?
                                                                                                           (i.CurrentBalance + i.Amount) :
                                                                                                           (i.CurrentBalance - i.Amount)
                                                                                                           ).FirstOrDefault(),
                TransactionDetails = monthlyStatement.TransactionDetails.Select(i => new AccountTransaction()
                {
                    Date = i.Date.ToString(DateFormat),
                    TransactionDetail = i.Description,
                    Withdrawal        = i.TransactionType == TransactionType.Withdrawal.ToString() ? i.Amount.ToString() : string.Empty,
                    Deposit           = i.TransactionType == TransactionType.Deposit.ToString() ? i.Amount.ToString() : string.Empty,
                    Balance           = i.TransactionType == TransactionType.Deposit.ToString() ?
                                        (i.CurrentBalance + i.Amount) :
                                        (i.CurrentBalance - i.Amount)
                })
            };

            return(accountStatement);
        }
Example #24
0
        public string ValidateAccountStatement(AccountStatement accountStatement)
        {
            if (accountStatement.StartBalance.Currency != accountStatement.EndBalance.Currency)
            {
                return($"Startbalance currency ({accountStatement.StartBalance.Currency}) does not match endbalance currency ({accountStatement.EndBalance.Currency})");
            }

            if (accountStatement.CreditTransactionSummary != null && accountStatement.DebitTransactionSummary != null)
            {
                var transactionSum = Math.Round(accountStatement.Transactions.Sum(t => (decimal)t.Value), 2);
                var totalNumber    = accountStatement.Transactions.Count;

                var transactionSumValidation = accountStatement.CreditTransactionSummary.Sum - accountStatement.DebitTransactionSummary.Sum;
                var totalNumberValidation    = accountStatement.CreditTransactionSummary.NumberOfTransaction + accountStatement.DebitTransactionSummary.NumberOfTransaction;

                if (transactionSum != transactionSumValidation)
                {
                    return($"Transaction sum ({transactionSum}) does not match validation sum ({transactionSumValidation})");
                }

                if (totalNumber != totalNumberValidation)
                {
                    return($"Transaction count ({totalNumber}) does not match validation count ({totalNumberValidation})");
                }
            }
            else if (accountStatement.StartBalance != null && accountStatement.EndBalance != null)
            {
                var transactionSum = Math.Round(accountStatement.Transactions.Sum(t => t.Value), 2);
                var end            = accountStatement.StartBalance.Value + transactionSum;
                if (end != accountStatement.EndBalance.Value)
                {
                    return($"Enbalance ({accountStatement.EndBalance.Value}) does not match startbalance ({accountStatement.StartBalance.Value}) + transactions ({transactionSum})");
                }
            }

            return(string.Empty);
        }
Example #25
0
        public async Task <ActionResult> TenDollarPromo()
        {
            try
            {
                var accountStatement = new AccountStatementRepository();

                var promo = new AccountStatement
                {
                    User            = User.Identity.Name,
                    Credit          = 10,
                    CurrentBalance  = 10,
                    TransactionDate = Helper.SetDateForMongo(DateTime.Now),
                    Description     = "Early adopter $10 promo"
                };

                accountStatement.Create(promo);
                return(Json(new { success = true, responseText = "Added." }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return(Json(new { success = false, responseText = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
Example #26
0
        public IHttpActionResult AccountStatement([FromBody] AccountStatement accountStatement)
        {
            try
            {
                //accountStatement.startDate = new DateTime.Now();
                if (!ModelState.IsValid)
                {
                    return(BadRequest("Invalid data."));
                }

                string accountStatementReq = App.GetRedboxAccountStatementPayload(accountStatement);

                string accountStatementRes = App.CallRedbox(accountStatementReq);

                LogWorker logworker = new LogWorker("AccountStatementController", "AccountStatement", "Ok");

                return(Ok(accountStatementRes));
            }
            catch (Exception ex)
            {
                LogWorker logworker = new LogWorker("AccountStatementController", "AccountStatement", ex.ToString());
                return(InternalServerError());
            }
        }
Example #27
0
 public AccountStatementResult(AccountStatement accountStatement, string error)
 {
     AccountStatement = accountStatement;
     Error            = error;
     IsSuccess        = string.IsNullOrEmpty(error);
 }
        private List <AccountStatement> GetAccountStement(List <UserTransaction> lstTransaction, User LoginUser)
        {
            List <AccountStatement> lstAccountStatement = new List <AccountStatement>();

            if (lstTransaction != null && lstTransaction.Count > 0)
            {
                ViewBag.AccountBalance = lstTransaction.Sum(ut => ut.TransactionAmount);
                foreach (UserTransaction tran in lstTransaction)
                {
                    AccountStatement statement = new AccountStatement();
                    if (tran.TransactionMode == TransactionMode.ADDFUND)
                    {
                        statement.PaymentAmount   = tran.TransactionAmount;
                        statement.OrderDetailID   = 0;
                        statement.InvoiceID       = 0;
                        statement.TransactionDate = tran.AuditDetails.DateCreated;
                        if (tran.PaymentID != null && tran.PaymentID > 0)
                        {
                            statement.TransactionDetail = "Fund Added By " + LoginUser.FirstName + " " + LoginUser.LastName;
                            statement.PaymentMode       = tran.Payment.PaymentMode;
                        }
                        else
                        {
                            statement.TransactionDetail = "Fund Added By Admin" + "<br />" + tran.ReceipientInstrumentDetails;
                            statement.PaymentMode       = null;
                        }
                        statement.TransactionMode   = TransactionMode.ADDFUND;
                        statement.UserTransactionID = tran.ID;
                    }
                    else if (tran.TransactionMode == TransactionMode.REFUND)
                    {
                        statement.PaymentAmount     = tran.TransactionAmount;
                        statement.OrderDetailID     = 0;
                        statement.InvoiceID         = 0;
                        statement.TransactionDate   = tran.AuditDetails.DateCreated;
                        statement.TransactionDetail = "Credit given against cancelled order #" + InvoicePrefix + tran.OrderDetail.OrderID;
                        statement.TransactionMode   = TransactionMode.REFUND;
                        statement.UserTransactionID = tran.ID;
                    }
                    else if (tran.TransactionMode == TransactionMode.ORDER)
                    {
                        if (lstAccountStatement.Where(ut => ut.OrderDetailID == tran.OrderDetailID).FirstOrDefault() == null)
                        {
                            statement.OrderDetailID     = Convert.ToInt32(tran.OrderDetailID);
                            statement.InvoiceID         = tran.OrderDetail.OrderID;
                            statement.TransactionDate   = tran.AuditDetails.DateCreated;
                            statement.TransactionDetail = "Order Placed for #" + InvoicePrefix + tran.OrderDetail.OrderID;
                            statement.TransactionMode   = TransactionMode.ORDER;
                            statement.UserTransactionID = tran.ID;
                            int             ordCount   = lstTransaction.Select(ut => ut.OrderDetailID == tran.OrderDetailID).Count();
                            UserTransaction ordCredit  = lstTransaction.Where(ut => (ut.PaymentID ?? 0) <= 0 && ut.OrderDetailID == tran.OrderDetailID).FirstOrDefault();
                            UserTransaction ordPayment = lstTransaction.Where(ut => (ut.PaymentID ?? 0) > 0 && ut.OrderDetailID == tran.OrderDetailID).FirstOrDefault();
                            if (ordPayment != null)
                            {
                                statement.PaymentMode   = ordPayment.Payment.PaymentMode;
                                statement.PaymentAmount = (ordCredit != null ? ordPayment.OrderDetail.Price + ordCredit.TransactionAmount : ordPayment.OrderDetail.Price);
                            }
                            if (ordCredit != null)
                            {
                                statement.CreditAmount = ordCredit.TransactionAmount * -1;
                            }
                        }
                    }
                    else if (tran.TransactionMode == TransactionMode.REISSUE)
                    {
                        statement.PaymentAmount     = tran.TransactionAmount * -1;
                        statement.OrderDetailID     = 0;
                        statement.InvoiceID         = 0;
                        statement.TransactionDate   = tran.AuditDetails.DateCreated;
                        statement.TransactionDetail = tran.ReceipientInstrumentDetails;
                        statement.TransactionMode   = TransactionMode.REISSUE;
                        statement.UserTransactionID = tran.ID;
                    }
                    if (statement.UserTransactionID > 0)
                    {
                        lstAccountStatement.Add(statement);
                    }
                }
            }
            else
            {
                ViewBag.AccountBalance = 0;
            }
            return(lstAccountStatement);
        }
Example #29
0
        public List <AccountStatement> ReadFile(string filePath, Encoding encoding)
        {
            var accountStatements = new List <AccountStatement>();
            var serializer        = new XmlSerializer(typeof(Document));

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                using (var reader = new StreamReader(fileStream, encoding))
                {
                    var document = (Document)serializer.Deserialize(reader);
                    foreach (var stmt in document.BkToCstmrStmt.Stmt)
                    {
                        var accountStatement = new AccountStatement();
                        accountStatements.Add(accountStatement);

                        accountStatement.AccountNumber = stmt.Acct.Id.Item.ToString();
                        accountStatement.Currency      = stmt.Acct.Ccy;

                        foreach (var balance in stmt.Bal)
                        {
                            // var balanceAmount =  balance.Amt.Value;
                            // var balanceCurrency = balance.Amt.Ccy;
                            // var balanceDate = balance.Dt.Item;
                            // var creditDebit = balance.CdtDbtInd;

                            var balanceType = (BalanceType12Code)balance.Tp.CdOrPrtry.Item;
                            if (balanceType == BalanceType12Code.OPBD)
                            {
                                accountStatement.StartBalance = new Balance
                                {
                                    BookingDate = balance.Dt.Item,
                                    Value       = (double)balance.Amt.Value,
                                };
                            }
                            else if (balanceType == BalanceType12Code.CLBD)
                            {
                                accountStatement.EndBalance = new Balance
                                {
                                    BookingDate = balance.Dt.Item,
                                    Value       = (double)balance.Amt.Value,
                                };
                            }
                        }

                        if (stmt.TxsSummry != null)
                        {
                            if (stmt.TxsSummry.TtlCdtNtries != null)
                            {
                                accountStatement.CreditTransactionSummary = new TransactionSummary
                                {
                                    NumberOfTransaction = int.Parse(stmt.TxsSummry.TtlCdtNtries.NbOfNtries),
                                    Sum = stmt.TxsSummry.TtlCdtNtries.Sum
                                };
                            }
                            else
                            {
                                accountStatement.CreditTransactionSummary = new TransactionSummary();
                            }

                            if (stmt.TxsSummry.TtlDbtNtries != null)
                            {
                                accountStatement.DebitTransactionSummary = new TransactionSummary
                                {
                                    NumberOfTransaction = int.Parse(stmt.TxsSummry.TtlDbtNtries.NbOfNtries),
                                    Sum = stmt.TxsSummry.TtlDbtNtries.Sum
                                };
                            }
                            else
                            {
                                accountStatement.DebitTransactionSummary = new TransactionSummary();
                            }
                        }

                        accountStatement.Transactions = new List <Transaction>();
                        if (stmt.Ntry != null)
                        {
                            foreach (var entry in stmt.Ntry)
                            {
                                (var text, var debtor, var creditor) = ParseEntry(entry);

                                var transaction = new Transaction();
                                transaction.Id          = stmt.Id + entry.NtryRef;
                                transaction.BookingDate = entry.BookgDt.Item;
                                transaction.Text        = text;
                                transaction.Debtor      = debtor;
                                transaction.Creditor    = creditor;
                                transaction.Value       = (double)entry.Amt.Value;
                                transaction.ValueDate   = entry.ValDt.Item;

                                if (entry.CdtDbtInd == CreditDebitCode.DBIT)
                                {
                                    transaction.Value *= -1;
                                }

                                accountStatement.Transactions.Add(transaction);
                            }
                        }
                    }
                }
            }

            return(accountStatements);
        }
 private string GetPreviosBalance(AccountStatement accountStatements)
 {
     if (accountStatements != null)
     {
         var prevBalance = accountStatements.PrevBalance;
         var accountStatementCurrency = accountStatements.Currency.ConvertToCurrencyDto();
         return string.Format("{0}{1} ", accountStatementCurrency.CurrencySymbol, prevBalance);
     }
     return string.Empty;
 }
Example #31
0
        public List <AccountStatement> ReadFile(string filePath, Encoding encoding)
        {
            var accountList                     = new List <AccountStatement>();
            AccountStatement account            = null;
            Transaction      currentTransaction = null;
            List <string>    transactionTexts   = null;

            foreach (var line in File.ReadLines(filePath, encoding))
            {
                if (line.Length < 3)
                {
                    continue;
                }

                var codeValue = ParseLine(line);
                switch (codeValue.Item1)
                {
                // Account
                case ":25:":
                    account = new AccountStatement();
                    accountList.Add(account);
                    account.AccountNumber = codeValue.Item2;
                    break;

                // Start balance
                case ":60F:":
                    account.StartBalance = ParseBalance(codeValue.Item2);
                    break;

                // End balance
                case ":62F:":
                    account.EndBalance = ParseBalance(codeValue.Item2);
                    break;

                // Transaction
                case ":61:":
                    // have we an old transaction
                    if (currentTransaction != null && transactionTexts.Any())
                    {
                        currentTransaction.Text = string.Join(", ", transactionTexts);
                    }
                    transactionTexts   = new List <string>();
                    currentTransaction = ParseTransaction(codeValue.Item2);
                    account.Transactions.Add(currentTransaction);
                    break;

                // Transaction text
                case ":NS:":
                    //if (currentTransaction != null) currentTransaction.Text = codeValue.Item2;
                    break;
                }
                if (codeValue.Item1.IndexOf(':') == -1 && currentTransaction != null)
                {
                    if (transactionTexts.Contains(codeValue.Item2) == false)
                    {
                        transactionTexts.Add(codeValue.Item2);
                    }
                }
            }
            // have we an old transaction
            if (currentTransaction != null && transactionTexts.Any())
            {
                currentTransaction.Text = string.Join(", ", transactionTexts);
            }

            return(accountList);
        }
        private string GetAccountStatementItemString(AccountStatement accountStatement, EntityDto[] entities)
        {
            var itemIdAndName = accountStatement.GetItemIdAndName();
            var entityName = accountStatement.GetEntityName(entities);
            var isCoupon = accountStatement.Coupon != null;
            var itemString = string.Empty;

            if (isCoupon)
            {
                var coupon = accountStatement.Coupon;
                var idAndName = coupon.GetCouponItemIdAndName();
                var couponItemEntityName = coupon.GetItemEntityName(entities);
                var sb = new StringBuilder();
                sb.AppendFormat("{0} {1}", entityName, itemIdAndName.Key);
                sb.AppendFormat(" {0} {1} {2} {3}", MyMentorResources.itemFor, couponItemEntityName, idAndName.Value, idAndName.Key);
                itemString = sb.ToString();
            }
            else
            {
                itemString = string.Format("{0} {1} {2}", entityName, itemIdAndName.Key, itemIdAndName.Value);
            }
            return itemString;
        }