Esempio n. 1
0
        private static ErrorCodes PayViaPrepaidCard()
        {
            try
            {
                // setup test variables
                var context = new IPTV2Entities();
                int offeringId = 2; // TFC.tv
                var currencyCode = "USD";
                int productId = 2; // TFC.tv Premium 10 Days
                SubscriptionProductType subscriptionType = SubscriptionProductType.Package;
                System.Guid userId = new System.Guid("896CA57E-67BC-4A28-86EA-A52E5426B693"); // albin's account

                string serial = "1";
                string pin = "72656";

                var testPPC = context.Ppcs.FirstOrDefault(p => p.SerialNumber == serial);
                if (testPPC != null)
                {
                    context.Ppcs.Remove(testPPC);
                }

                var thisUser = context.Users.FirstOrDefault(u => u.UserId == userId);

                foreach (var t in thisUser.Transactions)
                {
                    if (t is PpcPaymentTransaction)
                    {
                        thisUser.Transactions.Remove(t);
                    }
                }

                context.SaveChanges();

                var newPpc = new SubscriptionPpc
                {
                    SerialNumber = serial,
                    Pin = pin,
                    Amount = 4.99m,
                    Currency = "USD",
                    Duration = 10,
                    DurationType = "d",
                    PpcProductId = 523,
                    ProductId = productId,
                    ExpirationDate = DateTime.Now.AddYears(1)
                };
                context.Ppcs.Add(newPpc);
                context.SaveChanges();
                // end setup test variables

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

                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() != currencyCode) // Ppc not valid in your country
                    return ErrorCodes.IsNotValidInCountryPpc;
                if (ppc.Amount != priceOfProduct.Amount) // Ppc is of invalid amount
                    return ErrorCodes.IsNotValidAmountPpc;

                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.Currency.Code,
                    Remarks = product.Name
                };
                purchase.PurchaseItems.Add(item);

                PpcPaymentTransaction transaction = new PpcPaymentTransaction()
                {
                    Currency = priceOfProduct.Currency.Code,
                    Reference = serial.ToUpper(),
                    Amount = purchase.PurchaseItems.Sum(p => p.Price),
                    Product = product,
                    Purchase = purchase,
                    // SubscriptionPpc = sPpc,
                    SubscriptionPpcId = ppc.PpcId,
                    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)
                //        {
                //            registDt = registDt.AddMinutes(1);
                //            // DateAndTime.DateAdd(DateInterval.Minute, 1, registDt);
                //            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 = getEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt));
                //                    endDate = currentPackage.EndDate;
                //                }
                //                else
                //                {
                //                    PackageEntitlement entitlement = new PackageEntitlement()
                //                    {
                //                        EndDate = getEntitlementEndDate(subscription.Duration, subscription.DurationType, registDt),
                //                        Package = (Package)package.Package,
                //                        OfferingId = 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 = purchase.PurchaseId.ToString()
                //                };
                //                user.EntitlementRequests.Add(request);
                //            }
                //        }
                //        break;

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

                ////update the Ppc
                //ppc.UserId = userId;
                //ppc.UsedDate = registDt;

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

            catch (Exception e) { Debug.WriteLine(e.InnerException); throw; }
        }
Esempio n. 2
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; }
        }
        public ActionResult _Subscription(FormCollection f)
        {
            Dictionary<string, object> collection = new Dictionary<string, object>();
            collection = MyUtility.SetError(ErrorCode.UnidentifiedError, String.Empty);

            var email = f["EmailAddress"];
            var pId = f["Product"];
            var payment_mode = f["PaymentMode"];
            var reference = f["Reference"];
            var amt = f["Amount"];
            var currency = f["Currency"];
            var edt = f["EndDate"];
            var OverrideDuration = MyUtility.GetCheckBoxValue(Request, "OverrideDuration");
            var isRefund = MyUtility.GetCheckBoxValue(Request, "IsRefund");
            var IncludeWalletLoad = MyUtility.GetCheckBoxValue(Request, "IncludeWalletLoad");
            var registDt = DateTime.Now;
            try
            {
                int Duration = 0;
                string DurationType = String.Empty;
                DateTime endDt = registDt;

                if (String.IsNullOrEmpty(email) || String.IsNullOrEmpty(pId) || String.IsNullOrEmpty(payment_mode) || String.IsNullOrEmpty(reference) || String.IsNullOrEmpty(amt) || String.IsNullOrEmpty(currency))
                    throw new TFCtvMissingRequiredFields();

                if (isRefund && OverrideDuration)
                    throw new TFCtvUnidentifiedError("Is this a refund & Override product's duration can't be checked at the same time.");

                currency = currency.ToUpper();
                reference = reference.ToUpper();

                var context = new IPTV2Entities();
                var user = context.Users.FirstOrDefault(item => item.EMail.ToLower() == email.ToLower());
                if (user == null)
                    throw new TFCtvUserDoesNotExist();

                decimal amount;
                bool amt_result = decimal.TryParse(amt, out amount);
                if (!amt_result)
                    throw new TFCtvUnidentifiedError("Unable to convert Amount to decimal. User input was invalid.");

                int productId;
                bool pId_result = Int32.TryParse(pId, out productId);
                if (!pId_result)
                    throw new TFCtvUnidentifiedError("Unable to convert ProductId to Int32. User input was invalid.");

                if (OverrideDuration)
                {
                    DateTime overridingEndDate;
                    bool overrideDuration_result = DateTime.TryParse(edt, out overridingEndDate);
                    if (!overrideDuration_result)
                        throw new TFCtvUnidentifiedError("Unable to convert End Date to DateTime. User input was invalid.");
                }

                var currency_count = context.Currencies.Count(item => item.Code.ToUpper() == currency);
                if (currency_count == 0)
                    throw new TFCtvUnidentifiedError("Currency does not exist on our list. User input was invalid.");
                if (currency != Global.TrialCurrency)
                    if (user.Country.CurrencyCode.ToUpper() != currency)
                        throw new TFCtvUnidentifiedError("Currency does not match current user's currency.");

                var offering = context.Offerings.Find(Global.OfferingId);
                if (user.HasPendingGomsChangeCountryTransaction(offering))
                    throw new TFCtvUnidentifiedError("Change in location transaction found. Please retry later.");

                var product = context.Products.FirstOrDefault(item => item.ProductId == productId);

                if (product == null)
                    throw new TFCtvProductDoesNotExist();

                if (product is SubscriptionProduct)
                {
                    bool insertTransaction = false;
                    if (product is PackageSubscriptionProduct)
                    {
                        var package_subscription = (PackageSubscriptionProduct)product;
                        Duration = package_subscription.Duration;
                        DurationType = package_subscription.DurationType;

                        if (isRefund) //Refunding a subscription
                            Duration *= -1;

                        //Get Package
                        var package = package_subscription.Packages.FirstOrDefault();
                        if (package == null)
                            throw new TFCtvObjectIsNull("Package");

                        PackageEntitlement entitlement = null;

                        //Check entitlement for package
                        var package_entitlement = user.PackageEntitlements.FirstOrDefault(item => item.PackageId == package.PackageId);

                        if (isRefund) //Refunding a subscription
                            registDt = package_entitlement.EndDate;

                        endDt = MyUtility.GetEntitlementEndDate(Duration, DurationType, registDt);

                        if (package_entitlement != null)
                        {
                            endDt = MyUtility.GetEntitlementEndDate(Duration, DurationType, package_entitlement.EndDate > registDt ? package_entitlement.EndDate : registDt);
                            package_entitlement.EndDate = endDt;
                        }
                        else
                        {
                            entitlement = new PackageEntitlement()
                            {
                                EndDate = endDt,
                                Package = (Package)package.Package,
                                OfferingId = Global.OfferingId,
                            };
                            user.PackageEntitlements.Add(entitlement);
                        }

                        EntitlementRequest request = CreateEntitlementRequest(registDt, endDt, package.Product, "cPanel Settlement", reference);
                        if (request != null)
                        {
                            if (entitlement != null)
                                entitlement.LatestEntitlementRequest = request;
                            else
                                user.EntitlementRequests.Add(request);
                            insertTransaction = true;
                        }
                    }
                    else if (product is ShowSubscriptionProduct)
                    {
                        var show_subscription = (ShowSubscriptionProduct)product;
                        Duration = show_subscription.Duration;
                        DurationType = show_subscription.DurationType;

                        if (isRefund) //Refuding a subscription
                            Duration *= -1;

                        //Get Show
                        var category = show_subscription.Categories.FirstOrDefault();
                        if (category == null)
                            throw new TFCtvObjectIsNull("Category");

                        ShowEntitlement entitlement = null;

                        //Check entitlement for Category/Show
                        var show_entitlement = user.ShowEntitlements.FirstOrDefault(item => item.CategoryId == category.CategoryId);

                        if (isRefund) //Refunding a subscription
                            registDt = show_entitlement.EndDate;

                        endDt = MyUtility.GetEntitlementEndDate(Duration, DurationType, registDt);

                        if (show_entitlement != null)
                        {
                            endDt = MyUtility.GetEntitlementEndDate(Duration, DurationType, show_entitlement.EndDate > registDt ? show_entitlement.EndDate : registDt);
                            show_entitlement.EndDate = endDt;
                        }
                        else
                        {
                            entitlement = new ShowEntitlement()
                            {
                                EndDate = endDt,
                                Show = category.Show,
                                OfferingId = Global.OfferingId,
                            };
                            user.ShowEntitlements.Add(entitlement);
                        }

                        EntitlementRequest request = CreateEntitlementRequest(registDt, endDt, category.Product, "cPanel Settlement", reference);
                        if (request != null)
                        {
                            if (entitlement != null)
                                entitlement.LatestEntitlementRequest = request;
                            else
                                user.EntitlementRequests.Add(request);
                            insertTransaction = true;
                        }
                    }
                    else if (product is EpisodeSubscriptionProduct)
                    {
                        var episode_subscription = (EpisodeSubscriptionProduct)product;
                        Duration = episode_subscription.Duration;
                        DurationType = episode_subscription.DurationType;

                        if (isRefund) //Refuding a subscription
                            Duration *= -1;

                        //Get Episode
                        var episode = episode_subscription.Episodes.FirstOrDefault();
                        if (episode == null)
                            throw new TFCtvObjectIsNull("Episode");

                        EpisodeEntitlement entitlement = null;

                        //Check entitlement for Category/Show
                        var episode_entitlement = user.EpisodeEntitlements.FirstOrDefault(item => item.EpisodeId == episode.EpisodeId);

                        if (isRefund) //Refunding a subscription
                            registDt = episode_entitlement.EndDate;

                        endDt = MyUtility.GetEntitlementEndDate(Duration, DurationType, registDt);

                        if (episode_entitlement != null)
                        {
                            endDt = MyUtility.GetEntitlementEndDate(Duration, DurationType, episode_entitlement.EndDate > registDt ? episode_entitlement.EndDate : registDt);
                            episode_entitlement.EndDate = endDt;
                        }
                        else
                        {
                            entitlement = new EpisodeEntitlement()
                            {
                                EndDate = endDt,
                                Episode = episode.Episode,
                                OfferingId = Global.OfferingId,
                            };
                            user.EpisodeEntitlements.Add(entitlement);
                        }

                        EntitlementRequest request = CreateEntitlementRequest(registDt, endDt, episode.Product, "cPanel Settlement", reference);
                        if (request != null)
                        {
                            if (entitlement != null)
                                entitlement.LatestEntitlementRequest = request;
                            else
                                user.EntitlementRequests.Add(request);
                            insertTransaction = true;
                        }
                    }

                    //Create Purchase & Purchase Items
                    Purchase purchase = null; //CreatePurchase(registDt, "Settlement");
                    PurchaseItem purchase_item = null; //CreatePurchaseItem(user.UserId, product, amount, currency);

                    //user.Purchases.Add(purchase);
                    //user.PurchaseItems.Add(purchase_item);

                    //Insert transaction
                    if (insertTransaction)
                    {
                        switch (Convert.ToInt32(payment_mode))
                        {
                            case 1: // Prepaid Card
                                purchase = CreatePurchase(registDt, "Settlement via Prepaid Card");
                                user.Purchases.Add(purchase);
                                purchase_item = CreatePurchaseItem(user.UserId, product, amount, currency);
                                purchase.PurchaseItems.Add(purchase_item);

                                Ppc Ppc = context.Ppcs.FirstOrDefault(item => item.SerialNumber.ToUpper() == reference);
                                if (Ppc == null)
                                    throw new TFCtvObjectIsNull("Prepaid Card");
                                if (!(Ppc is SubscriptionPpc))
                                    throw new TFCtvEntityFrameworkError("Prepaid Card is not of type: Subscription.");

                                PpcPaymentTransaction pTransaction = new PpcPaymentTransaction()
                                {
                                    Currency = currency,
                                    Reference = reference,
                                    Amount = Convert.ToDecimal(amount),
                                    Product = product,
                                    Purchase = purchase,
                                    SubscriptionPpc = (SubscriptionPpc)Ppc,
                                    Date = registDt,
                                    OfferingId = Global.OfferingId
                                };
                                user.Transactions.Add(pTransaction);
                                break;
                            case 2: // E-Wallet
                                purchase = CreatePurchase(registDt, "Settlement via Wallet");
                                user.Purchases.Add(purchase);
                                purchase_item = CreatePurchaseItem(user.UserId, product, amount, currency);
                                purchase.PurchaseItems.Add(purchase_item);

                                var wallet = user.UserWallets.FirstOrDefault(item => item.IsActive == true);
                                if (IncludeWalletLoad)
                                    wallet.Balance += amount;

                                WalletPaymentTransaction wTransaction = new WalletPaymentTransaction()
                                {
                                    Currency = currency,
                                    Reference = reference,
                                    Amount = Convert.ToDecimal(amount),
                                    Date = registDt,
                                    User = user,
                                    OfferingId = Global.OfferingId
                                };
                                user.Transactions.Add(wTransaction);
                                wallet.WalletPaymentTransactions.Add(wTransaction);
                                break;
                            case 3: // Credit Card
                                purchase = CreatePurchase(registDt, "Settlement via Credit Card");
                                user.Purchases.Add(purchase);
                                purchase_item = CreatePurchaseItem(user.UserId, product, Convert.ToDecimal(amount), currency);
                                purchase.PurchaseItems.Add(purchase_item);

                                CreditCardPaymentTransaction cTransaction = new CreditCardPaymentTransaction()
                                {
                                    Amount = Convert.ToDecimal(amount),
                                    Currency = currency,
                                    Reference = reference,
                                    Date = registDt,
                                    Purchase = purchase,
                                    OfferingId = Global.OfferingId
                                };
                                user.Transactions.Add(cTransaction);
                                break;
                            case 4: // Paypal
                                purchase = CreatePurchase(registDt, "Settlement via Paypal");
                                user.Purchases.Add(purchase);
                                purchase_item = CreatePurchaseItem(user.UserId, product, Convert.ToDecimal(amount), currency);
                                purchase.PurchaseItems.Add(purchase_item);

                                PaypalPaymentTransaction ppTransaction = new PaypalPaymentTransaction()
                                {
                                    Currency = currency,
                                    Reference = reference,
                                    Amount = Convert.ToDecimal(amount),
                                    User = user,
                                    Date = registDt,
                                    OfferingId = Global.OfferingId
                                };
                                user.Transactions.Add(ppTransaction);
                                break;
                            case 5: // Migration
                                MigrationTransaction mTransaction = new MigrationTransaction()
                                {
                                };
                                user.Transactions.Add(mTransaction);
                                break;
                            default: break;
                        }

                        if (context.SaveChanges() > 0)
                        {
                            collection = MyUtility.SetError(ErrorCode.Success, "You have successfully settled a complaint.");
                            // Success
                        }
                    }
                }
            }
            catch (TFCtvException e)
            {
                collection = MyUtility.SetError(e.StatusCode, e.StatusMessage);
            }
            catch (Exception e)
            {
                collection = MyUtility.SetError(ErrorCode.UnidentifiedError, e.Message);
            }

            return Content(MyUtility.BuildJSON(collection), "application/json");
        }