Ejemplo n.º 1
0
        //public static ErrorCodes PayViaPayPal(IPTV2Entities context, System.Guid userId, int productId, SubscriptionProductType subscriptionType, string TransactionID)
        //{
        //    try
        //    {
        //        //var context = new IPTV2Entities();
        //        DateTime registDt = DateTime.Now;
        //        User user = context.Users.FirstOrDefault(u => u.UserId == userId);
        //        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));

        //        Transaction ppt = context.Transactions.FirstOrDefault(t => t.Reference == TransactionID);
        //        if (ppt != null)
        //            return ErrorCodes.IsProcessedPayPalTransaction;

        //        Purchase purchase = new Purchase()
        //        {
        //            Date = registDt,
        //            Remarks = "Payment via PayPal"
        //        };
        //        user.Purchases.Add(purchase);

        //        PurchaseItem item = new PurchaseItem()
        //        {
        //            RecipientUserId = userId,
        //            ProductId = product.ProductId,
        //            Price = priceOfProduct.Amount,
        //            Currency = priceOfProduct.CurrencyCode,
        //            Remarks = product.Name
        //        };
        //        purchase.PurchaseItems.Add(item);

        //        PaypalPaymentTransaction transaction = new PaypalPaymentTransaction()
        //        {
        //            Currency = priceOfProduct.CurrencyCode,
        //            Reference = TransactionID,
        //            Amount = purchase.PurchaseItems.Sum(p => p.Price),
        //            User = user,
        //            Date = registDt
        //        };

        //        purchase.PaymentTransaction.Add(transaction);

        //        item.SubscriptionProduct = (SubscriptionProduct)product;

        //        switch (subscriptionType)
        //        {
        //            case SubscriptionProductType.Show:

        //                break;
        //            case SubscriptionProductType.Package:

        //                if (product is PackageSubscriptionProduct)
        //                {
        //                    // DateAndTime.DateAdd(DateInterval.Minute, 1, registDt);
        //                    registDt = registDt.AddMinutes(1);
        //                    PackageSubscriptionProduct subscription = (PackageSubscriptionProduct)product;

        //                    //EntitlementRequest request = new EntitlementRequest()
        //                    //{
        //                    //    DateRequested = registDt,
        //                    //    EndDate = MyUtility.getEntitlementEndDate(subscription.Duration, subscription.DurationType, registDt),
        //                    //    Product = product,
        //                    //    Source = String.Format("{0}-{1}", "Paypal", TransactionID),
        //                    //    ReferenceId = purchase.PurchaseId.ToString()
        //                    //};
        //                    //user.EntitlementRequests.Add(request);

        //                    foreach (var package in subscription.Packages)
        //                    {
        //                        PackageEntitlement currentPackage = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId);
        //                        DateTime endDate = registDt;
        //                        if (currentPackage != null)
        //                        {
        //                            currentPackage.EndDate = MyUtility.getEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt));
        //                            endDate = currentPackage.EndDate;
        //                        }
        //                        else
        //                        {
        //                            PackageEntitlement entitlement = new PackageEntitlement()
        //                            {
        //                                EndDate = MyUtility.getEntitlementEndDate(subscription.Duration, subscription.DurationType, registDt),
        //                                Package = (Package)package.Package,
        //                                OfferingId = GlobalConfig.offeringId
        //                            };

        //                            user.PackageEntitlements.Add(entitlement);
        //                        }

        //                        EntitlementRequest request = new EntitlementRequest()
        //                        {
        //                            DateRequested = registDt,
        //                            EndDate = endDate,
        //                            Product = product,
        //                            Source = String.Format("{0}-{1}", "Paypal", TransactionID),
        //                            ReferenceId = TransactionID
        //                        };
        //                        user.EntitlementRequests.Add(request);
        //                    }
        //                }
        //                break;

        //            case SubscriptionProductType.Episode: break;
        //        }

        //        if (context.SaveChanges() > 0)
        //        {
        //            return ErrorCodes.Success;
        //        }
        //        return ErrorCodes.EntityUpdateError;
        //    }

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

        public static ErrorCodes PayViaPayPal(IPTV2Entities context, System.Guid userId, int productId, SubscriptionProductType subscriptionType, string TransactionID, System.Guid recipientUserId, int? cpId, bool IsAutoPaymentRenewal = false)
        {
            try
            {
                //email metadata
                string packageName = String.Empty;
                DateTime endDt = DateTime.Now;
                bool isExtension = false;

                bool isGift = false;
                if (userId != recipientUserId)
                    isGift = true;

                //var context = new IPTV2Entities();
                DateTime registDt = DateTime.Now;
                User user = context.Users.FirstOrDefault(u => u.UserId == userId);
                User recipient = context.Users.FirstOrDefault(u => u.UserId == recipientUserId);
                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 (!priceOfProduct.Currency.IsPayPalSupported)
                    priceOfProduct = product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == GlobalConfig.DefaultCurrency);

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

                if (GlobalConfig.UsePayPalIPNLog)
                {
                    if (context.PaypalIPNLogs.Count(t => String.Compare(t.UniqueTransactionId, TransactionID, true) == 0) > 0)
                        return ErrorCodes.IsProcessedPayPalTransaction;
                }
                else
                {
                    Transaction ppt = context.Transactions.FirstOrDefault(t => String.Compare(t.Reference, TransactionID, true) == 0);
                    if (ppt != null)
                        return ErrorCodes.IsProcessedPayPalTransaction;
                }

                //Transaction ppt = context.Transactions.FirstOrDefault(t => String.Compare(t.Reference, TransactionID, true) == 0);
                //if (ppt != null)
                //    return ErrorCodes.IsProcessedPayPalTransaction;

                /***************************** 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}", "Paypal", TransactionID), String.Format("EBP-{0}", TransactionID), 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);

                        PaypalPaymentTransaction earlyBirdTransaction = new PaypalPaymentTransaction()
                        {
                            Currency = earlyBirdPriceOfProduct.CurrencyCode,
                            Reference = String.Format("EBP-{0}", TransactionID),
                            Amount = earlyBirdPurchase.PurchaseItems.Sum(p => p.Price),
                            User = user,
                            Date = registDt,
                            OfferingId = GlobalConfig.offeringId
                        };


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

                        IsEarlyBird = true;

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



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

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

                PaypalPaymentTransaction transaction = new PaypalPaymentTransaction()
                {
                    Currency = priceOfProduct.CurrencyCode,
                    Reference = IsAutoPaymentRenewal ? String.Format("{0} (Auto Payment Renewal)", TransactionID) : TransactionID,
                    Amount = purchase.PurchaseItems.Sum(p => p.Price),
                    User = user,
                    Date = registDt,
                    OfferingId = GlobalConfig.offeringId,
                    StatusId = GlobalConfig.Visible
                };

                var ipnLog = new PaypalIPNLog()
                {
                    User = user,
                    UniqueTransactionId = TransactionID,
                    TransactionDate = registDt
                };

                user.PaypalIPNLogs.Add(ipnLog);

                purchase.PaymentTransaction.Add(transaction);

                item.SubscriptionProduct = (SubscriptionProduct)product;
                string ProductNameBought = product.Description;

                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}", "Paypal", TransactionID), TransactionID, registDt);
                            if (currentShow != null)
                            {
                                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}", "Paypal", TransactionID), TransactionID, registDt);

                                if (currentPackage != null)
                                {
                                    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
                                //Update recurring billing if it exists
                                UpdateRecurringBillingIfExist(context, recipient, endDt, (Package)package.Package, isPayPal: true);
                            }
                        }
                        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}", "Paypal", TransactionID), TransactionID, registDt);
                            if (currentEpisode != null)
                            {
                                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)
                {

                    SendConfirmationEmails(user, recipient, transaction, ProductNameBought, product, endDt, registDt, "Paypal", isGift, isExtension);
                    ////Send email
                    //string emailBody = String.Format(GlobalConfig.SubscribeToProductBodyTextOnly, user.FirstName, ProductNameBought, endDt.ToString("MM/dd/yyyy hh:mm:ss tt"), transaction.TransactionId, product.Name, registDt.ToString("MM/dd/yyyy hh:mm:ss tt"), transaction.Amount.ToString("F2"), transaction.Currency, "Paypal", transaction.Reference);
                    //if (isExtension)
                    //    emailBody = String.Format(GlobalConfig.ExtendSubscriptionBodyTextOnly, user.FirstName, ProductNameBought, endDt.ToString("MM/dd/yyyy hh:mm:ss tt"), transaction.TransactionId, product.Name, registDt.ToString("MM/dd/yyyy hh:mm:ss tt"), transaction.Amount.ToString("F2"), transaction.Currency, "Paypal", transaction.Reference);
                    //try
                    //{
                    //    MyUtility.SendEmailViaSendGrid(user.EMail, GlobalConfig.NoReplyEmail, String.Format("You are now subscribed to {0}", ProductNameBought), emailBody, MailType.TextOnly, emailBody);
                    //}
                    //catch (Exception)
                    //{
                    //}
                    return ErrorCodes.Success;
                }
                return ErrorCodes.EntityUpdateError;
            }

            catch (Exception e) { Debug.WriteLine(e.InnerException); throw; }
        }
Ejemplo n.º 2
0
        public static ErrorResponse PayViaWalletWithEndDate(IPTV2Entities context, System.Guid userId, int productId, SubscriptionProductType subscriptionType, System.Guid recipientUserId, int? cpId, DateTime subscriptionEndDate, string additionalRemarks = "")
        {
            ErrorResponse resp = new ErrorResponse() { Code = (int)ErrorCodes.UnknownError };
            try
            {
                //email metadata
                string packageName = String.Empty;
                DateTime endDt = DateTime.Now;
                bool isExtension = false;

                bool isGift = false;
                if (userId != recipientUserId)
                    isGift = true;

                //var context = new IPTV2Entities();
                DateTime registDt = DateTime.Now;
                User user = context.Users.FirstOrDefault(u => u.UserId == userId);
                User recipient = context.Users.FirstOrDefault(u => u.UserId == recipientUserId);
                Offering offering = context.Offerings.FirstOrDefault(o => o.OfferingId == GlobalConfig.offeringId);
                Product product = context.Products.FirstOrDefault(p => p.ProductId == productId);
                UserWallet userWallet = user.UserWallets.FirstOrDefault(w => w.Currency == MyUtility.GetCurrencyOrDefault(user.CountryCode));
                string Curr = MyUtility.GetCurrencyOrDefault(user.CountryCode);
                var FreeTrialProductIds = MyUtility.StringToIntList(GlobalConfig.FreeTrialProductIds);
                if (FreeTrialProductIds.Contains(productId))
                    Curr = GlobalConfig.TrialCurrency;
                ProductPrice priceOfProduct = product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == Curr);
                if (userWallet.Balance < priceOfProduct.Amount)
                {
                    resp.Code = (int)ErrorCodes.InsufficientWalletLoad;
                    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}", "Wallet", userWallet.WalletId.ToString()), String.Format("EBP-{0}", userWallet.WalletId.ToString()), 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);


                        WalletPaymentTransaction earlyBirdTransaction = new WalletPaymentTransaction()
                        {
                            Currency = earlyBirdPriceOfProduct.CurrencyCode,
                            Reference = String.Format("EBP-{0}", Guid.NewGuid().ToString().ToUpper()),
                            Amount = earlyBirdPurchase.PurchaseItems.Sum(p => p.Price),
                            Date = registDt,
                            User = user,
                            OfferingId = GlobalConfig.offeringId
                        };

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

                        IsEarlyBird = true;
                    }
                }
                /************************************ END OF EARLY BIRD PROMO *************************************/

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

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

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

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

                item.SubscriptionProduct = (SubscriptionProduct)product;
                string ProductNameBought = product.Description;

                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, subscriptionEndDate, product, String.Format("{0}-{1}", "Wallet", userWallet.WalletId.ToString()), userWallet.WalletId.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;
                            }
                            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; // Get PackageName
                                ProductNameBought = packageName;
                                PackageEntitlement currentPackage = recipient.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId);
                                DateTime endDate = registDt;
                                EntitlementRequest request = CreateEntitlementRequest(registDt, subscriptionEndDate, product, String.Format("{0}-{1}", "Wallet", userWallet.WalletId.ToString()), userWallet.WalletId.ToString(), registDt);

                                //EntitlementRequest earlyBirdRequest = null;
                                //if (IsEarlyBird)
                                //{
                                //    earlyBirdRequest = CreateEntitlementRequest(registDt, endDate, earlyBirdProduct, String.Format("{0}-{1}", "Wallet", userWallet.WalletId.ToString()), userWallet.WalletId.ToString(), registDt);
                                //    PackageSubscriptionProduct earlyBirdSubscription = (PackageSubscriptionProduct)earlyBirdProduct;
                                //    var earlyBirdPackage = earlyBirdSubscription.Packages.First();
                                //    PackageEntitlement EarlyBirdEntitlement = CreatePackageEntitlement(earlyBirdRequest, earlyBirdSubscription, earlyBirdPackage, registDt);
                                //    EarlyBirdEntitlement.LatestEntitlementRequest = earlyBirdRequest;                                    
                                //    recipient.PackageEntitlements.Add(EarlyBirdEntitlement);
                                //}

                                if (currentPackage != null)
                                {
                                    if (currentPackage.EndDate > request.StartDate)
                                        request.StartDate = currentPackage.EndDate;
                                    currentPackage.EndDate = subscriptionEndDate;

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

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


                                }
                                else
                                {
                                    PackageEntitlement entitlement = CreatePackageEntitlement(request, subscription, package, registDt);
                                    entitlement.EndDate = subscriptionEndDate;
                                    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
                                //Update recurring billing if it exists
                                UpdateRecurringBillingIfExist(context, recipient, endDt, (Package)package.Package);
                            }
                        }
                        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, subscriptionEndDate, product, String.Format("{0}-{1}", "Wallet", userWallet.WalletId.ToString()), userWallet.WalletId.ToString(), subscriptionEndDate);
                            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;
                            }
                            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;
                }

                userWallet.Balance -= priceOfProduct.Amount;
                userWallet.LastUpdated = registDt;

                if (context.SaveChanges() > 0)
                {
                    //Send email
                    SendConfirmationEmails(user, recipient, transaction, ProductNameBought, product, endDt, registDt, "E-Wallet", isGift, isExtension);
                    //string emailBody = String.Format(GlobalConfig.SubscribeToProductBodyTextOnly, user.FirstName, ProductNameBought, endDt.ToString("MM/dd/yyyy hh:mm:ss tt"), transaction.TransactionId, product.Name, registDt.ToString("MM/dd/yyyy hh:mm:ss tt"), transaction.Amount.ToString("F2"), transaction.Currency, "Wallet", transaction.Reference);
                    //try
                    //{
                    //    MyUtility.SendEmailViaSendGrid(user.EMail, GlobalConfig.NoReplyEmail, String.Format("You are now subscribed to {0}", ProductNameBought), emailBody, MailType.TextOnly, emailBody);
                    //}
                    //catch (Exception)
                    //{
                    //}
                    resp.Code = (int)ErrorCodes.Success;
                    resp.transaction = transaction;
                    resp.product = product;
                    resp.price = priceOfProduct;
                    resp.ProductType = subscriptionType == SubscriptionProductType.Package ? "Subscription" : "Retail";
                    return resp;
                }
                resp.Code = (int)ErrorCodes.EntityUpdateError;
                return resp;
            }

            catch (Exception e) { Debug.WriteLine(e.InnerException); throw; }
        }
Ejemplo n.º 3
0
        //public static Ppc.ErrorCode PayViaPrepaidCard(IPTV2Entities context, System.Guid userId, int productId, SubscriptionProductType subscriptionType, string serial, string pin)
        //{
        //    try
        //    {
        //        DateTime registDt = DateTime.Now;
        //        User user = context.Users.FirstOrDefault(u => u.UserId == userId);
        //        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));
        //        Ppc ppc = context.Ppcs.FirstOrDefault(p => p.SerialNumber == serial);
        //        if (ppc.Currency == GlobalConfig.TrialCurrency)
        //            priceOfProduct = product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == ppc.Currency);

        //        //if (ppc == null) //Serial does not exist
        //        //    return ErrorCodes.IsInvalidPpc;
        //        //if (!(ppc.SerialNumber == serial && ppc.Pin == pin)) //Invalid serial/pin combination
        //        //    return ErrorCodes.IsInvalidCombinationPpc;
        //        //if (ppc.UserId != null) // Ppc has already been used
        //        //    return ErrorCodes.IsUsedPpc;
        //        //if (!(ppc is SubscriptionPpc)) // Ppc is not of type Subscription
        //        //    return ErrorCodes.IsReloadPpc;
        //        //if (registDt > ppc.ExpirationDate) // Ppc is expired
        //        //    return ErrorCodes.IsExpiredPpc;
        //        //SubscriptionPpc sPpc = (SubscriptionPpc)ppc;
        //        //if (sPpc.ProductId != product.ProductId) // Ppc product is invalid.
        //        //    return ErrorCodes.IsProductIdInvalidPpc;
        //        //if (ppc.Currency.Trim() != MyUtility.GetCurrencyOrDefault(user.CountryCode) && ppc.Currency != "---") // Ppc not valid in your country
        //        //    return ErrorCodes.IsNotValidInCountryPpc;
        //        //if (ppc.Amount != priceOfProduct.Amount) // Ppc is of invalid amount
        //        //    return ErrorCodes.IsNotValidAmountPpc;

        //        Ppc.ErrorCode validate = Ppc.ValidateSubscriptionPpc(context, ppc.SerialNumber, ppc.Pin, MyUtility.GetCurrencyOrDefault(user.CountryCode), product);

        //        if (validate == Ppc.ErrorCode.Success)
        //        {
        //            SubscriptionPpc sPpc = (SubscriptionPpc)ppc;

        //            Purchase purchase = new Purchase()
        //            {
        //                Date = registDt,
        //                Remarks = "Payment via Ppc"
        //            };
        //            user.Purchases.Add(purchase);

        //            PurchaseItem item = new PurchaseItem()
        //            {
        //                RecipientUserId = userId,
        //                ProductId = product.ProductId,
        //                Price = priceOfProduct.Amount,
        //                Currency = priceOfProduct.CurrencyCode,
        //                Remarks = product.Name
        //            };
        //            purchase.PurchaseItems.Add(item);

        //            PpcPaymentTransaction transaction = new PpcPaymentTransaction()
        //            {
        //                Currency = priceOfProduct.CurrencyCode,
        //                Reference = serial.ToUpper(),
        //                Amount = purchase.PurchaseItems.Sum(p => p.Price),
        //                Product = product,
        //                Purchase = purchase,
        //                SubscriptionPpc = sPpc,
        //                Date = registDt
        //            };

        //            user.Transactions.Add(transaction);
        //            // purchase.PaymentTransaction.Add(transaction);
        //            // product.PpcPaymentTransactions.Add(transaction);

        //            item.SubscriptionProduct = (SubscriptionProduct)product;

        //            switch (subscriptionType)
        //            {
        //                case SubscriptionProductType.Show:

        //                    break;
        //                case SubscriptionProductType.Package:

        //                    if (product is PackageSubscriptionProduct)
        //                    {
        //                        // DateAndTime.DateAdd(DateInterval.Minute, 1, registDt);
        //                        registDt = registDt.AddMinutes(1);
        //                        PackageSubscriptionProduct subscription = (PackageSubscriptionProduct)product;

        //                        //EntitlementRequest request = new EntitlementRequest()
        //                        //{
        //                        //    DateRequested = registDt,
        //                        //    EndDate = MyUtility.getEntitlementEndDate(subscription.Duration, subscription.DurationType, registDt),
        //                        //    Product = product,
        //                        //    Source = String.Format("{0}-{1}", "Ppc", ppc.PpcId.ToString()),
        //                        //    ReferenceId = purchase.PurchaseId.ToString()
        //                        //};
        //                        //user.EntitlementRequests.Add(request);

        //                        foreach (var package in subscription.Packages)
        //                        {
        //                            PackageEntitlement currentPackage = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId);
        //                            DateTime endDate = registDt;
        //                            if (currentPackage != null)
        //                            {
        //                                currentPackage.EndDate = MyUtility.getEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt));
        //                                endDate = currentPackage.EndDate;
        //                            }
        //                            else
        //                            {
        //                                PackageEntitlement entitlement = new PackageEntitlement()
        //                                {
        //                                    EndDate = MyUtility.getEntitlementEndDate(subscription.Duration, subscription.DurationType, registDt),
        //                                    Package = (Package)package.Package,
        //                                    OfferingId = GlobalConfig.offeringId
        //                                };

        //                                user.PackageEntitlements.Add(entitlement);
        //                            }

        //                            EntitlementRequest request = new EntitlementRequest()
        //                            {
        //                                DateRequested = registDt,
        //                                EndDate = endDate,
        //                                Product = product,
        //                                Source = String.Format("{0}-{1}", "Ppc", ppc.PpcId.ToString()),
        //                                ReferenceId = ppc.PpcId.ToString()
        //                            };
        //                            user.EntitlementRequests.Add(request);
        //                        }
        //                    }
        //                    break;

        //                case SubscriptionProductType.Episode: break;
        //            }

        //            //update the Ppc

        //            ppc.UserId = userId;
        //            ppc.UsedDate = registDt;

        //            if (context.SaveChanges() > 0)
        //            {
        //                return Ppc.ErrorCode.Success;
        //            }
        //            return Ppc.ErrorCode.EntityUpdateError;
        //        }
        //        else
        //            return validate;
        //    }

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

        public static ErrorResponse PayViaPrepaidCard(IPTV2Entities context, System.Guid userId, int productId, SubscriptionProductType subscriptionType, string serial, string pin, System.Guid recipientUserId, int? cpId)
        {
            ErrorResponse resp = new ErrorResponse() { Code = (int)Ppc.ErrorCode.UnknownError };
            try
            {
                //email metadata
                string packageName = String.Empty;
                DateTime endDt = DateTime.Now;
                bool isExtension = false;

                bool isGift = false;
                if (userId != recipientUserId)
                    isGift = true;

                DateTime registDt = DateTime.Now;
                User user = context.Users.FirstOrDefault(u => u.UserId == userId);
                User recipient = context.Users.FirstOrDefault(u => u.UserId == recipientUserId);
                Offering offering = context.Offerings.FirstOrDefault(o => o.OfferingId == GlobalConfig.offeringId);
                Product product = context.Products.FirstOrDefault(p => p.ProductId == productId);
                Ppc ppc = context.Ppcs.FirstOrDefault(p => p.SerialNumber == serial);


                if (ppc == null) //Serial does not exist
                {
                    resp.Code = (int)Ppc.ErrorCode.InvalidSerialNumber;
                    return resp;
                }


                string Curr = ppc.Currency != GlobalConfig.TrialCurrency ? MyUtility.GetCurrencyOrDefault(user.CountryCode) : GlobalConfig.TrialCurrency;
                ProductPrice priceOfProduct = product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == Curr);

                //if (!(ppc.SerialNumber == serial && ppc.Pin == pin)) //Invalid serial/pin combination
                //    return ErrorCodes.IsInvalidCombinationPpc;
                //if (ppc.UserId != null) // Ppc has already been used
                //    return ErrorCodes.IsUsedPpc;
                //if (!(ppc is SubscriptionPpc)) // Ppc is not of type Subscription
                //    return ErrorCodes.IsReloadPpc;
                //if (registDt > ppc.ExpirationDate) // Ppc is expired
                //    return ErrorCodes.IsExpiredPpc;
                //SubscriptionPpc sPpc = (SubscriptionPpc)ppc;
                //if (sPpc.ProductId != product.ProductId) // Ppc product is invalid.
                //    return ErrorCodes.IsProductIdInvalidPpc;
                //if (ppc.Currency.Trim() != MyUtility.GetCurrencyOrDefault(user.CountryCode)) // Ppc not valid in your country
                //    return ErrorCodes.IsNotValidInCountryPpc;
                //if (ppc.Amount != priceOfProduct.Amount) // Ppc is of invalid amount
                //    return ErrorCodes.IsNotValidAmountPpc;

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

                Ppc.ErrorCode validate = Ppc.ValidateSubscriptionPpc(context, ppc.SerialNumber, ppc.Pin, MyUtility.GetCurrencyOrDefault(user.CountryCode), product);

                if (validate == Ppc.ErrorCode.Success)
                {
                    if (ppc.UserId != null)
                    {
                        resp.Code = (int)Ppc.ErrorCode.PpcAlreadyUsed;
                        return resp;
                    }
                    SubscriptionPpc sPpc = (SubscriptionPpc)ppc;

                    //Check if a user has already loaded a Trial Card
                    if (sPpc.IsTrial)
                    {
                        foreach (var trans in user.Transactions)
                        {
                            if (trans is PpcPaymentTransaction)
                            {
                                var trialPpc = context.Ppcs.Count(p => p.SerialNumber == trans.Reference);
                                if (trialPpc > 0)
                                {
                                    resp.Code = (int)Ppc.ErrorCode.HasConsumedTrialPpc;
                                    return resp;
                                }
                            }
                        }
                    }


                    /***************************** 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}", "Ppc", ppc.PpcId.ToString()), String.Format("EBP-{0},", ppc.PpcId.ToString()), 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);

                            PpcPaymentTransaction earlyBirdTransaction = new PpcPaymentTransaction()
                            {
                                Currency = earlyBirdPriceOfProduct.CurrencyCode,
                                Reference = String.Format("EBP-{0}", serial.ToUpper()),
                                Amount = earlyBirdPurchase.PurchaseItems.Sum(p => p.Price),
                                Product = product,
                                Purchase = earlyBirdPurchase,
                                SubscriptionPpc = sPpc,
                                Date = registDt
                            };

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

                            IsEarlyBird = true;

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


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

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

                    purchase.PurchaseItems.Add(item);

                    PpcPaymentTransaction transaction = new PpcPaymentTransaction()
                    {
                        Currency = priceOfProduct.CurrencyCode,
                        Reference = serial.ToUpper(),
                        Amount = purchase.PurchaseItems.Sum(p => p.Price),
                        Product = product,
                        Purchase = purchase,
                        SubscriptionPpc = sPpc,
                        Date = registDt,
                        OfferingId = GlobalConfig.offeringId,
                        StatusId = GlobalConfig.Visible
                    };

                    user.Transactions.Add(transaction);
                    // purchase.PaymentTransaction.Add(transaction);
                    // product.PpcPaymentTransactions.Add(transaction);

                    item.SubscriptionProduct = (SubscriptionProduct)product;

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

                            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}", "Ppc", ppc.PpcId.ToString()), ppc.PpcId.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));
                                    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;
                                    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;

                                    PackageEntitlement currentPackage = recipient.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId);
                                    DateTime endDate = registDt;
                                    EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, product, String.Format("{0}-{1}", "Ppc", ppc.PpcId.ToString()), ppc.PpcId.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
                                    //Update recurring billing if it exists
                                    UpdateRecurringBillingIfExist(context, recipient, endDt, (Package)package.Package);
                                }
                            }
                            break;

                        case SubscriptionProductType.Episode: break;
                    }

                    //update the Ppc

                    ppc.UserId = userId;
                    ppc.UsedDate = registDt;

                    if (context.SaveChanges() > 0)
                    {
                        //Send email
                        SendConfirmationEmails(user, recipient, transaction, packageName, product, endDt, registDt, "Prepaid Card", isGift, isExtension);
                        //string emailBody = String.Format(GlobalConfig.SubscribeToProductBodyTextOnly, user.FirstName, packageName, endDt.ToString("MM/dd/yyyy hh:mm:ss tt"), transaction.TransactionId, product.Name, registDt.ToString("MM/dd/yyyy hh:mm:ss tt"), transaction.Amount.ToString("F2"), transaction.Currency, "Prepaid Card", transaction.Reference);
                        //try
                        //{
                        //    MyUtility.SendEmailViaSendGrid(user.EMail, GlobalConfig.NoReplyEmail, String.Format("You are now subscribed to {0}", packageName), emailBody, MailType.TextOnly, emailBody);
                        //}
                        //catch (Exception)
                        //{
                        //}
                        resp.Code = (int)Ppc.ErrorCode.Success;
                        resp.transaction = transaction;
                        resp.product = product;
                        resp.price = priceOfProduct;
                        resp.ProductType = subscriptionType == SubscriptionProductType.Package ? "Subscription" : "Retail";
                        return resp;
                    }
                    resp.Code = (int)Ppc.ErrorCode.EntityUpdateError;
                    return resp;
                }
                else
                {
                    resp.Code = (int)validate;
                    return resp;
                }
            }

            catch (Exception e) { Debug.WriteLine(e.InnerException); throw; }
        }
Ejemplo n.º 4
0
        public static ErrorResponse PayViaCreditCardWithRecurringBilling_ValidateOnly(IPTV2Entities context, System.Guid userId, CreditCardInfo info, int productId, SubscriptionProductType subscriptionType, System.Guid recipientUserId, int? cpId, int? freeProductId)
        {
            ErrorResponse resp = new ErrorResponse();
            try
            {
                int regularProductId = productId;
                if (freeProductId != null)
                    productId = (int)freeProductId;

                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.ValidateCreditCard(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.IsSuccess)
                        {
                            EnrollCreditCard(context, offering, user, registDt, info);
                            if (freeProductId != null)
                            {
                                var regularProduct = context.Products.FirstOrDefault(p => p.ProductId == regularProductId);
                                if (regularProduct != null)
                                    AddToRecurringBilling(context, regularProduct, offering, user, registDt, info);
                                else
                                    AddToRecurringBilling(context, product, offering, user, registDt, info);

                                PaymentHelper.logUserPromo(context, userId, GlobalConfig.Xoom2PromoId);
                            }
                            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.IsSuccess, (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.IsSuccess)
                        {
                            resp.Message = String.Format("{0}. {1}", resp.Message, response.StatusMessage);
                            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.IsSuccess)
                { //Include CCenrollment status message in case enrolment fails.                    
                    resp.CCEnrollmentStatusMessage = response.StatusMessage;
                }
                return resp;
            }

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