Exemple #1
0
        public ActionResult SellStocks(SellStocksTrade Sale)
        {
            // Get the Customer
            // Query the Database for the logged in user
            var CustomerQuery = from c in db.Users
                                where c.UserName == User.Identity.Name
                                select c;
            // Get the Customer
            AppUser customer = CustomerQuery.FirstOrDefault();

            //Return frozen view if no go
            if (customer.ActiveStatus == false)
            {
                return(View("Frozen"));
            }

            // Get the original trade
            Trade OriginalTrade = db.Trades.Find(Sale.TradeID);

            // Get the Stock that is being sold
            StockMarket StockSale = db.StockMarket.Find(Sale.StockMarketID);

            // Get the Stock Account
            StockAccount CustomerStockAccount = db.StockAccount.Find(Sale.StockAccountID);

            // create a new transaction list for the trade
            List <BankingTransaction> TradeTrans = new List <BankingTransaction>();

            // Check the dates
            if (Sale.SaleDate < OriginalTrade.TransactionDate)
            {
                ViewBag.Error = "Cannot sell before purchase";
                return(View("SaleError"));
            }

            if (Sale.QuantitySold == 0)
            {
                ViewBag.Error = "Cannot sell with zero quantity";
                return(View("SaleError"));
            }

            // String for the description
            String Description = ($"Sale of {StockSale.CompanyName}, for {Sale.QuantitySold} shares, with initial price of {OriginalTrade.PricePerShare}, current price of {StockSale.StockPrice}, and a gain/loss of {Sale.Profit}");

            // Sale Amount
            Decimal SaleAmount = (Sale.QuantitySold * StockSale.StockPrice);

            // Create a new fee transaction and add it to the list
            BankingTransaction FeeTrans = new BankingTransaction
            {
                Amount = StockSale.Fee,
                BankingTransactionType = BankingTranactionType.Fee,
                Description            = ("Fee for sale of " + StockSale.CompanyName),
                StockAccount           = CustomerStockAccount,
                TransactionDate        = Sale.SaleDate,
                TransactionDispute     = DisputeStatus.NotDisputed
            };

            // Add the transaction to the list
            TradeTrans.Add(FeeTrans);

            // Make the trade happen
            Trade SaleTrade = new Trade()
            {
                TradeType           = TradeType.Sell,
                Amount              = (Sale.QuantitySold * StockSale.StockPrice),
                PricePerShare       = StockSale.StockPrice,
                Ticker              = StockSale.Ticker,
                Quantity            = Sale.QuantitySold,
                TransactionDate     = Sale.SaleDate,
                Description         = Description,
                StockMarket         = StockSale,
                StockAccount        = CustomerStockAccount,
                BankingTransactions = TradeTrans,
                TransactionDispute  = DisputeStatus.NotDisputed
            };

            // Create a new transaction for the actual sale
            BankingTransaction SaleTrans = new BankingTransaction
            {
                Amount = SaleAmount,
                BankingTransactionType = BankingTranactionType.Deposit,
                Description            = Description,
                StockAccount           = CustomerStockAccount,
                Trade              = SaleTrade,
                TransactionDate    = Sale.SaleDate,
                TransactionDispute = DisputeStatus.NotDisputed
            };

            // Add the transactions and the trades the the db
            db.BankingTransaction.Add(FeeTrans);
            db.SaveChanges();

            db.Trades.Add(SaleTrade);
            db.SaveChanges();

            db.BankingTransaction.Add(SaleTrans);
            db.SaveChanges();

            // Update the stock account

            // Take out the fee
            CustomerStockAccount.CashBalance -= Sale.Fee;

            // Add the fee to the account
            CustomerStockAccount.TradingFee += Sale.Fee;

            // Add/Subtract the profit
            CustomerStockAccount.CashBalance += Sale.Profit;

            // Update the Database
            db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();


            // Remove the shares from the account

            // Check to see if there is any stock left
            // If there is no stock left then we need to remove the original buy trade
            if (OriginalTrade.Quantity - Sale.QuantitySold == 0)
            {
                // Clear the associated foriegn keys
                OriginalTrade.BankingTransactions.Clear();

                // Remove the original trade
                db.Trades.Remove(OriginalTrade);
            }

            // If the original trade quantity is not zero
            else
            {
                // update the quantity
                OriginalTrade.Quantity -= Sale.QuantitySold;

                // update the database
                db.Entry(OriginalTrade).State = System.Data.Entity.EntityState.Modified;
            }

            // Save the changes
            db.SaveChanges();

            // Check to see if the account is balanced
            BalancedPortfolio.CheckBalanced(db, customer);

            // Return users to the stock account details page
            return(RedirectToAction("Details", "StockAccounts"));
        }
Exemple #2
0
        public ActionResult PurchaseStocks(PurchaseStockTrade PurchcaseTrade)
        {
            try
            {
                // get the customer
                AppUser Customer = db.Users.Find(PurchcaseTrade.CustomerProfile.Id);

                if (Customer == null)
                {
                    return(RedirectToAction("Portal", "Home"));
                }

                if (PurchcaseTrade.TradeDate < DateTime.Today || PurchcaseTrade.TradeDate == null)
                {
                    ViewBag.Error = "Date cannot be before today";
                    return(View("PurchaseError"));
                }

                if (PurchcaseTrade.Quantity == 0)
                {
                    ViewBag.Error = "Quantity cannot be 0";
                    return(View("PurchaseError"));
                }
                // Get the stock
                StockMarket SelectedStock = db.StockMarket.Find(PurchcaseTrade.SelectedStock.StockMarketID);

                // Get the total amount
                Decimal decTotal = (PurchcaseTrade.Quantity * SelectedStock.StockPrice);

                // create a new transaction list for the trade
                List <BankingTransaction> TradeTrans = new List <BankingTransaction>();

                // Create a new fee transaction and add it to the list
                BankingTransaction FeeTrans = new BankingTransaction
                {
                    Amount = SelectedStock.Fee,
                    BankingTransactionType = BankingTranactionType.Fee,
                    Description            = ("Fee for purchase of " + SelectedStock.CompanyName),
                    TransactionDate        = (PurchcaseTrade.TradeDate),
                    StockAccount           = Customer.StockAccount.FirstOrDefault(),
                    TransactionDispute     = DisputeStatus.NotDisputed
                };

                TradeTrans.Add(FeeTrans);

                // Make the trade happen
                Trade Trade = new Trade()
                {
                    Amount              = decTotal,
                    Quantity            = PurchcaseTrade.Quantity,
                    Ticker              = SelectedStock.Ticker,
                    TransactionDate     = PurchcaseTrade.TradeDate,
                    PricePerShare       = SelectedStock.StockPrice,
                    TradeType           = TradeType.Buy,
                    StockAccount        = Customer.StockAccount.FirstOrDefault(),
                    StockMarket         = SelectedStock,
                    BankingTransactions = TradeTrans,
                    DisputeMessage      = "None",
                    TransactionDispute  = DisputeStatus.NotDisputed,
                    Description         = "None",
                    CorrectedAmount     = 0
                };

                // Get the customer Savings account
                var SAQ = from sa in db.StockAccount
                          where sa.Customer.Id == Customer.Id
                          select sa;

                StockAccount CustomerStockAccount = SAQ.FirstOrDefault();

                // check the account nulls
                if (PurchcaseTrade.CheckingAccounts != null)
                {
                    // find the account
                    Checking CustomerChecking = db.CheckingAccount.Find(PurchcaseTrade.CheckingAccounts.CheckingID);

                    if (CustomerChecking == null)
                    {
                        return(RedirectToAction("Portal", "Home"));
                    }

                    // take the money from the account
                    if (CustomerChecking.Balance - decTotal >= 0)
                    {
                        // Check to see if the cash balance is enough for the fee
                        if (db.StockAccount.Find(Customer.StockAccount.FirstOrDefault().StockAccountID).CashBalance < SelectedStock.Fee)
                        {
                            ViewBag.Error = "Fee was greater than Stock Cash Balance";
                            return(View("PurchaseError"));
                        }

                        // create a list to hold the checking account
                        List <Checking> CheckingList = new List <Checking>();
                        CheckingList.Add(CustomerChecking);

                        //Create a new transaction
                        BankingTransaction CheckingTrans = new BankingTransaction
                        {
                            Amount = decTotal,
                            BankingTransactionType = BankingTranactionType.Withdrawl,
                            CheckingAccount        = CheckingList,
                            Description            = ("Stock Purchase - Stock Account " + Customer.StockAccount.FirstOrDefault().AccountNumber.ToString()),
                            TransactionDate        = PurchcaseTrade.TradeDate,
                            Trade = Trade,
                            TransactionDispute = DisputeStatus.NotDisputed
                        };

                        // add the stuff to the database
                        db.BankingTransaction.Add(FeeTrans);
                        db.SaveChanges();

                        db.Trades.Add(Trade);
                        db.SaveChanges();

                        // Take the money out
                        db.CheckingAccount.Find(CustomerChecking.CheckingID).Balance -= decTotal;

                        // take out the fee
                        CustomerStockAccount.CashBalance -= SelectedStock.Fee;

                        // take out the fee
                        CustomerStockAccount.TradingFee += SelectedStock.Fee;

                        db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified;
                        db.BankingTransaction.Add(CheckingTrans);
                        db.SaveChanges();
                    }

                    // HACK
                    else
                    {
                        ViewBag.Error = "Not Enough Money in Account to Purchase the Stocks";
                        return(View("PurchaseError"));
                    }


                    // Any further changes
                }
                else if (PurchcaseTrade.SavingsAccount != null)
                {
                    // Get the customer Savings account
                    Saving CustomerSavings = db.SavingsAccount.Find(PurchcaseTrade.SavingsAccount.SavingID);

                    // take the money from the account
                    if (CustomerSavings.Balance - decTotal >= 0)
                    {
                        // Check to see if the cash balance is enough for the fee
                        if (db.StockAccount.Find(Customer.StockAccount.FirstOrDefault().StockAccountID).CashBalance < SelectedStock.Fee)
                        {
                            ViewBag.Error = "Fee was greater than Stock Cash Balance";
                            return(View("PurchaseError"));
                        }

                        // create a list to hold the checking account
                        List <Saving> SavingsList = new List <Saving>();
                        SavingsList.Add(CustomerSavings);

                        //Create a new transaction
                        BankingTransaction SavingsTrans = new BankingTransaction
                        {
                            Amount = decTotal,
                            BankingTransactionType = BankingTranactionType.Withdrawl,
                            SavingsAccount         = SavingsList,
                            Description            = ("Stock Purchase - Stock Account " + Customer.StockAccount.FirstOrDefault().AccountNumber.ToString()),
                            TransactionDate        = PurchcaseTrade.TradeDate,
                            Trade = Trade,
                            TransactionDispute = DisputeStatus.NotDisputed
                        };

                        // add the stuff to the database
                        db.BankingTransaction.Add(FeeTrans);
                        db.SaveChanges();

                        db.Trades.Add(Trade);
                        db.SaveChanges();

                        // Take the money out
                        db.SavingsAccount.Find(CustomerSavings.SavingID).Balance -= decTotal;

                        // take out the fee
                        CustomerStockAccount.CashBalance -= SelectedStock.Fee;

                        // take out the fee
                        CustomerStockAccount.TradingFee += SelectedStock.Fee;

                        db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified;
                        db.BankingTransaction.Add(SavingsTrans);
                        db.SaveChanges();
                    }

                    // HACK
                    else
                    {
                        ViewBag.Error = "Not Enough Money in Account to Purchase the Stocks";
                        return(View("PurchaseError"));
                    }
                }
                else if (PurchcaseTrade.AccountStock != null)
                {
                    // take the money from the account
                    if (CustomerStockAccount.CashBalance - decTotal >= 0)
                    {
                        // Check to see if the cash balance is enough for the fee
                        if (db.StockAccount.Find(Customer.StockAccount.FirstOrDefault().StockAccountID).CashBalance < SelectedStock.Fee)
                        {
                            ViewBag.Error = "Fee was greater than Stock Cash Balance";
                            return(View("PurchaseError"));
                        }

                        // create a list to hold the checking account
                        List <StockAccount> StockAccountList = new List <StockAccount>();
                        StockAccountList.Add(CustomerStockAccount);

                        //Create a new transaction
                        BankingTransaction StocksTrans = new BankingTransaction()
                        {
                            Amount = decTotal,
                            BankingTransactionType = BankingTranactionType.Withdrawl,
                            StockAccount           = CustomerStockAccount,
                            Description            = ("Stock Purchase - Stock Account " + Customer.StockAccount.FirstOrDefault().AccountNumber.ToString()),
                            TransactionDate        = PurchcaseTrade.TradeDate,
                            Trade = Trade,
                            TransactionDispute = DisputeStatus.NotDisputed
                        };

                        // add the stuff to the database
                        db.BankingTransaction.Add(FeeTrans);
                        db.SaveChanges();

                        db.Trades.Add(Trade);
                        db.SaveChanges();

                        // Take the money out
                        CustomerStockAccount.CashBalance -= decTotal;

                        // take out the fee
                        CustomerStockAccount.CashBalance -= SelectedStock.Fee;

                        // take out the fee
                        CustomerStockAccount.TradingFee += SelectedStock.Fee;

                        db.Entry(CustomerStockAccount).State = System.Data.Entity.EntityState.Modified;
                        db.BankingTransaction.Add(StocksTrans);
                        db.SaveChanges();
                    }

                    // HACK
                    else
                    {
                        ViewBag.Error = "Not Enough Money in Account to Purchase the Stocks";
                        return(View("PurchaseError"));
                    }
                }

                else
                {
                    return(HttpNotFound());
                }

                // Add the stuff to the database
                // check to see if the porfolio is balanced
                BalancedPortfolio.CheckBalanced(db, Customer);

                return(View("PurchaseConfirmation"));
            }
            catch (Exception e)
            {
                ViewBag.Error = "An unknown error occured";
                return(View("PurchaseError"));
            }
        }