public ActivityHistoryModel(Transaction trans, SIEBUEntities db = null)
 {
     if (db == null) db = new SIEBUEntities();
     value = trans.total.Value;
     date = (DateTime)trans.dateprocessed;
     invoice = trans.invoice;
     transaction = trans.t_id;
     is_purchase = true;
 }
        public ActionResult ProcessAddress(FormCollection form)
        {
            Address shipping;
            Address billing;
            try
            {
                //discount
                decimal discount = 0;
                decimal.TryParse(form["walletCredit"], out discount);

                //shipping address

                int addressOption = 0;
                int.TryParse(form["savedAddressList"], out addressOption);
                shipping = db.Addresses.Where(ad => ad.address_id == addressOption).FirstOrDefault();
                if (shipping == null)
                    throw new Exception("A problem with the shipping address occured.");

                //billing address
                switch (form["billingOptions"])
                {
                    case "sameAsShipping":
                        billing = shipping;
                        break;
                    case "savedBillingAddress":
                        addressOption = 0;
                        int.TryParse(form["billing-savedAddressList"], out addressOption);
                        billing = db.Addresses.Where(ad => ad.address_id == addressOption).FirstOrDefault();
                        if (billing == null)
                            goto default;
                        break;
                    default:
                        throw new Exception("A problem with the billing address occured.");
                }

                //Create the incomplete transaction for processing
                Transaction progressTransaction = new Transaction();
                progressTransaction.datecreated = DateTime.Now;
                progressTransaction.payer_id = WebSecurity.CurrentUserId;
                progressTransaction.is_processed = false;
                progressTransaction.Address = shipping;
                progressTransaction.Address1 = billing;
                //Verify the discount credit is less than the user's credit
                User user = db.Users.Where(us => us.id == WebSecurity.CurrentUserId).FirstOrDefault();
                if (discount > user.credit)
                {
                    // The state does not exist.  State Option does not exist in the database
                    // TODO: Handle the error here.
                    var result = new
                    {
                        error = "Discount credit is greater than wallet credit"
                    };
                    throw new Exception("The discount credit should not be greater than the user's total credit");
                }
                progressTransaction.discount = discount;
                db.Transactions.Add(progressTransaction);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
            return RedirectToAction("ConfirmationPage");
        }
        public ActionResult IPN()
        {
            Debug.WriteLine("IPN received successfully");
            var formVals = new Dictionary<string, string>();
            formVals.Add("cmd", "_notify-validate");

            /* $1 Commission per item
             * Paypal Processing Fee: 2.9% + 0.30/#of vendors
             * Revenue = commission + processing fee access.
             *      = $1/item + fee for vendors - fee from paypal
             *      = $1/item + (2.9%+$0.30) - (2.9%+$0.30/#Vendors)
             */

            string strResponse = GetPayPalResponse(formVals, true);
            Debug.WriteLine(strResponse);

            if (strResponse == "VERIFIED")
            {
                //check the payment_status is Completed
                //check that txn_id has not been previously processed

                String paymentStatus = Request.Form["payment_status"];
                if (paymentStatus == "Completed")
                {
                    //Date Parsing
                    DateTime paymentDate;
                    DateTime.TryParseExact(Request.Form["payment_date"], dateFormats, new CultureInfo("en-US"), DateTimeStyles.None, out paymentDate);
                    paymentDate = paymentDate.AddHours(timezoneOffset); // Convert to local timezone

                    //Invoice parsing: format of invoice is INV1D20120128C1  Customer ID 1, Date Payment 2012/1/28, Number of total orders 1
                    String invoice = Request.Form["invoice"];
                    int customerID = int.Parse(invoice.Substring(3, invoice.IndexOf("D") - 3)); // 3 Because length of INV is 3
                    String transactionID = Request.Form["txn_id"];
                    decimal transactionFee = decimal.Parse(Request.Form["mc_fee"]);
                    decimal amountPaid = decimal.Parse(Request.Form["mc_gross"]);
                    //decimal totalShipping = decimal.Parse(Request.Form["mc_shipping"]);
                    decimal totalShipping = 0;

                    Debug.WriteLine("mc_fee: " + transactionFee);
                    Debug.WriteLine("mc_gross:" + amountPaid);

                    //Product proccessing
                    ArrayList itemIDs = new ArrayList();
                    ArrayList quantityArray = new ArrayList();
                    ArrayList itemCosts = new ArrayList();
                    //ArrayList shippingCosts = new ArrayList();

                    for (int i = 1; Request.Form["item_number" + i] != null; i++)
                    {
                        Debug.WriteLine(Request.Form["item_number" + i]);
                        itemIDs.Add(Request.Form["item_number" + i]);
                        quantityArray.Add(Request.Form["quantity" + i]);
                        itemCosts.Add(Request.Form["mc_gross_" + i]);
                        if (Request.Form["item_number" + i] == "sh")
                        {
                            totalShipping = decimal.Parse(Request.Form["mc_gross_" + i]);
                        }
                        //shippingCosts.Add(Request.Form["mc_shipping" + i]);
                    }

                    Transaction progressTransaction = db.Transactions.Where(tr => tr.invoice.Equals(invoice)).FirstOrDefault();

                    if (progressTransaction != null)
                    {
                        //Get the associated transaction and save the changes.
                        progressTransaction.is_processed = true;
                        progressTransaction.dateprocessed = paymentDate;
                        progressTransaction.paypal_transaction_id = transactionID;
                        progressTransaction.status = 1;
                        db.SaveChanges();

                        //Create paypal subtransaction records in the Paypal_Subtransaction
                        //this.createPaypalSubtransactions(paypal_transaction_id, report.report_id,itemIDs, itemCosts, quantityArray);
                        //Dictionary<int, int> subtransactionIds = new Dictionary<int, int>();
                        List<Transaction_Subtransaction> subtransactionList = db.Transaction_Subtransaction.Where(tr => tr.transaction_id ==
                            progressTransaction.t_id).ToList();

                        //give each store the discount from the transaction
                        foreach (Transaction_Subtransaction item in subtransactionList)
                        {
                            Store vendor = db.Stores.Where(st => st.s_id == item.store_id).FirstOrDefault();
                            vendor.credit = (vendor.credit != null) ? vendor.credit + item.total : item.total;
                        }

                        User user = db.Users.Where(us => us.id == customerID).FirstOrDefault();
                        user.credit = user.credit - progressTransaction.discount;
                        db.SaveChanges();

                        //delete all items in the user's shopping cart after the transaction is completed.
                        //AND decrease the product availability.
                        for (int i = 0; i < itemIDs.Count; i++)
                        {
                            int product_id = int.Parse(itemIDs[i].ToString());
                            int quantity = int.Parse(quantityArray[i].ToString());
                            Product prod = db.Products.Where(pr => pr.p_id == product_id).FirstOrDefault();
                            prod.avail_inventory = prod.avail_inventory - quantity;
                        }

                        db.SaveChanges();
                        Debug.WriteLine("Paypal Transaction Recorded");
                    }
                    else //payment pre processing did not occur.  Record it now.
                    {
                        Debug.Write("Invoice record does not exist.  Payment Pre-Process failed. Record the error.");
                        progressTransaction = new Transaction();
                        progressTransaction.status = 2;
                        progressTransaction.invoice = invoice;
                        progressTransaction.is_processed = false;

                        db.Transactions.Add(progressTransaction);
                        db.SaveChanges();
                    }

                    ViewData["status"] = "Complete";
                    return View();
                }
                else
                {
                    String invoice = Request.Form["invoice"];
                    Transaction progressTransaction = db.Transactions.Where(tr => tr.invoice.Equals(invoice)).FirstOrDefault();

                    if (progressTransaction != null)
                    {
                        //Get the associated transaction and save the changes.
                        progressTransaction.status = 2;
                        db.SaveChanges();
                    }
                    else //payment pre processing did not occur.  Record it now.
                    {
                        Debug.Write("Invoice record does not exist.  Payment Pre-Process failed. Record the error.");
                        progressTransaction = new Transaction();
                        progressTransaction.status = 2;
                        progressTransaction.invoice = invoice;
                        progressTransaction.is_processed = false;

                        db.Transactions.Add(progressTransaction);
                        db.SaveChanges();
                    }
                }

            }
            else if (strResponse == "INVALID")
            {
                //log for manual investigation
                System.Diagnostics.Debug.WriteLine("INVALID");
                String invoice = Request.Form["invoice"];
                Transaction progressTransaction = db.Transactions.Where(tr => tr.invoice.Equals(invoice)).FirstOrDefault();

                if (progressTransaction != null)
                {
                    //Get the associated transaction and save the changes.
                    progressTransaction.status = 2;
                    db.SaveChanges();
                }
                else //payment pre processing did not occur.  Record it now.
                {
                    Debug.Write("Invoice record does not exist.  Payment Pre-Process failed. Record the error.");
                    progressTransaction = new Transaction();
                    progressTransaction.status = 2;
                    progressTransaction.invoice = invoice;
                    progressTransaction.is_processed = false;

                    db.Transactions.Add(progressTransaction);
                    db.SaveChanges();
                }
                // Deal with payment failure

            }
            else
            {
                //log response/ipn data for manual investigation
            }
            return View();
        }