Пример #1
0
        //private static void ProcessEarlyBirdPromo(IPTV2Entities context, User user, DateTime registDt, Guid recipientUserId)
        //{
        //    if (CheckIfFirstTimeSubscriber(user))
        //    {

        //        var product = context.Products.FirstOrDefault(p => p.ProductId == GlobalConfig.FreeTrialEarlyBirdProductId);
        //        ProductPrice priceOfProduct = product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == GlobalConfig.TrialCurrency);

        //        //string Curr = MyUtility.GetCurrencyOrDefault(user.CountryCode);
        //        //var FreeTrialProductIds = MyUtility.StringToIntList(GlobalConfig.FreeTrialProductIds);
        //        //if (FreeTrialProductIds.Contains(product.ProductId))
        //        //    Curr = GlobalConfig.TrialCurrency;
        //        //ProductPrice priceOfProduct = product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == Curr);

        //        Purchase purchase = CreatePurchase(registDt, "Free Trial Early Bird Promo");
        //        user.Purchases.Add(purchase);

        //        PurchaseItem item = CreatePurchaseItem(recipientUserId, product, priceOfProduct);
        //        purchase.PurchaseItems.Add(item);

        //        WalletPaymentTransaction transaction = new WalletPaymentTransaction()
        //        {
        //            Currency = priceOfProduct.CurrencyCode,
        //            Reference = Guid.NewGuid().ToString().ToUpper(),
        //            Amount = purchase.PurchaseItems.Sum(p => p.Price),
        //            Date = registDt,
        //            User = user,
        //            OfferingId = GlobalConfig.offeringId
        //        };

        //        purchase.PaymentTransaction.Add(transaction);
        //        userWallet.WalletPaymentTransactions.Add(transaction);

        //    }
        //}

        public static ErrorResponse PayViaCreditCardWithRecurringBilling(IPTV2Entities context, System.Guid userId, CreditCardInfo info, int productId, SubscriptionProductType subscriptionType, System.Guid recipientUserId, int? cpId)
        {
            ErrorResponse resp = new ErrorResponse();
            try
            {
                bool isExtension = false;

                bool isGift = false;
                if (userId != recipientUserId)
                    isGift = true;
                //email metadata
                string packageName = String.Empty;
                DateTime endDt = DateTime.Now;
                string ProductNameBought = String.Empty;

                DateTime registDt = DateTime.Now;
                User user = context.Users.FirstOrDefault(u => u.UserId == userId);
                User recipient = context.Users.FirstOrDefault(u => u.UserId == recipientUserId);
                //UserWallet wallet = user.UserWallets.FirstOrDefault(w => w.Currency == MyUtility.GetCurrencyOrDefault(user.CountryCode));
                Offering offering = context.Offerings.FirstOrDefault(o => o.OfferingId == GlobalConfig.offeringId);
                Product product = context.Products.FirstOrDefault(p => p.ProductId == productId);
                ProductPrice priceOfProduct = product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == MyUtility.GetCurrencyOrDefault(user.CountryCode));
                if (priceOfProduct == null)
                    priceOfProduct = product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == GlobalConfig.DefaultCurrency);

                if (info == null) { }
                if (String.IsNullOrEmpty(info.Number)) { }
                if (String.IsNullOrEmpty(info.CardSecurityCode)) { }
                if (String.IsNullOrEmpty(info.Name)) { }
                if (String.IsNullOrEmpty(info.StreetAddress)) { }
                if (String.IsNullOrEmpty(info.PostalCode)) { }
                DateTime expiryDate = new DateTime(info.ExpiryYear, info.ExpiryMonth, 1);
                DateTime currentDate = new DateTime(registDt.Year, registDt.Month, 1);
                if (currentDate > expiryDate)
                {
                    resp.Code = (int)ErrorCodes.IsElapsedExpiryDate;
                    resp.Message = "Please check expiry date.";
                    return resp;
                }

                //Check if this is an upgrade
                if (cpId != null && cpId != 0)
                {
                    bool isUpgradeSuccess = Upgrade(context, userId, product, recipientUserId, cpId);
                }


                /***************************** Check for Early Bird Promo *******************************/
                bool IsEarlyBird = false;
                int FreeTrialConvertedDays = 0;
                Product earlyBirdProduct = null;
                ProductPrice earlyBirdPriceOfProduct = null;

                //REMOVE THIS LINE ON RELEASE OF EARLY BIRD.
                //if (false)
                if (GlobalConfig.IsEarlyBirdEnabled)
                {
                    if (user.IsFirstTimeSubscriber(offering, true, MyUtility.StringToIntList(GlobalConfig.FreeTrialPackageIds), context))
                    {
                        FreeTrialConvertedDays = GetConvertedDaysFromFreeTrial(user);

                        earlyBirdProduct = context.Products.FirstOrDefault(p => p.ProductId == GlobalConfig.FreeTrialEarlyBirdProductId);
                        earlyBirdPriceOfProduct = earlyBirdProduct.ProductPrices.FirstOrDefault(p => p.CurrencyCode == GlobalConfig.TrialCurrency);

                        Purchase earlyBirdPurchase = CreatePurchase(registDt, "Free Trial Early Bird Promo");
                        user.Purchases.Add(earlyBirdPurchase);

                        PurchaseItem earlyBirdItem = CreatePurchaseItem(recipientUserId, earlyBirdProduct, earlyBirdPriceOfProduct);

                        DateTime earlyBirdEndDate = registDt.AddDays(FreeTrialConvertedDays);
                        EntitlementRequest earlyBirdRequest = CreateEntitlementRequest(registDt, earlyBirdEndDate, earlyBirdProduct, String.Format("EBP-{0}-{1}", "CC", info.CardTypeString.Replace('_', ' ')), String.Format("EBP-{0}", info.CardTypeString.Replace('_', ' ')), registDt);
                        PackageSubscriptionProduct earlyBirdSubscription = (PackageSubscriptionProduct)earlyBirdProduct;
                        var earlyBirdPackage = earlyBirdSubscription.Packages.First();
                        PackageEntitlement EarlyBirdEntitlement = CreatePackageEntitlement(earlyBirdRequest, earlyBirdSubscription, earlyBirdPackage, registDt);


                        earlyBirdItem.EntitlementRequest = earlyBirdRequest;

                        earlyBirdPurchase.PurchaseItems.Add(earlyBirdItem);
                        recipient.EntitlementRequests.Add(earlyBirdRequest);

                        EarlyBirdEntitlement.EndDate = earlyBirdEndDate;
                        EarlyBirdEntitlement.LatestEntitlementRequest = earlyBirdRequest;
                        recipient.PackageEntitlements.Add(EarlyBirdEntitlement);

                        CreditCardPaymentTransaction earlyBirdTransaction = new CreditCardPaymentTransaction()
                        {
                            Amount = earlyBirdPriceOfProduct.Amount,
                            Currency = earlyBirdPriceOfProduct.CurrencyCode,
                            Reference = String.Format("EBP-{0}", info.CardType.ToString().Replace("_", " ").ToUpper()),
                            Date = registDt,
                            Purchase = earlyBirdPurchase,
                            OfferingId = GlobalConfig.offeringId,
                            StatusId = GlobalConfig.Visible
                        };

                        earlyBirdPurchase.PaymentTransaction.Add(earlyBirdTransaction);
                        user.Transactions.Add(earlyBirdTransaction);

                        IsEarlyBird = true;

                    }
                }
                /************************************ END OF EARLY BIRD PROMO *************************************/


                Purchase purchase = CreatePurchase(registDt, userId != recipientUserId ? "Gift via Credit Card" : "Payment via Credit Card");
                user.Purchases.Add(purchase);

                PurchaseItem item = CreatePurchaseItem(recipientUserId, product, priceOfProduct);

                purchase.PurchaseItems.Add(item);
                CreditCardPaymentTransaction transaction = new CreditCardPaymentTransaction()
                {
                    Amount = priceOfProduct.Amount,
                    Currency = priceOfProduct.CurrencyCode,
                    Reference = info.CardType.ToString().Replace("_", " "),
                    Date = registDt,
                    Purchase = purchase,
                    OfferingId = GlobalConfig.offeringId,
                    StatusId = GlobalConfig.Visible
                };

                var gomsService = new GomsTfcTv();
                /*** EARLY BIRD ***/
                //var response = gomsService.CreateOrderViaCreditCardWithRecurringBilling(context, userId, transaction, info);
                var response = gomsService.CreateOrderViaCreditCardWithRecurringBilling(context, userId, transaction, info, FreeTrialConvertedDays);

                if (response.IsSuccess)
                {
                    //transaction.Reference += "-" + response.TransactionId.ToString();
                    //user.Transactions.Add(transaction);

                    item.SubscriptionProduct = (SubscriptionProduct)product;

                    switch (subscriptionType)
                    {
                        case SubscriptionProductType.Show:
                            ShowSubscriptionProduct show_subscription = (ShowSubscriptionProduct)product;
                            ProductNameBought = show_subscription.Description;

                            /*** JAN 09 2012****/
                            bool isApplicableForEarlyBird = false;
                            if (IsEarlyBird)
                            {
                                var AlaCarteSubscriptionType = MyUtility.StringToIntList(GlobalConfig.FreeTrialAlaCarteSubscriptionTypes);
                                if (show_subscription.ALaCarteSubscriptionTypeId != null)
                                    if (AlaCarteSubscriptionType.Contains((int)show_subscription.ALaCarteSubscriptionTypeId))
                                        isApplicableForEarlyBird = true;
                            }

                            foreach (var show in show_subscription.Categories)
                            {
                                ShowEntitlement currentShow = recipient.ShowEntitlements.FirstOrDefault(s => s.CategoryId == show.CategoryId);
                                DateTime endDate = registDt;
                                EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, product, String.Format("{0}-{1}", "CC", info.CardTypeString.Replace('_', ' ')), response.TransactionId.ToString(), registDt);
                                if (currentShow != null)
                                {
                                    if (currentShow.EndDate > request.StartDate)
                                        request.StartDate = currentShow.EndDate;
                                    currentShow.EndDate = MyUtility.getEntitlementEndDate(show_subscription.Duration, show_subscription.DurationType, ((currentShow.EndDate > registDt) ? currentShow.EndDate : registDt));

                                    /** JAN 09 2012 **/
                                    if (IsEarlyBird && isApplicableForEarlyBird)
                                    {
                                        currentShow.EndDate = currentShow.EndDate.AddDays(FreeTrialConvertedDays);
                                    }

                                    endDate = currentShow.EndDate;
                                    currentShow.LatestEntitlementRequest = request;
                                    request.EndDate = endDate;
                                    endDt = endDate;
                                    isExtension = true;
                                }
                                else
                                {
                                    ShowEntitlement entitlement = CreateShowEntitlement(request, show_subscription, show, registDt);
                                    request.EndDate = entitlement.EndDate;

                                    /** JAN 09 2012 **/
                                    if (IsEarlyBird && isApplicableForEarlyBird)
                                    {
                                        entitlement.EndDate = entitlement.EndDate.AddDays(FreeTrialConvertedDays);
                                        request.EndDate = request.EndDate.AddDays(FreeTrialConvertedDays);
                                    }

                                    recipient.ShowEntitlements.Add(entitlement);
                                    endDt = entitlement.EndDate;
                                }
                                recipient.EntitlementRequests.Add(request);
                                item.EntitlementRequest = request; //UPDATED: November 22, 2012
                            }
                            break;
                        case SubscriptionProductType.Package:

                            if (product is PackageSubscriptionProduct)
                            {
                                PackageSubscriptionProduct subscription = (PackageSubscriptionProduct)product;

                                foreach (var package in subscription.Packages)
                                {
                                    packageName = package.Package.Description;
                                    ProductNameBought = packageName;

                                    PackageEntitlement currentPackage = recipient.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId);
                                    DateTime endDate = registDt;
                                    EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, product, String.Format("{0}-{1}", "CC", info.CardTypeString.Replace('_', ' ')), response.TransactionId.ToString(), registDt);
                                    if (currentPackage != null)
                                    {
                                        if (currentPackage.EndDate > request.StartDate)
                                            request.StartDate = currentPackage.EndDate;
                                        currentPackage.EndDate = MyUtility.getEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt));

                                        /** JAN 03 2012 **/
                                        if (IsEarlyBird)
                                        {
                                            currentPackage.EndDate = currentPackage.EndDate.AddDays(FreeTrialConvertedDays);
                                        }

                                        endDate = currentPackage.EndDate;
                                        currentPackage.LatestEntitlementRequest = request;
                                        request.EndDate = endDate;
                                        endDt = endDate;
                                        isExtension = true;

                                    }
                                    else
                                    {
                                        PackageEntitlement entitlement = CreatePackageEntitlement(request, subscription, package, registDt);
                                        request.EndDate = entitlement.EndDate;

                                        /** JAN 03 2012 **/
                                        if (IsEarlyBird)
                                        {
                                            entitlement.EndDate = entitlement.EndDate.AddDays(FreeTrialConvertedDays);
                                            request.EndDate = request.EndDate.AddDays(FreeTrialConvertedDays);
                                        }

                                        recipient.PackageEntitlements.Add(entitlement);
                                        endDt = entitlement.EndDate;


                                    }

                                    recipient.EntitlementRequests.Add(request);
                                    item.EntitlementRequest = request; //UPDATED: November 22, 2012
                                }
                            }
                            break;

                        case SubscriptionProductType.Episode:
                            EpisodeSubscriptionProduct ep_subscription = (EpisodeSubscriptionProduct)product;
                            foreach (var episode in ep_subscription.Episodes)
                            {
                                EpisodeEntitlement currentEpisode = recipient.EpisodeEntitlements.FirstOrDefault(e => e.EpisodeId == episode.EpisodeId);
                                DateTime endDate = registDt;
                                EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, product, String.Format("{0}-{1}", "CC", info.CardTypeString.Replace('_', ' ')), response.TransactionId.ToString(), registDt);
                                if (currentEpisode != null)
                                {
                                    if (currentEpisode.EndDate > request.StartDate)
                                        request.StartDate = currentEpisode.EndDate;
                                    currentEpisode.EndDate = MyUtility.getEntitlementEndDate(ep_subscription.Duration, ep_subscription.DurationType, ((currentEpisode.EndDate > registDt) ? currentEpisode.EndDate : registDt));
                                    endDate = currentEpisode.EndDate;
                                    currentEpisode.LatestEntitlementRequest = request;
                                    request.EndDate = endDate;
                                    endDt = endDate;
                                    isExtension = true;
                                }
                                else
                                {
                                    EpisodeEntitlement entitlement = CreateEpisodeEntitlement(request, ep_subscription, episode, registDt);
                                    request.EndDate = entitlement.EndDate;
                                    recipient.EpisodeEntitlements.Add(entitlement);
                                    endDt = entitlement.EndDate;
                                }
                                recipient.EntitlementRequests.Add(request);
                                item.EntitlementRequest = request; //UPDATED: November 22, 2012
                            }
                            break;
                    }

                    if (context.SaveChanges() > 0)
                    {
                        if (response.IsCCEnrollmentSuccess)
                        {
                            EnrollCreditCard(context, offering, user, registDt, info);
                            if (product.RegularProductId != null)
                            {
                                var regularProduct = context.Products.FirstOrDefault(p => p.ProductId == product.RegularProductId);
                                if (regularProduct != null)
                                    AddToRecurringBilling(context, regularProduct, offering, user, registDt, info);
                                else
                                    AddToRecurringBilling(context, product, offering, user, registDt, info);
                            }
                            else
                                AddToRecurringBilling(context, product, offering, user, registDt, info);
                        }
                        else
                        {
                            //Check if there's a currently enrolled recurring then add
                            //if (user.HasActiveRecurringProducts(offering))
                            //{
                            //    AddToRecurringBilling(context, product, offering, user, registDt, info);
                            //    response.IsCCEnrollmentSuccess = true;
                            //}

                            //Check if there is an enrolled credit card
                            //Commented out. if cc enrollment fails, everything fails.
                            //if (HasEnrolledCreditCard(offering, user))
                            //    AddToRecurringBilling(context, product, offering, user, registDt, info);
                        }

                        //SendConfirmationEmails(user, recipient, transaction, ProductNameBought, product, endDt, registDt, "Credit Card", isGift, isExtension, true, (DateTime)endDt.AddDays(-4).Date);
                        SendConfirmationEmails(user, recipient, transaction, ProductNameBought, product, endDt, registDt, "Credit Card", isGift, isExtension, response.IsCCEnrollmentSuccess, (DateTime)endDt.AddDays(-4).Date);
                        resp.Code = (int)ErrorCodes.Success;
                        resp.Message = "Successful";
                        resp.transaction = transaction;
                        resp.product = product;
                        resp.price = priceOfProduct;
                        resp.ProductType = subscriptionType == SubscriptionProductType.Package ? "Subscription" : "Retail";

                        if (!response.IsCCEnrollmentSuccess)
                        {
                            resp.Message = String.Format("{0}. {1}", resp.Message, response.CCEnrollmentStatusMessage);
                            resp.CCEnrollmentStatusMessage = "CC Enrollment Error";
                        }
                        return resp;
                    }

                    resp.Code = (int)ErrorCodes.EntityUpdateError;
                    resp.Message = "Entity Update Error";
                    return resp;
                }
                resp.Code = Convert.ToInt32(response.StatusCode);
                resp.Message = response.StatusMessage;
                if (!response.IsCCEnrollmentSuccess)
                { //Include CCenrollment status message in case enrolment fails.
                    resp.Message = String.Format("{0}. {1}", resp.Message, response.CCEnrollmentStatusMessage);
                    resp.CCEnrollmentStatusMessage = response.CCEnrollmentStatusMessage;
                }
                return resp;
            }

            catch (Exception)
            {
                //Debug.WriteLine(e.InnerException);
                throw;
            }
        }