private static double couponRate(List<CashFlow> leg, CashFlow cf) 
      {
         if (cf == null) return 0.0;

         Date paymentDate = cf.date();
         bool firstCouponFound = false;
         double nominal = 0;
         double accrualPeriod = 0;
         DayCounter dc = null;
         double result = 0.0;

         foreach (CashFlow x in leg.Where(x => x.date() == paymentDate)) {
             Coupon cp = x as Coupon;
             if (cp != null) {
                 if (firstCouponFound) {
                     if (!(nominal == cp.nominal() && accrualPeriod == cp.accrualPeriod() && dc == cp.dayCounter()))
                         throw new ApplicationException("cannot aggregate two different coupons on " + paymentDate);
                 } else {
                     firstCouponFound = true;
                     nominal = cp.nominal();
                     accrualPeriod = cp.accrualPeriod();
                     dc = cp.dayCounter();
                 }
                 result += cp.rate();
             }
         }

         if (!firstCouponFound) throw new ApplicationException("next cashflow (" + paymentDate + ") is not a coupon");
         return result;
      }
示例#2
0
        /// <summary>
        /// Calculates the maximum drawdown from a cash flow over a series. </summary>
        /// <param name="series"> the time series </param>
        /// <param name="cashFlow"> the cash flow </param>
        /// <returns> the maximum drawdown from a cash flow over a series </returns>
        private Decimal CalculateMaximumDrawdown(TimeSeries series, CashFlow cashFlow)
        {
            var maximumDrawdown = Decimal.Zero;
            var maxPeak         = Decimal.Zero;

            for (var i = series.Begin; i <= series.End; i++)
            {
                var value = cashFlow.GetValue(i);
                if (value.IsGreaterThan(maxPeak))
                {
                    maxPeak = value;
                }

                var drawdown = maxPeak.Minus(value).DividedBy(maxPeak);
                if (drawdown.IsGreaterThan(maximumDrawdown))
                {
                    maximumDrawdown = drawdown;
                }
            }
            return(maximumDrawdown);
        }
示例#3
0
        private static void AddOrNothingCashFlowByName(Database db, CashFlowGroup defautGroup, string cashFowName, string cashFlowDescription = null)
        {
            var sql = PetaPoco.Sql.Builder.Where("NAME = @0", cashFowName);

            if (!string.IsNullOrWhiteSpace(cashFlowDescription))
            {
                sql.Append(" AND Description = @0", cashFlowDescription);
            }
            var cashFlow = db.FirstOrDefault <CashFlow>(sql);

            if (cashFlow == null)
            {
                cashFlow = new CashFlow
                {
                    Name        = cashFowName,
                    Description = cashFlowDescription,
                    Group       = defautGroup,
                };
                db.Save(cashFlow);
            }
        }
示例#4
0
        public void CashFlowValue()
        {
            TimeSeries sampleTimeSeries = GenerateTimeSeries.From(3d, 2d, 5d, 1000d, 5000d, 0.0001d, 4d, 7d, 6d, 7d, 8d, 5d, 6d);
            var        tradingRecord    = new TradingRecord(Order.BuyAt(0), Order.SellAt(2), Order.BuyAt(6), Order.SellAt(8), Order.BuyAt(9), Order.SellAt(11));

            var cashFlow = new CashFlow(sampleTimeSeries, tradingRecord);

            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(0), 1);
            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(1), 2d / 3);
            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(2), 5d / 3);
            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(3), 5d / 3);
            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(4), 5d / 3);
            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(5), 5d / 3);
            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(6), 5d / 3);
            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(7), 5d / 3 * 7d / 4);
            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(8), 5d / 3 * 6d / 4);
            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(9), 5d / 3 * 6d / 4);
            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(10), 5d / 3 * 6d / 4 * 8d / 7);
            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(11), 5d / 3 * 6d / 4 * 5d / 7);
            TaTestsUtils.AssertDecimalEquals(cashFlow.GetValue(12), 5d / 3 * 6d / 4 * 5d / 7);
        }
示例#5
0
        public void _何も購入せずお金を排出する(Money inMoney, int inRepeat)
        {
            var role     = new CoinMeckRole();
            var received = new CashFlow();
            var reserved = this.InitInfinityReservedChange();

            for (var i = 0; i < inRepeat; ++i)
            {
                role.Receive(received, inMoney);
            }

            var changed = role.Eject(received, reserved)
                          .GroupBy(m => m)
                          .ToDictionary(g => g.Key, g => g)
            ;

            Assert.That(received.RecevedMoney.Count, Is.EqualTo(0));

            Assert.That(changed.Count, Is.EqualTo(1));
            Assert.True(changed.ContainsKey(inMoney));
            Assert.That(changed[inMoney].Count(), Is.EqualTo(inRepeat));
        }
示例#6
0
//-------------------------------------------------------------------------------------------
    private void BindCashFlow()
    {
        string sums = @"
                    select code as 'Code',
                    'Jan' = (select sum(l.amount) from accounting_ledgeritems l where month(dbo.localizedt(l.postat)) = 1 and l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1 or l.LedgerType = @LedgerType2)),
                    'Feb' = (select sum(l.amount) from accounting_ledgeritems l where month(dbo.localizedt(l.postat)) = 2 and l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1 or l.LedgerType = @LedgerType2)),
                    'Mar' = (select sum(l.amount) from accounting_ledgeritems l where month(dbo.localizedt(l.postat)) = 3 and l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1 or l.LedgerType = @LedgerType2)),
                    'Apr' = (select sum(l.amount) from accounting_ledgeritems l where month(dbo.localizedt(l.postat)) = 4 and l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1 or l.LedgerType = @LedgerType2)),
                    'May' = (select sum(l.amount) from accounting_ledgeritems l where month(dbo.localizedt(l.postat)) = 5 and l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1 or l.LedgerType = @LedgerType2)),
                    'Jun' = (select sum(l.amount) from accounting_ledgeritems l where month(dbo.localizedt(l.postat)) = 6 and l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1 or l.LedgerType = @LedgerType2)),
                    'Jul' = (select sum(l.amount) from accounting_ledgeritems l where month(dbo.localizedt(l.postat)) = 7 and l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1 or l.LedgerType = @LedgerType2)),
                    'Aug' = (select sum(l.amount) from accounting_ledgeritems l where month(dbo.localizedt(l.postat)) = 8 and l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1 or l.LedgerType = @LedgerType2)),
                    'Sep' = (select sum(l.amount) from accounting_ledgeritems l where month(dbo.localizedt(l.postat)) = 9 and l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1 or l.LedgerType = @LedgerType2)),
                    'Oct' = (select sum(l.amount) from accounting_ledgeritems l where month(dbo.localizedt(l.postat)) = 10 and l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1 or l.LedgerType = @LedgerType2)),
                    'Nov' = (select sum(l.amount) from accounting_ledgeritems l where month(dbo.localizedt(l.postat)) = 11 and l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1 or l.LedgerType = @LedgerType2)),
                    'Dec' = (select sum(l.amount) from accounting_ledgeritems l where month(dbo.localizedt(l.postat)) = 12 and l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1 or l.LedgerType = @LedgerType2)),
                    'Tot' = (select sum(l.amount) from accounting_ledgeritems l where l.code = li.code and year(l.postat) = @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1)),
                    'TD'  = (select sum(l.amount) from accounting_ledgeritems l where l.code = li.code and year(l.postat) <= @Year and l.organizationid = @OrganizationId and (l.LedgerType = @LedgerType1))
                    from accounting_ledgeritems li
                    where year(postat) = @Year
                    and li.LedgerType = @LedgerType1
                    and li.organizationid = @OrganizationId
                    group by code";


        using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["weavver"].ConnectionString))
        {
            SqlCommand command = new SqlCommand(sums, connection);
            command.Parameters.AddWithValue("OrganizationId", LoggedInUser.OrganizationId);
            command.Parameters.AddWithValue("Year", Int32.Parse(YearFilter.Text));
            command.Parameters.AddWithValue("LedgerType1", LedgerType.Checking.ToString());
            command.Parameters.AddWithValue("LedgerType2", LedgerType.Savings.ToString());
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            CashFlow.DataSource = reader;
            CashFlow.DataBind();
            reader.Close();
        }
    }
        /// <summary>
        /// Caculate overall savings for the given period
        /// </summary>
        /// <param name="start">The start.</param>
        /// <param name="end">The end.</param>
        /// <param name="tag">The tag.</param>
        /// <returns></returns>
        internal ISavingsPlanPeriodOverall CalculateOverallPeriod(DateTime start, DateTime end, string tag)
        {
            var query = new TransactionAllQuery()
                        .Register(new TransactionStartDateFilter(start))
                        .Register(new TransactionEndDateFilter(end))
                        .Register(new TransactionTagFilter(tag));

            var transactions = _queryDispatcher.Execute(query).ToList();

            var period = new SavingsPlanPeriod {
                IsForecast = false
            };

            if (!transactions.Any())
            {
                return(period);
            }

            //Inpayments
            period.SumInpayment = _transactionCalculationService.CalculateSumInpayments(query);

            //Order costs
            period.SumOrderCosts          -= transactions.Sum(t => t.OrderCosts);
            period.SumOrderCostsPercentage = decimal.Round((period.SumOrderCosts / (period.SumOrderCosts - period.SumInpayment) * 100), 2);

            //Sum capital
            period.SumCapital = _transactionCalculationService.CalculateSumCapital(query, end);

            //Dividends
            period.SumOverallDividends = _transactionCalculationService.CalculateSumDividends(query);

            //PerformancePercentage
            var cashFlowEnd = new CashFlow(period.SumCapital, end);

            period.PerformanceOverallPeriodPercentage = _transactionCalculationService.CalculatePerformancePercentageIir(query, new CashFlow(0, start), cashFlowEnd);

            return(period);
        }
示例#8
0
      private static double aggregateRate(Leg leg,CashFlow cf)
      {
         if ( cf == null) return 0.0;

         Date paymentDate = cf.date();
         bool firstCouponFound = false;
         double nominal = 0.0;
         double accrualPeriod = 0.0;
         DayCounter dc = null;
         double result = 0.0;

         foreach (CashFlow x in leg.Where(x => x.date() == paymentDate))
         {
            Coupon cp = x as Coupon;
            if (cp != null)
            {
               if (firstCouponFound)
               {
                  Utils.QL_REQUIRE(nominal == cp.nominal() &&
                                   accrualPeriod == cp.accrualPeriod() &&
                                   dc == cp.dayCounter(), () =>
                                   "cannot aggregate two different coupons on "
                                   + paymentDate);
               }
               else
               {
                  firstCouponFound = true;
                  nominal = cp.nominal();
                  accrualPeriod = cp.accrualPeriod();
                  dc = cp.dayCounter();
               }
               result += cp.rate();
            }
         }

         Utils.QL_REQUIRE( firstCouponFound, () => "no coupon paid at cashflow date " + paymentDate );
         return result;
        }
示例#9
0
 void Start()
 {
     if (PlayerPrefs.GetInt("ActiveWeapon") == 1)
     {
         hasBow = true;
     }
     else
     {
         hasBow = false;
     }
     canShoot    = true;
     health      = FindObjectOfType <Health>();
     myCollider  = GetComponent <CapsuleCollider2D>();
     feet        = GetComponent <BoxCollider2D>();
     animator    = GetComponent <Animator>();
     myRigidBody = GetComponent <Rigidbody2D>();
     weapon      = FindObjectOfType <Weapon>();
     gun         = gameObject.transform.GetChild(0);
     inventory   = FindObjectOfType <Inventory>();
     cashDisplay = FindObjectOfType <CashFlow>();
     inventory.SetKeyUnAquired();
     deathCanvas.SetActive(false);
 }
示例#10
0
        public void GenerateChecksOneTimePaymentsDate()
        {
            var payments = new Mock <IPaymentsRepository>();
            var payment  = new Payment()
            {
                Amount    = 2000,
                Date      = DateTime.Now.Date.AddDays(-10),
                Frequency = PaymentFrequency.Once,
                Name      = "test"
            };

            payments.Setup(p => p.Get()).Returns(new Payment[] { payment });

            var balance = new Balance()
            {
                Amount = 1000, Date = DateTime.Now.Date.AddDays(-1)
            };
            var generator = new CashFlowGenerator(payments.Object);

            CashFlow cashFlow = generator.Generate(balance, DateTime.Now.Date.AddDays(10));

            Assert.Equal(1, cashFlow.Items.Count());
        }
示例#11
0
        public bool OpenBudget(SqlConnection conn,
                               int commandTimeout        = 30,
                               bool includeActivePeriods = false,
                               bool includeOrderBook     = false)
        {
            try
            {
                reportMode = ReportMode.Budget;
                CashFlow.Activate(); CashFlow.Range["A1"].Select();
                Budget.Unprotect();
                ClearWorksheet(Budget);

                dataContext = new DataContext(conn);
                dataContext.CommandTimeout = commandTimeout;
                dataContext.Open();

                SetActivePeriod(Budget, Properties.Resources.BudgetStatementTitle);
                InitialiseWorksheet(Budget);
                InitialisePeriods(Budget);

                LoadCategories(Budget, CashType.Trade, includeActivePeriods, includeOrderBook, false);

                dataContext.Close();

                Budget.Activate();
                FreezeFrames();
                Budget.Protect();

                return(true);
            }
            catch (Exception err)
            {
                DataContext data = new DataContext(conn);
                data.ErrorLog($"{ err.Source}.{ err.TargetSite.Name} {err.Message}");
                return(false);
            }
        }
示例#12
0
        public void _商品購入後お金を排出する(
            [ValueSource(typeof(_商品購入後お金を排出するParams), "Source")]
            _商品購入後お金を排出するParams.Parameter inParameter)
        {
            var role     = new CoinMeckRole();
            var received = new CashFlow();
            var reserved = this.InitInfinityReservedChange();

            foreach (var m in inParameter.ReceivedMoney)
            {
                for (var i = 0; i < m.Item2; ++i)
                {
                    role.Receive(received, m.Item1);
                }
            }

            Assert.True(role.Purchase(received, 100));

            var changed = role.Eject(received, reserved)
                          .GroupBy(m => m)
                          .ToDictionary(g => g.Key, g => g)
            ;

            var lookup = inParameter.ChangedMoney.ToDictionary(m => m.Item1, m => m.Item2);

            Assert.That(received.RecevedMoney.Count, Is.EqualTo(0));

            Assert.That(received.UsedAmount, Is.EqualTo(100));

            Assert.That(changed.Count, Is.EqualTo(lookup.Count), "count money type (id = {0})", inParameter.Id);

            foreach (var pair in changed)
            {
                Assert.True(lookup.ContainsKey(pair.Key), "money ({0}) should be contained (id = {1})", pair.Key, inParameter.Id);
                Assert.That(pair.Value.Count(), Is.EqualTo(lookup[pair.Key]), "money ({0}) count should be equaled (id = {1})", pair.Key, inParameter.Id);
            }
        }
示例#13
0
        public void AddNewCashFlowType()
        {
            using (var tx = Database.GetTransaction())
            {
                var cashFlow = new CashFlow
                {
                    Name        = NewName,
                    Description = NewDescription,
                    Group       = NewCashFlowGroup,
                };

                Database.Save(cashFlow);
                tx.Complete();
                _cashFlows.Add(cashFlow);
            }
            CachedService.Clear();
            NewName          = string.Empty;
            NewDescription   = string.Empty;
            NewCashFlowGroup = CashFlowGroups.First();
            //LoadData();
            IsNewNameFocused = false;
            IsNewNameFocused = true;
            NotifyOfPropertyChange(() => CashFlows);
        }
示例#14
0
        public void Properties_Tests()
        {
            CashFlow cashFlow = new CashFlow()
            {
                Date             = DateTime.MaxValue,
                PositionOfTheDay = 100,
                Total            = 7080,
            };

            Assert.Null(cashFlow.Entries);
            Assert.Null(cashFlow.Exits);
            Assert.Null(cashFlow.Charges);
            Assert.Equal(DateTime.MaxValue, cashFlow.Date);
            Assert.Equal(100, cashFlow.PositionOfTheDay);
            Assert.Equal(7080, cashFlow.Total);

            cashFlow.Entries = new List <Entrie>();
            cashFlow.Exits   = new List <Exit>();
            cashFlow.Charges = new List <Charge>();

            Assert.NotNull(cashFlow.Entries);
            Assert.NotNull(cashFlow.Exits);
            Assert.NotNull(cashFlow.Charges);
        }
示例#15
0
        private static string PrintCashFlow(CashFlow cashFlow)
        {
            string result = null;

            switch (cashFlow)
            {
            case CashFlow.Input:
                result = @"+";
                break;

            case CashFlow.Output:
                result = @"-";
                break;

            case CashFlow.Invalid:
                result = @"?";
                break;

            default:
                result = null;
                break;
            }
            return(result);
        }
示例#16
0
        public CashFlow Get(int id)
        {
            try
            {
                Logger.LogInfo("Get: Cash flow by id process start");
                CashFlow cashFlow = new CashFlow();

                DataTable dtAppConfig = DataBase.DBService.ExecuteCommand(string.Format(SELECT_ID, id));
                foreach (DataRow dr in dtAppConfig.Rows)
                {
                    cashFlow = convertToCashFlow(dr);
                }
                Logger.LogInfo("Get: Cash flow by id process completed");
                return(cashFlow);
            }
            catch (Exception ex)
            {
                StackTrace st = new StackTrace();
                StackFrame sf = st.GetFrame(0);
                MethodBase currentMethodName = sf.GetMethod();
                LogDebug(currentMethodName.Name, ex);
                return(null);
            }
        }
示例#17
0
        public void CalculateSuccessProbabilitiesOnSuccessReturnsCorrectResults()
        {
            //arrange
            IList <double> simulations = new[] { 25D, 200D, 25D, 0 };
            var            node        = new Mock <INode>();

            node.Setup(n => n.InitialInvestment).Returns(100000);
            node.Setup(n => n.InitialPrice).Returns(100);
            node.Setup(n => n.IsPortfolioComponent).Returns(true);
            node.Setup(n => n.Simulations).Returns(simulations);
            node.Setup(n => n.PortfolioWeight).Returns(1);

            IList <INode> nodes = new[] { node.Object };

            var cashFlow0 = new CashFlow {
                Cost = 0
            };
            var cashFlow1 = new CashFlow {
                Cost = 50000
            };
            var cashFlow2 = new CashFlow {
                Cost = 50000
            };
            var cashFlows = new[] { cashFlow0, cashFlow1, cashFlow2 };


            var portfolioSimulator = new PortfolioSimulator();

            //act
            var result = portfolioSimulator.CalculateSuccessProbabilities(nodes, cashFlows);

            //assert
            Assert.AreEqual(1, result[0]);
            Assert.AreEqual(.5, result[1]);
            Assert.AreEqual(0, result[2]);
        }
示例#18
0
        public void Delete(CashFlow cashFlow)
        {
            try
            {
                string clientName = DataBase.DBService.ExecuteCommandScalar(string.Format(SELECT_ID, cashFlow.Id));

                DataBase.DBService.BeginTransaction();
                DataBase.DBService.ExecuteCommandString(string.Format(DELETE_CASHFLOW,
                                                                      cashFlow.Oid), true);

                Activity.ActivitiesService.Add(ActivityType.DeleteCashFlow, EntryStatus.Success,
                                               Source.Server, cashFlow.UpdatedByUserName, "CashFlow", cashFlow.MachineName);
                DataBase.DBService.CommitTransaction();
            }
            catch (Exception ex)
            {
                DataBase.DBService.RollbackTransaction();
                StackTrace st = new StackTrace();
                StackFrame sf = st.GetFrame(0);
                MethodBase currentMethodName = sf.GetMethod();
                LogDebug(currentMethodName.Name, ex);
                throw ex;
            }
        }
示例#19
0
        public void GenerateSortsItemsByDate()
        {
            var payments = new Mock <IPaymentsRepository>();
            var payment1 = new Payment()
            {
                Amount    = 2000,
                Date      = DateTime.Now.Date.AddDays(1),
                Frequency = PaymentFrequency.Weekly,
                Name      = "test"
            };
            var payment2 = new Payment()
            {
                Amount    = 300,
                Date      = DateTime.Now.Date.AddDays(2),
                Frequency = PaymentFrequency.Weekly,
                Name      = "test1"
            };

            payments.Setup(p => p.Get()).Returns(new Payment[] { payment1, payment2 });

            var balance = new Balance()
            {
                Amount = 1000, Date = DateTime.Now.Date.AddDays(-1)
            };
            var generator = new CashFlowGenerator(payments.Object);

            CashFlow cashFlow = generator.Generate(balance, DateTime.Now.Date.AddDays(100));

            CashFlowItem curItem = cashFlow.Items.First();

            foreach (CashFlowItem item in cashFlow.Items)
            {
                Assert.True(curItem.Date <= item.Date);
                curItem = item;
            }
        }
        public async Task <IActionResult> Create(SaleReturn saleReturn, IEnumerable <SaleBillItem> SaleBillItem_List, IEnumerable <SaleTransaction> SaleTransactionList)
        {
            string CompId = User.Claims.Where(r => r.Type == "CompanyID").FirstOrDefault().Value;
            int    CompID = Convert.ToInt32(CompId);

            int salReturnID = 0;

            var SaleBillItem_List_1 = SaleBillItem_List.ToList();

            SaleBillItem_List_1.RemoveAll(x => x.SaleBillExtraInt_2 == 0);

            foreach (var item in SaleBillItem_List_1)
            {
                SaleReturn obj = new SaleReturn();

                obj.CreatedBy          = User.Identity.Name;
                obj.CompanyID          = CompID;
                obj.SaleBillReturnDate = DateTime.Now;

                obj.SaleBillID = saleReturn.SaleBillID;
                obj.ItemID     = item.ItemID;

                obj.PartiesID = saleReturn.PartiesID;

                obj.PartiesID = saleReturn.PartiesID;

                obj.OldQuantity    = item.Quantity;
                obj.ReturnQuantity = item.SaleBillExtraInt_2;
                obj.AmountToPay    = item.SaleBillExtraDecimal_1;

                obj.Remarks = saleReturn.Remarks;

                _context.Add(obj);
                await _context.SaveChangesAsync();

                salReturnID = obj.SaleReturnID;

                // Increasing Item Quantity from ITEM Table
                Item    itemObj = new Item();
                decimal StockQuantity, final;

                itemObj       = _context.Item.Where(r => r.ItemID == item.ItemID).SingleOrDefault();
                StockQuantity = itemObj.Quantity;
                final         = StockQuantity + item.SaleBillExtraInt_2;

                itemObj.Quantity = final;
                _context.Update(itemObj);
                await _context.SaveChangesAsync();

                // Increasing Item Quantity from ITEM Table
            }


            if (saleReturn.PartiesID == null)
            {
                CashFlow CF = new CashFlow();
                CF.Debit        = saleReturn.AmountToPay;
                CF.SaleReturnID = salReturnID;
                CF.CompanyID    = CompID;

                // Sale Return  04-0002-0001
                int MainAccID = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "04").FirstOrDefault().MainAccountID;
                int SubAccID  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID).Where(r => r.SubAccountNumber == "0002").FirstOrDefault().SubAccountID;
                int TraAccID  = _context.TransactionAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountID == SubAccID).Where(r => r.TransactionAccountNumber == "0001").FirstOrDefault().TransactionAccountID;

                CF.MainAccountID        = MainAccID;
                CF.SubAccountID         = SubAccID;
                CF.TransactionAccountID = TraAccID;
                CF.VoucherType          = "Sale Return Voucher";
                CF.DateCreation         = DateTime.Now.Date;

                _context.CashFlow.Add(CF);
                await _context.SaveChangesAsync();

                CashFlow CF1 = new CashFlow();
                CF1.Credit       = saleReturn.AmountToPay;
                CF1.SaleReturnID = salReturnID;
                CF1.CompanyID    = CompID;

                // Cash In Hand 01-0001-0001 credit
                int MainAccID_1 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "01").FirstOrDefault().MainAccountID;
                int SubAccID_1  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID_1).Where(r => r.SubAccountNumber == "0001").FirstOrDefault().SubAccountID;
                int TraAccID_1  = _context.TransactionAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountID == SubAccID_1).Where(r => r.TransactionAccountNumber == "0001").FirstOrDefault().TransactionAccountID;

                CF1.MainAccountID        = MainAccID_1;
                CF1.SubAccountID         = SubAccID_1;
                CF1.TransactionAccountID = TraAccID_1;
                CF1.VoucherType          = "Sale Return Voucher";
                CF1.DateCreation         = DateTime.Now.Date;

                _context.CashFlow.Add(CF1);
                await _context.SaveChangesAsync();
            }

            else
            {
                CashFlow CF2 = new CashFlow();
                CF2.Credit       = saleReturn.AmountToPay;
                CF2.SaleReturnID = salReturnID;
                CF2.CompanyID    = CompID;
                CF2.PartiesID    = saleReturn.PartiesID;
                //
                int?PartyTransID = _context.Parties.Where(r => r.CompanyID == CompID).Where(r => r.PartiesID == saleReturn.PartiesID).FirstOrDefault().TransactionAccountID;
                int PartMainAcc1 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "00").FirstOrDefault().MainAccountID;
                int PartSubAcc1  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountNumber == "0000").FirstOrDefault().SubAccountID;

                CF2.MainAccountID        = PartMainAcc1;
                CF2.SubAccountID         = PartSubAcc1;
                CF2.TransactionAccountID = (int)PartyTransID;
                CF2.VoucherType          = "Sale Return Voucher";
                CF2.DateCreation         = DateTime.Now.Date;

                _context.CashFlow.Add(CF2);
                await _context.SaveChangesAsync();

                CashFlow CF3 = new CashFlow();
                CF3.Debit        = saleReturn.AmountToPay;
                CF3.SaleReturnID = salReturnID;
                CF3.CompanyID    = CompID;
                CF3.PartiesID    = saleReturn.PartiesID;

                // Sale Return  04-0002-0001
                int MainAccID = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "04").FirstOrDefault().MainAccountID;
                int SubAccID  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID).Where(r => r.SubAccountNumber == "0002").FirstOrDefault().SubAccountID;
                int TraAccID  = _context.TransactionAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountID == SubAccID).Where(r => r.TransactionAccountNumber == "0001").FirstOrDefault().TransactionAccountID;

                CF3.MainAccountID        = MainAccID;
                CF3.SubAccountID         = SubAccID;
                CF3.TransactionAccountID = TraAccID;
                CF3.VoucherType          = "Sale Return Voucher";
                CF3.DateCreation         = DateTime.Now.Date;

                _context.CashFlow.Add(CF3);
                await _context.SaveChangesAsync();

                if (SaleTransactionList.FirstOrDefault().Paid == true)
                {
                    CashFlow CF4 = new CashFlow();
                    CF4.Debit        = SaleTransactionList.FirstOrDefault().Amount;
                    CF4.SaleReturnID = salReturnID;
                    CF4.CompanyID    = CompID;
                    CF4.PartiesID    = saleReturn.PartiesID;

                    int?PartyTransID_1 = _context.Parties.Where(r => r.CompanyID == CompID).Where(r => r.PartiesID == saleReturn.PartiesID).FirstOrDefault().TransactionAccountID;
                    int PartMainAcc1_2 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "00").FirstOrDefault().MainAccountID;
                    int PartSubAcc1_2  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountNumber == "0000").FirstOrDefault().SubAccountID;

                    CF4.MainAccountID        = PartMainAcc1_2;
                    CF4.SubAccountID         = PartSubAcc1_2;
                    CF4.TransactionAccountID = (int)PartyTransID_1;
                    CF4.VoucherType          = "Sale Bill Voucher";
                    CF4.DateCreation         = DateTime.Now.Date;

                    _context.CashFlow.Add(CF4);
                    await _context.SaveChangesAsync();


                    if (SaleTransactionList.FirstOrDefault().Mode == Models.PaymentMode.Cash) // Mode 0 Means ==> Cash
                    {
                        CashFlow CF5 = new CashFlow();
                        CF5.Credit       = SaleTransactionList.FirstOrDefault().Amount;
                        CF5.SaleReturnID = salReturnID;
                        CF5.CompanyID    = CompID;
                        CF5.PartiesID    = saleReturn.PartiesID;
                        // Cash In Hand 01-0001-0001
                        int MainAccID_2 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "01").FirstOrDefault().MainAccountID;
                        int SubAccID_2  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID_2).Where(r => r.SubAccountNumber == "0001").FirstOrDefault().SubAccountID;
                        int TraAccID_2  = _context.TransactionAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountID == SubAccID_2).Where(r => r.TransactionAccountNumber == "0001").FirstOrDefault().TransactionAccountID;

                        CF5.MainAccountID        = MainAccID_2;
                        CF5.SubAccountID         = SubAccID_2;
                        CF5.TransactionAccountID = TraAccID_2;
                        CF5.VoucherType          = "Sale Return Voucher";
                        CF5.DateCreation         = DateTime.Now.Date;

                        _context.CashFlow.Add(CF5);
                        await _context.SaveChangesAsync();
                    }
                    else if (SaleTransactionList.FirstOrDefault().Mode == Models.PaymentMode.Cheque) // Mode 0 Means ==> Cheque
                    {
                        CashFlow CF6 = new CashFlow();
                        CF6.Credit       = SaleTransactionList.FirstOrDefault().Amount;
                        CF6.SaleReturnID = salReturnID;
                        CF6.CompanyID    = CompID;
                        CF6.PartiesID    = saleReturn.PartiesID;

                        int?bankID      = SaleTransactionList.FirstOrDefault().BankID;
                        int transBankID = _context.Bank.Where(r => r.CompanyID == CompID).Where(r => r.BankID == bankID).FirstOrDefault().TransactionAccountID;
                        int MainAccID_3 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "01").FirstOrDefault().MainAccountID;
                        int SubAccID_3  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID_3).Where(r => r.SubAccountNumber == "0002").FirstOrDefault().SubAccountID;

                        CF6.MainAccountID        = MainAccID_3;
                        CF6.SubAccountID         = SubAccID_3;
                        CF6.TransactionAccountID = transBankID;
                        CF6.VoucherType          = "Sale Return Voucher";
                        CF6.DateCreation         = DateTime.Now.Date;

                        _context.CashFlow.Add(CF6);
                        await _context.SaveChangesAsync();
                    }
                }
            }


            // Sale Transaction Entry
            var TransactionList_Result = SaleTransactionList.ToList();

            TransactionList_Result.RemoveAll(x => x.SaleTransactionID == 777777);
            TransactionList_Result.ForEach(x => x.SaleTransactionID = 0);

            foreach (var item in TransactionList_Result)
            {
                SaleReturnTransaction transaction = new SaleReturnTransaction();
                transaction.CompanyID    = CompID;
                transaction.SaleReturnID = salReturnID;
                transaction.Amount       = item.Amount;
                transaction.BankID       = item.BankID;
                transaction.Cheque       = item.Cheque;
                transaction.Date         = item.Date;
                transaction.Mode         = item.Mode;
                transaction.Paid         = item.Paid;
                transaction.SaleBillID   = saleReturn.SaleBillID;

                _context.SaleReturnTransaction.Add(transaction);

                await _context.SaveChangesAsync();
            }
            // Party Payments table data insertion

            return(RedirectToAction("Index", "Sale", new { area = "Sale" }));
        }
示例#21
0
        public async Task <IActionResult> Edit([Bind("CashInBankID,Amount,AmountInWords,BankID,CompanyID,CreatedBy,CreationDate,CurrencyID,Date,DepositedBy,ExternalRef,Particulars,PartiesID")] CashInBank cashInBank)
        {
            string CompId = User.Claims.Where(r => r.Type == "CompanyID").FirstOrDefault().Value;
            int    CompID = Convert.ToInt32(CompId);

            int CIB = cashInBank.CashInBankID;

            cashInBank.CompanyID    = CompID;
            cashInBank.CreatedBy    = User.Identity.Name;
            cashInBank.CreationDate = DateTime.Now;

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(cashInBank);
                    await _context.SaveChangesAsync();

                    // Cash Flow VOUCHER EDIT

                    _context.CashFlow.RemoveRange(_context.CashFlow.Where(x => x.CashInBankID == CIB));
                    _context.SaveChanges();

                    CashFlow CF2 = new CashFlow();
                    CF2.Credit       = cashInBank.Amount;
                    CF2.CashInBankID = CIB;
                    CF2.CompanyID    = CompID;
                    CF2.PartiesID    = cashInBank.PartiesID;
                    // Party Credit
                    int?PartyTransID   = _context.Parties.Where(r => r.CompanyID == CompID).Where(r => r.PartiesID == cashInBank.PartiesID).FirstOrDefault().TransactionAccountID;
                    int PartMainAcc1_2 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "00").FirstOrDefault().MainAccountID;
                    int PartSubAcc1_2  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountNumber == "0000").FirstOrDefault().SubAccountID;

                    CF2.MainAccountID        = PartMainAcc1_2;
                    CF2.SubAccountID         = PartSubAcc1_2;
                    CF2.TransactionAccountID = (int)PartyTransID;
                    CF2.VoucherType          = "Cash In Bank Voucher";
                    CF2.DateCreation         = DateTime.Now.Date;
                    //   CF2.Narration =

                    _context.CashFlow.Add(CF2);
                    await _context.SaveChangesAsync();

                    CashFlow CF3 = new CashFlow();
                    CF3.Debit        = cashInBank.Amount;
                    CF3.CashInBankID = CIB;
                    CF3.CompanyID    = CompID;
                    CF3.PartiesID    = cashInBank.PartiesID;
                    // Bank Debit
                    int?bankID      = cashInBank.BankID;
                    int transBankID = _context.Bank.Where(r => r.CompanyID == CompID).Where(r => r.BankID == bankID).FirstOrDefault().TransactionAccountID;
                    int MainAccID_3 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "01").FirstOrDefault().MainAccountID;
                    int SubAccID_3  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID_3).Where(r => r.SubAccountNumber == "0002").FirstOrDefault().SubAccountID;

                    CF3.MainAccountID        = MainAccID_3;
                    CF3.SubAccountID         = SubAccID_3;
                    CF3.TransactionAccountID = transBankID;
                    CF3.VoucherType          = "Cash In Bank Voucher";
                    CF3.DateCreation         = DateTime.Now.Date;

                    _context.CashFlow.Add(CF3);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CashInBankExists(cashInBank.CashInBankID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                if (User.IsInRole("CompanyAdmin"))
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(RedirectToAction("Index", "Home", new { area = "CompanyUser" }));
                }
            }
            ViewData["BankID"]     = new SelectList(_context.Bank.Where(r => r.CompanyID == CompID), "BankID", "BankName", cashInBank.BankID);
            ViewData["CurrencyID"] = new SelectList(_context.Currency.Where(r => r.CompanyID == CompID), "CurrencyID", "CurrencyName", cashInBank.CurrencyID);
            ViewData["PartiesID"]  = new SelectList(_context.Parties.Where(r => r.CompanyID == CompID), "PartiesID", "PartyName", cashInBank.PartiesID);
            return(View(cashInBank));
        }
        public async Task <IActionResult> Create([Bind("ChequeReceiptID,ChequeStatus,Amount,AmountInWords,BankID,ChequeNumber,CompanyID,CreatedBy,CreationDate,CurrencyID,CurrentStatus,Date,DateOfDeposite,DateOfMature,ExternalRef,InNameOf,Particulars,PartiesID")] ChequeReceipt chequeReceipt)
        {
            string CompId = User.Claims.Where(r => r.Type == "CompanyID").FirstOrDefault().Value;
            int    CompID = Convert.ToInt32(CompId);

            chequeReceipt.CompanyID    = CompID;
            chequeReceipt.CreatedBy    = User.Identity.Name;
            chequeReceipt.CreationDate = DateTime.Now;

            if (ModelState.IsValid)
            {
                _context.Add(chequeReceipt);
                await _context.SaveChangesAsync();

                int CIB = chequeReceipt.ChequeReceiptID;

                if (chequeReceipt.ChequeStatus == Purchase.Models.ChequeStatus.Cleared)
                {
                    CashFlow CF2 = new CashFlow();
                    CF2.Credit          = chequeReceipt.Amount;
                    CF2.ChequeReceiptID = CIB;
                    CF2.CompanyID       = CompID;
                    CF2.PartiesID       = chequeReceipt.PartiesID;
                    // Party Credit
                    int?PartyTransID = _context.Parties.Where(r => r.CompanyID == CompID).Where(r => r.PartiesID == chequeReceipt.PartiesID).FirstOrDefault().TransactionAccountID;
                    int PartMainAcc1 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "00").FirstOrDefault().MainAccountID;
                    int PartSubAcc1  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountNumber == "0000").FirstOrDefault().SubAccountID;

                    CF2.MainAccountID        = PartMainAcc1;
                    CF2.SubAccountID         = PartSubAcc1;
                    CF2.TransactionAccountID = (int)PartyTransID;
                    CF2.VoucherType          = "Cheque Receipt Voucher";
                    CF2.DateCreation         = chequeReceipt.DateOfMature;

                    _context.CashFlow.Add(CF2);
                    await _context.SaveChangesAsync();

                    CashFlow CF3 = new CashFlow();
                    CF3.Debit           = chequeReceipt.Amount;
                    CF3.ChequeReceiptID = CIB;
                    CF3.CompanyID       = CompID;
                    CF3.PartiesID       = chequeReceipt.PartiesID;
                    // Bank Debit
                    int?bankID      = chequeReceipt.BankID;
                    int transBankID = _context.Bank.Where(r => r.CompanyID == CompID).Where(r => r.BankID == bankID).FirstOrDefault().TransactionAccountID;
                    int MainAccID_3 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "01").FirstOrDefault().MainAccountID;
                    int SubAccID_3  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID_3).Where(r => r.SubAccountNumber == "0002").FirstOrDefault().SubAccountID;

                    CF3.MainAccountID        = MainAccID_3;
                    CF3.SubAccountID         = SubAccID_3;
                    CF3.TransactionAccountID = transBankID;
                    CF3.VoucherType          = "Cheque Receipt Voucher";
                    CF3.DateCreation         = chequeReceipt.DateOfMature;

                    _context.CashFlow.Add(CF3);
                    await _context.SaveChangesAsync();
                }
                if (User.IsInRole("CompanyAdmin"))
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(RedirectToAction("Index", "Home", new { area = "CompanyUser" }));
                }
            }
            ViewData["BankID"]     = new SelectList(_context.Bank.Where(r => r.CompanyID == CompID), "BankID", "BankName", chequeReceipt.BankID);
            ViewData["CurrencyID"] = new SelectList(_context.Currency.Where(r => r.CompanyID == CompID), "CurrencyID", "CurrencyName", chequeReceipt.CurrencyID);
            ViewData["PartiesID"]  = new SelectList(_context.Parties.Where(r => r.CompanyID == CompID), "PartiesID", "PartyName", chequeReceipt.PartiesID);
            return(View(chequeReceipt));
        }
示例#23
0
文件: CashFlow.cs 项目: minikie/test
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(CashFlow obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
示例#24
0
        //! NPV of a single cash flows
        public static double npv(CashFlow cashflow, YieldTermStructure discountCurve, Date settlementDate = null, Date npvDate = null, int exDividendDays = 0)
        {
            double NPV = 0.0;

            if (cashflow == null)
                return 0.0;

            if (settlementDate == null)
                settlementDate = discountCurve.referenceDate();

            if (!cashflow.hasOccurred(settlementDate + exDividendDays))
                NPV = cashflow.amount() * discountCurve.discount(cashflow.Date);

            if (npvDate == null)
                return NPV;
            else
                return NPV / discountCurve.discount(npvDate);
        }
示例#25
0
 public static FloatingRateCoupon as_floating_rate_coupon(CashFlow cf) {
   FloatingRateCoupon ret = new FloatingRateCoupon(NQuantLibcPINVOKE.as_floating_rate_coupon(CashFlow.getCPtr(cf)), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
示例#26
0
        public void Add(PortfolioPosition position, Enum enumeration, CashFlow cashFlow)
        {
            KeyValuePair <PortfolioPosition, Enum> key = new KeyValuePair <PortfolioPosition, Enum>(position, enumeration);

            _cashFlows.Add(key, cashFlow);
        }
        public async Task <IActionResult> Create([Bind("CashReceiptID,Amount,AmountInWords,CompanyID,CreatedBy,CreationDate,CurrencyID,Date,ExternalRef,PaidBy,Particulars,PartiesID")] CashReceipt cashReceipt)
        {
            string CompId = User.Claims.Where(r => r.Type == "CompanyID").FirstOrDefault().Value;
            int    CompID = Convert.ToInt32(CompId);

            cashReceipt.CompanyID    = CompID;
            cashReceipt.CreatedBy    = User.Identity.Name;
            cashReceipt.CreationDate = DateTime.Now;

            if (ModelState.IsValid)
            {
                _context.Add(cashReceipt);
                await _context.SaveChangesAsync();

                int CIB = cashReceipt.CashReceiptID;

                CashFlow CF2 = new CashFlow();
                CF2.Credit        = cashReceipt.Amount;
                CF2.CashReceiptID = CIB;
                CF2.CompanyID     = CompID;
                CF2.PartiesID     = cashReceipt.PartiesID;
                // Party Credit
                int?PartyTransID   = _context.Parties.Where(r => r.CompanyID == CompID).Where(r => r.PartiesID == cashReceipt.PartiesID).FirstOrDefault().TransactionAccountID;
                int PartMainAcc1_2 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "00").FirstOrDefault().MainAccountID;
                int PartSubAcc1_2  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountNumber == "0000").FirstOrDefault().SubAccountID;

                CF2.MainAccountID = PartMainAcc1_2;
                CF2.SubAccountID  = PartSubAcc1_2;

                CF2.TransactionAccountID = (int)PartyTransID;
                CF2.VoucherType          = "Cash Receipt Voucher";
                CF2.DateCreation         = DateTime.Now.Date;

                _context.CashFlow.Add(CF2);
                await _context.SaveChangesAsync();

                CashFlow CF3 = new CashFlow();
                CF3.Debit         = cashReceipt.Amount;
                CF3.CashReceiptID = CIB;
                CF3.CompanyID     = CompID;
                CF3.PartiesID     = cashReceipt.PartiesID;

                // Cash In Hand 01-0001-0001 Debit
                int MainAccID_2 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "01").FirstOrDefault().MainAccountID;
                int SubAccID_2  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID_2).Where(r => r.SubAccountNumber == "0001").FirstOrDefault().SubAccountID;
                int TraAccID_2  = _context.TransactionAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountID == SubAccID_2).Where(r => r.TransactionAccountNumber == "0001").FirstOrDefault().TransactionAccountID;

                CF3.MainAccountID        = MainAccID_2;
                CF3.SubAccountID         = SubAccID_2;
                CF3.TransactionAccountID = TraAccID_2;
                CF3.VoucherType          = "Cash Receipt Voucher";
                CF3.DateCreation         = DateTime.Now.Date;

                _context.CashFlow.Add(CF3);
                await _context.SaveChangesAsync();

                if (User.IsInRole("CompanyAdmin"))
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(RedirectToAction("Index", "Home", new { area = "CompanyUser" }));
                }
            }
            ViewData["CurrencyID"] = new SelectList(_context.Currency.Where(r => r.CompanyID == CompID), "CurrencyID", "CurrencyName", cashReceipt.CurrencyID);
            ViewData["PartiesID"]  = new SelectList(_context.Parties.Where(r => r.CompanyID == CompID), "PartiesID", "PartyName", cashReceipt.PartiesID);
            return(View(cashReceipt));
        }
示例#28
0
      //! NPV of a single cash flows 
      public static double npv(CashFlow cashflow, YieldTermStructure discountCurve,
                               Date settlementDate = null, Date npvDate = null, int exDividendDays = 0)
      {
         double NPV = 0.0;

         if (cashflow == null)
            return 0.0;

         if (settlementDate == null)
            settlementDate = Settings.evaluationDate();

         if (npvDate == null)
            npvDate = settlementDate;

         if (!cashflow.hasOccurred(settlementDate + exDividendDays))
            NPV = cashflow.amount() * discountCurve.discount(cashflow.date());

         
         return NPV / discountCurve.discount(npvDate);
      }
示例#29
0
 public bool SaveTransaction(CashFlow cashFlow)
 {
     throw new NotImplementedException();
 }
示例#30
0
        public CashFlowSchedule GenerateSchedule()
        {
            var startDate = EffectiveDate;
            var endDate   = TerminationDate.Date(startDate, ResetRollType, ResetCalendar);
            var f         = new CashFlowSchedule();
            var lf        = new List <CashFlow>();

            if (NotionalExchange == ExchangeType.FrontOnly || NotionalExchange == ExchangeType.Both)
            {
                lf.Add(new CashFlow
                {
                    Notional               = (double)Nominal * (Direction == SwapPayReceiveType.Payer ? -1.0 : 1.0),
                    Fv                     = (double)Nominal * (Direction == SwapPayReceiveType.Payer ? -1.0 : 1.0),
                    SettleDate             = startDate,
                    NotionalByYearFraction = 1.0,
                    Dcf                    = 1.0,
                    FlowType               = FlowType.FixedAmount
                });
            }

            //need to handle stub types and roll day types
            switch (StubType)
            {
            case StubType.ShortFront:
            case StubType.LongFront:
            {
                var nQ           = 0;
                var currentReset = GetNextResetDate(endDate, false);
                while (GetNextResetDate(currentReset, false) >= startDate)
                {
                    var q = new CashFlow()
                    {
                        ResetDateStart     = currentReset,
                        AccrualPeriodStart = currentReset,
                        FixingDateStart    = currentReset.SubtractPeriod(FixingRollType, FixingCalendar, FixingOffset),
                        AccrualPeriodEnd   = currentReset.AddPeriod(ResetRollType, ResetCalendar, ResetFrequency)
                    };
                    q.SettleDate = (PaymentOffsetRelativeTo == OffsetRelativeToType.PeriodEnd) ?
                                   q.AccrualPeriodEnd.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset) :
                                   q.AccrualPeriodStart.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset);
                    q.NotionalByYearFraction = (LegType != SwapLegType.FixedNoAccrual && LegType != SwapLegType.FloatNoAccrual) ?
                                               q.AccrualPeriodStart.CalculateYearFraction(q.AccrualPeriodEnd, AccrualDCB) :
                                               1.0;
                    q.Dcf = q.NotionalByYearFraction;
                    q.Fv  = (LegType == SwapLegType.Fixed) ?
                            (double)Nominal * q.NotionalByYearFraction * (double)FixedRateOrMargin :
                            0;
                    q.FixedRateOrMargin = (double)FixedRateOrMargin;
                    q.FlowType          = (LegType == SwapLegType.Fixed) ? FlowType.FixedRate : FlowType.FloatRate;
                    q.Notional          = (double)Nominal;
                    lf.Add(q);
                    nQ++;
                    currentReset = GetNextResetDate(currentReset, false);
                }

                if (lf.Count == 0 || lf.Last().AccrualPeriodStart != startDate)
                {
                    if (StubType == StubType.LongFront)
                    {
                        var Q = lf.Last();
                        Q.ResetDateStart     = startDate;
                        Q.AccrualPeriodStart = startDate;
                        Q.SettleDate         = (PaymentOffsetRelativeTo == OffsetRelativeToType.PeriodEnd) ?
                                               Q.AccrualPeriodEnd.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset) :
                                               Q.AccrualPeriodStart.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset);
                        Q.Dcf = (LegType != SwapLegType.FixedNoAccrual && LegType != SwapLegType.FloatNoAccrual) ?
                                Q.AccrualPeriodStart.CalculateYearFraction(Q.AccrualPeriodEnd, AccrualDCB) :
                                1.0;
                    }
                    else
                    {
                        var q = new CashFlow()
                        {
                            AccrualPeriodStart = startDate,
                            FixingDateStart    = startDate.SubtractPeriod(FixingRollType, FixingCalendar, FixingOffset),
                            AccrualPeriodEnd   = (lf.Count > 0 && lf.Last().AccrualPeriodEnd != DateTime.MinValue)? lf.Last().AccrualPeriodStart : endDate
                        };

                        q.SettleDate = (PaymentOffsetRelativeTo == OffsetRelativeToType.PeriodEnd) ?
                                       q.AccrualPeriodEnd.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset) :
                                       q.AccrualPeriodStart.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset);
                        //Q.Currency = CCY;
                        q.NotionalByYearFraction = (LegType != SwapLegType.FixedNoAccrual && LegType != SwapLegType.FloatNoAccrual) ?
                                                   q.AccrualPeriodStart.CalculateYearFraction(q.AccrualPeriodEnd, AccrualDCB) :
                                                   1.0;
                        q.Dcf = q.NotionalByYearFraction;
                        q.Fv  = (LegType == SwapLegType.Fixed) ?
                                (double)Nominal * q.NotionalByYearFraction * (double)FixedRateOrMargin :
                                0;
                        q.FixedRateOrMargin = (double)FixedRateOrMargin;
                        q.FlowType          = (LegType == SwapLegType.Fixed) ? FlowType.FixedRate : FlowType.FloatRate;
                        q.Notional          = (double)Nominal;
                        lf.Add(q);
                        nQ++;
                    }
                }


                break;
            }

            case StubType.ShortBack:
            case StubType.LongBack:
            {
                var nQ           = 0;
                var currentReset = startDate;
                while (GetNextResetDate(currentReset, true) <= endDate)
                {
                    var Q = new CashFlow()
                    {
                        AccrualPeriodStart = currentReset,
                        FixingDateStart    = currentReset.SubtractPeriod(FixingRollType, FixingCalendar, FixingOffset),
                        AccrualPeriodEnd   = currentReset.AddPeriod(ResetRollType, ResetCalendar, ResetFrequency)
                    };
                    Q.SettleDate = (PaymentOffsetRelativeTo == OffsetRelativeToType.PeriodEnd) ?
                                   Q.AccrualPeriodEnd.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset) :
                                   Q.AccrualPeriodStart.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset);
                    //Q.Currency = CCY;
                    Q.NotionalByYearFraction = (LegType != SwapLegType.FixedNoAccrual && LegType != SwapLegType.FloatNoAccrual) ?
                                               Q.AccrualPeriodStart.CalculateYearFraction(Q.AccrualPeriodEnd, AccrualDCB) :
                                               1.0;
                    Q.Dcf      = Q.NotionalByYearFraction;
                    Q.Notional = (double)Nominal;
                    Q.Fv       = (LegType == SwapLegType.Fixed) ?
                                 (double)Nominal * Q.NotionalByYearFraction * (double)FixedRateOrMargin :
                                 0;
                    Q.FixedRateOrMargin = (double)FixedRateOrMargin;
                    Q.FlowType          = (LegType == SwapLegType.Fixed) ? FlowType.FixedRate : FlowType.FloatRate;
                    lf.Add(Q);
                    nQ++;
                    currentReset = GetNextResetDate(currentReset, false);
                }



                if (lf.Last().AccrualPeriodEnd != endDate)
                {
                    if (StubType == StubType.LongBack)
                    {
                        var Q = lf.Last();
                        Q.AccrualPeriodEnd = endDate;
                        Q.SettleDate       = (PaymentOffsetRelativeTo == OffsetRelativeToType.PeriodEnd) ?
                                             Q.AccrualPeriodEnd.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset) :
                                             Q.AccrualPeriodStart.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset);
                        Q.Dcf = (LegType != SwapLegType.FixedNoAccrual && LegType != SwapLegType.FloatNoAccrual) ?
                                Q.AccrualPeriodStart.CalculateYearFraction(Q.AccrualPeriodEnd, AccrualDCB) :
                                1.0;
                    }
                    else
                    {
                        var Q = new CashFlow()
                        {
                            AccrualPeriodStart = lf.Last().AccrualPeriodEnd,
                            FixingDateStart    = startDate.SubtractPeriod(FixingRollType, FixingCalendar, FixingOffset),
                            AccrualPeriodEnd   = endDate
                        };
                        Q.SettleDate = (PaymentOffsetRelativeTo == OffsetRelativeToType.PeriodEnd) ?
                                       Q.AccrualPeriodEnd.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset) :
                                       Q.AccrualPeriodStart.AddPeriod(PaymentRollType, PaymentCalendar, PaymentOffset);
                        //Q.Currency = CCY;
                        Q.NotionalByYearFraction = (LegType != SwapLegType.FixedNoAccrual && LegType != SwapLegType.FloatNoAccrual) ?
                                                   Q.AccrualPeriodStart.CalculateYearFraction(Q.AccrualPeriodEnd, AccrualDCB) :
                                                   1.0; Q.Notional = (double)Nominal;
                        Q.Dcf = Q.NotionalByYearFraction;
                        Q.Fv  = (LegType == SwapLegType.Fixed) ?
                                (double)Nominal * Q.NotionalByYearFraction * (double)FixedRateOrMargin :
                                0;
                        Q.FixedRateOrMargin = (double)FixedRateOrMargin;
                        Q.FlowType          = (LegType == SwapLegType.Fixed) ? FlowType.FixedRate : FlowType.FloatRate;
                        Q.Notional          = (double)Nominal;
                        lf.Add(Q);
                        nQ++;
                    }
                }
                break;
            }

            case StubType.LongBoth:
            case StubType.ShortBoth:
                throw new NotImplementedException("Schedules with Both type stubs cannot be generated");
            }

            if (NotionalExchange == ExchangeType.BackOnly || NotionalExchange == ExchangeType.Both)
            {
                lf.Add(new CashFlow
                {
                    Notional               = (double)Nominal * (Direction == SwapPayReceiveType.Receiver ? -1.0 : 1.0),
                    Fv                     = (double)Nominal * (Direction == SwapPayReceiveType.Receiver ? -1.0 : 1.0),
                    SettleDate             = endDate,
                    NotionalByYearFraction = 1.0,
                    Dcf                    = 1.0,
                    FlowType               = FlowType.FixedAmount
                });
            }
            f.Flows = lf.OrderBy(x => x.AccrualPeriodStart).ToList();

            return(f);
        }
示例#31
0
文件: Bond.cs 项目: minikie/test
 public CashFlow redemption() {
   CashFlow ret = new CashFlow(NQuantLibcPINVOKE.Bond_redemption(swigCPtr), true);
   if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
示例#32
0
 public void PutCashFlow(CashFlow cashflow)
 {
     throw new NotImplementedException();
 }
示例#33
0
        public void CalculateOnSuccessRunsCalculations()
        {
            //arrange
            var cashFlow = new CashFlow()
            {
                Id = 3
            };
            var cashFlows = new[] { cashFlow };

            var isNotPortfolioNodeId = 1;
            var isNotPortfolioNode   = new Mock <INode>();

            isNotPortfolioNode.SetupAllProperties();
            isNotPortfolioNode.Setup(p => p.Id).Returns(isNotPortfolioNodeId);
            isNotPortfolioNode.Setup(p => p.IsPortfolioComponent).Returns(false);

            var IsPortfolioNodeId = 2;
            var isPortfolioNode   = new Mock <INode>();

            isPortfolioNode.SetupAllProperties();
            isPortfolioNode.Setup(c => c.Id).Returns(IsPortfolioNodeId);
            isPortfolioNode.Setup(p => p.IsPortfolioComponent).Returns(true);

            var nodeDictionary = new Dictionary <int, INode> {
                { isNotPortfolioNodeId, isNotPortfolioNode.Object },
                { IsPortfolioNodeId, isPortfolioNode.Object }
            };

            var isNotPortfolioSimulation = 4D;
            var isPortfolioSimulation    = 5D;
            var nodeSimulations          = new Dictionary <int, IList <double> > {
                { isNotPortfolioNodeId, new List <double> {
                      isNotPortfolioSimulation
                  } },
                { IsPortfolioNodeId, new List <double> {
                      isPortfolioSimulation
                  } }
            };

            var nodeSimulator = new Mock <INodeSimulator>();

            nodeSimulator.Setup(s => s.SimulateNodes(
                                    It.Is <IDictionary <int, INode> >(dict => dict == nodeDictionary)))
            .Returns(nodeSimulations);

            var portfolio = new Mock <IPortfolio>();

            portfolio.Setup(p => p.Init(
                                It.Is <IList <INode> >(list => list[0].Id == IsPortfolioNodeId && list.Count == 1),
                                It.Is <IList <CashFlow> >(cf => cf[0].Id == cashFlows[0].Id)));

            var network = new Network(portfolio.Object, nodeSimulator.Object);

            network.CashFlows = cashFlows;
            network.Nodes     = nodeDictionary;

            //act
            network.Calculate();

            //assert
            Assert.AreEqual(portfolio.Object, network.Portfolio);
            portfolio.Verify(p => p.Init(
                                 It.Is <IList <INode> >(list => list[0].Id == IsPortfolioNodeId && list.Count == 1),
                                 It.Is <IList <CashFlow> >(cf => cf[0].Id == cashFlows[0].Id)));

            Assert.AreEqual(cashFlow.Id, network.CashFlows.First().Id);

            Assert.AreEqual(IsPortfolioNodeId, network.Nodes.Values.Last().Id);
            isPortfolioNode.VerifySet(n => n.Portfolio = portfolio.Object);
            Assert.AreEqual(isPortfolioSimulation, isPortfolioNode.Object.Simulations[0]);

            Assert.AreEqual(isNotPortfolioNodeId, network.Nodes.Values.First().Id);
            isNotPortfolioNode.VerifySet(n => n.Portfolio = It.IsAny <IPortfolio>(), Times.Never);
            Assert.AreEqual(isNotPortfolioSimulation, isNotPortfolioNode.Object.Simulations[0]);
        }
        /// <summary>
        /// Calculates the performance with the internal rate of interest
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="beginPeriod">The begin period.</param>
        /// <param name="endPeriod">The end period.</param>
        /// <returns>  Performance in %  </returns>
        public decimal CalculatePerformancePercentageIir(IQuery <IEnumerable <ITransaction> > query, CashFlow beginPeriod, CashFlow endPeriod)
        {
            var transactions = _queryDispatcher.Execute(query);

            var cashflows = new List <CashFlow>();

            if (beginPeriod != null)
            {
                cashflows.Add(beginPeriod);
            }

            foreach (var tr in transactions.OrderBy(t => t.OrderDate))
            {
                if (tr is IBuyingTransaction)
                {
                    cashflows.Add(new CashFlow((tr.PositionSize + tr.OrderCosts) * -1, tr.OrderDate));
                }
                else if (tr is ISellingTransaction)
                {
                    cashflows.Add(new CashFlow(tr.PositionSize - tr.OrderCosts - ((ISellingTransaction)tr).Taxes, tr.OrderDate));
                }
                else if (tr is IDividendTransaction)
                {
                    cashflows.Add(new CashFlow(tr.PositionSize - tr.OrderCosts - ((IDividendTransaction)tr).Taxes, tr.OrderDate));
                }
            }

            cashflows.Add(endPeriod);

            var val = _iirCalculatorService.Calculate(cashflows);

            return(decimal.Round(Convert.ToDecimal(val) * 100, 2));
        }
示例#35
0
        public async Task <IActionResult> Create(PurchaseReturn purchaseReturn, IEnumerable <PurchaseBillItem> PurchaseBillItem_List, IEnumerable <Transaction> TransactionList)
        {
            string CompId = User.Claims.Where(r => r.Type == "CompanyID").FirstOrDefault().Value;
            int    CompID = Convert.ToInt32(CompId);

            int purReturnID = 0;

            var PurchaseBillItem_List_1 = PurchaseBillItem_List.ToList();

            PurchaseBillItem_List_1.RemoveAll(x => x.PurchaseBillExtraInt_2 == 0);

            foreach (var item in PurchaseBillItem_List_1)
            {
                PurchaseReturn obj = new PurchaseReturn();

                obj.PR_B_1            = purchaseReturn.PR_B_1;
                obj.CreatedBy         = User.Identity.Name;
                obj.CompanyID         = CompID;
                obj.PurBillReturnDate = DateTime.Now;

                obj.PurchaseBillID = purchaseReturn.PurchaseBillID;
                obj.ItemID         = item.ItemID;
                if (purchaseReturn.PartiesID == 0)
                {
                    obj.PartiesID = null;
                }
                else
                {
                    obj.PartiesID = purchaseReturn.PartiesID;
                }

                obj.OldQuantity     = item.Quantity;
                obj.ReturnQuantity  = item.PurchaseBillExtraInt_2;
                obj.AmountToReceive = item.PurchaseBillExtraDecimal_1;

                obj.Remarks = purchaseReturn.Remarks;

                _context.Add(obj);
                await _context.SaveChangesAsync();

                purReturnID = obj.PurchaseReturnID;

                // Decreasing Item Quantity from ITEM Table
                Item    itemObj = new Item();
                decimal StockQuantity, final;

                itemObj       = _context.Item.Where(r => r.ItemID == item.ItemID).SingleOrDefault();
                StockQuantity = itemObj.Quantity;
                final         = StockQuantity - item.PurchaseBillExtraInt_2;

                itemObj.Quantity = final;
                _context.Update(itemObj);
                await _context.SaveChangesAsync();

                // Decreasing Item Quantity from ITEM Table
            }


            if (purchaseReturn.PartiesID == null)
            {
                CashFlow CF = new CashFlow();
                CF.Credit           = purchaseReturn.AmountToReceive;
                CF.PurchaseReturnID = purReturnID;
                CF.CompanyID        = CompID;

                // Purchase Return  03-0002-0001
                int MainAccID = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "03").FirstOrDefault().MainAccountID;
                int SubAccID  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID).Where(r => r.SubAccountNumber == "0002").FirstOrDefault().SubAccountID;
                int TraAccID  = _context.TransactionAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountID == SubAccID).Where(r => r.TransactionAccountNumber == "0001").FirstOrDefault().TransactionAccountID;

                CF.MainAccountID        = MainAccID;
                CF.SubAccountID         = SubAccID;
                CF.TransactionAccountID = TraAccID;
                if (purchaseReturn.PR_B_1 == false)
                {
                    CF.VoucherType = "Purchase Return Voucher";
                }
                else
                {
                    CF.VoucherType = "Import Return Voucher";
                }

                CF.DateCreation = DateTime.Now.Date;

                _context.CashFlow.Add(CF);
                await _context.SaveChangesAsync();

                CashFlow CF1 = new CashFlow();
                CF1.Debit            = purchaseReturn.AmountToReceive;
                CF1.PurchaseReturnID = purReturnID;
                CF1.CompanyID        = CompID;

                // Cash In Hand 01-0001-0001
                int MainAccID_1 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "01").FirstOrDefault().MainAccountID;
                int SubAccID_1  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID_1).Where(r => r.SubAccountNumber == "0001").FirstOrDefault().SubAccountID;
                int TraAccID_1  = _context.TransactionAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountID == SubAccID_1).Where(r => r.TransactionAccountNumber == "0001").FirstOrDefault().TransactionAccountID;

                CF1.MainAccountID        = MainAccID_1;
                CF1.SubAccountID         = SubAccID_1;
                CF1.TransactionAccountID = TraAccID_1;
                if (purchaseReturn.PR_B_1 == false)
                {
                    CF1.VoucherType = "Purchase Return Voucher";
                }
                else
                {
                    CF1.VoucherType = "Import Return Voucher";
                }
                CF1.DateCreation = DateTime.Now.Date;

                _context.CashFlow.Add(CF1);
                await _context.SaveChangesAsync();
            }

            else
            {
                CashFlow CF2 = new CashFlow();
                CF2.Debit            = purchaseReturn.AmountToReceive;
                CF2.PurchaseReturnID = purReturnID;
                CF2.CompanyID        = CompID;
                CF2.PartiesID        = purchaseReturn.PartiesID;

                int?PartyTransID = _context.Parties.Where(r => r.CompanyID == CompID).Where(r => r.PartiesID == purchaseReturn.PartiesID).FirstOrDefault().TransactionAccountID;
                int PartMainAcc  = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "00").FirstOrDefault().MainAccountID;
                int PartSubAcc   = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountNumber == "0000").FirstOrDefault().SubAccountID;

                CF2.MainAccountID        = PartMainAcc;
                CF2.SubAccountID         = PartSubAcc;
                CF2.TransactionAccountID = (int)PartyTransID;
                if (purchaseReturn.PR_B_1 == false)
                {
                    CF2.VoucherType = "Purchase Return Voucher";
                }
                else
                {
                    CF2.VoucherType = "Import Return Voucher";
                }
                CF2.DateCreation = DateTime.Now.Date;

                _context.CashFlow.Add(CF2);
                await _context.SaveChangesAsync();

                CashFlow CF3 = new CashFlow();
                CF3.Credit           = purchaseReturn.AmountToReceive;
                CF3.PurchaseReturnID = purReturnID;
                CF3.CompanyID        = CompID;
                CF3.PartiesID        = purchaseReturn.PartiesID;

                // Purchase Return  03-0002-0001
                int MainAccID = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "03").FirstOrDefault().MainAccountID;
                int SubAccID  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID).Where(r => r.SubAccountNumber == "0002").FirstOrDefault().SubAccountID;
                int TraAccID  = _context.TransactionAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountID == SubAccID).Where(r => r.TransactionAccountNumber == "0001").FirstOrDefault().TransactionAccountID;

                CF3.MainAccountID        = MainAccID;
                CF3.SubAccountID         = SubAccID;
                CF3.TransactionAccountID = TraAccID;
                if (purchaseReturn.PR_B_1 == false)
                {
                    CF3.VoucherType = "Purchase Return Voucher";
                }
                else
                {
                    CF3.VoucherType = "Import Return Voucher";
                }
                CF3.DateCreation = DateTime.Now.Date;

                _context.CashFlow.Add(CF3);
                await _context.SaveChangesAsync();

                if (TransactionList.FirstOrDefault().Paid == true)
                {
                    CashFlow CF4 = new CashFlow();
                    CF4.Credit           = TransactionList.FirstOrDefault().Amount;
                    CF4.PurchaseReturnID = purReturnID;
                    CF4.CompanyID        = CompID;
                    CF4.PartiesID        = purchaseReturn.PartiesID;

                    int?PartyTransID_1 = _context.Parties.Where(r => r.CompanyID == CompID).Where(r => r.PartiesID == purchaseReturn.PartiesID).FirstOrDefault().TransactionAccountID;
                    int PartMainAcc_a  = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "00").FirstOrDefault().MainAccountID;
                    int PartSubAcc_a   = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountNumber == "0000").FirstOrDefault().SubAccountID;

                    CF4.MainAccountID        = PartMainAcc_a;
                    CF4.SubAccountID         = PartSubAcc_a;
                    CF4.TransactionAccountID = (int)PartyTransID_1;
                    if (purchaseReturn.PR_B_1 == false)
                    {
                        CF4.VoucherType = "Purchase Return Voucher";
                    }
                    else
                    {
                        CF4.VoucherType = "Import Return Voucher";
                    }
                    CF4.DateCreation = DateTime.Now.Date;

                    _context.CashFlow.Add(CF4);
                    await _context.SaveChangesAsync();


                    if (TransactionList.FirstOrDefault().Mode == PaymentMode.Cash) // Mode 0 Means ==> Cash
                    {
                        CashFlow CF5 = new CashFlow();
                        CF5.Debit            = TransactionList.FirstOrDefault().Amount;
                        CF5.PurchaseReturnID = purReturnID;
                        CF5.CompanyID        = CompID;
                        CF5.PartiesID        = purchaseReturn.PartiesID;
                        // Cash In Hand 01-0001-0001
                        int MainAccID_2 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "01").FirstOrDefault().MainAccountID;
                        int SubAccID_2  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID_2).Where(r => r.SubAccountNumber == "0001").FirstOrDefault().SubAccountID;
                        int TraAccID_2  = _context.TransactionAccount.Where(r => r.CompanyID == CompID).Where(r => r.SubAccountID == SubAccID_2).Where(r => r.TransactionAccountNumber == "0001").FirstOrDefault().TransactionAccountID;

                        CF5.SubAccountID         = SubAccID_2;
                        CF5.MainAccountID        = MainAccID_2;
                        CF5.TransactionAccountID = TraAccID_2;
                        if (purchaseReturn.PR_B_1 == false)
                        {
                            CF5.VoucherType = "Purchase Return Voucher";
                        }
                        else
                        {
                            CF5.VoucherType = "Import Return Voucher";
                        }
                        CF5.DateCreation = DateTime.Now.Date;

                        _context.CashFlow.Add(CF5);
                        await _context.SaveChangesAsync();
                    }
                    else if (TransactionList.FirstOrDefault().Mode == PaymentMode.Cheque) // Mode 0 Means ==> Cheque
                    {
                        CashFlow CF6 = new CashFlow();
                        CF6.Debit            = TransactionList.FirstOrDefault().Amount;
                        CF6.PurchaseReturnID = purReturnID;
                        CF6.CompanyID        = CompID;
                        CF6.PartiesID        = purchaseReturn.PartiesID;

                        int?bankID      = TransactionList.FirstOrDefault().BankID;
                        int transBankID = _context.Bank.Where(r => r.CompanyID == CompID).Where(r => r.BankID == bankID).FirstOrDefault().TransactionAccountID;

                        int MainAccID_3 = _context.MainAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountNumber == "01").FirstOrDefault().MainAccountID;
                        int SubAccID_3  = _context.SubAccount.Where(r => r.CompanyID == CompID).Where(r => r.MainAccountID == MainAccID_3).Where(r => r.SubAccountNumber == "0002").FirstOrDefault().SubAccountID;

                        CF6.MainAccountID = MainAccID_3;
                        CF6.SubAccountID  = SubAccID_3;

                        CF6.TransactionAccountID = transBankID;
                        if (purchaseReturn.PR_B_1 == false)
                        {
                            CF6.VoucherType = "Purchase Return Voucher";
                        }
                        else
                        {
                            CF6.VoucherType = "Import Return Voucher";
                        }
                        CF6.DateCreation = DateTime.Now.Date;

                        _context.CashFlow.Add(CF6);
                        await _context.SaveChangesAsync();
                    }
                }
            }

            var TransactionList_Result = TransactionList.ToList();

            TransactionList_Result.RemoveAll(x => x.TransactionID == 777777);
            TransactionList_Result.ForEach(x => x.TransactionID = 0);

            foreach (var item in TransactionList_Result)
            {
                PurchaseReturnTransaction transaction = new PurchaseReturnTransaction();
                transaction.CompanyID        = CompID;
                transaction.PurchaseReturnID = purReturnID;
                transaction.Amount           = item.Amount;
                transaction.BankID           = item.BankID;
                transaction.Cheque           = item.Cheque;
                transaction.Date             = item.Date;
                transaction.Mode             = item.Mode;
                transaction.Paid             = item.Paid;
                transaction.PurchaseBillID   = purchaseReturn.PurchaseBillID;

                _context.PurchaseReturnTransaction.Add(transaction);

                await _context.SaveChangesAsync();
            }
            if (User.IsInRole("CompanyAdmin"))
            {
                return(RedirectToAction("Index", "Home", new { area = "CompanyAdmin" }));
            }
            else
            {
                return(RedirectToAction("Index", "Home", new { area = "CompanyUser" }));
            }
        }
示例#36
0
 public void visit(CashFlow cf) 
 {
    nonSensNPV_ += cf.amount() * discountCurve_.discount(cf.date());
 }
示例#37
0
        public void MapEntityToViewModelOnSuccessMapsProperties()
        {
            //arrange
            var url     = "url";
            var name    = "name";
            var network = new Mock <INetwork>();

            network.Setup(n => n.Url).Returns(url);
            network.Setup(n => n.Name).Returns(name);

            var nodeId = 1;
            var node   = new Mock <INode>();

            node.Setup(n => n.Id).Returns(nodeId);
            IDictionary <int, INode> nodes = new Dictionary <int, INode> {
                { nodeId, node.Object }
            };

            network.Setup(n => n.Nodes).Returns(nodes);

            var initialValue = 100D;
            var portfolio    = new Mock <IPortfolio>();

            portfolio.Setup(p => p.InitialValue).Returns(initialValue);
            network.Setup(n => n.Portfolio).Returns(portfolio.Object);

            var cashFlowId = 3;
            var cashFlow   = new CashFlow {
                Id = cashFlowId
            };
            IList <CashFlow> cashFlows = new[] { cashFlow };

            network.Setup(n => n.CashFlows).Returns(cashFlows);

            var nodeViewModel = new NodeViewModel {
                Id = nodeId
            };
            IDictionary <int, NodeViewModel> nodeViewModels = new Dictionary <int, NodeViewModel> {
                { nodeId, nodeViewModel }
            };
            var nodeMapper = new Mock <INodeMapper>();

            nodeMapper.Setup(m => m.MapNodesToViewModels(
                                 It.Is <IDictionary <int, INode> >(dict => dict[nodeId].Id == nodeId)))
            .Returns(nodeViewModels);

            var successProbability   = .5D;
            var successProbabilities = new[] { successProbability };
            var portfolioViewModel   = new PortfolioViewModel
            {
                SuccessProbabilities = successProbabilities
            };
            var portfolioMapper = new Mock <IPortfolioMapper>();

            portfolioMapper.Setup(m => m.MapPortfolioToViewModel(
                                      It.Is <IPortfolio>(p => p.InitialValue == initialValue)))
            .Returns(portfolioViewModel);

            var networkMapper = new NetworkMapper(nodeMapper.Object, portfolioMapper.Object, null);

            //act
            var result = networkMapper.MapNetworkToViewModel(network.Object);

            //assert
            Assert.AreEqual(url, result.Url);
            Assert.AreEqual(name, result.Name);
            Assert.AreEqual(nodeId, result.Nodes[nodeId].Id);
            Assert.AreEqual(successProbability, result.Portfolio.SuccessProbabilities[0]);
            Assert.AreEqual(cashFlowId, result.CashFlows[0].Id);
        }
示例#38
0
 public void visit(CashFlow c)
 {
     // nothing to do
 }
示例#39
0
        public void InitOnSuccessReturnsCorrectProbabilities()
        {
            //arrange
            int expectedPortfolioSimulation = 10; // int avoids floating point errors
            var simulation  = 110D;
            var simulations = new[] { simulation };

            var nodeInitialInvestment = 1000D;
            var nodeInitialPrice      = 100D;
            var node = new Mock <INode>();

            node.Setup(n => n.InitialInvestment).Returns(nodeInitialInvestment);
            node.Setup(n => n.InitialPrice).Returns(nodeInitialPrice);
            node.Setup(n => n.Simulations).Returns(simulations);
            node.Setup(n => n.PortfolioWeight).Returns(1);
            var nodes = new[] { node.Object };

            var cashFlowId = 1;
            var cashFlow   = new CashFlow {
                Id = cashFlowId
            };
            var cashFlows = new[] { cashFlow };

            var successProbability   = .5D;
            var successProbabilities = new[] { successProbability };
            var portfolioSimulator   = new Mock <IPortfolioSimulator>();

            portfolioSimulator.Setup(ps => ps.CalculateSuccessProbabilities(
                                         It.Is <IList <INode> >(n => n[0].InitialInvestment == nodeInitialInvestment),
                                         It.Is <IList <CashFlow> >(cf => cf[0].Id == cashFlowId)))
            .Returns(successProbabilities);

            var statistics = new Mock <IStatistic>();

            var interval       = 3D;
            var histogramDatum = new HistogramDatum {
                Interval = interval
            };
            var histogramData = new[] { histogramDatum };
            var histogram     = new Mock <IHistogram>();

            histogram.Setup(h => h.GetHistogramData(
                                It.Is <HistogramContext>(
                                    ctx => (int)ctx.Simulations[0] == expectedPortfolioSimulation &&
                                    (int)ctx.GlobalXMin == expectedPortfolioSimulation &&
                                    (int)ctx.GlobalXMax == expectedPortfolioSimulation),
                                It.IsAny <int>()))
            .Returns(histogramData);

            var portfolio = new Portfolio(statistics.Object, histogram.Object, portfolioSimulator.Object);

            //act
            portfolio.Init(nodes, cashFlows);
            var initialValueResult         = portfolio.InitialValue;
            var statisticsResult           = portfolio.Statistics;
            var histogramResult            = portfolio.Histogram;
            var successProbabilitiesResult = portfolio.SuccessProbabilities;

            //assert
            Assert.AreEqual(nodeInitialInvestment, initialValueResult);
            Assert.AreSame(statistics.Object, statisticsResult);
            statistics.Verify(s => s.Init(
                                  It.Is <IList <double> >(sim => (int)sim[0] == expectedPortfolioSimulation)
                                  ));
            Assert.AreEqual(interval, histogramResult[0].Interval);
            Assert.AreEqual(successProbability, successProbabilitiesResult[0]);
        }