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; } }
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"); }