示例#1
0
    public void AddInvestment(Investment.InvestmentType thisType)
    {
        if( playerInvestments.Count < MAX_INVESTMENTS ) {

        } else {
            GUIManager.s_instance.DisplayNotification( "Notice!", "Investment limit reached." );
            return;
        }

        float cost;
        if (thisType == Investment.InvestmentType.IRA) {
            cost = IRA_INIT_COST;
        }
        else if (thisType == Investment.InvestmentType.Mutual){
            cost = MUTUAL_INIT_COST;
        }
        else {
            cost = STOCK_INIT_COST;
        }
        if (cost > money) {
            GUIManager.s_instance.DisplayNotification ("Notice!", "Insufficient funds.");
        } else {
            Investment newInvestment = new Investment();
            newInvestment.thisInvestmentType = thisType;
            newInvestment.SetMonetaryValue(cost);
            money -= cost;
            playerInvestments.Add( newInvestment );
        }
    }
        public PostInvestmentDto AddInvestment(InvestmentDto investmentDto)
        {
            var response = new PostInvestmentDto { Success = false };
            try
            {
                Investment investment = new Investment();
                investment.Name = investmentDto.Name;
                investment.Type = investmentDto.Type;
                investment.DateCreated = System.DateTime.Now;
                investment.DateModified = System.DateTime.Now;
                investment.Active = 1;

                InvestmentLINQDataContext db = new InvestmentLINQDataContext();
                db.Investments.InsertOnSubmit(investment);
                db.SubmitChanges();

                //logic to add investment
                response.Investment = investmentDto;
                response.Success = true;
            }
            catch(System.Exception ex)
            {
                response.Message = ex.ToString();
                response.Investment = investmentDto;
                response.Success = false;
            }

            return response;
        }
        //save investment
        protected void Button1_Click1(object sender, EventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                Investment inv = new Investment();
                inv.IsActive = true;
                if (RadioButtonList1.SelectedIndex == 0) //individual
                {
                    //no member selected
                    if (DropDownList1.SelectedIndex == 0)
                        return;

                    inv.Balance = 0;
                    inv.MemberID = Convert.ToInt32(DropDownList1.SelectedValue);
                    inv.InsterstRate = 0;

                    inv.InvestmentTypeId = 2; //2 for susu investments
                    db.Investments.InsertOnSubmit(inv);
                    db.SubmitChanges();

                    //audit
                    Utils.logAction("Insert", inv);

                    Response.Redirect("SUSUInvestmentContribution.aspx?InvId=" + inv.InvestmentID + "&mid=" + inv.MemberID);

                }
                else // group
                {
                    //no group selected
                    if (cboGroupName.SelectedIndex == 0)
                        return;

                    inv.Balance = 0;
                    inv.GroupId = Convert.ToInt32(cboGroupName.SelectedValue);

                    inv.InvestmentTypeId = 2; //2 for susu investments
                    db.Investments.InsertOnSubmit(inv);
                    db.SubmitChanges();

                    //audit
                    Utils.logAction("Insert", inv);

                    Response.Redirect("GroupsSUSUInvestmentContribution.aspx?InvId=" + inv.InvestmentID + "&gid=" + inv.GroupId);
                }

            }
        }
        protected bool ShouldSellInvestment(Quote quote, Investment investment, decimal highPercentage, decimal lowPercentage, int expireDays)
        {
            //lowPercentage = lowPercentage / 100;
            //highPercentage = 1 + (highPercentage / 100);

            if (quote.LastTradePrice == null)
            {
                // Sound the alarm bells
                Log.Error("Quote.LastTradePrice is null for investment with symbol {0} for {1}", quote.Symbol, GetType().Name);
                return false;
            }
            else if (quote.LastTradePrice.Value != investment.PurchasePrice)
            {
                decimal percentageChange = ((quote.LastTradePrice.Value - investment.PurchasePrice) / investment.PurchasePrice) * 100;

                if (percentageChange <= -lowPercentage)
                {
                    // Low
                    investment.SellReason = SellReason.LowPrice;
                    return true;
                }
                else if (percentageChange >= highPercentage)
                {
                    // High
                    investment.SellReason = SellReason.HighPrice;
                    return true;
                }
                else if ((DateTime.Today - investment.PurchaseDate).TotalDays >= expireDays)
                {
                    // Expired
                    investment.SellReason = SellReason.Expired;
                    return true;
                }
            }

            return false;
        }
示例#5
0
        public int Add(FinancialTransaction aTransaction)
        {
            int           returnValue = -1;
            SqlConnection con         = new ConnectionString().GetConnection();

            con.Open();

            using (con)
            {
                SqlTransaction tran = con.BeginTransaction();

                try
                {
                    returnValue = new FinancialTransactionDataHelper().Insert(aTransaction, tran);

                    if (aTransaction.CascadeChanges)
                    {
                        if (aTransaction.WalletType == WalletType.Investment)
                        {
                            #region Insert in Investment
                            Investment anInvestment = new Investment();
                            Investor   anInvestor   = new Investor();

                            anInvestment.ID = aTransaction.WalletReference;
                            anInvestor.ID   = aTransaction.ContactID;
                            anInvestment.InvestorDetails = anInvestor;
                            anInvestment.InHand          = (aTransaction.FlowType == FlowType.Debit) ? aTransaction.Amount * -1 : aTransaction.Amount;

                            new InvestmentDataHelper().Update(anInvestment.ID, anInvestment, tran);
                            #endregion Insert in Investment
                        }
                        else if (aTransaction.WalletType == WalletType.InvestmentGroup)
                        {
                            InvestmentGroupDetailDataHelper anInvestmentGroupDetailDH = new InvestmentGroupDetailDataHelper();
                            InvestmentGroupDetail           aInvestmentGroupDetail    = new InvestmentGroupDetail();
                            int ainvestmentID = anInvestmentGroupDetailDH.SelectByID(aTransaction.WalletReference, tran).InvestmentID;

                            aInvestmentGroupDetail.AmountDeducted = true;
                            aInvestmentGroupDetail.ID             = aTransaction.WalletReference;
                            aInvestmentGroupDetail.InHand         = (aTransaction.FlowType == FlowType.Debit) ? aTransaction.Amount * -1 : aTransaction.Amount;

                            //Update Investment/Group Tables
                            anInvestmentGroupDetailDH.Update(aInvestmentGroupDetail.ID, aInvestmentGroupDetail, tran);

                            aTransaction.WalletType = WalletType.Investment;
                            //aInvestmentGroupDetail = anInvestmentGroupDetailDH.SelectByID(aTransaction.WalletReference,tran).InvestmentID;
                            aTransaction.WalletReference = ainvestmentID; //aInvestmentGroupDetail.InvestmentID;
                            aTransaction.FlowType        = (aTransaction.FlowType == FlowType.Debit) ? FlowType.Credit : FlowType.Debit;

                            //double entry rule, 2nd entry in Investment Account
                            new FinancialTransactionDataHelper().Insert(aTransaction, tran);
                        }
                    }

                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }
            }

            return(returnValue);
        }
示例#6
0
        /// <summary>
        /// Calculate the CapitalGains
        /// </summary>
        private void Calculate()
        {
            IDictionary <Security, List <Investment> > map = myMoney.GetTransactionsGroupedBySecurity(null, toDate);

            byAccount = new Dictionary <Account, AccountHoldings>();

            // Now build the AccountHoldings  for all non-transfer add/buy transactions.
            // Don't handle transfers yet - for that we need to be able to compute the cost basis.
            foreach (KeyValuePair <Security, List <Investment> > pair in map)
            {
                Security          s    = pair.Key;
                List <Investment> list = pair.Value;

                List <StockSplit> splits = new List <StockSplit>(this.myMoney.StockSplits.GetStockSplitsForSecurity(s));
                splits.Sort(new Comparison <StockSplit>((a, b) => {
                    return(DateTime.Compare(a.Date, b.Date)); // ascending
                }));


                foreach (Investment i in list)
                {
                    ApplySplits(s, splits, i.Date);

                    var holdings = GetHolding(i.Transaction.Account);

                    if (i.Type == InvestmentType.Add || i.Type == InvestmentType.Buy)
                    {
                        // transfer "adds" will be handled on the "remove" side below so we get the right cost basis.
                        if (i.Transaction.Transfer == null && i.Units > 0)
                        {
                            holdings.Buy(s, i.Date, i.Units, i.OriginalCostBasis);
                            foreach (SecuritySale pending in holdings.ProcessPendingSales(s))
                            {
                                sales.Add(pending);
                            }
                        }
                    }
                    else if ((i.Type == InvestmentType.Remove || i.Type == InvestmentType.Sell) && i.Units > 0)
                    {
                        if (i.Transaction.Transfer == null)
                        {
                            foreach (SecuritySale sale in holdings.Sell(i.Security, i.Date, i.Units, i.OriginalCostBasis))
                            {
                                sales.Add(sale);
                            }
                        }
                        else
                        {
                            // bugbug; could this ever be a split? Don't think so...
                            Investment add = i.Transaction.Transfer.Transaction.Investment;
                            Debug.Assert(add != null, "Other side of the Transfer needs to be an Investment transaction");
                            if (add != null)
                            {
                                Debug.Assert(add.Type == InvestmentType.Add, "Other side of transfer should be an Add transaction");

                                // now instead of doing a simple Add on the other side, we need to remember the cost basis of each purchase
                                // used to cover the remove

                                foreach (SecuritySale sale in holdings.Sell(i.Security, i.Date, i.Units, 0))
                                {
                                    var targetHoldings = GetHolding(add.Transaction.Account);
                                    if (sale.DateAcquired.HasValue)
                                    {
                                        // now transfer the cost basis over to the target account.
                                        targetHoldings.Buy(s, sale.DateAcquired.Value, sale.UnitsSold, sale.CostBasisPerUnit * sale.UnitsSold);
                                        foreach (SecuritySale pending in targetHoldings.ProcessPendingSales(s))
                                        {
                                            sales.Add(pending);
                                        }
                                    }
                                    else
                                    {
                                        // this is the error case, but the error will be re-generated on the target account when needed.
                                    }
                                }
                            }
                        }
                    }
                }

                ApplySplits(s, splits, DateTime.Now);
            }
        }
示例#7
0
 public bool AddInvestment(Investment investment)
 {
     database.Investments.Add(investment);
     return(Save());
 }
示例#8
0
 public virtual bool Equals(Investment other)
 {
     if (ReferenceEquals(null, other)) return false;
     if (ReferenceEquals(this, other)) return true;
     return Equals(other.investor, investor) && Equals(other.venture, venture) && Equals(other.Value, Value);
 }
示例#9
0
        public async Task <bool> UpdateApprovedFunds(bool isApproved = true)
        {
            try
            {
                using (var dbContextTransaction = _unitOfWork.GetCurrentContext().Database.BeginTransaction())
                {
                    var listFundUpdate = (await _unitOfWork.FundRepository.FindByAsync(f => f.EditStatus == EditStatus.Updating && f.NAVNew != 0 && f.NAVNew != f.NAV)).ToList();
                    var listCustomer   = (await _customerManager.GetAllCustomer()).Where(x => x.CurrentAccountAmount > 0).ToList();
                    foreach (var fund in listFundUpdate)
                    {
                        if (isApproved)
                        {
                            fund.NAVOld           = fund.NAV;
                            fund.NAV              = fund.NAVNew;
                            fund.DateLastApproved = DateTime.Now;
                            await _unitOfWork.FundRepository.ExecuteSql($"Update Fund Set NAVOld = {fund.NAVOld}, NAV= {fund.NAV}, DateLastApproved = GETDATE(), EditStatus={(int)EditStatus.Success} WHERE Id = {fund.Id} ");
                        }
                        else
                        {
                            fund.NAVNew = fund.NAV;
                            await _unitOfWork.FundRepository.ExecuteSql($"Update Fund Set NAVOld = {fund.NAVOld}, NAV= {fund.NAV}, DateLastApproved = GETDATE(), EditStatus={(int)EditStatus.Success} WHERE Id = {fund.Id} ");
                        }
                    }

                    if (isApproved)
                    {
                        var allFund     = (await _unitOfWork.FundRepository.GetAllAsync()).ToList();
                        var allUserFund = (await _unitOfWork.UserFundRepository.GetAllAsync("Fund")).ToList();
                        var sbd         = new StringBuilder();
                        var i           = 0;
                        foreach (var custom in listCustomer)
                        {
                            i++;
                            var     currentAccountAmount = custom.CurrentAccountAmount;
                            decimal newAccountAmount     = allUserFund.Where(x => x.UserId == custom.Id).Sum(x => (decimal)x.NoOfCertificates * x.Fund.NAV);


                            sbd.AppendLine($"UPDATE AspNetUsers SET CurrentAccountAmount = {newAccountAmount} WHERE UserName='******';");

                            //var transactionHistory = new TransactionHistory();
                            //transactionHistory.UserId = custom.Id;
                            //transactionHistory.CurrentAccountAmount = newAccountAmount;
                            //transactionHistory.Amount = Math.Abs(newAccountAmount - currentAccountAmount);
                            //transactionHistory.TransactionType = TransactionType.None;
                            //transactionHistory.Status = TransactionStatus.Success;
                            //transactionHistory.TransactionDate = DateTime.Now;

                            sbd.AppendLine($"INSERT INTO [dbo].[TransactionHistory]  ([UserId],[Amount],[Status],[TransactionDate],[CurrentAccountAmount],[TransactionType],[TotalWithdrawal],[RemittanceStatus],[WithdrawalType],[Description]) VALUES (N'{custom.Id}'," +
                                           $"{ Math.Abs(newAccountAmount - currentAccountAmount)},{ (int)TransactionStatus.Success},GETDATE(),{ newAccountAmount},{ (int)TransactionType.None},{ 0 },NULL,NULL,N'Cập Nhật NAV');");


                            if (newAccountAmount > currentAccountAmount)
                            {
                                var investment = new Investment();
                                investment.Amount         = newAccountAmount - currentAccountAmount;
                                investment.RemainAmount   = newAccountAmount - currentAccountAmount;
                                investment.UserId         = custom.Id;
                                investment.DateInvestment = DateTime.Now;
                                sbd.AppendLine($"INSERT INTO [dbo].[Investment] ([UserId], [Amount],[RemainAmount],[DateInvestment])     VALUES     ('{investment.UserId}',{investment.Amount},{investment.RemainAmount},GETDATE());");// Add(investment);
                            }

                            if (i == 100)
                            {
                                await _unitOfWork.FundRepository.ExecuteSql(sbd.ToString());

                                sbd.Clear();
                                i = 0;
                            }
                            //await _unitOfWork.SaveChangesAsync();
                        }

                        if (sbd.ToString() != "")
                        {
                            await _unitOfWork.FundRepository.ExecuteSql(sbd.ToString());
                        }
                    }
                    dbContextTransaction.Commit();
                }
                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#10
0
 public Task <IEnumerable <InvestmentRecord> > GetInvestmentRecordsAsync(Investment investment, DateTime from, DateTime to)
 {
     throw new NotImplementedException();
 }
示例#11
0
        private void CreateInvestmentSamples(SampleData data, List <Account> brokerageAccounts)
        {
            if (brokerageAccounts.Count == 0)
            {
                return;
            }

            // now balance the accounts.
            foreach (Account a in money.Accounts.GetAccounts())
            {
                money.Rebalance(a);
            }

            // first figure out how much we can spend each year.
            int      year  = DateTime.Now.Year - 10;
            DateTime start = new DateTime(year, 1, 1); // start in January
            DateTime end   = start.AddYears(1);
            Dictionary <int, decimal> cash = new Dictionary <int, decimal>();
            Ownership ownership            = new Ownership();
            decimal   removed = 0;

            foreach (var t in money.Transactions.GetTransactionsFrom(this.checking))
            {
                if (t.Date > end)
                {
                    cash[year] = GetStockMoney(t.Balance);
                    end        = end.AddYears(1);
                    year++;
                }
            }

            money.BeginUpdate(this);

            Dictionary <Account, decimal> cashBalance = new Dictionary <Account, decimal>();

            foreach (var a in brokerageAccounts)
            {
                cashBalance[a] = 0;
            }

            Transactions transactions = money.Transactions;

            for (year = DateTime.Now.Year - 10; year <= DateTime.Now.Year; year++)
            {
                cash.TryGetValue(year, out decimal balance);
                balance -= removed;
                if (balance < 100)
                {
                    continue; // not enough.
                }
                decimal startBalance = balance;

                int numberOfTransactionForThatYear = rand.Next(5, 100); // up to 100 transactions max per year.

                // keep track of how much we own so we never go negative.
                IList <int> selectedDays = GetRandomDaysInTheYearForTransactions(numberOfTransactionForThatYear);

                foreach (var day in selectedDays)
                {
                    // select random security.
                    SampleSecurity ss = data.Securities[rand.Next(0, data.Securities.Count)];
                    // Get or Create the security
                    Security stock = money.Securities.FindSecurity(ss.Name, true);
                    stock.SecurityType = ss.SecurityType;
                    stock.Symbol       = ss.Symbol;

                    // select a random brokerage.
                    Account a = brokerageAccounts[rand.Next(brokerageAccounts.Count)];

                    var canSpend = balance + cashBalance[a];
                    if (canSpend < 100)
                    {
                        break;
                    }

                    // the date the purchase or sale was done
                    var date = new DateTime(year, 1, 1).AddDays(day);

                    // How many unit bought or sold
                    var quote = GetClosingPrice(ss.Symbol, date);

                    Transaction t     = null;
                    decimal     owned = ownership.GetUnits(a, ss.Symbol);
                    if (owned > 4 && rand.Next(3) == 1)
                    {
                        // make this a sell transaction.
                        // Create a new Transaction
                        t      = money.Transactions.NewTransaction(a);
                        t.Date = date;
                        //-----------------------------------------------------
                        // Create the matching Investment transaction
                        Investment i = t.GetOrCreateInvestment();
                        i.Transaction = t;
                        i.Security    = stock;
                        i.UnitPrice   = quote;
                        i.Price       = quote;
                        i.Type        = InvestmentType.Sell;
                        // Create the a SELL transaction
                        i.Units = rand.Next(1, (int)(owned / 2));
                        ownership.AddUnits(a, ss.Symbol, -i.Units);
                        // Calculate the Payment or Deposit amount
                        t.Amount = RoundCents(i.Units * i.UnitPrice);
                    }
                    else
                    {
                        int max = (int)(canSpend / quote);
                        if (max > 0)
                        {
                            // Create a new Transaction
                            t      = money.Transactions.NewTransaction(a);
                            t.Date = date;

                            //-----------------------------------------------------
                            // Create the matching Investment transaction
                            Investment i = t.GetOrCreateInvestment();
                            i.Transaction = t;
                            i.Security    = stock;
                            i.UnitPrice   = quote;
                            i.Price       = quote;
                            i.Type        = InvestmentType.Buy;
                            i.Units       = rand.Next(1, max);
                            ownership.AddUnits(a, ss.Symbol, i.Units);
                            // Calculate the Payment or Deposit amount
                            t.Amount = RoundCents(i.Units * i.UnitPrice * -1);
                        }
                    }

                    if (t != null)
                    {
                        t.Payee         = money.Payees.FindPayee(ss.Name, true);
                        t.Category      = money.Categories.InvestmentStocks;
                        balance        += t.Amount;
                        cashBalance[a] += t.Amount;
                        // Finally add the new transaction
                        money.Transactions.AddTransaction(t);
                    }
                }

                foreach (var acct in brokerageAccounts)
                {
                    var amount = cashBalance[acct];
                    if (amount < 0)
                    {
                        // then we need to transfer money to cover the cost of the stock purchases.
                        Transaction payment = transactions.NewTransaction(checking);
                        payment.Date   = new DateTime(year, 1, 1);
                        payment.Amount = RoundCents(amount);
                        transactions.AddTransaction(payment);
                        money.Transfer(payment, acct);
                        removed           += -amount;
                        cashBalance[acct] += -amount;
                    }
                }
            }
            money.EndUpdate();

            // now balance the accounts again!
            foreach (Account a in money.Accounts.GetAccounts())
            {
                money.Rebalance(a);
            }
        }
        void LoadData(int InvestmentID)
        {
            _CurrentInvestment = Utils.GetDataContext().Investments.FirstOrDefault(i => i.InvestmentID == InvestmentID);
            //DropDownList3.SelectedValue = _CurrentInvestment.AccountTypeId.Value.ToString();
            PrincipalTextBox.Text = _CurrentInvestment.InvestmentAmount.Value.ToString();
            InterestTypeDropDownList.SelectedValue = _CurrentInvestment.InterestTypeId.Value.ToString();
            try
            {
                cboInterestDuration.SelectedValue = _CurrentInvestment.DurationTypeId.Value.ToString();
            }
            catch (Exception)
            {

            }
            InterestTextBox.Text = _CurrentInvestment.InsterstRate.Value.ToString();
            cboLoanDurationType.SelectedValue = _CurrentInvestment.DurationTypeId.Value.ToString();
            DurationTextBox.Text = _CurrentInvestment.Duration.Value.ToString();
            //RepaymentFrequencyDropdownList.SelectedValue = _CurrentInvestment.ContributionFrequencyId.Value.ToString();
            //txtStartCalculationFrom.Text = _CurrentInvestment.InvestmentCalculationStartDate.Value.ToString("dd/MM/yyyy");
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            // Populate the ledger with existing data

            using (var dbContext = new MemeEconomyContext(_config))
            {
                dbContext.Opportunities
                .Include(q => q.Investments)
                .Where(q => q.Timestamp > DateTime.UtcNow.AddDays(-1))
                .ToList()
                .ForEach(q => _ledger.AddOpportunity(q));
            }

            _memeInvestorBot = _reddit.GetUser("MemeInvestor_bot");

            _ = Task.Run(() =>
            {
                foreach (var comment in _memeInvestorBot.Comments.GetListingStream())
                {
                    try
                    {
                        var match  = _checkInvestment.Match(comment.Body);
                        var postId = comment.LinkId.Split('_')[1];
                        //Guid opportunityId = Guid.Empty;

                        using (var store = new MemeEconomyContext(_config))
                        {
                            if (comment.Body.Contains("**INVESTMENTS GO HERE - ONLY DIRECT REPLIES TO ME WILL BE PROCESSED**"))
                            {
                                var opportunity = new Opportunity
                                {
                                    Id        = Guid.NewGuid(),
                                    Title     = comment.LinkTitle,
                                    Timestamp = comment.Created.UtcDateTime,
                                    PostId    = postId,
                                    MemeUri   = _reddit.GetPost(new Uri(comment.Shortlink)).Url.ToString()
                                };

                                _ledger.AddOpportunity(opportunity);

                                Program.Opportunities.OnNext(opportunity);

                                store.Opportunities.Add(opportunity);
                                store.SaveChanges();
                            }
                            else if (match.Success)
                            {
                                var opportunityId = store
                                                    .Opportunities
                                                    ?.SingleOrDefault(q => q.PostId == postId)
                                                    ?.Id ?? Guid.Empty;

                                if (opportunityId == Guid.Empty)
                                {
                                    var opportunity = new Opportunity
                                    {
                                        Id        = Guid.NewGuid(),
                                        Title     = comment.LinkTitle,
                                        Timestamp = comment.Created.UtcDateTime,
                                        PostId    = postId,
                                        MemeUri   = _reddit.GetPost(new Uri(comment.Shortlink)).Url.ToString()
                                    };

                                    _ledger.AddOpportunity(opportunity);

                                    store.Opportunities.Add(opportunity);
                                    store.SaveChanges();

                                    opportunityId = opportunity.Id;
                                }

                                var investment = new Investment
                                {
                                    Id            = Guid.NewGuid(),
                                    OpportunityId = opportunityId,
                                    Timestamp     = comment.Created.UtcDateTime,
                                    Amount        = Convert.ToInt64(match.Groups[1].Value.Replace(",", "")),
                                    Upvotes       = Convert.ToInt32(match.Groups[2].Value.Replace(",", ""))
                                };

                                _ledger.AddTransaction(investment);

                                Program.Investments.OnNext(investment);

                                store.Investments.Add(investment);
                                store.SaveChanges();
                            }
                        }
                    } catch (Exception)
                    {
                    }
                }
            }, cancellationToken);

            return(Task.CompletedTask);
        }
 public InvestmentSettledDomainEvent(Investment investment)
 {
     Investment = investment ?? throw new ArgumentNullException(nameof(investment));
 }
        public void DeductFinancialTransaction(int anInvestmentGroupID)
        {
            SqlConnection con = new ConnectionString().GetConnection();

            List <InvestmentGroupDetail>    anInvestmentGroupDetailList = new List <InvestmentGroupDetail>();
            InvestmentGroupDetailDataHelper aInvestmentGroupDetailDH    = new InvestmentGroupDetailDataHelper();

            Investment anInvestment = new Investment();
            Investor   anInvestor   = new Investor();


            FinancialTransactionDataHelper financialTransactionH = new FinancialTransactionDataHelper();
            FinancialTransaction           aTransaction          = new FinancialTransaction();

            aTransaction.CascadeChanges = false;



            con.Open();

            using (con)
            {
                SqlTransaction tran = con.BeginTransaction();

                try
                {
                    anInvestmentGroupDetailList = aInvestmentGroupDetailDH.SelectByGroupID(anInvestmentGroupID);

                    //Do financial Transaction
                    foreach (var item in anInvestmentGroupDetailList)
                    {
                        if (!item.AmountDeducted)
                        {
                            anInvestment = new InvestmentDataHelper().SelectByID(item.InvestmentID);
                            anInvestor   = anInvestment.InvestorDetails;

                            aTransaction.ContactID            = anInvestor.ID;
                            aTransaction.WalletType           = WalletType.Investment;
                            aTransaction.WalletReference      = item.InvestmentID;
                            aTransaction.Amount               = item.InHand;
                            aTransaction.FlowType             = FlowType.Debit;
                            aTransaction.TransactionType      = TransactionType.ApplicationTransfer;
                            aTransaction.TransactionReference = "Transfered to InvestmentGroup";
                            aTransaction.TransactionDate      = DateTime.Now;

                            // Deduct from Investment
                            financialTransactionH.Insert(aTransaction, tran);

                            //------------------------
                            // Add in InvestmentGroup
                            aTransaction.WalletType           = WalletType.InvestmentGroup;
                            aTransaction.WalletReference      = item.ID;
                            aTransaction.FlowType             = FlowType.Credit;
                            aTransaction.TransactionReference = "Transfered from Investment";

                            financialTransactionH.Insert(aTransaction, tran);
                        }
                    }

                    //do Update requied Tables
                    aInvestmentGroupDetailDH.UpdateDeductFT(anInvestmentGroupID, tran);

                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }
            }
        }
示例#16
0
 public void SaveInvestment(Investment investment)
 {
     Session.Save(investment);
 }
示例#17
0
 public void OnInvestmentClicked(Investment investment)
 {
     GameManager.Instance.OnInvestmentPurchased(investment);
     RefreshUIButtons();
 }
示例#18
0
 public abstract void ApproveInvestment(Investment investment);
示例#19
0
        private void ComPanyInv()
        {
            var jawaInvestment = (Investment.GetAllInvestmet() ?? new List <Investment>()).Where(w => w.InvestType == InvestmentFrom.Company).Sum(s => s.Amount);

            btnComPanyInv.Text = $"OutGoing From Company: {Environment.NewLine}{jawaInvestment}";
        }
        private static void InvestmentChoiceAdapterPropertiesWork()
        {
            var re = new Investment();

            Assert.Null(re.Item);
            Assert.Null(re.ConstructionYear);
            re.ConstructionYear = 1900;
            Assert.Equal(1900, re.Item);
            Assert.Equal(1900, re.ConstructionYear);
            re.ConstructionYear = null;
            Assert.Null(re.ConstructionYear);
            Assert.True(re.ConstructionYearUnknown);
            re.ConstructionYearUnknown = true;
            Assert.IsType<bool>(re.Item);
            Assert.True((bool)re.Item);
            Assert.Null(re.ConstructionYear);
        }
示例#21
0
        private void IntOnly()
        {
            var jawaInvestment = (Investment.GetAllInvestmet() ?? new List <Investment>()).Sum(s => s.Interest);

            btnIntOnly.Text = $"Interest Only Income: {Environment.NewLine}{jawaInvestment}";
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            //withdraw all money
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                MemberWithdrawal _memberWithdrawal = new MemberWithdrawal() {
                    CreatedBy = HttpContext.Current.User.Identity.Name,
                    DateCreated = DateTime.Now,
                    IsDeleted = false,
                    InvestmentID = Convert.ToInt32( InvestmentIDHiddenField.Value),
                    Narration = "Withdrawal For Rollover",
                    WithdrawalIssuedByUserName = HttpContext.Current.User.Identity.Name, WithdrawnBy = "System", WithdrawalAmount = Convert.ToDecimal( txtFriend.Text)

                };

                //submit withdrawal changes
                db.MemberWithdrawals.InsertOnSubmit(_memberWithdrawal);

                //update the status of the current investment
                Investment _currentinvestment = db.Investments.FirstOrDefault(i => i.InvestmentID == Convert.ToInt32(InvestmentIDHiddenField.Value));
                _currentinvestment.IsActive = false;

                //get company profile
                 LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();

                //get compound type -- thus, annully, monthly, weekly etc
                int compoundType = cProfile.CompoundFrequency.Value;

                LoanDuration _loanDuration = db.LoanDurations.FirstOrDefault(l => l.LoanDurationId == _currentinvestment.DurationTypeId.Value);//Convert.ToInt32(cboLoanDurationType.SelectedValue));
                if (_loanDuration == null)
                    return;

                //calculate matured amount for the new investment
                double _maturedAmountForNewInvestment;
                DateTime _maturityDate = DateTime.Now;

                decimal period = _currentinvestment.Duration.Value * _loanDuration.NumberOfMonths.Value / 12;
                if (_currentinvestment.InterestTypeId.Value == 1) //compound
                {
                    _maturedAmountForNewInvestment = Utils.calculateCompoundInterest(Convert.ToDouble(_currentinvestment.MaturedAmount.Value), Convert.ToDouble(_currentinvestment.InsterstRate.Value), period, Utils.GetCompoundType(compoundType));
                }
                else //2 for simple interest
                {
                    _maturedAmountForNewInvestment = Utils.calculateSimpleInterest(Convert.ToDouble(_currentinvestment.MaturedAmount.Value), Convert.ToDouble(_currentinvestment.InsterstRate.Value), period);
                }

                //create new investment
                Investment _newInvestment = new Investment()
                {
                    IsActive = true,
                    InvestmentTypeId = _currentinvestment.InvestmentTypeId,
                    IsMatured = false,
                    //ContributionFreqAmount = _currentinvestment.ContributionFreqAmount, //not calculating ContributionFreqAmount because after an investment is rolled over it becomes a fixed deposit
                    Duration = _currentinvestment.Duration,
                    DurationTypeId = _currentinvestment.DurationTypeId,
                    GroupId = RadioButtonList1.SelectedIndex == 1 ? _currentinvestment.GroupId : null,
                    InterestTypeId = _currentinvestment.InterestTypeId,
                    InvestmentAmount = _currentinvestment.MaturedAmount,
                    MaturedAmount = (decimal)_maturedAmountForNewInvestment,
                    InvestmentCalculationStartDate = DateTime.Today,
                    MaturityDate = _maturityDate,
                    MemberID = RadioButtonList1.SelectedIndex == 0 ? _currentinvestment.MemberID : null,
                    ParentInvestmentID = _currentinvestment.InvestmentID,
                    InsterstRate = _currentinvestment.InsterstRate
                };

                //calculate maturity date
                //variable to hold period for the calculation of MaturityDate calculation
                int tempPeriod;
                tempPeriod = Convert.ToInt32(_currentinvestment.Duration.Value) * _loanDuration.NumberOfMonths.Value;

                //start calculation from the LoanCalculationStartDate specified
                _newInvestment.MaturityDate = _newInvestment.InvestmentCalculationStartDate.Value.AddMonths(tempPeriod);

                //if the expected repayment end date falls on a weekend, move it to a working
                if (_newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Saturday)
                {
                    _newInvestment.MaturityDate = _newInvestment.MaturityDate.Value.AddDays(2);
                }
                else if (_newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Sunday)
                {
                    _newInvestment.MaturityDate = _newInvestment.MaturityDate.Value.AddDays(1);
                }

                db.Investments.InsertOnSubmit(_newInvestment);
                db.SubmitChanges();

                //audit
                Utils.logAction("Insert", _newInvestment);
                Utils.logAction("Insert", _memberWithdrawal);

                //set current receipt number
                Parameter prm = db.Parameters.FirstOrDefault();

                //increase receipt number by one
                prm.ReceiptNumber++;
                Contribution _newDeposit = new Contribution()
                {
                    ContributionAmount = _currentinvestment.MaturedAmount,
                    InvestmentId = _currentinvestment.InvestmentID,
                    ContributionAmountInWords = Utils.ConvertMoneyToText(_currentinvestment.MaturedAmount.ToString()),
                    ContributionBy = "System",
                    Description = "Rollover from Investment: " + _currentinvestment.InvestmentID.ToString(),
                    ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'),
                    RecievedBy = User.Identity.Name
                };

                Response.Redirect(DropDownList1.SelectedIndex > 0 ? "MemberInvestments.aspx?mid=" + DropDownList1.SelectedValue : "GroupInvestments.aspx?gid=" + cboGroupName.SelectedValue);
            }
        }
示例#23
0
 public Investment NewInvestment(Investment invesetment)
 {
     invesetment.Guid = Guid.NewGuid().ToString();
     invesetment.Id   = Insert(invesetment.GetTableObject());
     return(invesetment);
 }
示例#24
0
 public IEnumerable <InvestmentRecord> GetInvestmentRecords(Investment investment)
 {
     throw new NotImplementedException();
 }
示例#25
0
        public int UpdateInvestment(Investment investment)
        {
            var investmentTable = investment.GetTableObject();

            return(m_db.Update("Investment", "investment_id", investmentTable, investment.Id));
        }
        public static bool LearnSkill(Skill sk, int nAdjustmentValue)
        {
            if (nAdjustmentValue == 0)
            {
                return(false); // but y tho
            }
            if (nAdjustmentValue > 0)
            {
                if (!CanSkillBeLearned(sk, (uint)nAdjustmentValue)) // going up but cant, done
                {
                    return(false);
                }
            }

            // optimization for multiple usage
            bool bContains = m_vLearned.Contains(sk);

            // see if cant unlearn something we dont have
            if (nAdjustmentValue < 0 && !bContains)
            {
                return(false);
            }

            if (sk.IsAbility) // make sure we're not trying to rank an ability invalidly
            {
                // cant adjust by more than 1 for abilities
                if (nAdjustmentValue != -1 && nAdjustmentValue != 1)
                {
                    return(false);
                }
            }

            // see if this, as a talent, can be adjusted by this much
            if (!sk.AdjustRank(nAdjustmentValue) && sk.IsTalent) // will catch going down too much on learned talents
            {
                return(false);                                   // capped out on either end, sorry
            }
            // it happened, do adjustments
            int nAEAdjustment = sk.AECost * nAdjustmentValue;
            int nTEAdjustment = sk.TECost * nAdjustmentValue;

            // adjust currency
            AvailableAE = AvailableAE - nAEAdjustment;
            AvailableTE = AvailableTE - nTEAdjustment;

            // adjust investment
            // get the classtag of this skill
            string szClasstag = sk.Classtag;

            // update the investment by pointer
            Investment pInvestment = m_vInvestments[szClasstag];

            pInvestment.AE += nAEAdjustment;
            pInvestment.TE += nTEAdjustment;

            // is now officially "learned" or "unlearned"
            if (!bContains) // learning
            {
                m_vLearned.Add(sk);
                m_vAvailable.Remove(sk);
            }
            else //unlearning (OR LOSING SOME RANKS)
            {
                bool bRemove = false;
                if (sk.IsAbility) // if its an ability its just gone
                {
                    bRemove = true;
                }
                else if (sk.CurrentRanks == 0)// if its a talent AND it has 0 curr ranks, its gone
                {
                    bRemove = true;
                }
                if (bRemove)
                {
                    m_vLearned.Remove(sk);
                    m_vAvailable.Add(sk);
                }
            }

            if (m_bSuspendLearnEvent == false)
            {
                List <Skill> list = new List <Skill>();
                list.Add(sk); // everybody expecting a list for mass, gotta have singles too

                // pass arg as the actual skill (up to the receiver to decypher polymorphic type)
                Invoke(EVENT.DATA_LEARNSKILL.ToString(), list);
            }

            return(true); // all good
        }
        private static void RandomlyAssignToInvestment(List <InvestmentInfluenceFactor> factors, List <InvestmentGroup> groups, List <Region> regions, List <InvestmentRisk> risks, Investment investment)
        {
            // now randomly assign some of the risks/factors/groups/regions to this investment
            // Get a randome number/sequence of items and then of those sequnece, choose a randome item each value in the sequence
            int gmax = gmax = new Random(DateTime.Now.Millisecond).Next(1, groups.Count);

            for (int g = 0; g < gmax; g++)
            {
                var index = new Random(DateTime.Now.Millisecond).Next(1, groups.Count);
                var group = groups[index];
                group.Investments.Add(investment);
                investment.Groups.Add(group);
            }

            int fmax = new Random(DateTime.Now.Millisecond).Next(1, factors.Count);

            for (int f = 0; f < fmax; f++)
            {
                var index  = new Random(f).Next(1, factors.Count);
                var factor = factors[index];
                factor.Investments.Add(investment);
                investment.Factors.Add(factor);
            }

            int rmax = new Random(DateTime.Now.Millisecond).Next(1, risks.Count);

            for (int r = 0; r < rmax; r++)
            {
                int index = new Random(r).Next(1, risks.Count);
                var risk  = risks[index];
                risk.Investments.Add(investment);
                investment.Risks.Add(risk);
            }

            int regionmax = new Random(DateTime.Now.Millisecond).Next(1, regions.Count);

            for (int r = 0; r < rmax; r++)
            {
                int index  = new Random(r).Next(1, regions.Count);
                var region = regions[index];
                region.Investments.Add(investment);
                investment.Regions.Add(region);
            }
        }
示例#28
0
 public bool UpdateInvestment(Investment investment)
 {
     database.Investments.Update(investment);
     return(Save());
 }
示例#29
0
        /// <summary>
        /// Import the given XML content which can contain Account, Transaction, Investment or Split objects.
        /// It deserializes each type of object and merges the accounts with existing accounts, and returns the
        /// Transactions, Investment and/or Split objects unmerged, leaving it up to the caller to figure out
        /// how to merge them.  It also adds the transactions and investments to the given selected account.
        /// Splits are added to the given selectedTransaction if any.
        /// </summary>
        public IEnumerable <object> ImportObjects(XmlReader reader, Account selected, Transaction selectedTransaction)
        {
            List <object> result = new List <object>();

            Money.BeginUpdate(this);
            try
            {
                reader.MoveToElement();
                while (!reader.EOF)
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        switch (reader.LocalName)
                        {
                        case "Account":
                            Account a = (Account)AccountSerializer.ReadObject(reader, false);
                            a = MergeAccount(a);
                            result.Add(a);
                            break;

                        case "Transaction":
                            Transaction t  = (Transaction)TransactionSerializer.ReadObject(reader, false);
                            Account     ta = selected;
                            if (ta == null)
                            {
                                // this code path is used when importing entire account from a file.
                                ta = Money.Accounts.FindAccount(t.AccountName);
                            }
                            AddTransaction(ta, t);
                            result.Add(t);
                            break;

                        case "Split":
                            Split s = (Split)SplitSerializer.ReadObject(reader, false);
                            if (selectedTransaction != null)
                            {
                                s.PostDeserializeFixup(this.Money, selectedTransaction, true);
                                s.Id = -1;
                                selectedTransaction.NonNullSplits.AddSplit(s);
                            }
                            result.Add(s);
                            break;

                        case "Investment":
                            Investment i = (Investment)InvestmentSerializer.ReadObject(reader, false);
                            if (i.SecurityName != null)
                            {
                                result.Add(i);
                                AddInvestment(selected, i);
                            }
                            break;

                        default:
                            reader.Read();
                            break;
                        }
                    }
                    else
                    {
                        reader.Read();
                    }
                }
            }
            finally
            {
                Money.EndUpdate();
            }
            return(result);
        }
示例#30
0
        public async Task <AccountQueryResult> GetAccount(System.Guid accountId)
        {
            Entities.Account account = await _context
                                       .Accounts
                                       .Find(x => x.Id == accountId)
                                       .SingleOrDefaultAsync();

            if (account == null)
            {
                throw new AccountNotFoundException($"The account {accountId} does not exists");
            }

            if (!account.Actived)
            {
                throw new AccountDeactivatedException($"The account {accountId} is deactivated!");
            }

            IEnumerable <Entities.FinanceStatement> incomes = await _context
                                                              .Incomes
                                                              .Find(x => x.AccountId == accountId)
                                                              .ToListAsync();

            IEnumerable <Entities.FinanceStatement> expenses = await _context
                                                               .Expenses
                                                               .Find(x => x.AccountId == accountId)
                                                               .ToListAsync();

            IEnumerable <Entities.FinanceStatement> investments = await _context
                                                                  .Investments
                                                                  .Find(x => x.AccountId == accountId)
                                                                  .ToListAsync();


            FinanceStatementCollection incomeCollection = new FinanceStatementCollection();

            foreach (var income in incomes)
            {
                IEnumerable <Entities.AmountRecord> amountRecords = await _context
                                                                    .AmountRecords
                                                                    .Find(x => x.FinanceStatementId == income.Id)
                                                                    .ToListAsync();

                AmountRecordCollection amountRecordCollection = new AmountRecordCollection(amountRecords.Select(x => AmountRecord.Load(x.Id, x.Description, x.Amount)));

                incomeCollection.Add(Income.Load(income.Id, income.Title, amountRecordCollection, income.ReferenceDate));
            }

            FinanceStatementCollection expenseCollection = new FinanceStatementCollection();

            foreach (var expense in expenses)
            {
                IEnumerable <Entities.AmountRecord> amountRecords = await _context
                                                                    .AmountRecords
                                                                    .Find(x => x.FinanceStatementId == expense.Id)
                                                                    .ToListAsync();

                AmountRecordCollection amountRecordCollection = new AmountRecordCollection(amountRecords.Select(x => AmountRecord.Load(x.Id, x.Description, x.Amount)));

                expenseCollection.Add(Expense.Load(expense.Id, expense.Title, amountRecordCollection, expense.ReferenceDate));
            }

            FinanceStatementCollection investmentsCollection = new FinanceStatementCollection();

            foreach (var investment in investments)
            {
                IEnumerable <Entities.AmountRecord> amountRecords = await _context
                                                                    .AmountRecords
                                                                    .Find(x => x.FinanceStatementId == investment.Id)
                                                                    .ToListAsync();

                AmountRecordCollection amountRecordCollection = new AmountRecordCollection(amountRecords.Select(x => AmountRecord.Load(x.Id, x.Description, x.Amount)));

                investmentsCollection.Add(Investment.Load(investment.Id, investment.Title, amountRecordCollection, investment.ReferenceDate));
            }

            AccountQueryResult result = new AccountQueryResult(account.Id, expenseCollection, incomeCollection, investmentsCollection);

            return(result);
        }
示例#31
0
 public async Task Delete(Investment investment)
 {
     _context.Remove(investment);
     await _context.SaveChangesAsync();
 }
示例#32
0
        public static void Initialize(IServiceProvider service)
        {
            using (var context = new InvestmentContext(
                       service.GetRequiredService <DbContextOptions <InvestmentContext> >()))
            {
                Random rand = new Random();

                var inv1 = new Investment()
                {
                    Id             = 1,
                    UserId         = 100,
                    Name           = "APPL",
                    TimeOfPurchase = DateTime.Now
                };

                var inv2 = new Investment()
                {
                    Id             = 2,
                    UserId         = 100,
                    Name           = "TSLA",
                    TimeOfPurchase = DateTime.Now
                };

                var inv3 = new Investment()
                {
                    Id             = 3,
                    UserId         = 100,
                    Name           = "NKE",
                    TimeOfPurchase = DateTime.Now
                };

                var inv1Detail = new InvestmentDetail()
                {
                    SystemId          = 100,
                    InvestmentId      = 1,
                    Shares            = rand.Next(1, 20),
                    CostBasisPerShare = Math.Round(rand.NextDouble() * 500, 2),
                    CurrentPrice      = 0,
                    CurrentValue      = 0,
                    Term         = 0,
                    NetValuation = 0
                };

                var inv2Detail = new InvestmentDetail()
                {
                    SystemId          = 101,
                    InvestmentId      = 2,
                    Shares            = rand.Next(1, 20),
                    CostBasisPerShare = Math.Round(rand.NextDouble() * 500, 2),
                    CurrentPrice      = 0,
                    CurrentValue      = 0,
                    Term         = 0,
                    NetValuation = 0
                };

                var inv3Detail = new InvestmentDetail()
                {
                    SystemId          = 102,
                    InvestmentId      = 3,
                    Shares            = rand.Next(1, 20),
                    CostBasisPerShare = Math.Round(rand.NextDouble() * 500, 2),
                    CurrentPrice      = 0,
                    CurrentValue      = 0,
                    Term         = 1,
                    NetValuation = 0
                };

                inv1Detail.CurrentPrice = InvestmentCalculator.GeneratePrice(inv1Detail.CostBasisPerShare);
                inv1Detail.CurrentValue = InvestmentCalculator.DetermineValue(inv1Detail.Shares, inv1Detail.CurrentPrice);
                inv1Detail.NetValuation = InvestmentCalculator.DetermineNetValuation(inv1Detail.CurrentValue,
                                                                                     inv1Detail.Shares,
                                                                                     inv1Detail.CostBasisPerShare);

                inv2Detail.CurrentPrice = InvestmentCalculator.GeneratePrice(inv2Detail.CostBasisPerShare);
                inv2Detail.CurrentValue = InvestmentCalculator.DetermineValue(inv2Detail.Shares, inv2Detail.CurrentPrice);
                inv2Detail.NetValuation = InvestmentCalculator.DetermineNetValuation(inv2Detail.CurrentValue,
                                                                                     inv2Detail.Shares,
                                                                                     inv2Detail.CostBasisPerShare);

                inv3Detail.CurrentPrice = InvestmentCalculator.GeneratePrice(inv3Detail.CostBasisPerShare);
                inv3Detail.CurrentValue = InvestmentCalculator.DetermineValue(inv3Detail.Shares, inv3Detail.CurrentPrice);
                inv3Detail.NetValuation = InvestmentCalculator.DetermineNetValuation(inv3Detail.CurrentValue,
                                                                                     inv3Detail.Shares,
                                                                                     inv3Detail.CostBasisPerShare);

                context.Investments.Add(inv1);
                context.Investments.Add(inv2);
                context.Investments.Add(inv3);
                context.InvestmentDetails.Add(inv1Detail);
                context.InvestmentDetails.Add(inv2Detail);
                context.InvestmentDetails.Add(inv3Detail);
                context.SaveChanges();
            }
        }
示例#33
0
 public async Task Edit(Investment investment)
 {
     _context.Update(investment);
     await _context.SaveChangesAsync();
 }
示例#34
0
        private void InitializeCommands()
        {
            AddBalanceCommand = new RelayCommand((x) =>
            {
                Balance += Atm;
                CurrentBankAccount.Deposit = Balance;
                bankRepo.UpdateBankAccount(CurrentBankAccount);
            });
            RemoveBalanceCommand = new RelayCommand((x) =>
            {
                if (Balance - Atm <= 0)
                {
                    MessageBox.Show("You don't enoguh money", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                Balance -= Atm;
                CurrentBankAccount.Deposit = Balance;
                bankRepo.UpdateBankAccount(CurrentBankAccount);
            });
            MoneyTransferCommand = new RelayCommand((x) =>
            {
                if (!userRepo.DoesUserExist(TransferName))
                {
                    MessageBox.Show("There is no user with this login", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (Balance - Atm <= 0)
                {
                    MessageBox.Show("You don't enoguh money", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                Balance -= Atm;
                CurrentBankAccount.Deposit = Balance;
                bankRepo.UpdateBankAccount(CurrentBankAccount);

                var transferBankAccount      = bankRepo.GetBankAccountByOwnerName(TransferName);
                transferBankAccount.Deposit += Atm;
                broker.OnSendMoneyTransfer();
            });
            AddInvestmentCommand = new RelayCommand((x) =>
            {
                if (InvestmentToPut > Balance)
                {
                    MessageBox.Show("You don't enoguh money", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                var inv = new Investment()
                {
                    OwnerUserId = CurrentUser.Id,
                    Invested    = InvestmentToPut
                };
                investRepo.AddInvestment(inv);
                Balance -= InvestmentToPut;
                CurrentBankAccount.Deposit = Balance;
                bankRepo.UpdateBankAccount(CurrentBankAccount);
                PopulateInvestments();
            });
            RemoveInvestmentCommand = new RelayCommand((x) =>
            {
                if (SelectedInvestment == null)
                {
                    return;
                }


                investRepo.RemoveInvestment(SelectedInvestment.Id);
                Balance += SelectedInvestment.Invested;
                CurrentBankAccount.Deposit = Balance;
                bankRepo.UpdateBankAccount(CurrentBankAccount);
                Investments.Remove(SelectedInvestment);
                SelectedInvestment = null;
            });
            AddLoanCommand = new RelayCommand((x) =>
            {
                if (LoanToTake > Balance * 2)
                {
                    MessageBox.Show("You cannot take loan with more than 2 times your current balance", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                var loan = new Loan()
                {
                    OwnerUserId = CurrentUser.Id,
                    ToPay       = LoanToTake
                };
                loanRepo.AddLoan(loan);
                Balance += LoanToTake;
                CurrentBankAccount.Deposit = Balance;
                bankRepo.UpdateBankAccount(CurrentBankAccount);
                PopulateLoans();
            });
            RemoveLoanCommand = new RelayCommand((x) =>
            {
                if (SelectedLoan == null)
                {
                    return;
                }
                if (SelectedLoan.ToPay > Balance)
                {
                    MessageBox.Show("You don't enoguh money", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                Balance -= SelectedLoan.ToPay;
                CurrentBankAccount.Deposit = Balance;
                bankRepo.UpdateBankAccount(CurrentBankAccount);
                loanRepo.RemoveLoan(SelectedLoan.Id);
                Loans.Remove(SelectedLoan);
                SelectedLoan = null;
            });
            KickUser = new RelayCommand((x) =>
            {
                if (AdminSelectedUser == null)
                {
                    return;
                }

                broker.ForceLogout(AdminSelectedUser.Id);
                Broker_Update(null, null);
                AdminSelectedUser = null;
            });
        }
示例#35
0
 public abstract bool ShouldSellInvestment(Quote quote, Investment investment);
示例#36
0
    public static void GenerateContributionSchedule(int months, RepaymentFrequency repaymentFrequency, Investment currentLoan)
    {
        using (FinanceManagerDataContext db = new FinanceManagerDataContext())
        {

            decimal repaymentIntervals = (decimal)(currentLoan.MaturityDate.Value.Date - currentLoan.InvestmentCalculationStartDate.Value).Days / (repaymentFrequency.ConversionUnit.Value * (decimal)months);
            DateTime tempScheduleDate = currentLoan.InvestmentCalculationStartDate.Value;
            DateTime tempDate = currentLoan.InvestmentCalculationStartDate.Value;
            CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();
            decimal balance = 0;
            for (decimal i = 0; i < Math.Round((currentLoan.MaturityDate.Value - currentLoan.InvestmentCalculationStartDate.Value).Days / repaymentIntervals, MidpointRounding.AwayFromZero); i++)
            {
                tempScheduleDate = tempDate = tempDate.AddDays((int)repaymentIntervals);
                if (tempScheduleDate.DayOfWeek == DayOfWeek.Sunday)
                {
                    tempScheduleDate = tempScheduleDate.AddDays(1);
                }
                else if (tempScheduleDate.DayOfWeek == DayOfWeek.Saturday)
                {
                    tempScheduleDate = tempScheduleDate.AddDays(2);
                }

                //decimal totalAmountContributed = db.Contributions.Where<Contribution>(cont => cont.InvestmentId == currentLoan.InvestmentID).Sum<Contribution>(c => c.ContributionAmount).Value;

                //update balance
                balance += currentLoan.ContributionFreqAmount.Value;

                var _contributionSchedule = new ContributionSchedule()
                {
                    IsContributionMade = false,
                    ExpectedContributionAmount = currentLoan.ContributionFreqAmount,
                    InvestmentId = currentLoan.InvestmentID,
                    ContributionDate = tempScheduleDate,
                    Balance = balance
                };

                db.SubmitChanges();
                db.ContributionSchedules.InsertOnSubmit(_contributionSchedule);

                //audit
                Utils.logAction("Insert", _contributionSchedule);
            }

            //DateTime.Now.Month

        }
    }
        void LoadData(int InvestmentID)
        {
            _CurrentInvestment = Utils.GetDataContext().Investments.FirstOrDefault(i => i.InvestmentID == InvestmentID);

            if (_CurrentInvestment.InvestmentDescriptionId.HasValue)
            {
                cboInvestmentDescription.SelectedValue = _CurrentInvestment.InvestmentDescriptionId.Value.ToString();
            }

            PrincipalTextBox.Text = _CurrentInvestment.InvestmentAmount.Value.ToString();
            InterestTypeDropDownList.SelectedValue = _CurrentInvestment.InterestTypeId.Value.ToString();
            cboInterestDuration.SelectedValue = _CurrentInvestment.DurationTypeId.Value.ToString();
            InterestTextBox.Text = _CurrentInvestment.InsterstRate.Value.ToString();
            cboLoanDurationType.SelectedValue = _CurrentInvestment.DurationTypeId.Value.ToString();
            DurationTextBox.Text = _CurrentInvestment.Duration.Value.ToString();
            RepaymentFrequencyDropdownList.SelectedValue = _CurrentInvestment.ContributionFrequencyId.Value.ToString();
            txtStartCalculationFrom.Text = _CurrentInvestment.InvestmentCalculationStartDate.Value.ToString("dd/MM/yyyy");
            txtInvestmentDate.Text = _CurrentInvestment.CreatedDate.Value.ToString("dd/MM/yyyy");
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();

                double InvsetmentAmount = double.Parse(PrincipalTextBox.Text);
                double MaturedInvestmentAmount;// = double.Parse(lblTotalAmount.Text);

                // double interestRate = Convert.ToDouble(InterestTextBox.Text); //Convert.ToDouble(cProfile.CompoundInterestRate.Value);
                LoanDuration _loanDuration = db.LoanDurations.FirstOrDefault(l => l.LoanDurationId == Convert.ToInt32(cboLoanDurationType.SelectedValue));
                if (_loanDuration == null)
                    return;

                //int period = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value;
                decimal period = decimal.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value / 12;

                //LoanPreset _loanPreset = db.LoanPresets.First(l => l.LoanPresetId == Convert.ToInt32(cboInterestDuration.SelectedValue));
                //double interestRate = Utils.CalculateInterestRateByDuration(_loanPreset.InsterestRate.Value, period);

                //double interestRate = Utils.CalculateInterestRateByDuration(decimal.Parse(InterestTextBox.Text), period);
                double interestRate = double.Parse(InterestTextBox.Text);

                // int period = int.Parse(DurationTextBox.Text);
                int compoundType = cProfile.CompoundFrequency.Value;

                //using repayment frequency for contribution frequency
                //RepaymentFrequency _repaymentFrequency = db.RepaymentFrequencies.FirstOrDefault(r => r.RepaymentFrequencyId == int.Parse(RepaymentFrequencyDropdownList.SelectedValue));
                double amount;

                if (InterestTypeDropDownList.SelectedValue == "1") //compound
                {
                    amount = Utils.calculateCompoundInterest(InvsetmentAmount, interestRate, period, Utils.GetCompoundType(compoundType));
                }
                else //2 for simple interest
                {
                    amount = Utils.calculateSimpleInterest(InvsetmentAmount, interestRate, period);
                }

                decimal _originalInvestmentAmount = 0;
                //get an existing investment or create a new one
                Investment newInvestment;
                if (Request.QueryString["InvId"] != null)
                {
                    newInvestment = db.Investments.FirstOrDefault(i => i.InvestmentID == Convert.ToInt32(Request.QueryString["InvId"]));
                    _originalInvestmentAmount = newInvestment.InvestmentAmount.Value;
                }
                else
                {
                    newInvestment = new Investment();
                }

                //set invementType to 3 for fixed deposit investment
                newInvestment.InvestmentTypeId = 3;

                //newLoan.ActualRepaymentEndDate = DateTime.Today.AddMonths(period);
               // newLoan.Amount = (decimal)amount;

                if (Request.QueryString["mid"] != null)
                {
                    newInvestment.MemberID = Convert.ToInt32(Request.QueryString["mid"]);
                }
                else
                {
                    newInvestment.GroupId = Convert.ToInt32(Request.QueryString["gid"]);
                }

                newInvestment.IsDeleted = false;
                newInvestment.InvestmentAmount = (decimal)InvsetmentAmount;
                //newInvestment.ContributionFrequencyId = _repaymentFrequency.RepaymentFrequencyId;
                newInvestment.IsMatured = false;
                newInvestment.InsterstRate = (decimal)interestRate;
                newInvestment.Duration = decimal.Parse(DurationTextBox.Text);
                newInvestment.InterestTypeId = Convert.ToInt32(InterestTypeDropDownList.SelectedValue);
                //newLoan.payWithContribution = false;
                newInvestment.InvestmentCalculationStartDate = DateWebUserControl1.DtSelectedDate;
                newInvestment.IsActive = true;
                newInvestment.InterestDurationTypeID = Convert.ToInt32(cboLoanDurationType.SelectedValue);
                //variable to hold period for the calculation of MaturityDate calculation
                int tempPeriod;
                tempPeriod = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value;

                //start calculation from the LoanCalculationStartDate specified
                newInvestment.MaturityDate = newInvestment.InvestmentCalculationStartDate.Value.AddMonths(tempPeriod);

                //if the expected repayment end date falls on a weekend, move it to a working
                if (newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Saturday)
                {
                   newInvestment.MaturityDate =  newInvestment.MaturityDate.Value.AddDays(2);
                }
                else if (newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Sunday)
                {
                    newInvestment.MaturityDate = newInvestment.MaturityDate.Value.AddDays(1);
                }

                newInvestment.DurationTypeId = Convert.ToInt32(cboLoanDurationType.SelectedValue);
                //newLoan.RawDurationEntered = DurationTextBox.Text;

                newInvestment.InvestmentCalculationStartDate = DateTime.Now;

                TimeSpan tSpan = newInvestment.MaturityDate.Value - newInvestment.InvestmentCalculationStartDate.Value;// -DateTime.Today;
                double numberOfDaysBetweenExpectedEndDateAndNow = tSpan.TotalDays;

                //int xx = (int)numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value;

                //int numberOfDaysBetweenExpectedEndDateAndNow = 30 * period; //assuming there are 30 days in a month
                //decimal xx = numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value;
                //newInvestment.ContributionFreqAmount = ((decimal)newInvestment.InvestmentAmount / xx);

                //maturity amount
                MaturedInvestmentAmount = amount;
                newInvestment.CreatedBy = this.User.Identity.Name;
                newInvestment.MaturedAmount = (decimal)amount;

                //set invementType to 3 for fixed deposit investment
                newInvestment.InvestmentTypeId = 3;

                Parameter prm = db.Parameters.FirstOrDefault();

                //increase receipt number by one
                prm.ReceiptNumber++;

                if (Request.QueryString["InvId"] != null)
                {
                    newInvestment.ModifiedDate = DateTime.Now;
                    newInvestment.ModifiedBy = HttpContext.Current.User.Identity.Name;

                    //audit
                    Utils.logAction("Edit", newInvestment);
                    db.SubmitChanges();

                    //make contibution if the original amount is less than the new amount otherwise make a withrawal
                    if (newInvestment.InvestmentAmount > _originalInvestmentAmount)
                    {
                        //make contribution
                        Contribution _contribution = new Contribution()
                        {
                            ContributionAmount = newInvestment.InvestmentAmount - _originalInvestmentAmount,
                            ContributionBy = "Self",
                            ContributionAmountInWords = Utils.ConvertMoneyToText(newInvestment.InvestmentAmount.ToString()),
                            Description = "Fixed deposit contribution as a result of a edit action on an the investment",
                            ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'),
                            RecievedBy = User.Identity.Name,
                            InvestmentId = newInvestment.InvestmentID,
                            PaymentMethodId = PaymentMethodWebUserControl1.PaymentTypeID,
                            ChequeNumber = PaymentMethodWebUserControl1.ChequeNumber,
                            IsDeleted = false,
                            CreatedDate = DateWebUserControl1.DtSelectedDate,
                            CreatedBy = HttpContext.Current.User.Identity.Name
                        };
                        _contribution.CreatedDate = DateWebUserControl1.DtSelectedDate;

                        db.Contributions.InsertOnSubmit(_contribution);
                        db.SubmitChanges();

                        //audit
                        Utils.logAction("Insert", _contribution);

                    }
                    else  if (newInvestment.InvestmentAmount < _originalInvestmentAmount)
                    {
                        //make withdrawal
                        MemberWithdrawal _memberWithdrawal = new MemberWithdrawal()
                        {
                            CreatedBy = HttpContext.Current.User.Identity.Name,
                            DateCreated = DateTime.Now,
                            IsDeleted = false,
                            WithdrawalAmount = _originalInvestmentAmount - newInvestment.InvestmentAmount ,
                            WithdrawnBy = "Self",
                            //ContributionAmountInWords = Utils.ConvertMoneyToText(newInvestment.InvestmentAmount.ToString()),
                            Narration = "Fixed deposit withdrawal as a result of a edit action on an the investment",
                            //ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'),
                            WithdrawalIssuedByUserName = User.Identity.Name,
                            InvestmentID = newInvestment.InvestmentID
                        };

                        db.MemberWithdrawals.InsertOnSubmit(_memberWithdrawal);
                        db.SubmitChanges();

                        //audit
                        Utils.logAction("Insert", _memberWithdrawal);
                    }
                }
                else
                {
                    newInvestment.CreatedDate = DateTime.Now;
                    db.Investments.InsertOnSubmit(newInvestment);

                    db.SubmitChanges();
                    //audit
                    Utils.logAction("Insert", newInvestment);

                    //make initial contribution if fixed deposit investment is a new one
                    //add contribution since it a fixed deposit
                    Contribution _contribution = new Contribution()
                    {
                        ContributionAmount = newInvestment.InvestmentAmount,
                        ContributionBy = "Self",
                        ContributionAmountInWords = Utils.ConvertMoneyToText(newInvestment.InvestmentAmount.ToString()),
                        Description = "Fixed deposit contribution",
                        ReceiptNumber = prm.ReceiptNumber.Value.ToString().PadLeft(6, '0'),
                        RecievedBy = User.Identity.Name,
                        InvestmentId = newInvestment.InvestmentID,
                        IsDeleted = false,
                        CreatedDate = DateWebUserControl1.DtSelectedDate,
                        CreatedBy = HttpContext.Current.User.Identity.Name
                    };

                    db.Contributions.InsertOnSubmit(_contribution);
                    db.SubmitChanges();

                    //audit
                    Utils.logAction("Insert", _contribution);

                }
                //ResponseHelper.Redirect(this.Response, "ContributionReceipt.aspx?cid=" + _contribution.ContributionId.ToString() + "&mid=" + _contribution.Investment.MemberID, "_blank", "menubar=0,width=100,height=100");
                if (Request.QueryString["mid"] != null)
                {
                    Response.Redirect("FixedDepositInvestmentStatement.aspx?invID=" + newInvestment.InvestmentID + "&mid=" + Request.QueryString["mid"]);
                }
                else if(Request.QueryString["gid"] != null)
                {
                    Response.Redirect("FixedDepositInvestmentStatement.aspx?invID=" + newInvestment.InvestmentID + "&gid=" + Request.QueryString["gid"]);
                }

            }
        }
示例#39
0
        private static void SaveDailyActivity(Dictionary <Entity, List <Investment> > dic)
        {
            if (dic.Count == 0)
            {
                return;
            }
            Dictionary <Entity, List <Investment> > toSave = new Dictionary <Entity, List <Investment> >();

            foreach (var item in dic)
            {
                toSave.Add(item.Key, item.Value);
            }
            #region Update FundInvestment existant
            try
            {
                List <FundInvestment> existingFundInvestments = InvestmentDataAccess.FindExistingInvestments(toSave.Select(i => i.Key.Id).ToList());

                if (existingFundInvestments.Count > toSave.Count)
                {
                    Log.Error("SaveDailyActivity", "Too much FundInvestment found");
                    return;
                }
                foreach (var fundInvestment in existingFundInvestments)
                {
                    var               current            = toSave.FirstOrDefault(i => i.Key.Id == fundInvestment.Fund.Id);
                    Entity            fund               = current.Key;
                    List <Investment> updatedInvestments = fundInvestment.Investments;
                    bool              newInvestment      = false;
                    foreach (var invest in current.Value)
                    {
                        // vérifie que l'investissement courant n'existe pas dans l'investissement existant
                        Investment investement = fundInvestment.Investments.FirstOrDefault(i => i.Id == invest.Id);
                        if (investement == null)
                        {
                            updatedInvestments.Add(invest);
                            newInvestment = true;
                        }
                        else
                        {
                            toSave.Remove(fund);
                        }
                    }
                    if (newInvestment)
                    {
                        var updatedFundInvestment = new FundInvestment(fundInvestment, fund, updatedInvestments);
                        InvestmentDataAccess.Update(updatedFundInvestment);
                        Log.Info("SaveDailyActivity", "Update fund investments",
                                 string.Format("{0} in {1}",
                                               updatedFundInvestment.Fund.Name,
                                               string.Join(", ", updatedFundInvestment.Investments.Select(investment => investment.Startup.Name))));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("SaveDailyActivity", "Update", ex);
                throw;
            }
            #endregion

            #region Insert nouveau FundInvestment
            try
            {
                if (toSave.Any())
                {
                    List <FundInvestment> investments = new List <FundInvestment>();
                    foreach (var item in toSave)
                    {
                        investments.Add(new FundInvestment()
                        {
                            Fund        = item.Key,
                            Investments = item.Value,
                            LastUpdate  = DateTime.UtcNow
                        });
                    }
                    InvestmentDataAccess.SaveDailyActivity(investments);
                    Log.Info("SaveDailyActivity", "New funds investments", string.Join(", ", investments.ToString()));
                }
                else
                {
                    Log.Info("SaveDailyActivity", "No new fund investment");
                }
            }
            catch (Exception ex)
            {
                Log.Error("SaveDailyActivity", "Insert", ex);
                throw;
            }
            #endregion
        }
        private static void InvestmentChoiceAdapterPropertiesWork()
        {
            var re = new Investment();

            Assert.Null(re.Item);
            Assert.Null(re.ConstructionYear);
            re.ConstructionYear = 1900;
            Assert.Equal(1900, re.Item);
            Assert.Equal(1900, re.ConstructionYear);
            re.ConstructionYear = null;
            Assert.Null(re.ConstructionYear);
            Assert.True(re.ConstructionYearUnknown);
            re.ConstructionYearUnknown = true;
            Assert.IsType<bool>(re.Item);
            Assert.True((bool)re.Item);
            Assert.Null(re.ConstructionYear);

            Assert.Null(re.Item1);
            Assert.Null(re.HeatingType);
            Assert.Null(re.HeatingTypeEnev2014);
            re.HeatingType = HeatingType.STOVE_HEATING;
            Assert.IsType<HeatingType>(re.Item1);
            Assert.Equal(HeatingType.STOVE_HEATING, re.Item1);
            re.HeatingTypeEnev2014 = HeatingTypeEnev2014.FLOOR_HEATING;
            Assert.IsType<HeatingTypeEnev2014>(re.Item1);
            Assert.Equal(HeatingTypeEnev2014.FLOOR_HEATING, re.Item1);
            Assert.Null(re.HeatingType);

            Assert.Null(re.Item2);
            Assert.Null(re.FiringTypes);
            Assert.Null(re.EnergySourcesEnev2014);
            re.FiringTypes = new FiringTypes();
            Assert.IsType<FiringTypes>(re.Item2);
            Assert.Null(re.EnergySourcesEnev2014);
            re.EnergySourcesEnev2014 = new EnergySourcesEnev2014();
            Assert.IsType<EnergySourcesEnev2014>(re.Item2);
            Assert.Null(re.FiringTypes);
        }
示例#41
0
 public LoanInvestment(Investment investment, Money amount)
 {
     Investment = investment;
     Amount     = amount;
 }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (FinanceManagerDataContext db = new FinanceManagerDataContext())
            {
                LoanWebApplication4.CompanyProfile cProfile = db.CompanyProfiles.FirstOrDefault();

                double InvsetmentAmount = double.Parse(PrincipalTextBox.Text);
                double MaturedInvestmentAmount;// = double.Parse(lblTotalAmount.Text);

                // double interestRate = Convert.ToDouble(InterestTextBox.Text); //Convert.ToDouble(cProfile.CompoundInterestRate.Value);
                LoanDuration _loanDuration = db.LoanDurations.FirstOrDefault(l => l.LoanDurationId == Convert.ToInt32(cboLoanDurationType.SelectedValue));
                if (_loanDuration == null)
                    return;

                //int period = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value;
                decimal period = decimal.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value / 12;

                //LoanPreset _loanPreset = db.LoanPresets.First(l => l.LoanPresetId == Convert.ToInt32(cboInterestDuration.SelectedValue));
                //double interestRate = Utils.CalculateInterestRateByDuration(_loanPreset.InsterestRate.Value, period);

                //double interestRate = Utils.CalculateInterestRateByDuration(decimal.Parse(InterestTextBox.Text), period);
                double interestRate = double.Parse(InterestTextBox.Text);

                // int period = int.Parse(DurationTextBox.Text);
                int compoundType = cProfile.CompoundFrequency.Value;

                //using repayment frequency for contribution frequency
                RepaymentFrequency _repaymentFrequency = null;            // = db.RepaymentFrequencies.FirstOrDefault(r => r.RepaymentFrequencyId == int.Parse(RepaymentFrequencyDropdownList.SelectedValue));
                //check if repayment frequency has been selected
                int _repaymentFrequencyID;
                int.TryParse(RepaymentFrequencyDropdownList.SelectedValue, out _repaymentFrequencyID);

                if (_repaymentFrequencyID > 0)
                    _repaymentFrequency = db.RepaymentFrequencies.FirstOrDefault(r => r.RepaymentFrequencyId == int.Parse(RepaymentFrequencyDropdownList.SelectedValue));

                double amount;

                if (InterestTypeDropDownList.SelectedValue == "1") //compound
                {
                    amount = Utils.calculateCompoundInterest(InvsetmentAmount, interestRate, period, Utils.GetCompoundType(compoundType));
                }
                else //2 for simple interest
                {
                    amount = Utils.calculateSimpleInterest(InvsetmentAmount, interestRate, period);
                }

                //get an existing investment or create a new one
                Investment newInvestment;
                if (Request.QueryString["InvId"] != null)
                {
                    newInvestment = db.Investments.FirstOrDefault(i => i.InvestmentID == Convert.ToInt32(Request.QueryString["InvId"]));
                }
                else
                {
                    newInvestment = new Investment();
                }

                //set invementType to 1 for regular investment
                newInvestment.InvestmentTypeId = 1;

                //newLoan.ActualRepaymentEndDate = DateTime.Today.AddMonths(period);
                // newLoan.Amount = (decimal)amount;

                if (Request.QueryString["mid"] != null)
                {
                    newInvestment.MemberID = Convert.ToInt32(Request.QueryString["mid"]);
                }
                else if (Request.QueryString["gid"] != null)
                {
                    newInvestment.GroupId = Convert.ToInt32(Request.QueryString["gid"]);
                }

                newInvestment.InvestmentAmount = (decimal)InvsetmentAmount;
                if (_repaymentFrequencyID > 0)
                {
                    newInvestment.ContributionFrequencyId = _repaymentFrequency.RepaymentFrequencyId;
                }
                newInvestment.IsMatured = false;
                newInvestment.InsterstRate = (decimal)interestRate;
                newInvestment.Duration = decimal.Parse(DurationTextBox.Text);
                newInvestment.InterestTypeId = Convert.ToInt32(InterestTypeDropDownList.SelectedValue);
                //newLoan.payWithContribution = false;
                newInvestment.InvestmentCalculationStartDate = DateTime.Parse(txtStartCalculationFrom.Text);
                newInvestment.InvestmentDescriptionId = Convert.ToInt32(cboInvestmentDescription.SelectedValue);
                newInvestment.CreatedDate = Convert.ToDateTime(txtInvestmentDate.Text);

                //variable to hold period for the calculation of MaturityDate calculation
                int tempPeriod;
                tempPeriod = int.Parse(DurationTextBox.Text) * _loanDuration.NumberOfMonths.Value;

                //start calculation from the LoanCalculationStartDate specified
                newInvestment.MaturityDate = newInvestment.InvestmentCalculationStartDate.Value.AddMonths(tempPeriod);

                //if the expected repayment end date falls on a weekend, move it to a working
                if (newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Saturday)
                {
                    newInvestment.MaturityDate = newInvestment.MaturityDate.Value.AddDays(2);
                }
                else if (newInvestment.MaturityDate.Value.DayOfWeek == DayOfWeek.Sunday)
                {
                    newInvestment.MaturityDate = newInvestment.MaturityDate.Value.AddDays(1);
                }

                newInvestment.DurationTypeId = Convert.ToInt32(cboLoanDurationType.SelectedValue);
                //newLoan.RawDurationEntered = DurationTextBox.Text;

                newInvestment.InvestmentCalculationStartDate = DateTime.Parse(txtStartCalculationFrom.Text);

                TimeSpan tSpan = newInvestment.MaturityDate.Value - newInvestment.InvestmentCalculationStartDate.Value;// -DateTime.Today;
                double numberOfDaysBetweenExpectedEndDateAndNow = tSpan.TotalDays;

                if (_repaymentFrequencyID > 0)
                {
                    int xx = (int)numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value;

                    //int numberOfDaysBetweenExpectedEndDateAndNow = 30 * period; //assuming there are 30 days in a month
                    //decimal xx = numberOfDaysBetweenExpectedEndDateAndNow / _repaymentFrequency.NumberOfDays.Value;
                    newInvestment.ContributionFreqAmount = ((decimal)newInvestment.InvestmentAmount / xx);
                }
                else
                {
                    newInvestment.ContributionFreqAmount = 0;
                }

                //maturity amount
                MaturedInvestmentAmount = amount;
                newInvestment.CreatedBy = this.User.Identity.Name;
                newInvestment.MaturedAmount = (decimal)amount;
                newInvestment.InvestmentTypeId = 1; //investmentTypeId 1 means regular investment
                newInvestment.IsActive = true;

                if (Request.QueryString["InvId"] != null)
                {
                    newInvestment.ModifiedDate = DateTime.Now;
                    newInvestment.ModifiedBy = HttpContext.Current.User.Identity.Name;
                   // db.Investments.InsertOnSubmit(newInvestment);

                    //audit
                    Utils.logAction("Edit", newInvestment);
                }
                else
                {
                    newInvestment.CreatedDate = DateTime.Now;
                    newInvestment.CreatedBy = HttpContext.Current.User.Identity.Name;
                    db.Investments.InsertOnSubmit(newInvestment);

                    //audit
                    Utils.logAction("Insert", newInvestment);
                }
                db.SubmitChanges();

                //if (_repaymentFrequencyID > 0)
                //{
                //    Utils.GenerateContributionSchedule(tempPeriod, _repaymentFrequency, newInvestment);
                //}
                if (Request.QueryString["gid"] != null)
                {
                    Response.Redirect("InvestmentStatement_Real_Group.aspx?invID=" + newInvestment.InvestmentID + "&gid=" + Request.QueryString["gid"]);
                }
                else
                {
                    Response.Redirect("InvestmentStatement_real.aspx?invID=" + newInvestment.InvestmentID + "&mid=" + Request.QueryString["mid"]);
                }

            }
        }
示例#43
0
        void ExportToXml(XmlWriter writer, IEnumerable <object> data)
        {
            // write out the referenced accounts first.
            writer.WriteStartElement("Accounts");

            foreach (object row in data)
            {
                Transaction t = row as Transaction;
                Investment  i = row as Investment;
                Split       s = row as Split;

                if (i != null)
                {
                    t = i.Transaction;
                }
                if (t != null)
                {
                    ExportAccount(writer, t.Account);
                    if (t.Transfer != null)
                    {
                        ExportAccount(writer, t.Transfer.Transaction.Account);
                    }
                }
                else if (s != null)
                {
                    ExportAccount(writer, s.Transaction.Account);
                    if (s.Transfer != null)
                    {
                        ExportAccount(writer, s.Transfer.Transaction.Account);
                    }
                }
            }

            writer.WriteEndElement();

            foreach (object row in data)
            {
                Transaction t = row as Transaction;
                Investment  i = row as Investment;
                Split       s = row as Split;
                if (t != null)
                {
                    TransactionSerializer.WriteObject(writer, t);
                    i = t.Investment;
                }

                if (i != null)
                {
                    InvestmentSerializer.WriteObject(writer, i);
                }

                if (s != null)
                {
                    SplitSerializer.WriteObject(writer, s);
                }
                else if (t == null && i == null)
                {
                    throw new Exception("Row type " + row.GetType().FullName + " not supported");
                }
            }
        }
示例#44
0
 public override bool ShouldSellInvestment(Quote quote, Investment investment)
 {
     return ShouldSellInvestment(quote, investment, HIGHPERCENTAGE, LOWPERCENTAGE, DAYS);
 }
示例#45
0
 public IBankProduct Visit(Investment investment)
 {
     return(null);
 }