public JsonResult MoveInvoiceToNextStatus(string invoiceId, string status)
 {
     try
     {
         status = status.Replace("Move To", "").Trim();
         PaymentGateway pg = new PaymentGateway();
         string s = status.Replace(" ", "_");
         InvoiceStatus st = (InvoiceStatus)Enum.Parse(typeof(InvoiceStatus), s);
         pg.SetInvoiceStatus(new Guid(invoiceId), st);
         if (st == InvoiceStatus.Shipped)
         {
             var voice = pg.GetDisplayInvoice(new Guid(invoiceId));
             StoreGateway sg = new StoreGateway();
             sg.CompileAndSendShippedEmailsForStore(voice);
         }
         return Json(new { isSuccess = true, status = st.ToString() }, JsonRequestBehavior.AllowGet);
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return Json(new { isSuccess = false }, JsonRequestBehavior.AllowGet);
 }
        public void HandleStoreItemPayments(DisplayInvoice invoice, string additionalReportingInformation = null, string customerId = null)
        {
            try
            {
                var items = invoice.InvoiceItems;

                PaymentGateway pg = new PaymentGateway();
                //change invoice to ready to be shipped
                pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Awaiting_Shipping, customerId);

                CompileAndSendReceiptsEmailsForStore(invoice);

                //clear item from shooping cart.
                foreach (var item in items)
                {
                    bool isRemoved = RemoveItemFromCart(invoice.ShoppingCartId, item.StoreItemId);
                    bool isSuccess = SubtractNumberOfItemsBeingSoldByMerchant(invoice.Merchant.MerchantId, item.StoreItemId, item.Quantity);
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: additionalReportingInformation);
            }
        }
        private void PerformPaypalRollinNewsWritersPayment(CreateInvoiceReturn output)
        {
            try
            {
                var status = (byte)InvoiceStatus.Payment_Awaiting_For_Mass_Payout;
                var dc = new ManagementContext();
                var invoices = dc.Invoices.Include("InvoiceBilling").Include("WriterPayouts").Where(x => x.InvoiceStatus == status).ToList();


                // Create request object
                List<Fund> tempFundsBeingPaid = new List<Fund>();
                MassPayRequestType request = new MassPayRequestType();
                ReceiverInfoCodeType receiverInfoType = ReceiverInfoCodeType.EMAILADDRESS;

                request.ReceiverType = receiverInfoType;
                // (Optional) The subject line of the email that PayPal sends when the transaction completes. The subject line is the same for all recipients.
                request.EmailSubject = "Payment For Rollin News Content " + DateTime.UtcNow.ToString("yyyy/MM/dd");

                foreach (var invoice in invoices)
                {
                    var payout = invoice.WriterPayouts.FirstOrDefault();

                    //gotta check if we are already paying this user.
                    var f = tempFundsBeingPaid.Where(x => x.UserId == payout.UserPaidId).FirstOrDefault();
                    if (f != null)
                    {
                        if (f.ActiveInUserAccount >= (f.AmountToWithdraw + (double)invoice.BasePriceForItems))
                        {
                            f.AmountToWithdraw += (double)payout.PriceAfterFees;
                            f.AmountToDeductFromTotal += (double)invoice.BasePriceForItems;

                        }
                    }
                    else
                    {
                        var fundSettings = Fund.GetCurrentFundsInformation(payout.UserPaidId);
                        if ((double)invoice.BasePriceForItems <= fundSettings.ActiveInUserAccount)
                        {
                            fundSettings.AmountToWithdraw += (double)payout.PriceAfterFees;
                            fundSettings.AmountToDeductFromTotal += (double)invoice.BasePriceForItems;
                            tempFundsBeingPaid.Add(fundSettings);
                        }
                    }

                }
                for (int i = 0; i < tempFundsBeingPaid.Count; i++)
                {
                    // (Required) Details of each payment.
                    // Note:
                    // A single MassPayRequest can include up to 250 MassPayItems.
                    MassPayRequestItemType massPayItem = new MassPayRequestItemType();
                    CurrencyCodeType currency = CurrencyCodeType.USD;
                    massPayItem.Amount = new BasicAmountType(currency, tempFundsBeingPaid[i].AmountToWithdraw.ToString("N2"));
                    massPayItem.ReceiverEmail = tempFundsBeingPaid[i].PaypalAddress;
                    massPayItem.Note = "Thanks for writing for Rollin News!  We appreciate your content. ID:" + invoice.InvoiceId.ToString().Replace("-", "");
                    if (!String.IsNullOrEmpty(tempFundsBeingPaid[i].PaypalAddress))
                        request.MassPayItem.Add(massPayItem);

                }

                // Invoke the API
                MassPayReq wrapper = new MassPayReq();
                wrapper.MassPayRequest = request;


                // Create the PayPalAPIInterfaceServiceService service object to make the API call
                PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();

                // # API call 
                // Invoke the MassPay method in service wrapper object  
                MassPayResponseType massPayResponse = service.MassPay(wrapper);

                // Display response values. 
                Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
                if (!(massPayResponse.Ack == AckCodeType.FAILURE) &&
                    !(massPayResponse.Ack == AckCodeType.FAILUREWITHWARNING))
                {


                    if (!(massPayResponse.Ack == AckCodeType.SUCCESS))
                    {

                        SendErrorsOfMassPayToAdmins(output, massPayResponse);
                        ErrorDatabaseManager.AddException(new Exception("MASSPAYERROR"), GetType(), additionalInformation: Newtonsoft.Json.JsonConvert.SerializeObject(tempFundsBeingPaid) + "______" + Newtonsoft.Json.JsonConvert.SerializeObject(massPayResponse));

                    }

                    for (int i = 0; i < tempFundsBeingPaid.Count; i++)
                    {
                        try
                        {
                            var user = SiteCache.GetPublicMemberFullWithUserId(tempFundsBeingPaid[i].UserId);
                            bool success = Fund.UpdateAmounts(tempFundsBeingPaid[i].UserId, tempFundsBeingPaid[i].TotalPaidToUser);

                            var emailData = new Dictionary<string, string> 
                            { 
                            { "derbyName", user.DerbyName},
                            {"amountPaid", tempFundsBeingPaid[i].AmountToDeductFromTotal.ToString("N2")}};
                            EmailServer.EmailServer.SendEmail(RollinNewsConfig.DEFAULT_EMAIL, RollinNewsConfig.DEFAULT_EMAIL_FROM_NAME, user.UserName, EmailServer.EmailServer.DEFAULT_SUBJECT_ROLLIN_NEWS + " You Were Just Paid!", emailData, EmailServer.EmailServerLayoutsEnum.RNPaymentJustPaid);
                        }
                        catch (Exception exception)
                        {
                            ErrorDatabaseManager.AddException(exception, exception.GetType());
                        }
                    }
                    var emailDataComplete = new Dictionary<string, string> { { "totalPaid", tempFundsBeingPaid.Sum(x=>x.AmountToDeductFromTotal).ToString("N2") },
                    {"totalUsersPaid", tempFundsBeingPaid.Count.ToString()}};
                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, RollinNewsConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, EmailServer.EmailServer.DEFAULT_SUBJECT_ROLLIN_NEWS + " Mass Pay Completed!", emailDataComplete, EmailServer.EmailServerLayoutsEnum.RNPaymentJustCompleted);

                    for (int i = 0; i < invoices.Count; i++)
                    {
                        Payment.PaymentGateway pg = new PaymentGateway();
                        pg.SetInvoiceStatus(invoices[i].InvoiceId, InvoiceStatus.Payment_Successful);
                    }
                }
                else
                {
                    SendErrorsOfMassPayToAdmins(output, massPayResponse);
                }


            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
        }
 public void HandleStoreItemPaymentPending(DisplayInvoice invoice, string additionalReportingInformation = null)
 {
     try
     {
         var items = invoice.InvoiceItems;
         PaymentGateway pg = new PaymentGateway();
         //change invoice to ready to be shipped
         pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Awaiting_Payment);
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: additionalReportingInformation);
     }
 }