public async Task ThenTheProviderNameIsTakenFromTheService()
        {
            //Arrange
            var expectedUkprn = 545646541;
            var transactions  = new TransactionLine[]
            {
                new PaymentTransactionLine()
                {
                    AccountId       = 1,
                    TransactionDate = DateTime.Now.AddMonths(-3),
                    Amount          = 1000,
                    TransactionType = TransactionItemType.Payment,
                    UkPrn           = expectedUkprn,
                    PeriodEnd       = "17-18"
                }
            };

            _dasLevyService.Setup(x => x.GetAccountTransactionsByDateRange(It.IsAny <long>(), It.IsAny <DateTime>(), It.IsAny <DateTime>()))
            .ReturnsAsync(transactions);

            _dasLevyService.Setup(x => x.GetProviderName(expectedUkprn, It.IsAny <long>(), It.IsAny <string>())).ReturnsAsync("test");
            //Act
            var actual = await RequestHandler.Handle(_request);

            //Assert
            _dasLevyService.Verify(x => x.GetProviderName(expectedUkprn, It.IsAny <long>(), It.IsAny <string>()), Times.Once);
        }
        private async Task GenerateTransactionDescription(TransactionLine transaction)
        {
            if (transaction.GetType() == typeof(LevyDeclarationTransactionLine))
            {
                transaction.Description = transaction.Amount >= 0 ? "Levy" : "Levy adjustment";
            }
            else if (transaction.GetType() == typeof(PaymentTransactionLine))
            {
                var paymentTransaction = (PaymentTransactionLine)transaction;

                transaction.Description = await GetPaymentTransactionDescription(paymentTransaction);
            }
            else if (transaction.GetType() == typeof(ExpiredFundTransactionLine))
            {
                transaction.Description = "Expired levy";
            }
            else if (transaction.GetType() == typeof(TransferTransactionLine))
            {
                var transferTransaction = (TransferTransactionLine)transaction;

                if (transferTransaction.TransactionAccountIsTransferSender)
                {
                    transaction.Description = $"Transfer sent to {transferTransaction.ReceiverAccountName}";
                }
                else
                {
                    transaction.Description = $"Transfer received from {transferTransaction.SenderAccountName}";
                }
            }
        }
        public async Task ThenTheProviderNameIsSetToUnknownProviderIfTheRecordCantBeFound()
        {
            //Arrange
            var transactions = new TransactionLine[]
            {
                new PaymentTransactionLine
                {
                    AccountId       = 1,
                    TransactionDate = DateTime.Now.AddMonths(-3),
                    Amount          = 1000,
                    TransactionType = TransactionItemType.Payment,
                    UkPrn           = 1254545
                }
            };

            _dasLevyService.Setup(x => x.GetAccountTransactionsByDateRange(It.IsAny <long>(), It.IsAny <DateTime>(), It.IsAny <DateTime>()))
            .ReturnsAsync(transactions);

            _dasLevyService.Setup(x => x.GetProviderName(It.IsAny <long>(), It.IsAny <long>(), It.IsAny <string>()))
            .ReturnsAsync((string)null);

            //Act
            var actual = await RequestHandler.Handle(_request);

            //Assert
            Assert.AreEqual("Training provider - name not recognised", actual.Data.TransactionLines.First().Description);
        }
        public override async Task ThenIfTheMessageIsValidTheValueIsReturnedInTheResponse()
        {
            //Arrange
            var transactions = new TransactionLine[]
            {
                new LevyDeclarationTransactionLine
                {
                    AccountId       = 1,
                    SubmissionId    = 1,
                    TransactionDate = DateTime.Now.AddDays(-3),
                    Amount          = 1000,
                    TransactionType = TransactionItemType.TopUp,
                    EmpRef          = "123"
                }
            };

            _dasLevyService.Setup(x => x.GetAccountTransactionsByDateRange(It.IsAny <long>(), It.IsAny <DateTime>(), It.IsAny <DateTime>()))
            .ReturnsAsync(transactions);

            //Act
            var response = await RequestHandler.Handle(_request);

            //Assert
            Assert.AreEqual(_request.HashedAccountId, response.Data.HashedAccountId);
            Assert.AreEqual(1, response.Data.AccountId);
            Assert.AreEqual(1, response.Data.TransactionLines.Length);
        }
Esempio n. 5
0
        /// <summary>
        /// Adjust product stock based on a transaction occurred.
        /// </summary>
        internal void RecordTransaction(TransactionLine transactionLine)
        {
            if (transactionLine.Quantity > NumberInStock)
            {
                throw new InsufficientStockException(this, transactionLine.Quantity);
            }

            if (transactionLine.Quantity < 1)
            {
                throw new ArgumentException("Product quantity in transaction must be 1 or greater.");
            }

            if (transactionLine.Transaction.TransactionType == TransactionType.Sales)
            {
                NumberInStock -= transactionLine.Quantity;
            }
            else if (transactionLine.Transaction.TransactionType == TransactionType.Procurement)
            {
                NumberInStock += transactionLine.Quantity;
            }
            else
            {
                throw new InvalidEnumArgumentException($"Unexpected {nameof(TransactionType)}: '{transactionLine.Transaction.TransactionType}'.");
            }
        }
        public async Task ThenShouldLogIfExceptionOccursWhenGettingProviderName()
        {
            //Arrange
            var transactions = new TransactionLine[]
            {
                new PaymentTransactionLine
                {
                    AccountId       = 1,
                    TransactionDate = DateTime.Now.AddMonths(-3),
                    Amount          = 1000,
                    TransactionType = TransactionItemType.Payment,
                    UkPrn           = 1254545
                }
            };

            _dasLevyService.Setup(x => x.GetAccountTransactionsByDateRange(It.IsAny <long>(), It.IsAny <DateTime>(), It.IsAny <DateTime>()))
            .ReturnsAsync(transactions);

            _dasLevyService.Setup(x => x.GetProviderName(It.IsAny <long>(), It.IsAny <long>(), It.IsAny <string>()))
            .Throws <Exception>();

            //Act
            await RequestHandler.Handle(_request);

            //Assert
            _logger.Verify(x => x.Info(It.Is <string>(y => y.StartsWith("Provider not found for UkPrn:1254545"))));
        }
Esempio n. 7
0
        public long?CreateOffer(long id, decimal price, long customerId)
        {
            var     entities = GeneralService.GetDbEntities();
            Product product  = entities.Products.FirstOrDefault(p => p.ID == id);

            if (product == null)
            {
                return(null);
            }
            product.OfferPrice = price;
            TransactionLine transaction = new TransactionLine
            {
                ProductID       = id,
                CategoryID      = product.CategoryID,
                CustomerID      = customerId,
                SellerID        = product.CustomerID,
                OfferPrice      = price,
                TransactionType = TransactionTypes.Offer,
                CreatedDate     = DateTime.Now,
            };

            entities.TransactionLines.Add(transaction);
            entities.SaveChanges();
            return(transaction.ID);
        }
Esempio n. 8
0
        public void SaveTransactionTaxLines(TransactionLine trxLine, int trxId)
        {
            try
            {
                if (trxLine.tax_amount > 0)
                {
                    SqlParameter[] sqlParameters = new SqlParameter[7];

                    sqlParameters[0]       = new SqlParameter("@trxId", SqlDbType.Int);
                    sqlParameters[0].Value = trxId;

                    sqlParameters[1] = new SqlParameter("@LineId", trxLine.LineId);

                    sqlParameters[2] = new SqlParameter("@TaxId", trxLine.tax_id);

                    sqlParameters[3] = new SqlParameter("@TaxStructureId", trxLine.tax_structer_id);

                    sqlParameters[4] = new SqlParameter("@Percentage", trxLine.tax_percentage);

                    sqlParameters[5] = new SqlParameter("@Amount", trxLine.tax_amount);

                    sqlParameters[6] = new SqlParameter("@ProductSplitAmount", 0);

                    conn.executeUpdateQuery("sp_InsertTransactionTaxLines", sqlParameters);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 9
0
        LedgerOperationStatus ILedger.RemoveFunds(AccountID accountID, decimal balance)
        {
            LedgerOperationStatus status      = LedgerOperationStatus.Success;
            TransactionLine       transaction = new TransactionLine(accountID,
                                                                    balance,
                                                                    LedgerDatabase.TransactionType.RemoveFunds);

            //find account line, lock it, update
            if (accountsTable.Contains(accountID))
            {
                AccountLine account = accountsTable.Select(accountID);
                lock (account)
                {
                    if (balance > account.Balance)
                    {
                        transaction.Status       = LedgerDatabase.TransactionStatus.Rejected;
                        transaction.RejectReason = TransactionRejectReason.InsufficientFunds;
                        status = LedgerOperationStatus.InsufficientFunds;
                    }
                    else
                    {
                        account.Balance -= balance;
                    }
                }
            }
            else
            {
                transaction.Status       = LedgerDatabase.TransactionStatus.Rejected;
                transaction.RejectReason = TransactionRejectReason.InvalidAccount;
                status = LedgerOperationStatus.InvalidAccount;
            }

            transactionsTable.Insert(transaction);
            return(status);
        }
        public async Task ThenShouldReturnPreviousTransactionsAreNotAvailableIfThereAreNone()
        {
            //Arrange
            var transactions = new TransactionLine[]
            {
                new LevyDeclarationTransactionLine
                {
                    AccountId       = 1,
                    SubmissionId    = 1,
                    TransactionDate = DateTime.Now.AddDays(-3),
                    Amount          = 1000,
                    TransactionType = TransactionItemType.TopUp,
                    EmpRef          = "123"
                }
            };

            _dasLevyService.Setup(x => x.GetAccountTransactionsByDateRange(It.IsAny <long>(), It.IsAny <DateTime>(), It.IsAny <DateTime>()))
            .ReturnsAsync(transactions);

            _dasLevyService.Setup(x => x.GetPreviousAccountTransaction(It.IsAny <long>(), It.IsAny <DateTime>()))
            .ReturnsAsync(0);

            //Act
            var result = await RequestHandler.Handle(_request);

            //Assert
            Assert.IsFalse(result.AccountHasPreviousTransactions);
        }
        public async Task ThenTheProviderNameIsNotRecognisedIfTheRecordThrowsAndException()
        {
            //Arrange
            var transactions = new TransactionLine[]
            {
                new PaymentTransactionLine
                {
                    AccountId       = 1,
                    TransactionDate = DateTime.Now.AddMonths(-3),
                    Amount          = 1000,
                    TransactionType = TransactionItemType.Payment,
                    UkPrn           = 1254545
                }
            };

            _dasLevyService.Setup(x => x.GetAccountTransactionsByDateRange(It.IsAny <long>(), It.IsAny <DateTime>(), It.IsAny <DateTime>()))
            .ReturnsAsync(transactions);

            _dasLevyService.Setup(x => x.GetProviderName(It.IsAny <long>(), It.IsAny <long>(), It.IsAny <string>())).Throws(new WebException());

            //Act
            var actual = await RequestHandler.Handle(_request);

            //Assert
            Assert.AreEqual("Training provider - name not recognised", actual.Data.TransactionLines.First().Description);
            _logger.Verify(x => x.Info(It.Is <string>(y => y.StartsWith("Provider not found for UkPrn:1254545"))));
        }
Esempio n. 12
0
        /// <summary>
        /// Adjust product stock based on a transaction occurred.
        /// </summary>
        internal void RecordTransaction(TransactionLine transactionLine)
        {
            if (transactionLine.Quantity < 1)
            {
                throw new ArgumentException("Product quantity in transaction must be 1 or greater.");
            }

            switch (transactionLine.Transaction.TransactionType)
            {
            case TransactionType.Sales:
                if (transactionLine.Quantity > NumberInStock)
                {
                    throw new InsufficientStockException(this, transactionLine.Quantity, NumberInStock);
                }
                NumberInStock -= transactionLine.Quantity;
                break;

            case TransactionType.Procurement:
                NumberInStock += transactionLine.Quantity;
                break;

            default:
                throw new InvalidEnumArgumentException($"Unexpected {nameof(TransactionType)}: '{transactionLine.Transaction.TransactionType}'.");
            }
        }
Esempio n. 13
0
        public void MergePayments(List <ReceiptOrPayment> found)
        {
            // add total, delete all but the latest date
            decimal          totalPayment     = 0;
            decimal          totalReceipt     = 0;
            DateTime         oldestPayment    = new DateTime(0);
            DateTime         oldestReceipt    = new DateTime(0);
            ReceiptOrPayment oldestPaymentObj = null;
            ReceiptOrPayment oldestReceiptObj = null;

            foreach (ReceiptOrPayment receiptOrPayment in found)
            {
                if (receiptOrPayment.Lines == null || receiptOrPayment.Lines.Length != 1)
                {
                    continue;
                }
                if (receiptOrPayment.Date == null)
                {
                    continue;
                }

                TransactionLine transactionLine = receiptOrPayment.Lines [0];
                if (receiptOrPayment.Type == Manager.Model.Enums.ReceiptOrPaymentType.Payment)
                {
                    totalPayment += transactionLine.Amount.Value;
                    if (oldestPayment.CompareTo(receiptOrPayment.Date) < 0)
                    {
                        oldestPayment    = receiptOrPayment.Date;
                        oldestPaymentObj = receiptOrPayment;
                    }
                }
                else if (receiptOrPayment.Type == Manager.Model.Enums.ReceiptOrPaymentType.Receipt)
                {
                    totalReceipt += transactionLine.Amount.Value;
                    if (oldestReceipt.CompareTo(receiptOrPayment.Date) < 0)
                    {
                        oldestReceipt    = receiptOrPayment.Date;
                        oldestReceiptObj = receiptOrPayment;
                    }
                }
                else
                {
                    continue;
                }

                DeleteObject(receiptOrPayment.Key);
            }
            if (oldestPaymentObj != null)
            {
                oldestPaymentObj.Lines [0].Amount = totalPayment;
                InsertObject(oldestPaymentObj);
            }
            if (oldestReceiptObj != null)
            {
                oldestReceiptObj.Lines [0].Amount = totalReceipt;
                InsertObject(oldestReceiptObj);
            }
        }
Esempio n. 14
0
        public void ImportPositiveStatement()
        {
            string line = "29/03			REMUNERACAO/SALARIO       	1370	4.730,81		";

            TransactionLine statement = parser.Parse(line)
                                        .First();

            Assert.Equal(4_730.81m, statement.Amount);
        }
Esempio n. 15
0
        public void ImportStatementWithCompleteDate()
        {
            string line = "18/03/2018	 D		INT PAG TIT BANCO 237        		952,27	-	";

            TransactionLine statement = parser.Parse(line)
                                        .First();

            ValidateStatement(statement, date: DateTime.Parse("2018-03-18"));
        }
Esempio n. 16
0
        public void ImportNegativeStatement()
        {
            string line = "18/03	 D		INT PAG TIT BANCO 237        		9.952,27	-	";

            TransactionLine statement = parser.Parse(line)
                                        .First();

            Assert.Equal(-9_952.27m, statement.Amount);
        }
Esempio n. 17
0
        LedgerOperationStatus ILedger.TransferFunds(AccountID srcAccountID, AccountID tgtAccountID, decimal balance)
        {
            LedgerOperationStatus status   = LedgerOperationStatus.Success;
            TransactionLine       srcTrans = new TransactionLine(srcAccountID,
                                                                 balance,
                                                                 LedgerDatabase.TransactionType.RemoveFunds, TransactionSubType.TransferFunds);
            TransactionLine tgtTrans = new TransactionLine(tgtAccountID,
                                                           balance,
                                                           LedgerDatabase.TransactionType.AddFunds, TransactionSubType.TransferFunds);

            lock (transactionsTable)
            {
                srcTrans.TransferId = tgtTrans.TransferId = ++transferID;
            }

            if (accountsTable.Contains(srcAccountID) && accountsTable.Contains(tgtAccountID))
            {
                AccountLine accSrc = accountsTable.Select(srcAccountID);
                AccountLine accTgt = accountsTable.Select(tgtAccountID);

                AccountLine firstAccToLock = accSrc, secondAccToLock = accTgt;
                if (srcAccountID > tgtAccountID) // avoid deadlocks by always locking at the same order
                {
                    firstAccToLock  = accTgt;
                    secondAccToLock = accSrc;
                }

                lock (firstAccToLock)
                {
                    lock (secondAccToLock)
                    {
                        if (balance > accSrc.Balance)
                        {
                            srcTrans.Status       = tgtTrans.Status = LedgerDatabase.TransactionStatus.Rejected;
                            srcTrans.RejectReason = tgtTrans.RejectReason = TransactionRejectReason.InsufficientFunds;
                            status = LedgerOperationStatus.InsufficientFunds;
                        }
                        else
                        {
                            accSrc.Balance -= balance;
                            accTgt.Balance += balance;
                        }
                    }
                }
            }
            else
            {
                srcTrans.Status       = tgtTrans.Status = LedgerDatabase.TransactionStatus.Rejected;
                srcTrans.RejectReason = tgtTrans.RejectReason = TransactionRejectReason.InvalidAccount;
                status = LedgerOperationStatus.InvalidAccount;
            }

            transactionsTable.Insert(srcTrans);
            transactionsTable.Insert(tgtTrans);
            return(status);
        }
Esempio n. 18
0
        public TransactionModel GetLeadingOffer(long productId)
        {
            var             entities    = GeneralService.GetDbEntities();
            TransactionLine transaction = entities.TransactionLines.Where(t => t.ProductID == productId).OrderByDescending(p => p.OfferPrice).FirstOrDefault();

            if (transaction == null)
            {
                return(null);
            }
            return(new TransactionModel(transaction));
        }
Esempio n. 19
0
        private static void ValidateStatement(TransactionLine transactionLine, decimal amount, string description, DateTime date, string responsible = "")
        {
            Assert.Equal(amount, transactionLine.Amount);
            Assert.Equal(description, transactionLine.Description);
            Assert.Equal(date, transactionLine.TransactionDate);

            if (transactionLine is ClassifiedTransactionLine)
            {
                Assert.Equal(responsible, ((ClassifiedTransactionLine)transactionLine).Responsible);
            }
        }
Esempio n. 20
0
        private void GenerateTransactionDescription(TransactionLine transaction)
        {
            if (transaction.GetType() == typeof(LevyDeclarationTransactionLine))
            {
                transaction.Description = transaction.Amount >= 0 ? "Levy" : "Levy adjustment";
            }
            else if (transaction.GetType() == typeof(PaymentTransactionLine))
            {
                var paymentTransaction = (PaymentTransactionLine)transaction;

                transaction.Description = GetPaymentTransactionDescription(paymentTransaction);
            }
        }
Esempio n. 21
0
        LedgerOperationStatus ILedger.UnfreezeFunds(AccountID accountID, out decimal balance, UInt64 freezeID)
        {
            LedgerOperationStatus status = LedgerOperationStatus.Success;
            //prepare AddFunds/Unfreeze transaction
            TransactionLine transaction = new TransactionLine(accountID,
                                                              0,
                                                              LedgerDatabase.TransactionType.AddFunds, TransactionSubType.Unfreeze);

            if (accountsTable.Contains(accountID))
            {
                AccountLine account = accountsTable.Select(accountID);
                lock (account)
                {
                    if (frozenBalancesTable.Contains(freezeID))
                    {
                        FrozenBalanceLine frozenBalance = frozenBalancesTable.Select(freezeID);
                        balance = frozenBalance.Balance;
                        if (frozenBalance.AccountId != accountID)
                        {
                            transaction.Status       = LedgerDatabase.TransactionStatus.Rejected;
                            transaction.RejectReason = TransactionRejectReason.InvalidAccount;
                            status = LedgerOperationStatus.InvalidAccount;
                        }
                        else
                        {
                            //update account balance and delete freeze record
                            account.Balance += frozenBalance.Balance;
                            frozenBalancesTable.Delete(freezeID);
                        }
                    }
                    else
                    {
                        balance                  = 0;
                        transaction.Status       = LedgerDatabase.TransactionStatus.Rejected;
                        transaction.RejectReason = TransactionRejectReason.InvalidFreezeID;
                        status = LedgerOperationStatus.InvalidFreezeID;
                    }
                }
            }
            else
            {
                balance                  = 0;
                transaction.Status       = LedgerDatabase.TransactionStatus.Rejected;
                transaction.RejectReason = TransactionRejectReason.InvalidAccount;
                status = LedgerOperationStatus.InvalidAccount;
            }

            transactionsTable.Insert(transaction);
            return(status);
        }
Esempio n. 22
0
        public List <ReceiptOrPayment> FindPaymentsFromDate(DateTime startDate, DateTime endDate, Guid balanceSheetAccount)
        {
            List <ReceiptOrPayment> found    = new List <ReceiptOrPayment> ();
            List <ReceiptOrPayment> payments = GetPayments();
            Guid?bankAccount = null;

            foreach (ReceiptOrPayment receiptOrPayment in payments)
            {
                if (receiptOrPayment.Lines == null || receiptOrPayment.Lines.Length != 1)
                {
                    continue;
                }
                if (receiptOrPayment.BankAccount == null)
                {
                    continue;
                }


                TransactionLine transactionLine = receiptOrPayment.Lines [0];
                if (transactionLine.Account == null || !transactionLine.Account.Value.Equals(balanceSheetAccount))
                {
                    continue;
                }
                if (receiptOrPayment.Date == null)
                {
                    continue;
                }

                if (receiptOrPayment.Date.CompareTo(startDate) < 0 ||
                    receiptOrPayment.Date.CompareTo(endDate) > 0
                    )
                {
                    continue;
                }

                if (bankAccount == null)
                {
                    bankAccount = receiptOrPayment.BankAccount.Value;
                }

                if (!bankAccount.Value.Equals(receiptOrPayment.BankAccount.Value))
                {
                    continue;
                }

                found.Add(receiptOrPayment);
            }
            return(found);
        }
Esempio n. 23
0
 private static void ValidateStatement(TransactionLine statement, decimal?amount = null, string description = null, DateTime?date = null)
 {
     if (amount.HasValue)
     {
         Assert.Equal(amount, statement.Amount);
     }
     if (description != null)
     {
         Assert.Equal(description, statement.Description);
     }
     if (date.HasValue)
     {
         Assert.Equal(date, statement.TransactionDate);
     }
 }
Esempio n. 24
0
 public TransactionModel(TransactionLine transaction)
 {
     ID         = transaction.ID;
     ProductID  = transaction.ProductID;
     CustomerID = transaction.CustomerID;
     OfferPrice = transaction.OfferPrice;
     Type       = TransactionTypes.GetDescription(transaction.TransactionType);
     Date       = transaction.CreatedDate.ToString("g");
     if (transaction.Customer != null)
     {
         CustomerName = transaction.Customer.FirstName + " " + transaction.Customer.LastName;
     }
     if (transaction.Product != null)
     {
         ProductName = transaction.Product.Name;
     }
 }
Esempio n. 25
0
        //public List<Transaction> FillTransactionList(DataTable dtTrx, DataTable dtTrxLines)
        //{
        //    List<Transaction> lstTransaction = new List<Transaction>();
        //    Transaction trx;
        //    if (dtTrx != null && dtTrx.Rows.Count > 0)
        //    {
        //        foreach(DataRow rw in dtTrx.Rows)
        //        {
        //            trx = new Transaction();
        //            trx.Trx_id = rw["TrxId"] == DBNull.Value ? 0 : Convert.ToInt32(rw["TrxId"]);

        //            trx.TransactionLines = GetTraxLines(trx.Trx_id, dtTrxLines);
        //            lstTransaction.Add(trx);
        //        }
        //    }
        //    return lstTransaction;
        //}

        public List <TransactionLine> GetTraxLines(int trxId, DataTable dtTrxLines)
        {
            List <TransactionLine> trxLines = new List <TransactionLine>();
            TransactionLine        trxLn;

            try
            {
                if (dtTrxLines != null && dtTrxLines.Rows.Count > 0)
                {
                    var result = dtTrxLines.AsEnumerable().Where(myRow => myRow.Field <int>("TrxId") == trxId);

                    if (result != null)
                    {
                        DataTable dt = result.CopyToDataTable <DataRow>();

                        foreach (DataRow rw in dt.Rows)
                        {
                            trxLn                = new TransactionLine();
                            trxLn.trxId          = trxId;
                            trxLn.ProductName    = rw["name"] != DBNull.Value ? rw["name"].ToString() : string.Empty;
                            trxLn.ProductID      = rw["ProductId"] == DBNull.Value ? 0 : Convert.ToInt32(rw["ProductId"]);
                            trxLn.Price          = rw["Price"] == DBNull.Value ? 0 : Convert.ToDecimal(rw["Price"]);
                            trxLn.trxId          = rw["TrxId"] == DBNull.Value ? 0 : Convert.ToInt32(rw["TrxId"]);
                            trxLn.LineId         = rw["LineId"] == DBNull.Value ? 0 : Convert.ToInt32(rw["LineId"]);
                            trxLn.quantity       = rw["Quantity"] == DBNull.Value ? 0 : Convert.ToInt32(rw["Quantity"]);
                            trxLn.amount         = rw["Amount"] == DBNull.Value ? 0 : Convert.ToDecimal(rw["Amount"]);
                            trxLn.cardId         = rw["CardId"] == DBNull.Value ? 0 : Convert.ToInt32(rw["CardId"]);
                            trxLn.CardNumber     = rw["CardNumber"] != DBNull.Value ? rw["CardNumber"].ToString() : string.Empty;
                            trxLn.Credits        = rw["Credits"] == DBNull.Value ? 0 : Convert.ToDecimal(rw["Credits"]);
                            trxLn.Courtesy       = rw["Courtesy"] == DBNull.Value ? 0 : Convert.ToDecimal(rw["Courtesy"]);
                            trxLn.tax_percentage = rw["TaxPercentage"] == DBNull.Value ? 0 : Convert.ToDecimal(rw["TaxPercentage"]);
                            trxLn.time           = rw["Time"] == DBNull.Value ? 0 : Convert.ToDecimal(rw["Time"]);
                            trxLn.Bonus          = rw["Bonus"] == DBNull.Value ? 0 : Convert.ToDecimal(rw["Bonus"]);
                            trxLn.tickets        = rw["Tickets"] == DBNull.Value ? 0 : Convert.ToDecimal(rw["Tickets"]);
                            trxLn.Remarks        = rw["Remarks"] != DBNull.Value ? rw["Remarks"].ToString() : string.Empty;

                            trxLines.Add(trxLn);
                        }
                    }
                }
            }
            catch { }

            return(trxLines);
        }
Esempio n. 26
0
        LedgerOperationStatus ILedger.FreezeFunds(AccountID accountID, decimal balance, out FreezeID freezeID)
        {
            LedgerOperationStatus status = LedgerOperationStatus.Success;
            //prepare RemoveFunds/Freeze transaction
            TransactionLine transaction = new TransactionLine(accountID,
                                                              balance,
                                                              LedgerDatabase.TransactionType.RemoveFunds, TransactionSubType.Freeze);

            if (accountsTable.Contains(accountID))
            {
                AccountLine account = accountsTable.Select(accountID);
                lock (account)
                {
                    if (balance > account.Balance)
                    {
                        freezeID                 = 0;
                        transaction.Status       = LedgerDatabase.TransactionStatus.Rejected;
                        transaction.RejectReason = TransactionRejectReason.InsufficientFunds;
                        status = LedgerOperationStatus.InsufficientFunds;
                    }
                    else
                    {
                        //update account balance and add freeze record
                        account.Balance -= balance;
                        FrozenBalanceLine frozenBalance = new FrozenBalanceLine(accountID, balance);
                        freezeID = frozenBalancesTable.Insert(frozenBalance);
                    }
                }
            }
            else
            {
                freezeID                 = 0;
                transaction.Status       = LedgerDatabase.TransactionStatus.Rejected;
                transaction.RejectReason = TransactionRejectReason.InvalidAccount;
                status = LedgerOperationStatus.InvalidAccount;
            }

            transactionsTable.Insert(transaction);
            return(status);
        }
Esempio n. 27
0
        public void SaveTransactionDiscountLines(TransactionLine trxLine, int trxId)
        {
            try
            {
                List <Discounts.DiscountLine> activeDiscountLines = trxLine.discountLines.FindAll(x => x.LineValid);

                if (activeDiscountLines != null && activeDiscountLines.Count > 0)
                {
                    foreach (Discounts.DiscountLine dsLn in activeDiscountLines)
                    {
                        SqlParameter[] sqlParameters = new SqlParameter[7];

                        sqlParameters[0]       = new SqlParameter("@trxId", SqlDbType.Int);
                        sqlParameters[0].Value = trxId;

                        sqlParameters[1] = new SqlParameter("@LineId", trxLine.LineId);

                        sqlParameters[2] = new SqlParameter("@DiscountId", dsLn.DiscountId);

                        decimal trxLineDiscountAmnt = (trxLine.LineAmount * dsLn.DiscountPercentage) / 100;

                        sqlParameters[3] = new SqlParameter("@DiscountAmount", trxLineDiscountAmnt);

                        sqlParameters[4] = new SqlParameter("@DiscountPercentage", dsLn.DiscountPercentage);

                        sqlParameters[5] = new SqlParameter("@Remarks", string.Empty);

                        sqlParameters[6] = new SqlParameter("@ApprovedBy", 0);

                        conn.executeUpdateQuery("sp_InsertTransactionDiscountLines", sqlParameters);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 28
0
        public ImportResult Import(Guid account, dynamic rows, bool execute)
        {
            List <ReceiptOrPayment> existingPayments = GetPayments();
            //List<BankReceipt> existingReceipts=GetReceipts();
            ImportResult importResult = new ImportResult {
                exists = 0, done = 0, failed = 0
            };

            List <Manager.Model.Object> newObjs = new List <Manager.Model.Object>();

            foreach (dynamic row in rows)
            {
                Decimal  amount;
                DateTime dateTime = DateTime.Now;
                if (!Decimal.TryParse(row.Amount, out amount) ||
                    !DateTime.TryParse(row.Date, out dateTime)
                    )
                {
                    ++importResult.failed;
                    continue;
                }
                String description = row.Description;
                if (hasTransaction(account, existingPayments,
                                   dateTime, amount, description) != null)
                {
                    ++importResult.exists;
                    continue;
                }
                Manager.Model.Object mObj;

                /*
                 *              if(amount > 0) {
                 *                      BankReceipt receipt = new BankReceipt() {
                 *                              Date = dateTime,
                 *                              Description = description,
                 *                              BankAccount=account
                 *                      };
                 *                      //receipt.DebitAccount;
                 *                      //receipt.Description;
                 *                      //Amount = 0 - amount;
                 *                      TransactionLine line = new TransactionLine() {
                 *                              Amount = amount
                 *                      };
                 *                      receipt.Lines = new TransactionLine[1] { line };
                 *                      mObj = receipt;
                 *              } else {
                 */
                ReceiptOrPayment payment = new ReceiptOrPayment()
                {
                    Date        = dateTime,
                    BankAccount = account,
                    Description = description
                };
                TransactionLine line = new TransactionLine()
                {
                    Amount = amount
                };
                payment.Lines = new TransactionLine[1] {
                    line
                };
                mObj = payment;

                mObj.Key = Guid.NewGuid();
                newObjs.Add(mObj);
                ++importResult.done;
            }
            PreChangeEvents();
            if (execute)
            {
                foreach (var obj in newObjs)
                {
                    InsertObject(obj);
                }
            }
            return(importResult);
        }
Esempio n. 29
0
        void CreateTransactionLinesList(List <StockPosition> stockPositionList, DateTime startDate, ref bool isStockTransactionRequired, List <TransactionLine> transactionLinesList)
        {
            var localIsStockTransactionRequired = false;

            foreach (var position in stockPositionList)
            {
                // generate transaction for the certain Stock Position
                //if (position.StockPositionId != 8003738) continue;

                int localQuantity = 0;

                //if stock position direction = recycle then create two transaction lines
                if (position.Direction == (int)Direction.Recycle)
                {
                    var transactionLineIssue   = new TransactionLine(position, "Issue", "Recycle", startDate, isStockTransactionRequired);
                    var transactionLineCollect = new TransactionLine(position, "Collect", "Recycle", startDate, isStockTransactionRequired);

                    transactionLinesList.Add(transactionLineIssue);
                    if (!isStockTransactionRequired)
                    {
                        transactionLinesList.Add(transactionLineCollect);
                    }

                    localQuantity = transactionLineCollect.Quantity - transactionLineIssue.Quantity;

                    if (!isStockTransactionRequired)
                    {
                        position.Quantity += localQuantity;
                    }
                    else
                    {
                        position.Quantity = position.Capacity / 2;
                    }
                }
                else
                {
                    var lineType  = position.Direction == (int)Direction.Issue ? "Issue" : "Collect"; // line type depends on stock position direction
                    var direction = position.Direction == (int)Direction.Issue ? "issue" : "collect";

                    var transactionLine = new TransactionLine(position, lineType, direction, startDate, isStockTransactionRequired);
                    transactionLinesList.Add(transactionLine);

                    localQuantity = transactionLine.Quantity;
                    if (!isStockTransactionRequired)
                    {
                        position.Quantity = position.Direction == (int)Direction.Issue ? position.Quantity - localQuantity : position.Quantity + localQuantity;
                    }
                    else
                    {
                        position.Quantity = position.Direction == (int)Direction.Issue ? position.Capacity : 0;
                    }
                }

                if (!localIsStockTransactionRequired)
                {
                    localIsStockTransactionRequired = Helper.GetIsStockTransactionRequired(position, localQuantity);
                }
            }

            if (localIsStockTransactionRequired)
            {
                isStockTransactionRequired = true;
            }
        }
Esempio n. 30
0
 public TransactionListBuilder Add(TransactionLine line)
 {
     transactionList.Add(line);
     return(this);
 }