public ActionResult PaywallRefundOrder(DisplayInvoice invoice)
        {
            try
            {
                bool isSuccess = false;
                var sg = new Paywall();
                PaymentGateway pg = new PaymentGateway();
                var f = pg.StartInvoiceWizard().Initalize(invoice.Merchant.MerchantId, "USD", invoice.PaymentProvider, PaymentMode.Live, ChargeTypeEnum.Refund_Paywall)
                    .SetInvoiceId(invoice.InvoiceId)
                .SetRefundAmount(invoice.RefundAmount)
                .SetNotes(null, invoice.AdminNote);

                var response = f.FinalizeInvoice();
                if (response.Status == InvoiceStatus.Refunded)
                    isSuccess = true;

                if (isSuccess)
                    return Redirect(Url.Content("~/paywall/order/" + invoice.Merchant.PrivateManagerId.ToString().Replace("-", "") + "/" + invoice.Merchant.MerchantId.ToString().Replace("-", "") + "/" + invoice.InvoiceId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.ro));
                else
                    return Redirect(Url.Content("~/paywall/order/" + invoice.Merchant.PrivateManagerId.ToString().Replace("-", "") + "/" + invoice.Merchant.MerchantId.ToString().Replace("-", "") + "/" + invoice.InvoiceId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.sww));
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
        }
        public ActionResult PaywallOrder(DisplayInvoice invoice)
        {
            try
            {


                var sg = new Paywall();
                sg.UpdatePaywallOrder(invoice);
                return Redirect(Url.Content("~/paywall/order/" + invoice.Merchant.PrivateManagerId.ToString().Replace("-", "") + "/" + invoice.Merchant.MerchantId.ToString().Replace("-", "") + "/" + invoice.InvoiceId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.s));
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
        }
 public bool UpdatePaywallOrder(DisplayInvoice v)
 {
     try
     {
         var mc = new ManagementContext();
         var invoice = mc.Invoices.Where(x => x.InvoiceId == v.InvoiceId && x.Merchant.MerchantId == v.Merchant.MerchantId && x.Merchant.PrivateManagerId == v.Merchant.PrivateManagerId).FirstOrDefault();
         if (invoice.Paywall != null)
             invoice.Paywall.ValidUntil = Convert.ToDateTime(v.Paywall.ValidUntilDisplay);
         int c = mc.SaveChanges();
         return c > 0;
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return false;
 }
        private static DisplayInvoice DisplayInvoice(DataModels.PaymentGateway.Invoices.Invoice voice)
        {
            DisplayInvoice v = new DisplayInvoice();
            try
            {
                v.UserId = voice.UserId;
                v.AdminNote = voice.AdminNote;
                if (voice.CurrencyRate != null)
                {
                    v.Currency = voice.CurrencyRate.CurrencyAbbrName;
                    v.CurrencyCost = voice.CurrencyRate.CurrencyExchangePerUSD;
                }
                else
                {
                    v.Currency = "USD";
                    v.CurrencyCost = 1;
                }

                v.InvoiceId = voice.InvoiceId;
                v.TotalIncludingTax = voice.BasePriceForItems;
                v.RefundAmount = voice.BasePriceForItems;
                v.ShoppingCartId = voice.ShoppingCartId;
                v.ShippingCost = voice.Shipping;
                v.RDNDeductedFee = voice.RDNDeductedFee;
                v.CreditCardCompanyProcessorDeductedFee = voice.CreditCardCompanyProcessorDeductedFee;
                v.PaymentProvider = (PaymentProvider)voice.PaymentProvider;
                v.Note = voice.Note;
                v.InvoiceStatus = (InvoiceStatus)voice.InvoiceStatus;
                v.Created = voice.Created;
                v.CustomerId = voice.PaymentProviderCustomerId;
                if (!String.IsNullOrEmpty(v.CustomerId) && v.PaymentProvider == PaymentProvider.Stripe)
                    v.CanRefundCustomer = true;

                v.TotalItemsBeingSold = 0;
                foreach (var refund in voice.Refunds)
                {
                    InvoiceRefund r = new InvoiceRefund();
                    r.RefundAmount = refund.PriceRefunded;
                    r.RefundId = refund.InvoiceRefundId;
                    v.Refunds.Add(r);
                }
                v.RefundAmount -= v.Refunds.Sum(x => x.RefundAmount);
                if (voice.InvoiceBilling != null)
                {
                    try
                    {
                        v.InvoiceBilling.City = voice.InvoiceBilling.City;
                        if (!String.IsNullOrEmpty(voice.InvoiceBilling.Country))
                        {
                            var count = SiteCache.GetCountries().Where(x => x.CountryId == Convert.ToInt32(voice.InvoiceBilling.Country)).FirstOrDefault();
                            v.InvoiceBilling.Country = count.Name;
                        }
                        v.InvoiceBilling.Email = voice.InvoiceBilling.Email;
                        v.InvoiceBilling.FirstName = voice.InvoiceBilling.FirstName;
                        v.InvoiceBilling.LastName = voice.InvoiceBilling.LastName;
                        v.InvoiceBilling.State = voice.InvoiceBilling.State;
                        v.InvoiceBilling.Street = voice.InvoiceBilling.Street;
                        v.InvoiceBilling.Street2 = voice.InvoiceBilling.Street2;
                        v.InvoiceBilling.Zip = voice.InvoiceBilling.Zip;
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }
                if (voice.Paywall != null)
                {
                    InvoicePaywall i = new InvoicePaywall();
                    i.Price = voice.Paywall.BasePrice;
                    i.Description = voice.Paywall.Description;
                    i.PaywallPassword = voice.Paywall.GeneratedPassword;
                    i.PaywallId = voice.Paywall.InvoicePaywallId;
                    i.MemberPaidId = voice.Paywall.MemberPaidId;
                    i.ValidUntil = voice.Paywall.ValidUntil;
                    i.ValidUntilDisplay = voice.Paywall.ValidUntil.ToShortDateString() + " " + voice.Paywall.ValidUntil.ToShortTimeString();
                    i.PriceType = (PaywallPriceTypeEnum)voice.Paywall.PaywallPriceTypeEnum;
                    i.SecondsViewedPaywall = voice.Paywall.SecondsViewedPaywall;
                    i.TimesUsedPassword = voice.Paywall.TimesUsedPassword;
                    i.LastViewedPaywall = voice.Paywall.LastViewedPaywall;
                    v.Paywall = i;
                }

                v.Merchant.MerchantId = voice.Merchant.MerchantId;
                v.Merchant.PrivateManagerId = voice.Merchant.PrivateManagerId;
                v.Merchant.ShopName = voice.Merchant.ShopName;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return v;
        }
        private void CompileAndSendRefundEmailsForPaywall(DisplayInvoice invoice, string reportingInformation = null)
        {
            try
            {

                StringBuilder shippingAddress = new StringBuilder();
                InvoiceContactInfo shipping = null;
                if (invoice.InvoiceShipping == null)
                    shipping = invoice.InvoiceBilling;
                else
                    shipping = invoice.InvoiceShipping;

                var emailData = new Dictionary<string, string>
                                        {
                                            { "PaywallDescription", invoice.Paywall.Description},
                                            { "invoiceId", invoice.InvoiceId.ToString().Replace("-","")},
                                            { "amountPaid", "$"+ invoice.RefundAmount.ToString("N2") },
                                            { "receiptLink", "<a href='"+ServerConfig.WEBSITE_DEFAULT_LOCATION+"/streaming/receipt/"+invoice.InvoiceId.ToString().Replace("-","")+"'>Your Receipt and Order Status</a>"},
                                            { "emailRDNation", "<a href='mailto:"+ServerConfig.DEFAULT_INFO_EMAIL+"'>"+ ServerConfig.DEFAULT_INFO_EMAIL+"</a>"}                                                                                      };

                //sends email to user for their payment.
                EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_INFO_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, invoice.InvoiceBilling.Email, EmailServer.EmailServer.DEFAULT_SUBJECT + " Refund for " + invoice.Paywall.Name, emailData, EmailServer.EmailServerLayoutsEnum.PaywallRefunded);
                if (invoice.Merchant.OrderPayedNotificationEmail != ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN)
                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_INFO_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, invoice.Merchant.OrderPayedNotificationEmail, EmailServer.EmailServer.DEFAULT_SUBJECT + " Paywall Refund Made, " + invoice.Paywall.Name, emailData, EmailServer.EmailServerLayoutsEnum.PaywallRefundedMerchant);

                EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_INFO_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, EmailServer.EmailServer.DEFAULT_SUBJECT + " Paywall Refund Made, " + invoice.Paywall.Name, emailData, EmailServer.EmailServerLayoutsEnum.PaywallRefundedMerchant);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: reportingInformation);
            }
        }
        public void HandlePaywallPayments(DisplayInvoice invoice, string additionalReportingInformation = null, string customerId = null)
        {
            try
            {
                PaymentGateway pg = new PaymentGateway();
                //change invoice to ready to be shipped
                pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Payment_Successful, customerId);

                CompileAndSendReceiptsEmailsForPaywall(invoice);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: additionalReportingInformation);
            }
        }
 public void HandlePaywallRefund(DisplayInvoice invoice, string additionalReportingInformation = null)
 {
     try
     {
         CompileAndSendRefundEmailsForPaywall(invoice);
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: additionalReportingInformation);
     }
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="invoice"></param>
        /// <param name="reportInformation"></param>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public static bool HandleDuesPayments(DisplayInvoice invoice, string reportInformation, string customerId = null)
        {
            try
            {
                var duesItem = invoice.DuesItems.FirstOrDefault();
                bool success = Dues.DuesFactory.PayDuesAmount(duesItem.DuesItemId, duesItem.DuesId, (double)duesItem.BasePrice, duesItem.MemberPaidId, "Paid Via Paypal, Invoice:" + invoice.InvoiceId.ToString().Replace("-", ""));
                PaymentGateway pg = new PaymentGateway();
                pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Payment_Successful, customerId);
                if (success)
                {
                    //email people.
                    WebClient client = new WebClient();
                    WebClient client1 = new WebClient();
                    client.DownloadStringAsync(new Uri(ServerConfig.URL_TO_CLEAR_MEMBER_CACHE + duesItem.MemberPaidId));
                    client1.DownloadStringAsync(new Uri(ServerConfig.URL_TO_CLEAR_MEMBER_CACHE_API + duesItem.MemberPaidId));

                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Dues Payment Made", reportInformation);
                    var member = MemberCache.GetMemberDisplay(duesItem.MemberPaidId);
                    var league = MemberCache.GetLeagueOfMember(duesItem.MemberPaidId);
                    var settings = Dues.DuesFactory.GetDuesSettings(duesItem.DuesId);
                    if (settings != null && member != null)
                    {
                        var emailData = new Dictionary<string, string>
                                        {
                                            { "memberName",  member.DerbyName },
                                            { "leagueName", settings.LeagueOwnerName   },
                                            { "invoiceId", invoice.InvoiceId.ToString().Replace("-","")},
                                            { "amountPaid", duesItem.PriceAfterFees.ToString("N2") },
                                            { "baseAmountPaid",duesItem.BasePrice.ToString("N2")  },
                                            { "monthOfDuesPayment",duesItem.PaidForDate.ToShortDateString()},
                                            { "emailForPaypal", settings.PayPalEmailAddress},
                                            { "statusOfPayment",RDN.Portable.Util.Enums.EnumExt.ToFreindlyName( InvoiceStatus.Pending_Payment_From_Paypal)}
                                          };

                        //sends email to user for their payment.
                        if (!String.IsNullOrEmpty(member.UserName))
                            EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, member.UserName, EmailServer.EmailServer.DEFAULT_SUBJECT + " Dues Payment Receipt", emailData, EmailServer.EmailServerLayoutsEnum.DuesPaymentMadeForUser);
                        else if (!String.IsNullOrEmpty(member.Email))
                            EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, member.Email, EmailServer.EmailServer.DEFAULT_SUBJECT + " Dues Payment Receipt", emailData, EmailServer.EmailServerLayoutsEnum.DuesPaymentMadeForUser);

                        if (league != null && !String.IsNullOrEmpty(league.Email))
                        {
                            //sends email to league for notification of their payment.
                            EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, league.Email, EmailServer.EmailServer.DEFAULT_SUBJECT + " Dues Payment Made", emailData, EmailServer.EmailServerLayoutsEnum.DuesPaymentMadeForLeague);
                        }

                        MobileNotificationFactory mnf = new MobileNotificationFactory();
                        mnf.Initialize("Dues Payment Made", "Receipt For Payment", NotificationTypeEnum.DuesPaymentReceipt)
                            .AddId(invoice.InvoiceId)
                            .AddMember(duesItem.MemberPaidId)
                            .SendNotifications();
                    }
                    else
                    {
                        throw new Exception("Settings or Member was null.  Can't send Receipts." + invoice.InvoiceId);
                    }
                }
                else
                {
                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: Dues Updates Were not successful", reportInformation);
                }
                return true;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: reportInformation);
            }
            return false;
        }
        /// <summary>
        /// Gets an invoice to be displayed in the merchant admin section
        /// </summary>
        /// <param name="invoiceId"></param>
        /// <param name="isRdn"></param>
        /// <returns></returns>
        private DisplayInvoice GetDisplayInvoice(DataModels.PaymentGateway.Invoices.Invoice invoice)
        {
            var output = new DisplayInvoice();
            try
            {
                output.InvoiceId = invoice.InvoiceId;

                output.InvoiceStatus = (InvoiceStatus)invoice.InvoiceStatus;
                output.InvoiceStatusUpdated = invoice.InvoiceStatusUpdated;
                output.PaymentProvider = (PaymentProvider)invoice.PaymentProvider;
                output.Note = invoice.Note;
                output.AdminNote = invoice.AdminNote;
                output.TotalBeforeTax = invoice.TotalBeforeTax;
                output.TotalIncludingTax = invoice.TotalIncludingTax;
                if (output.TotalIncludingTax == 0)
                    output.TotalIncludingTax = invoice.BasePriceForItems;
                output.TaxRate = invoice.TaxRate;
                output.Tax = invoice.Tax;
                output.ShippingCost = invoice.Shipping;
                output.ShippingType = (ShippingType)invoice.ShippingType;
                output.InvoicePaid = invoice.InvoicePaid;
                output.CreditCardCompanyProcessorDeductedFee = invoice.CreditCardCompanyProcessorDeductedFee;
                output.RDNDeductedFee = invoice.RDNDeductedFee;
                if (invoice.CurrencyRate != null)
                {
                    output.Currency = invoice.CurrencyRate.CurrencyAbbrName;
                    output.CurrencyCost = invoice.CurrencyRate.CurrencyExchangePerUSD;
                }
                else
                {
                    output.Currency = "USD";
                    output.CurrencyCost = 1;
                }
                output.Created = invoice.Created;
                output.UserId = invoice.UserId;
                output.ShoppingCartId = invoice.ShoppingCartId;
                output.CustomerId = invoice.PaymentProviderCustomerId;
                if (invoice.Merchant != null)
                {
                    output.Merchant.MerchantId = invoice.Merchant.MerchantId;
                    output.Merchant.PrivateManagerId = invoice.Merchant.PrivateManagerId;
                    output.Merchant.ShopName = invoice.Merchant.ShopName;
                    output.Merchant.PaypalEmail = invoice.Merchant.PaypalEmail;
                    output.Merchant.OrderPayedNotificationEmail = invoice.Merchant.OrderPayedNotificationEmail;
                    output.Merchant.OwnerName = invoice.Merchant.OwnerName;
                }
                if (invoice.Subscription != null)
                {
                    var subscription = new Classes.Invoice.InvoiceSubscription();
                    subscription.Name = invoice.Subscription.Name;
                    subscription.Description = invoice.Subscription.Description;
                    subscription.ArticleNumber = invoice.Subscription.ArticleNumber;
                    subscription.SubscriptionPeriod = (SubscriptionPeriod)invoice.Subscription.SubscriptionPeriod;
                    subscription.Price = invoice.Subscription.Price;
                    subscription.ValidUntil = invoice.Subscription.ValidUntil;
                    subscription.InternalObject = invoice.Subscription.InternalObject;
                    subscription.SubscriptionPeriodLengthInDays = invoice.Subscription.SubscriptionPeriodLengthInDays;
                    output.Subscription = subscription;
                }
                if (invoice.Paywall != null)
                {
                    var paywall = new Classes.Invoice.InvoicePaywall();
                    paywall.Name = invoice.Paywall.Name;
                    paywall.Description = invoice.Paywall.Description;
                    paywall.PaywallLocation = invoice.Paywall.PaywallLocation;
                    paywall.PaywallId = invoice.Paywall.InvoicePaywallId;
                    paywall.MemberPaidId = invoice.Paywall.MemberPaidId;
                    paywall.PriceType = (Enums.Paywall.PaywallPriceTypeEnum)invoice.Paywall.PaywallPriceTypeEnum;
                    paywall.Price = invoice.Paywall.BasePrice;
                    paywall.ValidUntil = invoice.Paywall.ValidUntil;
                    paywall.InternalObject = invoice.Paywall.InternalObject;
                    paywall.PaywallLengthOfDays = invoice.Paywall.PaywallLengthOfDays;
                    paywall.PaywallPassword = invoice.Paywall.GeneratedPassword;

                    output.Paywall = paywall;
                }
                if (output.InvoiceItems == null)
                    output.InvoiceItems = new List<Classes.Invoice.InvoiceItem>();
                foreach (var refund in invoice.Refunds)
                {
                    var r = new RDN.Library.Classes.Payment.Classes.Invoice.InvoiceRefund();
                    r.RefundAmount = refund.PriceRefunded;
                    r.RefundId = refund.InvoiceRefundId;
                    output.Refunds.Add(r);
                }

                foreach (var dbitem in invoice.Items)
                {
                    var item = new Classes.Invoice.InvoiceItem();
                    item.ArticleNumber = dbitem.ArticleNumber;
                    item.Article2Number = dbitem.Article2Number;
                    item.Description = dbitem.Description;
                    item.Name = dbitem.Name;
                    item.StoreItemId = dbitem.StoreItemId;
                    item.Price = dbitem.Price;
                    item.TotalShipping = dbitem.Shipping;
                    item.Quantity = dbitem.Quantity;
                    item.Weight = dbitem.Weight;
                    item.SizeOfItem = dbitem.SizeOfItem;
                    if (dbitem.ColorOfItem != null)
                    {
                        item.ColorOfItem = dbitem.ColorOfItem.ColorIdCSharp;
                        item.ColorName = dbitem.ColorOfItem.ColorName;
                    }
                    //no need to use this line as it doubles the damn price.
                    // output.TotalIncludingTax += dbitem.Price + dbitem.Shipping;
                    output.InvoiceItems.Add(item);
                }

                if (output.DuesItems == null)
                    output.DuesItems = new List<Classes.Invoice.InvoiceDuesItem>();
                foreach (var dbitem in invoice.DuesItems)
                {
                    var item = new Classes.Invoice.InvoiceDuesItem();
                    item.BasePrice = dbitem.BasePrice;
                    item.DuesId = dbitem.DuesId;
                    item.DuesItemId = dbitem.DuesItemId;
                    item.MemberPaidId = dbitem.MemberPaidId;
                    item.PriceAfterFees = dbitem.PriceAfterFees;
                    item.ProcessorFees = dbitem.ProcessorFees;
                    item.RDNationsFees = dbitem.RDNationsFees;
                    item.Name = dbitem.Name;
                    item.Description = dbitem.Description;
                    item.WhoPaysFees = (WhoPaysProcessorFeesEnum)Enum.Parse(typeof(WhoPaysProcessorFeesEnum), dbitem.WhoPaysFees.ToString());
                    var d = Dues.DuesFactory.GetDuesCollectionItem(dbitem.DuesItemId, dbitem.DuesId, RDN.Library.Classes.Account.User.GetMemberId());
                    if (d.DuesFees.FirstOrDefault() != null)
                        item.PaidForDate = d.DuesFees.FirstOrDefault().PayBy;
                    output.DuesItems.Add(item);
                }

                output.InvoiceBilling = GetInvoiceAddressFromDbInvoice(invoice.InvoiceBilling);
                output.InvoiceShipping = GetInvoiceAddressFromDbInvoice(invoice.InvoiceShipping);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return output;
        }
        public DisplayInvoice GetDisplayInvoiceWithStripeCustomerId(string customerId)
        {
            var output = new DisplayInvoice();

            var mc = new ManagementContext();
            var invoice = GetDatabaseInvoice(ref mc, customerId);
            if (invoice == null)
                return null;
            return GetDisplayInvoice(invoice);
        }
        public DisplayInvoice GetDisplayInvoice(Guid invoiceId, bool isRdn = false)
        {
            var output = new DisplayInvoice();
            if (!ValidateInvoice(invoiceId)) return null;

            var mc = new ManagementContext();
            var invoice = GetDatabaseInvoice(ref mc, invoiceId);
            if (invoice == null)
                return null;
            return GetDisplayInvoice(invoice);
        }
        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);
            }
        }
 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);
     }
 }
        public void CompileAndSendShippedEmailsForStore(DisplayInvoice invoice, string reportingInformation = null)
        {
            try
            {

                StringBuilder itemsSold = new StringBuilder();
                itemsSold.Append("<ul>");
                foreach (var item in invoice.InvoiceItems)
                {
                    itemsSold.Append("<li>");
                    //http://localhost:8847/roller-derby-item/Name-of-ITem-PicturesName-of-ITem-Pictures/12
                    itemsSold.Append("<a href='" + ServerConfig.WEBSITE_STORE_DEFAULT_LOCATION + "/roller-derby-item/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(item.Name) + "/" + item.StoreItemId + "'>" + item.Name + "</a>");
                    itemsSold.Append(" - " + item.Description);
                    itemsSold.Append("</li>");
                }
                itemsSold.Append("</ul>");
                StringBuilder shippingAddress = new StringBuilder();
                InvoiceContactInfo shipping = null;
                if (invoice.InvoiceShipping == null)
                    shipping = invoice.InvoiceBilling;
                else
                    shipping = invoice.InvoiceShipping;

                shippingAddress.Append(shipping.FirstName + " " + shipping.LastName + "<br/>");
                if (!String.IsNullOrEmpty(shipping.Street))
                    shippingAddress.Append(shipping.Street + "<br/>");
                if (!String.IsNullOrEmpty(shipping.Street2))
                    shippingAddress.Append(shipping.Street2 + "<br/>");
                shippingAddress.Append(shipping.State + " " + shipping.Zip + "<br/>");
                if (!String.IsNullOrEmpty(shipping.Country))
                {
                    var countries = Location.LocationFactory.GetCountries();
                    var count = countries.Where(x => x.CountryId == Convert.ToInt32(shipping.Country)).FirstOrDefault();
                    shippingAddress.Append(count.Name + "<br/>");
                }

                var emailData = new Dictionary<string, string>
                                        {
                                            { "memberName",  invoice.InvoiceBilling.FirstName +" "+ invoice.InvoiceBilling.LastName},
                                            { "shopName", "<a href='"+ServerConfig.WEBSITE_STORE_DEFAULT_LOCATION+"/roller-derby-shop/"+invoice.Merchant.MerchantId.ToString().Replace("-","")+"/"+ RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(invoice.Merchant.ShopName) +"'>"+ invoice.Merchant.ShopName+"</a>"},
                                            { "invoiceId", invoice.InvoiceId.ToString().Replace("-","")},
                                            { "amountPaid", "$"+ (invoice.TotalIncludingTax + invoice.ShippingCost).ToString("N2") },
                                            { "receiptLink", "<a href='"+ServerConfig.WEBSITE_STORE_DEFAULT_LOCATION+"/receipt/"+invoice.InvoiceId.ToString().Replace("-","")+"'>Your Receipt and Order Status</a>"},
                                            { "merchantLink", "<a href='"+ServerConfig.WEBSITE_INTERNAL_DEFAULT_LOCATION+"/store/orders/"+invoice.Merchant.PrivateManagerId.ToString().Replace("-","")+"/"+invoice.Merchant.MerchantId.ToString().Replace("-","")+"'>View the Order</a>"},
                                            { "shippingAddress",shippingAddress.ToString()},
                                            { "itemsSold", itemsSold.ToString()},
                                            { "notesForPayment", invoice.Note},
                                            { "emailRDNation", "<a href='mailto:"+ServerConfig.DEFAULT_INFO_EMAIL+"'>"+ ServerConfig.DEFAULT_INFO_EMAIL+"</a>"}                                            
                                          };

                //sends email to user for their payment.
                EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL_MESSAGES, ServerConfig.DEFAULT_EMAIL_FROM_NAME, invoice.InvoiceBilling.Email, EmailServer.EmailServer.DEFAULT_SUBJECT + " Your Items Have Shipped", emailData, EmailServer.EmailServerLayoutsEnum.StoreSendShippedItemsForOrder);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: reportingInformation);
            }
        }
        private static DisplayInvoice DisplayInvoice(DataModels.PaymentGateway.Invoices.Invoice voice)
        {
            DisplayInvoice v = new DisplayInvoice();
            try
            {
                v.UserId = voice.UserId;
                v.AdminNote = voice.AdminNote;
                if (voice.CurrencyRate != null)
                {
                    v.Currency = voice.CurrencyRate.CurrencyAbbrName;
                    v.CurrencyCost = voice.CurrencyRate.CurrencyExchangePerUSD;
                }
                else
                {
                    v.Currency = "USD";
                    v.CurrencyCost = 1;
                }
                v.InvoiceId = voice.InvoiceId;
                v.TotalIncludingTax = voice.BasePriceForItems;
                v.ShoppingCartId = voice.ShoppingCartId;
                v.ShippingCost = voice.Shipping;
                v.RDNDeductedFee = voice.RDNDeductedFee;
                v.CreditCardCompanyProcessorDeductedFee = voice.CreditCardCompanyProcessorDeductedFee;
                v.PaymentProvider = (PaymentProvider)voice.PaymentProvider;
                v.Note = voice.Note;
                v.InvoiceStatus = (InvoiceStatus)voice.InvoiceStatus;
                v.ShippingType = (ShippingType)voice.ShippingType;
                v.Created = voice.Created;
                v.TotalItemsBeingSold = 0;
                if (voice.InvoiceShipping != null)
                {
                    v.InvoiceShipping.City = voice.InvoiceShipping.City;
                    if (!String.IsNullOrEmpty(voice.InvoiceShipping.Country))
                    {
                        var count = SiteCache.GetCountries().Where(x => x.CountryId == Convert.ToInt32(voice.InvoiceShipping.Country)).FirstOrDefault();
                        v.InvoiceShipping.Country = count.Name;
                    }
                    v.InvoiceShipping.Email = voice.InvoiceShipping.Email;
                    v.InvoiceShipping.FirstName = voice.InvoiceShipping.FirstName;
                    v.InvoiceShipping.LastName = voice.InvoiceShipping.LastName;
                    v.InvoiceShipping.State = voice.InvoiceShipping.State;
                    v.InvoiceShipping.Street = voice.InvoiceShipping.Street;
                    v.InvoiceShipping.Street2 = voice.InvoiceShipping.Street2;
                    v.InvoiceShipping.Zip = voice.InvoiceShipping.Zip;
                }
                foreach (var item in voice.Items)
                {
                    InvoiceItem i = new InvoiceItem();
                    i.Article2Number = item.Article2Number;
                    i.ArticleNumber = item.ArticleNumber;
                    i.Description = item.Description;
                    i.Name = item.Name;
                    i.Price = item.Price;
                    i.InvoiceItemId = item.InvoiceItemId;
                    i.Quantity = item.Quantity;
                    i.SizeOfItem = item.SizeOfItem;
                    if (i.SizeOfItem > 0)
                        i.SizeOfItemName = Enum.Parse(typeof(StoreItemShirtSizesEnum), item.SizeOfItem.ToString()).ToString();
                    i.StoreItemId = item.StoreItemId;
                    i.TotalShipping = item.Shipping;
                    if (item.ColorOfItem != null)
                    {
                        i.ColorName = item.ColorOfItem.ColorName;
                        Color c = Color.FromArgb(item.ColorOfItem.ColorIdCSharp);
                        i.ColorHex = ColorTranslator.ToHtml(c);
                    }
                    v.TotalItemsBeingSold += item.Quantity;
                    v.InvoiceItems.Add(i);
                }
                v.Merchant.MerchantId = voice.Merchant.MerchantId;
                v.Merchant.PrivateManagerId = voice.Merchant.PrivateManagerId;
                v.Merchant.ShopName = voice.Merchant.ShopName;
                var loc = Location.LocationFactory.DisplayLocation(voice.Merchant.Locations.FirstOrDefault());
                var address = loc.Contact.Addresses.FirstOrDefault();
                if (address != null)
                {
                    v.SellersAddress = new InvoiceContactInfo() { City = address.CityRaw, CompanyName = loc.LocationName, Country = address.Country, State = address.StateRaw, Street = address.Address1, Street2 = address.Address2, Zip = address.Zip };
                }

            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return v;
        }
 public bool UpdateInvoiceForStoreOrder(DisplayInvoice invoice)
 {
     try
     {
         var mc = new ManagementContext();
         var voice = mc.Invoices.Where(x => x.InvoiceId == invoice.InvoiceId).FirstOrDefault();
         voice.AdminNote = invoice.AdminNote;
         voice.Merchant = voice.Merchant;
         int c = mc.SaveChanges();
         return c > 0;
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return false;
 }