public void TestToStringReturnsExpectedValue()
 {
     Financial financial = new Financial(_gbp, _amount);
     Assert.IsNotNull(financial.Currency);
     string expectedFormat = String.Format("{0:C}", _amount);
     Assert.AreEqual(expectedFormat, financial.ToString());
 }
        public void TestEqualFinancialRangesReturnTrue()
        {
            Financial financialA = new Financial(CurrencyInfoProvider.Current.Get("GBP"), 10);
            Financial financialB = new Financial(CurrencyInfoProvider.Current.Get("GBP"), 10);

            Range<Financial> rangeA = new Range<Financial>(financialA, financialB);
            Range<Financial> rangeB = new Range<Financial>(financialA, financialB);

            Assert.IsTrue(rangeA.Equals(rangeB));
        }
        public void TestAddOperatorAddsTheAmountsInTheFinancials()
        {
            decimal amountA = Random.RandomDecimal();
            decimal amountB = Random.RandomDecimal();

            Financial financialA = new Financial(_gbp, amountA);
            Financial financialB = new Financial(_gbp, amountB);

            Financial result = financialA + financialB;
            Assert.IsNotNull(result);
            Assert.AreEqual(amountA + amountB, result.Amount);
        }
        public void TestSumCorrectlySumsTheAmountsInTheProvidedFinancials()
        {
            Financial financialA = new Financial(_gbp, 10);
            Financial financialB = new Financial(_gbp, 2036.54M);
            Financial financialC = new Financial(_gbp, -153);

            Assert.AreEqual(1893.54M, Financial.Sum(new[] {financialA, financialB, financialC}).Amount);
        }
Example #5
0
 // Save - Update
 public void SaveClient(Financial financial)
 {
     _financialRepository.Update(financial);
 }
Example #6
0
 public void RateArgs1()
 {
     double d = Financial.Rate(-1, 1, 1, 1, DueDate.BegOfPeriod, 1);
 }
Example #7
0
 public void IRRArgs1()
 {
     double [] arr = new double [0];
     Financial.IRR(ref arr, 0.1);
 }
Example #8
0
 public void DDB_4()
 {
     // Argument 'Factor' is not a valid value.
     double d = Financial.DDB(1500, -2, 48, 24, 2.0);
 }
Example #9
0
 public void SYDArgs3()
 {
     Financial.SYD(1, 1, 1, 2);
 }
 public void TestFormatWithNoFormatUsesFormatI()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get("EUR");
     Financial financial = new Financial(currencyInfo, amount);
     String expectedFormat = String.Format("{0:I}", financial);
     Assert.AreEqual(expectedFormat, String.Format("{0}", financial));
 }
Example #11
0
        public void Calculate(ReportGrouping grouping, double discountRatePerYear)
        {
            // The underlying data is always monthly
            var discountRate = grouping == ReportGrouping.Yearly ? discountRatePerYear : Financial.ConvertDiscountRateYearToMonth(discountRatePerYear);

            if (CalculateNpv)
            {
                Npv = (decimal)Financials.Npv.Calculate(_cashFlows, discountRate);
            }
            if (CalculateIrr)
            {
                var irr = Financials.Irr.Calculate(_cashFlows, discountRate);
                Irr = double.IsNaN(irr) ? 0m : (decimal)irr;
            }

            // If we ask for yearly, convert the resulting IRR
            if (grouping == ReportGrouping.Monthly)
            {
                Irr = Financial.ConvertDiscountRateMonthToYear(Irr);
            }
        }
 public void TestFormatWithFormatIReturnsAmountAndIsoCode()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get("EUR");
     Financial financial = new Financial(currencyInfo, amount);
     Trace.WriteLine(CultureInfo.CurrentUICulture);
     String expectedFormat = String.Format("{0} {1}", amount, currencyInfo.Code);
     Assert.AreEqual(expectedFormat, String.Format("{0:I}", financial));
 }
 public void TestFormatWithFormatIAndFormatProviderReturnsAmountAndIsoCode()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get("EUR");
     Financial financial = new Financial(currencyInfo, amount);
     IFormatProvider provider = new CultureInfo("fr-ca").NumberFormat;
     String expectedFormat = String.Format(provider, "{0} {1}", amount, currencyInfo.Code);
     Assert.AreEqual(expectedFormat, String.Format(provider, "{0:I}", financial));
 }
 public void TestFormatWithFormatProviderAndInvalidFormatThrowsFormatException()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get("GBP");
     Financial financial = new Financial(currencyInfo, amount);
     string s = String.Format(CultureInfo.CurrentUICulture, "{0:NOTVALID}", financial);
 }
 public void TestToStringFormatsUsingCurrentCultureIfCorrectCurrencyIsNotPossible()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get("XXX"); // Noone uses this dubiously named currency
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("De-de");
     Financial financial = new Financial(currencyInfo, amount);
     String expectedFormat = String.Format(CultureInfo.CurrentUICulture, "{0:C}", amount);
     Assert.AreEqual(expectedFormat, financial.ToString());
 }
 public void TestToStringFormatsUsingCorrectCurrencyWhenCurrencyOfCurrentUICultureDoesNotMatch()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get("GBP");
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("De-de");
     // No pound in Germany, nor any German speaking countries.
     Financial financial = new Financial(currencyInfo, amount);
     List<String> expectedFormats = CultureInfoProvider.Current.FindByCurrency(currencyInfo).Select(
         mc =>
             String.Format(mc, "{0:C}", amount)).ToList();
     CollectionAssert.Contains(expectedFormats, financial.ToString());
 }
Example #17
0
      public override Transaction Charge(PaySession session, ITransactionContext context, Account from, Account to, Financial.Amount amount, bool capture = true, string description = null, object extraData = null)
      {
        var fromActualData = PaySystemHost.AccountToActualData(context, from);

        if (fromActualData == null)
        {
          StatChargeError();
          throw new PaymentMockException(StringConsts.PAYMENT_UNKNOWN_ACCOUNT_ERROR.Args(from) + this.GetType().Name + ".Charge");
        }

        if (m_Accounts.CreditCardDeclined.Any(c => c.AccountNumber == fromActualData.AccountNumber))
        {
          StatChargeError();
          throw new PaymentMockException(this.GetType().Name + ".Charge: card '{0}' declined".Args(fromActualData));
        }

        if (m_Accounts.CreditCardLuhnError.Any(c => c.AccountNumber == fromActualData.AccountNumber))
        {
          StatChargeError();
          throw new PaymentMockException(this.GetType().Name + ".Charge: card number '{0}' is incorrect".Args(fromActualData));
        }


        AccountData foundAccount = null;

        foundAccount = m_Accounts.CreditCardsCorrect.FirstOrDefault(c => c.AccountNumber == fromActualData.AccountNumber);

        if (foundAccount != null)
        {
          if (foundAccount.CardExpirationYear != fromActualData.CardExpirationYear)
          {
            StatChargeError();
            throw new PaymentMockException(StringConsts.PAYMENT_INVALID_EXPIRATION_DATE_ERROR
              .Args(fromActualData.CardExpirationYear, fromActualData.CardExpirationMonth) + this.GetType().Name + ".Charge");
          }

          if (foundAccount.CardExpirationMonth != fromActualData.CardExpirationMonth)
          {
            StatChargeError();
            throw new PaymentMockException(StringConsts.PAYMENT_INVALID_EXPIRATION_DATE_ERROR
              .Args(fromActualData.CardExpirationYear, fromActualData.CardExpirationMonth) + this.GetType().Name + ".Charge");
          }

          if (foundAccount.CardVC != fromActualData.CardVC)
          {
            StatChargeError();
            throw new PaymentMockException(StringConsts.PAYMENT_INVALID_CVC_ERROR + this.GetType().Name + ".Charge");
          }

          var created = DateTime.UtcNow;

          var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Charge);

          var ta = Transaction.Charge(taId, this.Name, taId, from, to, amount, created, description);

          StatCharge(amount);

          return ta;
        }

        foundAccount = m_Accounts.CreditCardCorrectWithAddr.FirstOrDefault(c => c.AccountNumber == fromActualData.AccountNumber);

        if (foundAccount != null)
        {
          if (foundAccount.CardExpirationYear != fromActualData.CardExpirationYear)
          {
            StatChargeError();
            throw new PaymentMockException(StringConsts.PAYMENT_INVALID_EXPIRATION_DATE_ERROR
              .Args(fromActualData.CardExpirationYear, fromActualData.CardExpirationMonth) + this.GetType().Name + ".Charge");
          }

          if (foundAccount.CardExpirationMonth != fromActualData.CardExpirationMonth)
          {
            StatChargeError();
            throw new PaymentMockException(StringConsts.PAYMENT_INVALID_EXPIRATION_DATE_ERROR
              .Args(fromActualData.CardExpirationYear, fromActualData.CardExpirationMonth) + this.GetType().Name + ".Charge");
          }

          if (foundAccount.CardVC != fromActualData.CardVC)
          {
            StatChargeError();
            throw new PaymentMockException(StringConsts.PAYMENT_INVALID_CVC_ERROR.Args(fromActualData.CardVC) + this.GetType().Name + ".Charge");
          }

          if (foundAccount.BillingAddress1 != fromActualData.BillingAddress1 ||
              foundAccount.BillingAddress2 != fromActualData.BillingAddress2 ||
              foundAccount.BillingCountry != fromActualData.BillingCountry ||
              foundAccount.BillingCity != fromActualData.BillingCity ||
              foundAccount.BillingPostalCode != fromActualData.BillingPostalCode ||
              foundAccount.BillingRegion != fromActualData.BillingRegion ||
              foundAccount.BillingEmail != fromActualData.BillingEmail ||
              foundAccount.BillingPhone != fromActualData.BillingPhone)
          {
            StatChargeError();
            throw new PaymentMockException(StringConsts.PAYMENT_INVALID_ADDR_ERROR + this.GetType().Name + ".Charge");
          }

          var created = DateTime.UtcNow;

          var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Charge);

          var ta = Transaction.Charge(taId, this.Name, taId, from, to, amount, created, description);

          StatCharge(amount);

          return ta;
        }

        throw new PaymentException(StringConsts.PAYMENT_INVALID_CARD_NUMBER_ERROR + this.GetType().Name + ".Charge");
      }
 public void TestFormatWithFormatCReturnsSameAsToString()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get("EUR");
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-ca");
     Financial financial = new Financial(currencyInfo, amount);
     String expectedFormat = financial.ToString();
     Assert.AreEqual(expectedFormat, String.Format("{0:C}", financial));
 }
Example #19
0
      public override Transaction Refund(PaySession session, ITransactionContext context, ref Transaction charge, Financial.Amount? amount = null, string description = null, object extraData = null)
      {
        var refundAmount = amount ?? charge.Amount;

        var created = DateTime.UtcNow;

        var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Refund);

        var refundTA = new Transaction(taId, TransactionType.Refund, this.Name, taId, Account.EmptyInstance, charge.From, refundAmount, created, description, relatedTransactionID: charge.ID, canRefund: false);

        StatRefund(charge, amount);

        return refundTA;
      }
 public void TestFormatWithFormatCAndWhenProviderIsNotCultureInfoReturnsSameAsToString()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get("EUR");
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-ca");
     Financial financial = new Financial(currencyInfo, amount);
     IFormatProvider provider = NumberFormatInfo.InvariantInfo;
     String expectedFormat = financial.ToString();
     Assert.AreEqual(expectedFormat, String.Format(provider, "{0:C}", financial));
 }
Example #21
0
        //审核
        void VerifyData()
        {
            string files = string.Empty;

            foreach (DataGridViewRow dgvr in dgvBillReceivable.Rows)
            {
                if (Convert.ToBoolean(dgvr.Cells[colCheck.Name].EditedFormattedValue))
                {
                    files += string.Format("'{0}',", dgvr.Cells[colPayableSingleID.Name].Value);
                }
            }
            if (files.Length == 0)
            {
                MessageBoxEx.Show("请选择要审核的数据!");
                return;
            }
            UCVerify frmVerify = new UCVerify();

            if (frmVerify.ShowDialog() == DialogResult.OK)
            {
                files = files.TrimEnd(',');
                SysSQLString sql = new SysSQLString();
                sql.cmdType   = CommandType.Text;
                sql.sqlString = string.Format("update tb_bill_receivable set order_status='{0}',Verify_advice='{1}' where payable_single_id in ({2}) and order_status='{3}';",
                                              (int)frmVerify.auditStatus, frmVerify.Content, files, (int)DataSources.EnumAuditStatus.SUBMIT);
                sql.Param = new Dictionary <string, string>();
                List <SysSQLString> listSql = new List <SysSQLString>();
                listSql.Add(sql);
                //如果是审核不通过,则将没有提交或审核状态的单据设为正常
                if (frmVerify.auditStatus == DataSources.EnumAuditStatus.NOTAUDIT)
                {
                    #region 将没有提交或审核状态的单据设为正常
                    if (orderType == DataSources.EnumOrderType.RECEIVABLE)
                    {
                        SysSQLString receivableSql = new SysSQLString();
                        receivableSql.cmdType   = CommandType.Text;
                        receivableSql.sqlString = string.Format(@"update tb_parts_sale_billing set is_lock=@is_lock where where sale_billing_id in (select documents_id from tb_balance_documents where order_id in ({0})) and  exists (
select a.documents_id from tb_balance_documents a inner join tb_bill_receivable b on a.order_id=b.payable_single_id
where order_status in ('1','2') and a.documents_id =sale_billing_id
union all
select b.order_id from tb_account_verification a inner join tb_verificationn_documents b on a.account_verification_id=b.account_verification_id
where a.order_status in ('1','2') and b.order_id=sale_billing_id
);
update tb_parts_sale_order set is_lock=@is_lock where where sale_order_id in (select documents_id from tb_balance_documents where order_id in ({0})) and  exists (
select a.documents_id from tb_balance_documents a inner join tb_bill_receivable b on a.order_id=b.payable_single_id
where order_status in ('1','2') and a.documents_id =sale_order_id
union all
select b.order_id from tb_account_verification a inner join tb_verificationn_documents b on a.account_verification_id=b.account_verification_id
where a.order_status in ('1','2') and b.order_id=sale_order_id
);
update tb_maintain_settlement_info set is_lock=@is_lock where where settlement_id in (select documents_id from tb_balance_documents where order_id in ({0})) and  exists (
select a.documents_id from tb_balance_documents a inner join tb_bill_receivable b on a.order_id=b.payable_single_id
where order_status in ('1','2') and a.documents_id =settlement_id
union all
select b.order_id from tb_account_verification a inner join tb_verificationn_documents b on a.account_verification_id=b.account_verification_id
where a.order_status in ('1','2') and b.order_id=settlement_id
);
update tb_maintain_three_guaranty_settlement set is_lock=@is_lock where where st_id in (select documents_id from tb_balance_documents where order_id in ({0})) and  exists (
select a.documents_id from tb_balance_documents a inner join tb_bill_receivable b on a.order_id=b.payable_single_id
where order_status in ('1','2') and a.documents_id =st_id
union all
select b.order_id from tb_account_verification a inner join tb_verificationn_documents b on a.account_verification_id=b.account_verification_id
where a.order_status in ('1','2') and b.order_id=st_id
);", files);
                        receivableSql.Param     = new Dictionary <string, string>();
                        receivableSql.Param.Add("is_lock", ((int)DataSources.EnumImportStaus.OPEN).ToString());
                        //receivableSql.Param.Add("@id", files);
                        listSql.Add(receivableSql);
                    }
                    else
                    {
                        SysSQLString purchaseBillingSql = new SysSQLString();
                        purchaseBillingSql.cmdType   = CommandType.Text;
                        purchaseBillingSql.sqlString = string.Format(@"update tb_parts_purchase_billing set is_lock=@is_lock where purchase_billing_id in (select documents_id from tb_balance_documents where order_id in ({0})) and  exists (
select a.documents_id from tb_balance_documents a inner join tb_bill_receivable b on a.order_id=b.payable_single_id
where order_status in ('1','2') and a.documents_id =purchase_billing_id
union all
select b.order_id from tb_account_verification a inner join tb_verificationn_documents b on a.account_verification_id=b.account_verification_id
where a.order_status in ('1','2') and b.order_id=purchase_billing_id
);
                                                  update tb_parts_purchase_order set is_lock=@is_lock where order_id in (select documents_id from tb_balance_documents where order_id in ({0})) and  exists (
select a.documents_id from tb_balance_documents a inner join tb_bill_receivable b on a.order_id=b.payable_single_id
where order_status in ('1','2') and a.documents_id =order_id
union all
select b.order_id from tb_account_verification a inner join tb_verificationn_documents b on a.account_verification_id=b.account_verification_id
where a.order_status in ('1','2') and b.order_id=order_id
);  ", files);
                        purchaseBillingSql.Param     = new Dictionary <string, string>();
                        purchaseBillingSql.Param.Add("is_lock", ((int)DataSources.EnumImportStaus.OPEN).ToString());
                        //purchaseBillingSql.Param.Add("@id", files);
                        listSql.Add(purchaseBillingSql);
                    }
                    #endregion
                    //审核失败需重新计算已结算/预收付金额
                    foreach (DataGridViewRow dgvr in dgvBillReceivable.Rows)
                    {
                        if (Convert.ToBoolean(dgvr.Cells[colCheck.Name].EditedFormattedValue))
                        {
                            int    strOrderType = Convert.ToInt32(dgvr.Cells[colOrderType.Name].Tag);
                            string order_id     = dgvr.Cells[colPayableSingleID.Name].Value.ToString();
                            //如果是应收付,则计算已结算金额
                            if (strOrderType == 1)
                            {
                                Financial.DocumentSettlementByBill(orderType, order_id, listSql);
                            }
                            //预收付,则计算预收付金额
                            else if (strOrderType == 0)
                            {
                                Financial.DocumentAdvanceByBill(orderType, order_id, listSql);
                            }
                        }
                    }
                }
                if (DBHelper.BatchExeSQLStringMultiByTrans("审核应收应付", listSql))
                {
                    MessageBoxEx.Show("审核成功!");
                    BindData();
                }
                else
                {
                    MessageBoxEx.Show("审核失败!");
                }
            }
        }
 public void TestFormatWithFormatCFormatsUsingSpecifiedCultureWhenPossible()
 {
     Decimal amount = Random.RandomDecimal();
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-ca");
     CultureInfo provider = new CultureInfo("en-GB");
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get(provider);
     Financial financial = new Financial(currencyInfo, amount);
     String expectedFormat = String.Format(provider, "{0:C}", amount);
     Assert.AreEqual(expectedFormat, String.Format(provider, "{0:C}", financial));
 }
 public void TestToStringFormatsUsingCurrentLanguageWhenPossible()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get("EUR");
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");
     // No Euro in GB, but Ireland has and also at least speaks English (en).
     Financial financial = new Financial(currencyInfo, amount);
     String currentLanguage = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
     List<String> expectedFormats =
         CultureInfoProvider.Current.FindByCurrency(currencyInfo).Where(c => c.TwoLetterISOLanguageName == currentLanguage).Select(
             mc =>
                 String.Format(
                     mc,
                     "{0:C}",
                     amount)).
             ToList();
     CollectionAssert.Contains(expectedFormats, financial.ToString());
 }
 public void TestConstructorSetsCurrencyInfoPropertyToExpectedValue()
 {
     Financial financial = new Financial(_gbp, 0);
     Assert.IsNotNull(financial.Currency);
     Assert.AreEqual("GBP", financial.Currency.Code);
 }
Example #25
0
 public void SYD_3()
 {
     // Argument 'Period' must be less than or equal to argument 'Life'.
     Financial.SYD(1500, 100, 8, 12);
 }
 public void TestFormatWithFormatCFormatsUsingCorrectLanguageWhenPossible()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get("EUR");
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-fr");
     // Now if CurrentUICulture is used instead, we get French formatting.
     CultureInfo provider = new CultureInfo("en-GB");
     // No Euro in GB, but Ireland has and also at least speaks English (en).
     Financial financial = new Financial(currencyInfo, amount);
     String correctLanguage = provider.TwoLetterISOLanguageName;
     List<String> expectedFormats =
         CultureInfoProvider.Current.FindByCurrency(currencyInfo).Where(c => c.TwoLetterISOLanguageName == correctLanguage).Select(
             mc =>
                 String.Format(
                     mc,
                     "{0:C}",
                     amount)).
             ToList();
     String actualFormat = String.Format(provider, "{0:C}", financial);
     CollectionAssert.Contains(expectedFormats, actualFormat);
 }
Example #27
0
 public void Rate_4()
 {
     // Argument 'NPer' must be greater than zero.
     Financial.Rate(-10, -120, 50000, 0, DueDate.EndOfPeriod, 0.1);
 }
 public void TestFormatWithFormatCFormatsUsingCurrentCurrencyWhenSpecifiedCurrencyDoesNotMatch()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get("GBP");
     CultureInfo provider = new CultureInfo("De-de"); // No pound in Germany, nor any German speaking countries.
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-ca");
     Financial financial = new Financial(currencyInfo, amount);
     List<String> expectedFormats = CultureInfoProvider.Current.FindByCurrency(currencyInfo).Select(
         mc =>
             String.Format(mc, "{0:C}", amount)).ToList();
     String actualFormat = String.Format(provider, "{0:C}", financial);
     CollectionAssert.Contains(expectedFormats, actualFormat);
 }
Example #29
0
 public void MIRRArgs1()
 {
     double [] arr = new double [] { -70000, 22000, 25000, 28000, 31000 };
     double    d   = Financial.MIRR(ref arr, -1, 1);
 }
 public void TestFormatWithFormatCFormatsUsingSpecifiedCultureIfCorrectCurrencyIsNotPossible()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get("XXX"); // Noone uses this dubiously named currency
     CultureInfo provider = new CultureInfo("De-de");
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");
     Financial financial = new Financial(currencyInfo, amount);
     String expectedFormat = String.Format(provider, "{0:C}", amount);
     Assert.AreEqual(expectedFormat, String.Format(provider, "{0:C}", financial));
 }
Example #31
0
 public void GetPayment_PresentValueEqualToZero_Test()
 {
     decimal getPayment = Financial.GetPayment(0.1m, 54, 0);
 }
        public void TestFinancialEqualityComparerReturnsTrueForEqualFinancials()
        {
            Financial financialA = new Financial(CurrencyInfoProvider.Current.Get("GBP"), 10);
            Financial financialB = new Financial(CurrencyInfoProvider.Current.Get("GBP"), 10);

            Assert.IsTrue(financialA == financialB);
        }
Example #33
0
 public override PaymentException VerifyPotentialTransaction(PaySession session, ITransactionContext context, bool transfer, IActualAccountData from, IActualAccountData to, Financial.Amount amount)
 {
   throw new NotImplementedException();
 }
        public void TestFinancialEqualityComparerReturnsFalseForNonEqualFinancialCurrencies()
        {
            Financial financialA = new Financial(CurrencyInfoProvider.Current.Get("GBP"), 10);
            Financial financialB = new Financial(CurrencyInfoProvider.Current.Get("EUR"), 10);

            Assert.IsFalse(financialA == financialB);
        }
Example #35
0
 public override void Capture(PaySession session, ITransactionContext context, ref Transaction charge, Financial.Amount? amount = null, string description = null, object extraData = null)
 {
   StatCapture(charge, amount);
 }
 public void TestConstructorSetsAmountPropertyToExpectedValue()
 {
     Financial financial = new Financial(_gbp, _amount);
     Assert.IsNotNull(financial.Currency);
     Assert.AreEqual(_amount, financial.Amount);
 }
Example #37
0
      public override Transaction Transfer(PaySession session, ITransactionContext context, Account from, Account to, Financial.Amount amount, string description = null, object extraData = null)
      {
        var actualAccountData = PaySystemHost.AccountToActualData(context, to);

        if (actualAccountData == null)
        {
          StatTransferError();
          throw new PaymentMockException(StringConsts.PAYMENT_UNKNOWN_ACCOUNT_ERROR.Args(from) + this.GetType().Name + ".Transfer");
        }

        AccountData accountData = null;

        accountData = m_Accounts.DebitBankCorrect.FirstOrDefault(c => c.AccountNumber == actualAccountData.AccountNumber 
                                                && c.CardExpirationYear == actualAccountData.CardExpirationYear
                                                && c.CardExpirationMonth == actualAccountData.CardExpirationMonth
                                                && c.CardVC == actualAccountData.CardVC);

        if (accountData != null)
        {
          var created = DateTime.Now;

          var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Transfer);

          var ta = Transaction.Transfer(taId, this.Name, taId, Account.EmptyInstance, to, amount, created, description, extraData);

          StatTransfer(amount);

          return ta;
        }

        accountData = m_Accounts.DebitCardCorrect.FirstOrDefault(c => c.AccountNumber == actualAccountData.AccountNumber 
                                                && c.CardExpirationYear == actualAccountData.CardExpirationYear
                                                && c.CardExpirationMonth == actualAccountData.CardExpirationMonth
                                                && c.CardVC == actualAccountData.CardVC);

        if (accountData != null)
        {
          var created = DateTime.Now;

          var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Transfer);

          var ta = Transaction.Transfer(taId, this.Name, taId, Account.EmptyInstance, to, amount, created, description, extraData);

          StatTransfer(amount);

          return ta;
        }

        accountData = m_Accounts.DebitCardCorrectWithAddr.FirstOrDefault(c => c.AccountNumber == actualAccountData.AccountNumber 
                                                && c.CardExpirationYear == actualAccountData.CardExpirationYear
                                                && c.CardExpirationMonth == actualAccountData.CardExpirationMonth
                                                && c.CardVC == actualAccountData.CardVC
                                                && c.BillingAddress1 != actualAccountData.BillingAddress1
                                                && c.BillingAddress2 != actualAccountData.BillingAddress2
                                                && c.BillingCountry != actualAccountData.BillingCountry
                                                && c.BillingCity != actualAccountData.BillingCity
                                                && c.BillingPostalCode != actualAccountData.BillingPostalCode
                                                && c.BillingRegion != actualAccountData.BillingRegion
                                                && c.BillingEmail != actualAccountData.BillingEmail
                                                && c.BillingPhone != actualAccountData.BillingPhone);

        if (accountData != null)
        {
          var created = DateTime.Now;

          var taId = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Transfer);

          var ta = Transaction.Transfer(taId, this.Name, taId, Account.EmptyInstance, to, amount, created, description, extraData);

          StatTransfer(amount);

          return ta;
        }

        StatTransferError();
        throw new PaymentException(StringConsts.PAYMENT_INVALID_CARD_NUMBER_ERROR + this.GetType().Name + ".Transfer");
      }
        public void TestAverageReturnsTheAverageAmountOfTheProvidedFinancials()
        {
            Financial financialA = new Financial(_gbp, 10);
            Financial financialB = new Financial(_gbp, 2036.54M);
            Financial financialC = new Financial(_gbp, -153);

            Assert.AreEqual(631.18M, Financial.Average(new[] {financialA, financialB, financialC}).Amount);
        }
Example #39
0
        //提交,只有草稿状态才可以提交
        void SubmitData()
        {
            dgvBillReceivable.EndEdit();
            List <SysSQLString> listSql = new List <SysSQLString>();
            string submit   = ((int)DataSources.EnumAuditStatus.SUBMIT).ToString();   //提交
            string draft    = ((int)DataSources.EnumAuditStatus.DRAFT).ToString();    //草稿
            string notAudit = ((int)DataSources.EnumAuditStatus.NOTAUDIT).ToString(); //审核失败
            string message  = string.Empty;                                           //错误消息

            foreach (DataGridViewRow dgvr in dgvBillReceivable.Rows)
            {
                object isCheck = dgvr.Cells["colCheck"].Value;
                string status  = CommonCtrl.IsNullToString(dgvr.Cells[colOrderStatus.Name].Tag);
                if (isCheck != null && (bool)isCheck && (status == draft || status == notAudit))
                {
                    string order_id     = dgvr.Cells["colPayableSingleID"].Value.ToString();
                    int    strOrderType = Convert.ToInt32(dgvr.Cells[colOrderType.Name].Tag);
                    //应收应付验证单据本次结算金额和明细金额是否一样
                    if ((orderType == DataSources.EnumOrderType.RECEIVABLE && (DataSources.EnumReceivableType)strOrderType == DataSources.EnumReceivableType.RECEIVABLE) ||
                        (orderType == DataSources.EnumOrderType.PAYMENT && (DataSources.EnumPaymentType)strOrderType == DataSources.EnumPaymentType.PAYMENT))
                    {
                        if (!DBHelper.IsExist("验证单据和明细金额是否一样", "v_bill_money", string.Format("order_id='{0}'", order_id)))
                        {
                            dgvBillReceivable.CurrentCell = dgvr.Cells[colOrderNum.Name];
                            message = "单据实收金额不等于明细金额!";
                            break;
                        }
                    }
                    if (orderType == DataSources.EnumOrderType.PAYMENT)
                    {
                        if (DBHelper.IsExist("验证应付单据本次结算金额", "v_payable_document_checking", string.Format("order_id='{0}'", order_id)))
                        {
                            dgvBillReceivable.CurrentCell = dgvr.Cells[colOrderNum.Name];
                            message = "单据本次结算金额大于待结算金额!";
                            break;
                        }
                    }
                    else if (orderType == DataSources.EnumOrderType.RECEIVABLE)
                    {
                        if (DBHelper.IsExist("验证应收单据本次结算金额", "v_receivable_document_checking", string.Format("order_id='{0}'", order_id)))
                        {
                            dgvBillReceivable.CurrentCell = dgvr.Cells[colOrderNum.Name];
                            message = "单据本次结算金额大于待结算金额!";
                            break;
                        }
                    }
                    SysSQLString sql = new SysSQLString();
                    sql.cmdType = CommandType.Text;
                    sql.Param   = new Dictionary <string, string>();
                    sql.Param.Add("submit", submit);
                    sql.Param.Add("draft", draft);
                    sql.Param.Add("notAudit", notAudit);
                    if (orderType == DataSources.EnumOrderType.RECEIVABLE)
                    {
                        sql.Param.Add("order_num", CommonUtility.GetNewNo(DataSources.EnumProjectType.RECEIVABLE));
                    }
                    else
                    {
                        sql.Param.Add("order_num", CommonUtility.GetNewNo(DataSources.EnumProjectType.PAYMENT));
                    }
                    sql.Param.Add("payable_single_id", order_id);
                    sql.sqlString = "update tb_bill_receivable set order_status=@submit,order_num=@order_num where payable_single_id=@payable_single_id and (order_status=@draft or order_status=@notAudit)";
                    listSql.Add(sql);
                    SetDocumentImportStatus("is_lock", DataSources.EnumImportStaus.LOCK, listSql, order_id, dgvr.Cells[colOrderType.Name].Tag.ToString());
                    //如果是应收付,则计算已结算金额
                    if (strOrderType == 1)
                    {
                        Financial.DocumentSettlementByBill(orderType, order_id, listSql);
                    }
                    else if (strOrderType == 0)//预收付,则计算预收付金额
                    {
                        Financial.DocumentAdvanceByBill(orderType, order_id, listSql);
                    }
                }
            }
            if (message.Length > 0)
            {
                MessageBoxEx.ShowError(message);
                return;
            }
            if (listSql.Count == 0)
            {
                MessageBoxEx.Show("请选择要提交的数据!");
                return;
            }
            if (!MessageBoxEx.ShowQuestion("是否要提交选择的数据!"))
            {
                return;
            }
            if (DBHelper.BatchExeSQLStringMultiByTrans("提交应收应付", listSql))
            {
                MessageBoxEx.Show("提交成功!");
                BindData();
            }
            else
            {
                MessageBoxEx.ShowWarning("提交失败!");
            }
        }
Example #40
0
 public void DDB_7()
 {
     // Argument 'Factor' is not a valid value.
     double d = Financial.DDB(1500, 120, -2, -5, 2.0);
 }
Example #41
0
 public void DDB_3()
 {
     // Argument 'Factor' is not a valid value.
     double d = Financial.DDB(1500, 120, 48, 24, -1);
 }
Example #42
0
 public void SLN_2()
 {
     //Argument 'Life' cannot be zero.
     Financial.SLN(1500, 500, 0);
 }
Example #43
0
 //[ExpectedException(typeof(ArgumentException))]
 //LAMESPEC: MSDN claims the exception should be thrown in this case
 public void DDB_5()
 {
     // Argument 'Factor' is not a valid value.
     double d = Financial.DDB(-5, 120, 48, 24, 2.0);
 }
 public void TestToStringFormatsUsingCurrentCultureWhenPossible()
 {
     Decimal amount = Random.RandomDecimal();
     CurrencyInfo currencyInfo = CurrencyInfoProvider.Current.Get(CultureInfo.CurrentUICulture);
     Financial financial = new Financial(currencyInfo, amount);
     String expectedFormat = String.Format(CultureInfo.CurrentUICulture, "{0:C}", amount);
     Assert.AreEqual(expectedFormat, financial.ToString());
 }
Example #45
0
 public void TestSLNArgs()
 {
     Financial.SLN(0, 0, 0);
 }
 public void TestAddOperatorThrowsExceptionIfTheCurrenciesAreDifferent()
 {
     Financial financialA = new Financial(CurrencyInfoProvider.Current.Get("GBP"), 0);
     Financial financialB = new Financial(CurrencyInfoProvider.Current.Get("USD"), 0);
     Financial result = financialA + financialB;
 }
Example #47
0
 public void SYDArgs2()
 {
     Financial.SYD(1, -1, 1, 1);
 }
Example #48
0
        public void Calculator()
        {
            IsBusy = true;
            try
            {
                InterestRate = Math.Pow((1 + (double.Parse(CanadianMortgageRate) / 100) / CompoundPeriod), (double)CompoundPeriod / PeriodsPerYear) - 1;
                Payment      = Math.Round(-Financial.Pmt(InterestRate, AmortizationPeriod * PeriodsPerYear, double.Parse(LoanAmount)), 2);
                var nPer = AmortizationPeriod * PeriodsPerYear;

                var additionalPaymentList = Mortgages?.Where(x => x.AdditionalPayment > 0).ToList();

                if (Mortgages == null)
                {
                    Mortgages = new ObservableCollection <Mortgage>();
                }
                else
                {
                    Mortgages.Clear();
                }

                Mortgage previousMortgage = new Mortgage()
                {
                    No      = 0,
                    Balance = double.Parse(LoanAmount)
                };

                while (previousMortgage.Balance != 0)
                {
                    var mortgage = new Mortgage();

                    if (previousMortgage.No >= nPer || Math.Round(previousMortgage.Balance, 2) <= 0)
                    {
                        mortgage.No = 0;
                    }
                    else
                    {
                        mortgage.No = previousMortgage.No + 1;
                    }

                    if (mortgage.No != 0)
                    {
                        // Due date
                        if (PeriodsPerYear == 26)
                        {
                            if (mortgage.No == 1)
                            {
                                mortgage.DueDate = FirstPaymentDate;
                            }
                            else
                            {
                                mortgage.DueDate = mortgage.DueDate.AddDays(14);
                            }
                        }
                        else if (PeriodsPerYear == 52)
                        {
                            if (mortgage.No == 1)
                            {
                                mortgage.DueDate = FirstPaymentDate;
                            }
                            else
                            {
                                mortgage.DueDate = mortgage.DueDate.AddDays(7);
                            }
                        }
                        else
                        {
                            mortgage.DueDate = new DateTime(FirstPaymentDate.Year, FirstPaymentDate.Month, FirstPaymentDate.Day);
                            mortgage.DueDate = mortgage.DueDate.AddMonths((int)((mortgage.No - 1) * MonthsPerPeriod));

                            if (PeriodsPerYear == 24)
                            {
                                if (1 - (mortgage.No % 2) == 1)
                                {
                                    mortgage.DueDate = mortgage.DueDate.AddDays(14);
                                }
                                else
                                {
                                    mortgage.DueDate = new DateTime(mortgage.DueDate.Year, mortgage.DueDate.Month, FirstPaymentDate.Day);
                                }
                            }
                            else
                            {
                                mortgage.DueDate = new DateTime(mortgage.DueDate.Year, mortgage.DueDate.Month, FirstPaymentDate.Day);
                            }
                        }

                        // Payment
                        if (mortgage.No == nPer || Payment > Math.Round((1 + InterestRate) * previousMortgage.Balance, 2))
                        {
                            mortgage.Payment = Math.Round((1 + InterestRate) * previousMortgage.Balance, 2);
                        }
                        else
                        {
                            mortgage.Payment = Payment;
                        }

                        // Extra Payment
                        if (previousMortgage.Balance <= Payment || mortgage.No == 0)
                        {
                            mortgage.ExtraPayments = 0;
                        }
                        else
                        {
                            if (double.Parse(ExtraAnnualPayment) > 0)
                            {
                                if (mortgage.No % PeriodsPerYear == 0)
                                {
                                    mortgage.ExtraPayments = double.Parse(ExtraAnnualPayment);
                                }
                                else
                                {
                                    mortgage.ExtraPayments = 0;
                                }
                            }
                            else
                            {
                                mortgage.ExtraPayments = 0;
                            }

                            if (PaymentInterval == 0)
                            {
                                mortgage.ExtraPayments += 0;
                            }
                            else
                            {
                                if (mortgage.No % PaymentInterval == 0)
                                {
                                    mortgage.ExtraPayments += double.Parse(ExtraPayment);
                                }
                                else
                                {
                                    mortgage.ExtraPayments += 0;
                                }
                            }
                        }
                        // Additional Payment
                        mortgage.AdditionalPayment = additionalPaymentList?.FirstOrDefault(x => x.No == mortgage.No)?.AdditionalPayment ?? 0;

                        //  Interest
                        mortgage.Interest = Math.Round(InterestRate * previousMortgage.Balance, 2);

                        // Principal
                        mortgage.Principal = mortgage.Payment - mortgage.Interest + mortgage.AdditionalPayment +
                                             mortgage.ExtraPayments;

                        // Balance
                        mortgage.Balance = previousMortgage.Balance - mortgage.Principal;

                        Mortgages.Add(mortgage);
                        previousMortgage = mortgage;
                    }
                    else
                    {
                        break;
                    }
                }

                // Fully Amortized
                TotalPayments         = Mortgages.Sum(x => x.Interest) + Mortgages.Sum(x => x.Principal);
                TotalInterest         = Mortgages.Sum(x => x.Interest);
                NumberOfPayments      = Mortgages.Max(x => x.No);
                LastPaymentDate       = Mortgages.Max(x => x.DueDate);
                NumberOfPaymentsYears = Math.Round((decimal)(NumberOfPayments / PeriodsPerYear), 2);

                // Balance at Term
                DateAtTerm         = Mortgages.FirstOrDefault(x => x.No == (Term * PeriodsPerYear)).DueDate;
                InterestPaid       = Mortgages.Where(x => x.No <= (Term * PeriodsPerYear)).Sum(x => x.Interest);
                PrincipalPaid      = Mortgages.Where(x => x.No <= (Term * PeriodsPerYear)).Sum(x => x.Principal);
                OutstandingBalance = Mortgages.FirstOrDefault(x => x.No == (Term * PeriodsPerYear)).Balance;

                // Totals Assuming No Extra Payments
                if (TotalInterestWithNoExtraPayment - TotalInterest < 0)
                {
                    InterestSavings = 0;
                }
                else
                {
                    InterestSavings = TotalInterestWithNoExtraPayment - TotalInterest;
                }

                TotalPaymentsWithNoExtraPayment = TotalInterest + InterestSavings + double.Parse(LoanAmount);
                TotalInterestWithNoExtraPayment = TotalPaymentsWithNoExtraPayment - double.Parse(LoanAmount);

                //await Task.Delay(200);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            IsBusy = false;
        }
Example #49
0
 public void SYD_2()
 {
     // Argument 'Salvage' must be greater than or equal to zero.
     Financial.SYD(1500, -100, 48, 12);
 }
Example #50
0
 public void GetPayment_RateLessThanZero_Test()
 {
     decimal getPayment = Financial.GetPayment(-0.1m, 54, 2000);
 }
Example #51
0
 public void SYD_5()
 {
     // Argument 'Period' must be greater than zero.
     Financial.SYD(1500, 100, 48, -2);
 }
Example #52
0
 public void GetPayment_RateLMoreThanOne_Test()
 {
     decimal getPayment = Financial.GetPayment(1.1m, 54, 2000);
 }
Example #53
0
 public void Rate()
 {
     Assert.AreEqual(-1.5000000000001, Financial.Rate(1, 1, 1, 1, DueDate.BegOfPeriod, 0.1), 0.1);
     Assert.AreEqual(-1.5000000000001, Financial.Rate(1, -1, -1, -1, DueDate.BegOfPeriod, 0.1), 0.1);
     Assert.AreEqual(-1.71428571428571, Financial.Rate(1, 2, 12, 10, DueDate.BegOfPeriod, 0.5), 0.1);
 }
Example #54
0
 public void GetPayment_RateEqualToOne_Test()
 {
     decimal getPayment = Financial.GetPayment(0, 54, 2000);
 }
Example #55
0
 public void Rate_5()
 {
     // Cannot calculate rate using the arguments provided.
     Financial.Rate(48, -1000, 5000, 0, DueDate.EndOfPeriod, 0.3);
 }
Example #56
0
 public void GetPayment_NumberOfPaymentPeriodsLessThanZero_Test()
 {
     decimal getPayment = Financial.GetPayment(0.1m, -1, 2000);
 }
Example #57
0
 public void IRRArgs2()
 {
     double [] arr = new double [] { 134 };
     Financial.IRR(ref arr, 0.1);
 }
Example #58
0
 public void GetPayment_NumberOfPaymentPeriodsEqualToZero_Test()
 {
     decimal getPayment = Financial.GetPayment(0.1m, 0, 2000);
 }
Example #59
0
File: Portal.cs Project: yhhno/nfx
 /// <summary>
 /// Converts financial amount to string per portal
 /// </summary>
 public abstract string AmountToString(Financial.Amount amount, 
     MoneyFormat format = MoneyFormat.WithCurrencySymbol,
     ISession session = null);
Example #60
0
 public void GetPayment_PresentValueLessThanZero_Test()
 {
     decimal getPayment = Financial.GetPayment(0.1m, 54, -1);
 }