Пример #1
0
        static public void CreditCardReload()
        {
            var context = new IPTV2_Model.IPTV2Entities();
            var gomsService = new GomsTfcTv();

            var user = context.Users.FirstOrDefault(u => u.EMail == "*****@*****.**");
            if (user != null)
            {
                // create transaction
                var transaction = new IPTV2_Model.CreditCardReloadTransaction
                    {
                        Amount = 10,
                        Currency = user.Country.CurrencyCode,
                        Date = DateTime.Now,
                    };

                var resp = gomsService.ReloadWalletViaCreditCard(context, user.UserId, transaction, GetCreditCard());
                if (resp.IsSuccess)
                {
                    // YEY
                }

            }

        }
Пример #2
0
 public static void ProcessAllGomsPendingTransactions()
 {
     var context = new IPTV2Entities();
     var service = new GomsTfcTv();
     var offering = context.Offerings.Find(2);
     service.ProcessAllPendingTransactionsInGoms(context, offering);
 }
Пример #3
0
        public static void TestRegisterUser(System.Guid userId)
        {
            var context = new IPTV2_Model.IPTV2Entities();
            var service = new GomsTfcTv();
            // System.Guid userId = new System.Guid("D9720726-217C-4431-AEAB-468E818132A8");

            var user = context.Users.Find(userId);
            if (user == null)
            {
                var country = context.Countries.Find("US");
                user = new IPTV2_Model.User
                {
                    UserId = userId,
                    EMail = userId.ToString().Substring(10) + "@tfc.tv",
                    FirstName = userId.ToString().Substring(10),
                    LastName = userId.ToString().Substring(10),
                    Password = userId.ToString().Substring(10),
                    RegistrationDate = DateTime.Now,
                    LastUpdated = DateTime.Now,
                    Country = country,
                    State = user.State,
                    City = user.City

                };
                context.Users.Add(user);
                context.SaveChanges();
            }

            var resp = service.RegisterUser(context, userId);
            Assert.Equal(resp.IsSuccess, true);
        }
Пример #4
0
        public override void Run()
        {

            // This is a sample worker implementation. Replace with your logic.
            Trace.WriteLine("$projectname$ entry point called", "Information");

            int waitDuration = Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("LoopWaitDurationInSeconds"));
            int fillCacheDurationInMinutes = Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("FillCacheDurationInMinutes"));
            bool fillCache = Convert.ToBoolean(RoleEnvironment.GetConfigurationSettingValue("FillCache"));
            while (true)
            {
                try
                {
                    Thread.Sleep(TimeSpan.FromSeconds(waitDuration));
                    int offeringId = 2;
                    var service = new GomsTfcTv();
                    var context = new IPTV2Entities();
                    var offering = context.Offerings.Find(offeringId);
                    Trace.WriteLine("Process start.");
                    // Update Forex
                    // service.GetExchangeRates(context, "USD");
                    // Process Transactions
                    // service.ProcessAllPendingTransactionsInGoms(context, offering);
                    Trace.WriteLine("Process finish.");
                }
                catch (Exception ex)
                {
                    Trace.TraceError("fail in Run", ex);
                }
            }
        }
Пример #5
0
        public static void GetExchangeRates()
        {
            var context = new IPTV2_Model.IPTV2Entities();
            var gomsService = new GomsTfcTv();

            gomsService.GetExchangeRates(context, "USD");

        }
Пример #6
0
        public static void ProcessAllGomsPendingTransactionsForUser()
        {

            var context = new IPTV2Entities();
            var service = new GomsTfcTv();
            var offering = context.Offerings.Find(2);
            var user = context.Users.FirstOrDefault(u => u.EMail == "*****@*****.**");            
            service.ProcessAllPendingTransactionsInGoms(context, offering, user);
        }
Пример #7
0
        public static void PpcReload()
        {
            var context = new IPTV2Entities();
            var service = new GomsTfcTv();

            // get transaction
            // List<PpcReloadTransaction> ts = context.Transactions.Where(t => t is PpcReloadTransaction && t.GomsTransactionId == null).ToList();
            var trans = context.Transactions.OfType<PpcReloadTransaction>().FirstOrDefault(t => t.GomsTransactionId == null && t.ReloadPpc.PpcType.GomsSubsidiaryId == t.User.GomsSubsidiaryId);
            var resp = service.ReloadWallet(context, trans.User.UserId, trans.TransactionId);
        }
Пример #8
0
        static public void CreditCardPurchase()
        {
            var context = new IPTV2Entities();
            var gomsService = new GomsTfcTv();

            var user = context.Users.FirstOrDefault(u => u.EMail == "*****@*****.**");
            if (user != null)
            {

                var product = (SubscriptionProduct)context.Products.Find(1);
                var currency = user.Country.Currency;
                var productPrice = product.ProductPrices.FirstOrDefault(pp => pp.CurrencyCode == user.Country.CurrencyCode);

                var amount = productPrice.Amount;

                // create purchase item
                var purchaseItem = new PurchaseItem
                {
                    Currency = currency.Code,
                    SubscriptionProduct = product,
                    Price = productPrice.Amount,
                    User = user,
                    RecipientUserId = user.UserId
                };

                // create purchase
                var purchase = new Purchase
                {
                    Date = DateTime.Now,
                    User = user,
                    PurchaseItems = new List<PurchaseItem> { purchaseItem },                     
                };

                // create transaction
                var transaction = new CreditCardPaymentTransaction
                {
                      Date = DateTime.Now,
                      Purchase = purchase,
                      Currency = currency.Code, 
                      Amount = amount,                         
                };

                var resp = gomsService.CreateOrderViaCreditCard(context, user.UserId, transaction, GetCreditCard());
                if (resp.IsSuccess)
                {
                    // YEY
                }

            }

        }
Пример #9
0
 private void Send()
 {
     try
     {
         Console.WriteLine("Updating Forex Exchange Rate...");
         var context = new IPTV2Entities();
         var service = new GomsTfcTv();
         service.GetExchangeRates(context, "USD");
         Console.WriteLine("Updating of Forex Exchange Rate Complete!");
     }
     catch (Exception e)
     {
         Console.WriteLine("Outer Exception: " + e.Message);
     }
 }
Пример #10
0
        public static void CreateCase()
        {
            var context = new IPTV2Entities();
            var gomsService = new GomsTfcTv();

            // var email = "*****@*****.**";
            var email = "*****@*****.**";
            var user = context.Users.FirstOrDefault(u => u.EMail == email);
            var agent = (GomsCaseAgent)context.GomsReferences.FirstOrDefault(r => r is GomsCaseAgent);
            var caseIssueType = (GomsCaseIssueType)context.GomsReferences.FirstOrDefault(r => r is GomsCaseIssueType);
            var caseSubIssueType = (GomsCaseSubIssueType)context.GomsReferences.FirstOrDefault(r => r is GomsCaseSubIssueType);
            var resp = gomsService.CreateSupportCase(context, user.UserId, "test case", "hope this works, please help...", agent, caseIssueType, caseSubIssueType);


        }
Пример #11
0
        public static void TestRegisterAllUsers()
        {
            var context = new IPTV2_Model.IPTV2Entities();
            var service = new GomsTfcTv();

            var users = context.Users.Where(u => u.GomsCustomerId == null);
            foreach (var user in users)
            {
                var anotherContext = new IPTV2_Model.IPTV2Entities();
                var resp = service.RegisterUser(anotherContext, user.UserId);
                if (!resp.IsSuccess)
                {
                    Console.WriteLine(user.FirstName + " " + user.LastName + " - " + resp.StatusMessage);
                }
            }
        }
Пример #12
0
        public ActionResult _ResendTVEActivationCode(FormCollection fc)
        {
            Dictionary<string, object> collection = new Dictionary<string, object>();
            ErrorCodes errorCode = ErrorCodes.UnknownError;
            string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError);
            collection = MyUtility.setError(errorCode, errorMessage);
            try
            {
                if (String.IsNullOrEmpty(fc["MacAddressOrSmartCard"]) && String.IsNullOrEmpty(fc["AccountNumber"]))
                {
                    collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "Please fill up the required fields.");
                    return Content(MyUtility.buildJson(collection), "application/json");
                }

                var context = new IPTV2Entities();
                User user;
                if (MyUtility.isUserLoggedIn())
                {
                    var userId = new Guid(User.Identity.Name);
                    user = context.Users.FirstOrDefault(u => u.UserId == userId);
                }
                else
                {
                    var userId = (Guid)TempData["tempUid"];
                    TempData["tempUserId"] = userId; // REASSIGN
                    TempData["tempUid"] = userId; // REASSIGN
                    user = context.Users.FirstOrDefault(u => u.UserId == userId);
                }

                if (user != null)
                {
                    var gomsService = new GomsTfcTv();
                    var response = gomsService.ResendTVEActivationCode(user.EMail, fc["MacAddressOrSmartCard"], fc["AccountNumber"], user.LastName);
                    if (response.IsSuccess)
                    {
                        collection = MyUtility.setError(ErrorCodes.Success, String.Empty);
                        collection.Add("href", GlobalConfig.RegistrationCompleteTVE);
                    }
                    else
                        collection = MyUtility.setError(ErrorCodes.UnknownError, response.StatusMessage);
                }
                else
                    collection = MyUtility.setError(ErrorCodes.UserDoesNotExist, "User does not exist.");
            }
            catch (Exception e) { collection = MyUtility.setError(ErrorCodes.UnknownError, e.Message); }
            return Content(MyUtility.buildJson(collection), "application/json");
        }
Пример #13
0
        public ActionResult _ClaimTVE(FormCollection fc, string EmailAddress, string MacAddressOrSmartCard, string AccountNumber, string ActivationCode)
        {
            Dictionary<string, object> collection = new Dictionary<string, object>();
            ErrorCodes errorCode = ErrorCodes.UnknownError;
            string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError);
            collection = MyUtility.setError(errorCode, errorMessage);

            try
            {
                DateTime registDt = DateTime.Now;

                var context = new IPTV2Entities();

                var userId = new Guid("E21D87F3-5940-451A-B7EE-ADA4F3CEC234");

                if (!String.IsNullOrEmpty(EmailAddress))
                {
                    var user = context.Users.FirstOrDefault(u => String.Compare(u.EMail, EmailAddress, true) == 0);
                    if (user != null)
                    {
                        userId = user.UserId;
                        string CurrencyCode = GlobalConfig.DefaultCurrency;
                        Country country = context.Countries.FirstOrDefault(c => c.Code == user.CountryCode);
                        if (country != null)
                        {
                            Currency currency = context.Currencies.FirstOrDefault(c => c.Code == country.CurrencyCode);
                            if (currency != null) CurrencyCode = currency.Code;
                        }

                        var transaction = new TfcEverywhereTransaction()
                        {
                            Amount = 0,
                            Date = DateTime.Now,
                            Currency = CurrencyCode,
                            OfferingId = GlobalConfig.offeringId,
                            StatusId = GlobalConfig.Visible,
                            Reference = "TFC Everywhere - Activate"
                        };

                        //string MacAddressOrSmartCard = "00172F0108FC";
                        //string AccountNumber = "US-000179857";
                        //string ActivationCode = "5S3UDP";
                        var gomsService = new GomsTfcTv();
                        var response = gomsService.ClaimTVEverywhere(context, userId, transaction, MacAddressOrSmartCard, AccountNumber, ActivationCode);
                        if (response.IsSuccess)
                        {

                            //ADD Entitlement
                            AddTfcEverywhereEntitlement(context, response.TFCTVSubItemId, response.ExpiryDate, response.TVEServiceId, user);

                            transaction.GomsTFCEverywhereEndDate = Convert.ToDateTime(response.ExpiryDate);
                            transaction.GomsTFCEverywhereStartDate = registDt;
                            user.Transactions.Add(transaction);
                            user.IsTVEverywhere = true;
                            if (context.SaveChanges() > 0)
                                collection = MyUtility.setError(ErrorCodes.Success, "Claimed TVE");
                        }
                        else
                            collection = MyUtility.setError(ErrorCodes.UnknownError, response.StatusMessage);
                    }

                }



            }
            catch (Exception e) { collection = MyUtility.setError(ErrorCodes.UserDoesNotExist, e.Message); }
            return Content(MyUtility.buildJson(collection), "application/json");

        }
Пример #14
0
        public ActionResult _CreateSmartPit(FormCollection fc)
        {
            Dictionary<string, object> collection = new Dictionary<string, object>();
            ErrorCodes errorCode = ErrorCodes.UnknownError;
            string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError);
            collection = MyUtility.setError(errorCode, errorMessage);
            if (!MyUtility.isUserLoggedIn())
            {
                collection = MyUtility.setError(ErrorCodes.NotAuthenticated);
                return Content(MyUtility.buildJson(collection), "application/json");
            }

            var context = new IPTV2Entities();
            var userId = new Guid(User.Identity.Name);

            User user = context.Users.FirstOrDefault(u => u.UserId == userId);
            if (user == null)
            {
                collection = MyUtility.setError(ErrorCodes.UnknownError, "User does not exist");
                return Content(MyUtility.buildJson(collection), "application/json");
            }

            if (user.Country == null)
            {
                collection = MyUtility.setError(ErrorCodes.UnknownError, "User's country is missing.");
                return Content(MyUtility.buildJson(collection), "application/json");
            }
            if (user.Country.Code != GlobalConfig.JapanCountryCode)
            {
                collection = MyUtility.setError(ErrorCodes.UnknownError, "User is not authorized.");
                return Content(MyUtility.buildJson(collection), "application/json");
            }
            if (!String.IsNullOrEmpty(user.SmartPitId))
            {
                collection = MyUtility.setError(ErrorCodes.UnknownError, "User is already enrolled.");
                return Content(MyUtility.buildJson(collection), "application/json");
            }

            DateTime registDt = DateTime.Now;
            var smartpitcardno = String.IsNullOrEmpty(fc["SmartPitCardNumber"]) ? String.Empty : fc["SmartPitCardNumber"];

            var service = new GomsTfcTv();
            try
            {
                var response = service.EnrollSmartPit(context, userId, smartpitcardno);

                if (response.IsSuccess)
                {
                    user.SmartPitId = response.SmartPitCardNo;
                    user.SmartPitRegistrationDate = registDt;
                    if (context.SaveChanges() > 0)
                    {
                        collection = MyUtility.setError(ErrorCodes.Success, response.StatusMessage);
                        collection.Add("spcno", response.SmartPitCardNo);
                    }
                    else
                        collection = MyUtility.setError(ErrorCodes.EntityUpdateError, "Unable to process your request. Please try again later.");
                }
                else
                    collection = MyUtility.setError(ErrorCodes.EntityUpdateError, response.StatusMessage);
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                collection = MyUtility.setError(ErrorCodes.UnknownError, String.Format("{0} {1}", e.Message, e.InnerException == null ? String.Empty : e.InnerException.Message));
            }

            return Content(MyUtility.buildJson(collection), "application/json");
        }
Пример #15
0
 private void SetGomsServiceVariables(GomsTfcTv gomsService)
 {
     gomsService.UserId = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvUserId");
     gomsService.Password = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvPassword");
     gomsService.ServiceUserId = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServiceUserId");
     gomsService.ServicePassword = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServicePassword");
     gomsService.ServiceUrl = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServiceUrl");
     gomsService.ServiceId = Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServiceId"));
     gomsService.GSapikey = RoleEnvironment.GetConfigurationSettingValue("GSapikey");
     gomsService.GSsecretkey = RoleEnvironment.GetConfigurationSettingValue("GSsecretkey");
 }
Пример #16
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;
            }
        }
Пример #17
0
        public JsonResult ResendTVEActivationCode(FormCollection fc)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty
            };

            string url = Url.Action("Index", "Home").ToString();
            try
            {
                if (String.IsNullOrEmpty(fc["smartCardNum"]) && String.IsNullOrEmpty(fc["cusAccount"]))
                {
                    ReturnCode.StatusMessage = "Please fill up the required fields.";
                }
                else
                {
                    if (!User.Identity.IsAuthenticated)
                    {
                        ReturnCode.StatusMessage = "Your session has expired. Please login again.";
                    }
                    else
                    {
                        var context = new IPTV2Entities();
                        var UserId = new Guid(User.Identity.Name);
                        User user = context.Users.FirstOrDefault(u => u.UserId == UserId);

                        if (user != null)
                        {
                            var gomsService = new GomsTfcTv();
                            var response = gomsService.ResendTVEActivationCode(user.EMail, fc["smartCardNum"], fc["cusAccount"], user.LastName);
                            if (response.IsSuccess)
                            {
                                ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                ReturnCode.StatusMessage = response.StatusMessage;
                            }
                            else
                                ReturnCode.StatusMessage = response.StatusMessage;
                        }
                        else
                            ReturnCode.StatusMessage = "User does not exist.";
                    }
                }
            }
            catch (Exception e) { ReturnCode.StatusMessage = e.Message; }
            return Json(ReturnCode, JsonRequestBehavior.AllowGet);
        }
Пример #18
0
        private void UpdateRecurringBillingViaEditProfile(IPTV2Entities context, User user, string list, bool? enable)
        {
            try
            {
                DateTime registDt = DateTime.Now;
                var rb_list = list.Split(',');

                var gomsService = new GomsTfcTv();

                if (rb_list.Count() > 0)
                {
                    foreach (var item in rb_list)
                    {
                        if (!String.IsNullOrEmpty(item))
                        {
                            var name = item;
                            if (MyUtility.isUserLoggedIn())
                            {
                                bool RecurringStatus = false;
                                if (enable != null)
                                    RecurringStatus = (bool)enable;

                                int RecurringBillingId = 0;
                                try { RecurringBillingId = Convert.ToInt32(name.Substring(2)); }
                                catch (Exception e) { MyUtility.LogException(e); }

                                if (user != null)
                                {
                                    var CurrencyCode = GlobalConfig.DefaultCurrency;
                                    try { CurrencyCode = user.Country.CurrencyCode; }
                                    catch (Exception) { }
                                    string cancellation_remarks = String.Empty;
                                    string reference = String.Empty;
                                    bool serviceUpdateSuccess = false;
                                    var billing = user.RecurringBillings.FirstOrDefault(r => r.RecurringBillingId == RecurringBillingId && r.StatusId != 2);
                                    if (billing != null)
                                    {
                                        //Check first if there is a same package with recurring turned on
                                        if (user.RecurringBillings.Count(r => r.PackageId == billing.PackageId && r.StatusId == GlobalConfig.Visible && r.RecurringBillingId != billing.RecurringBillingId) > 0)
                                        {
                                            //there is same package with recurring enabled.                                            
                                        }
                                        else
                                        {
                                            if (billing is PaypalRecurringBilling)
                                            {
                                                try
                                                {
                                                    var paypalrbilling = (PaypalRecurringBilling)billing;

                                                    billing.StatusId = RecurringStatus ? 1 : 0;
                                                    billing.UpdatedOn = registDt;
                                                    if (registDt.Date > billing.NextRun && RecurringStatus)
                                                        billing.NextRun = registDt.AddDays(1).Date;
                                                    if (!RecurringStatus)
                                                    {
                                                        try
                                                        {
                                                            if (PaymentHelper.CancelPaypalRecurring(paypalrbilling.SubscriberId))
                                                            {
                                                                reference = String.Format("PayPal Payment Renewal {0} cancelled", billing.RecurringBillingId);
                                                                String.Format("{0} - PayPal Recurring Billing Id cancelled", billing.RecurringBillingId);
                                                                serviceUpdateSuccess = true;
                                                            }
                                                        }
                                                        catch (Exception) { }
                                                    }
                                                }
                                                catch (Exception) { }
                                            }
                                            else
                                            {
                                                if (RecurringStatus)
                                                {
                                                    billing.StatusId = RecurringStatus ? 1 : 0;
                                                    billing.UpdatedOn = registDt;
                                                    if (registDt.Date > billing.NextRun && RecurringStatus)
                                                        billing.NextRun = registDt.AddDays(1).Date;
                                                }
                                                else //if (!RecurringStatus)
                                                {
                                                    try
                                                    {
                                                        var result = gomsService.CancelRecurringPayment(user, billing.Product);
                                                        if (result.IsSuccess)
                                                        {
                                                            billing.StatusId = RecurringStatus ? 1 : 0;
                                                            billing.UpdatedOn = registDt;
                                                            reference = String.Format("Credit Card Payment Renewal {0} cancelled", billing.RecurringBillingId);
                                                            cancellation_remarks = String.Format("{0} - Credit Card Recurring Billing Id cancelled", billing.RecurringBillingId);
                                                            serviceUpdateSuccess = true;
                                                        }
                                                        else
                                                            throw new Exception(result.StatusMessage);
                                                    }
                                                    catch (Exception e) { MyUtility.LogException(e); }
                                                }
                                            }

                                            if (!RecurringStatus && serviceUpdateSuccess)
                                            {
                                                var transaction = new CancellationTransaction()
                                                {
                                                    Amount = 0,
                                                    Currency = CurrencyCode,
                                                    OfferingId = GlobalConfig.offeringId,
                                                    CancellationRemarks = cancellation_remarks,
                                                    OriginalTransactionId = -1,
                                                    GomsTransactionId = -1000,
                                                    Date = registDt,
                                                    Reference = reference,
                                                    StatusId = GlobalConfig.Visible
                                                };
                                                user.Transactions.Add(transaction);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e) { MyUtility.LogException(e); }
        }
Пример #19
0
        private ErrorResponse CreateGomsTicket(string subject, string message)
        {
            ErrorResponse response;
            if (!MyUtility.isUserLoggedIn())
                return new ErrorResponse() { Code = (int)ErrorCodes.NotAuthenticated, Message = "User is not logged in." };

            var context = new IPTV2Entities();

            var user = context.Users.FirstOrDefault(u => u.UserId == new System.Guid(HttpContext.User.Identity.Name));
            if (user != null)
            {
                var gomsService = new GomsTfcTv();
                var agent = (GomsCaseAgent)context.GomsReferences.FirstOrDefault(r => r is GomsCaseAgent);
                var caseIssueType = (GomsCaseIssueType)context.GomsReferences.FirstOrDefault(r => r is GomsCaseIssueType);
                var caseSubIssueType = (GomsCaseSubIssueType)context.GomsReferences.FirstOrDefault(r => r is GomsCaseSubIssueType);
                try
                {
                    var resp = gomsService.CreateSupportCase(context, user.UserId, subject, message, agent, caseIssueType, caseSubIssueType);
                    response = new ErrorResponse() { Code = Convert.ToInt32(resp.StatusCode), Message = resp.StatusMessage };
                    response.Message = response.Code == 0 ? "You have successfully submitted a ticket." : resp.StatusMessage;
                }
                catch (Exception e)
                {
                    response = new ErrorResponse() { Code = (int)ErrorCodes.UnknownError, Message = e.Message };
                }
            }
            else
                response = new ErrorResponse() { Code = (int)ErrorCodes.UserDoesNotExist, Message = "User does not exist." };
            return response;
        }
Пример #20
0
 public static void ProcessUser(Object stateInfo)
 {
     try
     {
         UserForProcessing user = (UserForProcessing)stateInfo;
         using (var context = new IPTV2Entities())
         {
             var thisUser = context.Users.Find(user.UserId);
             var offering = context.Offerings.Find(user.OfferingId);
             var service = new GomsTfcTv();
             service.ProcessAllPendingTransactionsInGoms(context, offering, thisUser);
             //var rand = new Random();
             //Thread.Sleep(rand.Next(2000));
             //Console.WriteLine("Processing for user {0}-{1}", user.UserId, System.DateTime.Now);
             user.Status = 1;
         }
     }
     catch (Exception) { throw; }
 }
Пример #21
0
        static void Main(string[] args)
        {
            Console.WriteLine("Startup...");
            int waitDuration = 10;
            int maxThreads = Convert.ToInt32(ConfigurationManager.AppSettings["MaxThreads"]); ;
            bool loopThru = true;
            bool isSingleTransaction = false;

            //Create job to update exchange rate (daily)

            if (args.Length == 0)
            {
                ISchedulerFactory schedFact = new StdSchedulerFactory();
                sched = schedFact.GetScheduler();
                sched.Start();
                CreateScheduledJob();
            }

            while (loopThru)
            {
                try
                {
                    Console.WriteLine("Waiting...");
                    Thread.Sleep(TimeSpan.FromSeconds(waitDuration));
                    int offeringId = 2;
                    Console.WriteLine("Initializing Iptv2Context service...");
                    using (var context = new IPTV2Entities())
                    {
                        var offering = context.Offerings.Find(offeringId);
                        Console.WriteLine("Initializing GomsTfcTv service...");
                        var service = new GomsTfcTv();
                        Console.WriteLine("Process start.");
                        // Update Forex
                        Console.WriteLine("Updating FOREX...");
                        service.GetExchangeRates(context, "USD");
                        Console.WriteLine("Finished FOREX...");


                        // Process Single transactionsint check;                        
                        if (args.Length > 0)
                        {
                            try
                            {
                                // Process Single transactions
                                service.ProcessSinglePendingTransactionInGoms(context, offering, Convert.ToInt32(args[0]));
                                isSingleTransaction = true;
                            }
                            catch (Exception)
                            {
                                loopThru = false;
                            }
                        }
                        else
                            DoProcessByIncrement(offeringId, maxThreads);
                    }
                    Console.WriteLine("Process finish.");
                    if (isSingleTransaction)
                        Environment.Exit(0);
                    //DoProcess(offeringId, maxThreads);
                    //DoProcessByIncrement(offeringId, maxThreads);
                    // Process Transactions
                    // service.ProcessAllPendingTransactionsInGoms(context, offering);
                    // Process Single transactions
                    // service.ProcessSinglePendingTransactionInGoms(context, offering, Convert.ToInt32(args[0]));
                }
                catch (Exception ex)
                {
                    Console.WriteLine("error: " + ex.Message);
                    Trace.TraceError("fail in Run", ex);
                }
            }
        }
Пример #22
0
        private void Send()
        {
            //Trace.WriteLine(context.Database.Connection.ConnectionString);
            try
            {
                int successfullyProcessed = 0;
                int failedProcessed = 0;

                var failedEmails = new StringBuilder();
                var emailBody = new StringBuilder();
                List<Int32> listOfFailedRecurringBillingId = new List<Int32>();

                emailBody.AppendLine(@"Recurring Billing Consolidated Report\r\n\r\n");
                emailBody.AppendLine(String.Format(@"Current date: {0}\r\n\r\n\r\n", registDt));

                Console.WriteLine("Fetching users for recurring billing...");

                DateTime dtRecur = registDt.Date.AddDays(addDays);
                var recurringBillings = GetUsersEligibleForRenewal(dtRecur);
                Console.WriteLine(String.Format("Total users eligible for renewal: {0}", recurringBillings.Count()));

                if (recurringBillings != null)
                {
                    if (recurringBillings.Count > 0)
                    {

                        using (var context = new IPTV2Entities())
                        {
                            var gomsService = new GomsTfcTv();
                            try
                            {
                                gomsService.TestConnect();
                                Console.WriteLine("Test Connect success");
                            }
                            catch (Exception) { Console.WriteLine("Test Connect failed."); }

                            foreach (var i in recurringBillings)
                            {
                                using (var context3 = new IPTV2Entities())
                                {
                                    var user = context3.Users.FirstOrDefault(u => u.UserId == i.UserId);
                                    var recurringBilling = context3.RecurringBillings.Find(i.RecurringBillingId);
                                    var product = context3.Products.Find(i.ProductId);

                                    string productName = String.Empty;

                                    Console.WriteLine(String.Format("Processing user {0} with productId {1}, endDate {2}", user.EMail, product.Description, recurringBilling.EndDate));
                                    try
                                    {
                                        ProductPrice priceOfProduct = context3.ProductPrices.FirstOrDefault(p => p.CurrencyCode == user.Country.CurrencyCode && p.ProductId == product.ProductId);
                                        if (priceOfProduct == null)
                                            priceOfProduct = context3.ProductPrices.FirstOrDefault(p => p.CurrencyCode == DefaultCurrencyCode && p.ProductId == product.ProductId);

                                        Purchase purchase = CreatePurchase(registDt, "Payment via Credit Card");
                                        user.Purchases.Add(purchase);
                                        PurchaseItem item = CreatePurchaseItem(user.UserId, product, priceOfProduct);
                                        purchase.PurchaseItems.Add(item);

                                        var cardType = user.CreditCards.LastOrDefault(c => c.StatusId == 1).CardType;
                                        CreditCardPaymentTransaction transaction = new CreditCardPaymentTransaction()
                                        {
                                            Amount = priceOfProduct.Amount,
                                            Currency = priceOfProduct.CurrencyCode,
                                            Reference = cardType.ToUpper(),
                                            Date = registDt,
                                            Purchase = purchase,
                                            OfferingId = offeringId,
                                            StatusId = 1
                                        };
                                        var response = gomsService.CreateOrderViaRecurringPayment(context3, user.UserId, transaction);
                                        if (response.IsSuccess)
                                        {
                                            DateTime endDate = registDt;
                                            item.SubscriptionProduct = (SubscriptionProduct)product;
                                            if (item.SubscriptionProduct is PackageSubscriptionProduct)
                                            {
                                                PackageSubscriptionProduct subscription = (PackageSubscriptionProduct)product;

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

                                                    PackageEntitlement currentPackage = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId);

                                                    EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, product, String.Format("{0}-{1}", "CC", cardType), response.TransactionId.ToString(), registDt);
                                                    if (currentPackage != null)
                                                    {
                                                        request.StartDate = currentPackage.EndDate;
                                                        currentPackage.EndDate = GetEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt));

                                                        endDate = currentPackage.EndDate;
                                                        currentPackage.LatestEntitlementRequest = request;
                                                        request.EndDate = endDate;
                                                    }
                                                    else
                                                    {
                                                        PackageEntitlement entitlement = CreatePackageEntitlement(request, subscription, package, registDt);
                                                        request.EndDate = entitlement.EndDate;
                                                        user.PackageEntitlements.Add(entitlement);
                                                    }
                                                    user.EntitlementRequests.Add(request);
                                                    item.EntitlementRequest = request; //UPDATED: November 22, 2012                                        
                                                }

                                                recurringBilling.EndDate = endDate;
                                                recurringBilling.NextRun = endDate.AddDays(-3).Date;
                                                recurringBilling.UpdatedOn = registDt;
                                                recurringBilling.GomsRemarks = null;
                                                recurringBilling.NumberOfAttempts = 0;

                                            }
                                            Console.WriteLine(user.EMail + ": renewal process complete!");
                                            if (context3.SaveChanges() > 0)
                                            {
                                                successfullyProcessed += 1;
                                                Console.WriteLine("Saving changes...");
                                            }


                                            //Send email to user;
                                            try { SendConfirmationEmails(user, user, transaction, productName, product, endDate, registDt, "Credit Card", (DateTime)endDate.AddDays(-4).Date); }
                                            catch (Exception e) { recurringBilling.GomsRemarks = e.Message; }

                                        }
                                        else
                                        {
                                            using (var context2 = new IPTV2Entities())
                                            {
                                                var failedRecurring = context2.RecurringBillings.FirstOrDefault(r => r.RecurringBillingId == recurringBilling.RecurringBillingId);
                                                if (failedRecurring != null)
                                                {
                                                    failedRecurring.GomsRemarks = response.StatusMessage;
                                                    failedRecurring.NumberOfAttempts += 1;
                                                    listOfFailedRecurringBillingId.Add(failedRecurring.RecurringBillingId);
                                                    if (failedRecurring.NumberOfAttempts == 2)
                                                    {
                                                        //Send failure email
                                                        try { SendConfirmationEmails(user, user, transaction, productName, product, registDt, registDt, "Credit Card", registDt, response.StatusMessage); }
                                                        catch (Exception e) { failedRecurring.GomsRemarks = e.Message; }
                                                    }

                                                    string failedSpecificsCopy = String.Format("RBId: {0}\r\n\r\nEmail: {1}\r\n\r\nProduct: {2}\r\n\r\nError: {3}\r\n\r\n", failedRecurring.RecurringBillingId, user.EMail, product.Description, response.StatusMessage);
                                                    failedEmails.AppendLine(failedSpecificsCopy);
                                                    failedEmails.AppendLine("--------------------------------------------------\r\n\r\n");
                                                    failedProcessed += 1;

                                                    if (context2.SaveChanges() > 0)
                                                        Console.WriteLine("Saving error...");
                                                }
                                            }
                                            throw new Exception(user.EMail + ": " + response.StatusMessage);
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine("Inner Exception: " + e.Message);
                                    }
                                }

                            }
                            //if (context.SaveChanges() > 0)
                            //{
                            //    Console.WriteLine("Saving changes...");
                            Console.WriteLine("Processing of eligible users for recurring billing has completed");
                            //}

                            //Finish the copy of the email
                            emailBody.AppendLine(String.Format(@"Total number of successful transactions: {0}\r\n\r\n", successfullyProcessed));
                            emailBody.AppendLine(String.Format(@"Total number of failed transactions (GOMS): {0}\r\n\r\n\r\n", failedProcessed));

                            if (failedEmails.Length > 0)
                            {
                                emailBody.AppendLine(@"Specifics can be found below\r\n\r\n\r\n");
                                emailBody.AppendLine(String.Format(@"{0}\r\n\r\n\r\n", failedEmails.ToString()));
                            }
                            emailBody.AppendLine("=================================================================\r\n\r\n\r\n");

                            //Get total numbers of recurring billing that have reached processing threshold
                            //var reachedThreshold = context.RecurringBillings.Where(r => r.StatusId == 1 && r.NumberOfAttempts == 3);
                            //if (reachedThreshold != null)
                            //{
                            //    emailBody.AppendLine(String.Format(@"Total number of failed transactions (MAX ATTEMPT): {0}\r\n\r\n", reachedThreshold.Count()));
                            //    foreach (var item in reachedThreshold)
                            //    {
                            //        string failedSpecificsCopy = String.Format("RBId: {0}\r\n\r\nEmail: {1}\r\n\r\nProduct: {2}\r\n\r\nLast error received: {3}\r\n\r\n", item.RecurringBillingId, item.User.EMail, item.Product.Description, item.GomsRemarks);
                            //        emailBody.AppendLine(failedSpecificsCopy);
                            //        emailBody.AppendLine("--------------------------------------------------\r\n\r\n");
                            //    }
                            //}

                            failedEmails.AppendLine("=================================================================\r\n\r\n\r\n");

                            emailBody.AppendLine("Report ends here.");

                            var newEmailBody = new StringBuilder();
                            newEmailBody.AppendLine("<!DOCTYPE html><html><body style=\"font-family: \"Trebuchet MS\", Arial, sans-serif;color:#000; font-size: 14px;\">");
                            newEmailBody.AppendLine("<h3>Report summary</h3>");
                            newEmailBody.AppendLine(String.Format("DateTime of processing (UTC): {0}", UtcDt));
                            newEmailBody.AppendLine(String.Format("<p style=\"font-size: 16px; font-weight: bold;\">Total number of successful transactions: {0}</p>", successfullyProcessed));
                            newEmailBody.AppendLine(String.Format("<p style=\"font-size: 16px; font-weight: bold;\">Total number of failed transactions: {0}</p>", failedProcessed));
                            newEmailBody.AppendLine(CreateConsolidatedReport(1, "GOMS", listOfFailedRecurringBillingId));
                            newEmailBody.AppendLine("<hr />");
                            newEmailBody.AppendLine(CreateConsolidatedReport(3, "MAX ATTEMPT", null));
                            newEmailBody.AppendLine("<p style=\"font-size: 16px; font-weight: bold;\">Report ends here.</p>");
                            newEmailBody.AppendLine("</body></html>");

                            if (IsSendConsolidatedReportsEnabled)
                            {
                                var receivers = consolidatedReportReceivers.Split(',');
                                try
                                {
                                    //SendEmailViaSendGrid(null, NoReplyEmail, "TFC.tv Recurring Billing: Consolidated Report", emailBody.ToString(), MailType.TextOnly, emailBody.ToString(), receivers);
                                    //SendEmailViaSendGrid(null, NoReplyEmail, "TFC.tv Recurring Billing: Consolidated Report", newEmailBody.ToString(), MailType.HtmlOnly, newEmailBody.ToString(), receivers);
                                    SendEmailViaSendGrid(toRecipient, NoReplyEmail, "TFC.tv Recurring Billing: Consolidated Report", newEmailBody.ToString(), MailType.HtmlOnly, newEmailBody.ToString(), receivers);
                                    Console.WriteLine("Sending of consolidated report is successful!");
                                }
                                catch (Exception) { Console.WriteLine("Sending of consolidated report failed!"); }
                            }

                            //CANCELL ALL RECURRING
                            try
                            {
                                var cancellation_list = GetUsersEligibleForCancellation(dtRecur);
                                foreach (var i in cancellation_list)
                                {
                                    try { gomsService.CancelRecurringPayment(i.User, i.Product); }
                                    catch (Exception) { }
                                }
                            }
                            catch (Exception) { }
                        }
                    }
                    else
                        Console.WriteLine("Nothing to process..");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Outer Exception: " + e.Message);
            }
        }
Пример #23
0
        //[RequireHttps]
        public ActionResult _EnrollSmartPitCardNumber(FormCollection fc)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty,
                info = "SmartPit",
                TransactionType = "Load"
            };

            string url = Url.Action("Index", "Load").ToString();
            try
            {
                DateTime registDt = DateTime.Now;
                Dictionary<string, string> tmpCollection = fc.AllKeys.ToDictionary(k => k, v => fc[v]);
                bool isMissingRequiredFields = false;

                foreach (var x in tmpCollection)
                {
                    if (String.IsNullOrEmpty(x.Value))
                    {
                        isMissingRequiredFields = true;
                        break;
                    }
                }

                if (!isMissingRequiredFields) // process form
                {
                    if (GlobalConfig.IsSmartPitReloadEnabled)
                    {
                        if (User.Identity.IsAuthenticated)
                        {
                            var context = new IPTV2Entities();
                            System.Guid userId = new System.Guid(User.Identity.Name);
                            User user = context.Users.FirstOrDefault(u => u.UserId == userId);
                            if (user != null)
                            {
                                var offering = context.Offerings.FirstOrDefault(o => o.OfferingId == GlobalConfig.offeringId);
                                if (offering != null)
                                {
                                    if (user.HasPendingGomsChangeCountryTransaction(offering))
                                        ReturnCode.StatusMessage = "We are processing your recent change in location. Please try again after a few minutes.";
                                    else if (user.HasExceededMaximumReloadTransactionsForTheDay(GlobalConfig.reloadTransactionMaximumThreshold, registDt))
                                        ReturnCode.StatusMessage = String.Format("You have exceeded the maximum number of transactions ({0}) allowed per day. Please try again later.", GlobalConfig.reloadTransactionMaximumThreshold);
                                    else if (String.Compare(user.CountryCode, GlobalConfig.JapanCountryCode, true) != 0)
                                        ReturnCode.StatusMessage = "This payment mode is not available in your country.";
                                    else if (!String.IsNullOrEmpty(user.SmartPitId))
                                        ReturnCode.StatusMessage = "You already have enrolled a SmartPit Card Number.";
                                    else
                                    {
                                        var SmartPitCardNumber = String.IsNullOrEmpty(fc["SmartPitCardNumber"]) ? String.Empty : fc["SmartPitCardNumber"];
                                        var service = new GomsTfcTv();
                                        var response = service.EnrollSmartPit(context, user.UserId, SmartPitCardNumber);
                                        if (response.IsSuccess)
                                        {
                                            user.SmartPitId = response.SmartPitCardNo;
                                            user.SmartPitRegistrationDate = registDt;
                                            if (context.SaveChanges() > 0)
                                            {
                                                ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                                ReturnCode.StatusHeader = "You have successfully enrolled!";
                                                ReturnCode.StatusMessage = String.Format("You have successfully {0} SmartPit Card Number {1}.", String.IsNullOrEmpty(SmartPitCardNumber) ? "generated" : "enrolled", response.SmartPitCardNo);
                                                ReturnCode.StatusMessage2 = "You can now start reloading your E-Wallet using your SmartPit Card Number.";
                                                TempData["ErrorMessage"] = ReturnCode;
                                                return RedirectToAction("Index", "Home"); // successful reload
                                            }
                                            else
                                                ReturnCode.StatusMessage = "The system encountered an unspecified error. Please contact Customer Support.";

                                        }
                                        else
                                        {
                                            ReturnCode.StatusCode = (int)ErrorCodes.UnknownError;
                                            ReturnCode.StatusMessage = response.StatusMessage;
                                        }

                                    }
                                }
                                else
                                    ReturnCode.StatusMessage = "Service not found. Please contact support.";

                            }
                            else
                                ReturnCode.StatusMessage = "User does not exist.";
                        }
                        else
                            ReturnCode.StatusMessage = "Your session has already expired. Please login again.";
                    }
                    else
                        ReturnCode.StatusMessage = "Prepaid Card/ePIN payment is currenty disabled.";
                }
                else
                    ReturnCode.StatusMessage = "Please fill in all required fields.";

                TempData["ErrorMessage"] = ReturnCode;
                url = Request.UrlReferrer.AbsolutePath;
            }
            catch (Exception e)
            {
                MyUtility.LogException(e);
                ReturnCode.StatusMessage = e.Message;
                TempData["ErrorMessage"] = ReturnCode;
            }
            return Redirect(url);
        }
Пример #24
0
        public ActionResult _ClaimTVEverywhere(FormCollection fc)
        {
            Dictionary<string, object> collection = new Dictionary<string, object>();
            ErrorCodes errorCode = ErrorCodes.UnknownError;
            string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError);
            collection = MyUtility.setError(errorCode, errorMessage);
            DateTime registDt = DateTime.Now;
            try
            {
                if (HasConsumedNumberOfRetriesForTFCEverywhere())
                {
                    collection = MyUtility.setError(ErrorCodes.LimitReached, "Invalid data entered. Please call our Customer Service at 18778846832 or chat with our live support team for assistance.");
                    return Content(MyUtility.buildJson(collection), "application/json");
                }
                if (((String.IsNullOrEmpty(fc["MacAddressOrSmartCard"]) && String.IsNullOrEmpty(fc["AccountNumber"]))) || String.IsNullOrEmpty(fc["ActivationNumber"]))
                {
                    collection = MyUtility.setError(ErrorCodes.IsMissingRequiredFields, "Please fill up the required fields.");
                    return Content(MyUtility.buildJson(collection), "application/json");
                }

                var context = new IPTV2Entities();
                User user = null;
                if (MyUtility.isUserLoggedIn())
                {
                    var userId = new Guid(User.Identity.Name);
                    user = context.Users.FirstOrDefault(u => u.UserId == userId);
                }
                else
                {
                    var userId = (Guid)TempData["tempUid"];
                    TempData["tempUserId"] = userId; // REASSIGN
                    TempData["tempUid"] = userId; // REASSIGN
                    user = context.Users.FirstOrDefault(u => u.UserId == userId);
                }

                if (user != null)
                {
                    string CurrencyCode = GlobalConfig.DefaultCurrency;
                    Country country = context.Countries.FirstOrDefault(c => c.Code == user.CountryCode);
                    if (country != null)
                    {
                        Currency currency = context.Currencies.FirstOrDefault(c => c.Code == country.CurrencyCode);
                        if (currency != null) CurrencyCode = currency.Code;
                    }

                    var transaction = new TfcEverywhereTransaction()
                    {
                        Amount = 0,
                        Date = DateTime.Now,
                        Currency = CurrencyCode,
                        OfferingId = GlobalConfig.offeringId,
                        StatusId = GlobalConfig.Visible,
                        Reference = "TFC Everywhere - CLAIM",
                        UserId = user.UserId
                    };

                    var gomsService = new GomsTfcTv();


                    var MacAddressOrSmartCard = fc["MacAddressOrSmartCard"].Replace(" ", "");
                    var AccountNumber = fc["AccountNumber"].Replace(" ", "");
                    var ActivationNumber = fc["ActivationNumber"].Replace(" ", "");

                    var response = gomsService.ClaimTVEverywhere(context, user.UserId, transaction, MacAddressOrSmartCard, AccountNumber, ActivationNumber);
                    if (response.IsSuccess)
                    {
                        AddTfcEverywhereEntitlement(context, response.TFCTVSubItemId, response.ExpiryDate, response.TVEServiceId, user);
                        transaction.GomsTFCEverywhereEndDate = Convert.ToDateTime(response.ExpiryDate);
                        transaction.GomsTFCEverywhereStartDate = registDt;
                        user.Transactions.Add(transaction);
                        user.IsTVEverywhere = true;
                        if (context.SaveChanges() > 0)
                        {
                            collection = MyUtility.setError(ErrorCodes.Success, String.Empty);
                            collection.Add("href", GlobalConfig.RegistrationCompleteTVE);
                        }
                    }
                    else
                    {
                        SetNumberOfTriesForTFCEverywhereCookie();
                        if (String.Compare(response.StatusCode, "8", true) == 0)
                        {
                            var sb = new StringBuilder();
                            sb.Append(response.StatusMessage);
                            sb.Append(" Go to your <a href=\"/EditProfile\" target=\"_blank\">Edit My Profile</a> page to update the last name registered on your TFC.tv account.");
                            collection = MyUtility.setError(ErrorCodes.UnknownError, sb.ToString());
                        }
                        else
                            collection = MyUtility.setError(ErrorCodes.UnknownError, response.StatusMessage);

                    }

                }
                else
                    collection = MyUtility.setError(ErrorCodes.UserDoesNotExist, "User does not exist.");
            }
            catch (Exception e) { MyUtility.LogException(e); collection = MyUtility.setError(ErrorCodes.UnknownError, e.Message); }
            return Content(MyUtility.buildJson(collection), "application/json");
        }
Пример #25
0
        private void UpdateRecurringBillingViaEditProfile2(IPTV2Entities context, User user, string list, bool? enable)
        {
            try
            {
                if (User.Identity.IsAuthenticated)
                {
                    var rb_list = list.Replace("rs", "");
                    var billingIds = MyUtility.StringToIntList(rb_list);
                    DateTime registDt = DateTime.Now;
                    if (billingIds.Count() > 0)
                    {
                        var gomsService = new GomsTfcTv();
                        var recurring_billings = user.RecurringBillings.Where(r => billingIds.Contains(r.RecurringBillingId) && r.StatusId != 2);
                        if (recurring_billings != null)
                        {
                            if (recurring_billings.Count() > 0)
                            {
                                bool RecurringStatus = false;
                                if (enable != null)
                                    RecurringStatus = (bool)enable;

                                var CurrencyCode = GlobalConfig.DefaultCurrency;
                                try { CurrencyCode = user.Country.CurrencyCode; }
                                catch (Exception) { }

                                foreach (var billing in recurring_billings)
                                {
                                    string cancellation_remarks = String.Empty;
                                    string reference = String.Empty;
                                    bool serviceUpdateSuccess = false;

                                    if (user.RecurringBillings.Count(r => r.PackageId == billing.PackageId && r.StatusId == GlobalConfig.Visible && r.RecurringBillingId != billing.RecurringBillingId) > 0)
                                    {
                                        //there is same package with recurring enabled.                                            
                                    }
                                    else
                                    {
                                        if (billing is PaypalRecurringBilling)
                                        {
                                            try
                                            {
                                                var paypalrbilling = (PaypalRecurringBilling)billing;

                                                billing.StatusId = RecurringStatus ? 1 : 0;
                                                billing.UpdatedOn = registDt;
                                                if (registDt.Date > billing.NextRun && RecurringStatus)
                                                    billing.NextRun = registDt.AddDays(1).Date;
                                                if (!RecurringStatus)
                                                {
                                                    try
                                                    {
                                                        if (PaymentHelper.CancelPaypalRecurring(paypalrbilling.SubscriberId))
                                                        {
                                                            reference = String.Format("PayPal billing id {0} cancelled", billing.RecurringBillingId);
                                                            cancellation_remarks = String.Format("{0} - PayPal Recurring Billing Id cancelled", billing.RecurringBillingId);
                                                            serviceUpdateSuccess = true;
                                                        }
                                                    }
                                                    catch (Exception) { }
                                                }
                                            }
                                            catch (Exception) { }
                                        }
                                        else
                                        {
                                            billing.StatusId = RecurringStatus ? 1 : 0;
                                            billing.UpdatedOn = registDt;
                                            if (registDt.Date > billing.NextRun && RecurringStatus)
                                                billing.NextRun = registDt.AddDays(1).Date;

                                            if (!RecurringStatus)
                                            {
                                                try
                                                {
                                                    var result = gomsService.CancelRecurringPayment(user, billing.Product);
                                                    if (result.IsSuccess)
                                                    {
                                                        reference = String.Format("Credit Card billing id {0} cancelled", billing.RecurringBillingId);
                                                        cancellation_remarks = String.Format("{0} - Credit Card Recurring Billing Id cancelled", billing.RecurringBillingId);
                                                        serviceUpdateSuccess = true;
                                                    }
                                                    else
                                                        throw new Exception(result.StatusMessage);
                                                }
                                                catch (Exception e) { MyUtility.LogException(e); }
                                            }
                                        }

                                        if (!RecurringStatus && serviceUpdateSuccess)
                                        {
                                            var transaction = new CancellationTransaction()
                                            {
                                                Amount = 0,
                                                Currency = CurrencyCode,
                                                OfferingId = GlobalConfig.offeringId,
                                                CancellationRemarks = cancellation_remarks,
                                                OriginalTransactionId = -1,
                                                GomsTransactionId = -1000,
                                                Date = registDt,
                                                Reference = reference,
                                                StatusId = GlobalConfig.Visible
                                            };
                                            user.Transactions.Add(transaction);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e) { MyUtility.LogException(e); }
        }
Пример #26
0
 private static void TestGetUser()
 {
     var service = new GomsTfcTv();
     int userId = 577615;
     string email = "*****@*****.**";
     var resp = service.GetUser(userId, email);
     if (resp.IsSuccess)
     {
         var context = new IPTV2_Model.IPTV2Entities();
         var user = context.Users.FirstOrDefault(u => u.EMail == email);
         if (user != null)
         {
             user.GomsCustomerId = resp.CustomerId;
             user.GomsSubsidiaryId = resp.SubsidiaryId;
             var wallet = user.UserWallets.FirstOrDefault(w => w.Currency == user.Country.CurrencyCode);
             if (wallet == null)
             {
                 wallet = new IPTV2_Model.UserWallet
                 {
                     Currency = user.Country.CurrencyCode,
                     Balance = 0,
                     IsActive = true,
                     LastUpdated = DateTime.Now
                 };
                 user.UserWallets.Add(wallet);
                 context.SaveChanges();
             }
         }
     }
 }
Пример #27
0
        public ActionResult _RegisterTFCEverywhere(FormCollection fc)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty
            };

            string url = Url.Action("RegisterTFCEverywhere", "User").ToString();
            var field_names = new string[] { "smartCardNum", "cusAccount" };
            try
            {
                if (TempData["qs"] != null)
                {
                    var qs = (NameValueCollection)TempData["qs"];
                    ViewBag.qs = qs;
                    TempData["qs"] = qs;
                }

                DateTime registDt = DateTime.Now;
                Dictionary<string, string> tmpCollection = fc.AllKeys.ToDictionary(k => k, v => fc[v]);
                bool isMissingRequiredFields = false;

                foreach (var x in tmpCollection)
                {
                    if (!field_names.Contains(x.Key))
                        if (String.IsNullOrEmpty(x.Value))
                        {
                            isMissingRequiredFields = true;
                            break;
                        }
                }

                if (!isMissingRequiredFields) // process form
                {
                    if (HasConsumedNumberOfRetriesForTFCEverywhere())
                    {
                        ReturnCode.StatusMessage = "Invalid data entered. Please call our Customer Service at 18778846832 or chat with our live support team for assistance.";
                        TempData["ErrorMessage"] = ReturnCode;
                        return RedirectToAction("RegisterTFCEverywhere", "User");
                    }

                    if (String.IsNullOrEmpty(fc["smartCardNum"]) && String.IsNullOrEmpty(fc["cusAccount"]))
                    {
                        ReturnCode.StatusMessage = "Please fill up all the required fields.";
                        TempData["ErrorMessage"] = ReturnCode;
                        return RedirectToAction("RegisterTFCEverywhere", "User");
                    }

                    var context = new IPTV2Entities();
                    User user = null;
                    if (User.Identity.IsAuthenticated)
                    {
                        string CurrencyCode = GlobalConfig.DefaultCurrency;
                        var UserId = new Guid(User.Identity.Name);
                        user = context.Users.FirstOrDefault(u => u.UserId == UserId);
                        if (user != null)
                        {
                            CurrencyCode = user.Country.CurrencyCode;

                            var transaction = new TfcEverywhereTransaction()
                            {
                                Amount = 0,
                                Date = registDt,
                                Currency = CurrencyCode,
                                OfferingId = GlobalConfig.offeringId,
                                StatusId = GlobalConfig.Visible,
                                Reference = "TFC Everywhere - CLAIM",
                                UserId = user.UserId
                            };

                            var gomsService = new GomsTfcTv();

                            var MacAddressOrSmartCard = fc["smartCardNum"].Replace(" ", "");
                            var AccountNumber = fc["cusAccount"].Replace(" ", "");
                            var ActivationNumber = fc["actCode"].Replace(" ", "");

                            var response = gomsService.ClaimTVEverywhere(context, user.UserId, transaction, MacAddressOrSmartCard, AccountNumber, ActivationNumber);
                            if (response.IsSuccess)
                            {
                                AddTfcEverywhereEntitlement(context, response.TFCTVSubItemId, response.ExpiryDate, response.TVEServiceId, user);
                                transaction.GomsTFCEverywhereEndDate = Convert.ToDateTime(response.ExpiryDate);
                                transaction.GomsTFCEverywhereStartDate = registDt;
                                user.Transactions.Add(transaction);
                                user.IsTVEverywhere = true;
                                if (context.SaveChanges() > 0)
                                {
                                    ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                    ReturnCode.info = "TFC Everywhere Activation";
                                    ReturnCode.CCStatusMessage = "Congratulations! Your TFC Everywhere is now activated.";
                                    ReturnCode.StatusMessage = "Pwede ka nang manood ng piling Kapamilya shows at<br>movies mula sa paborito niyong TFC Channels.";
                                    TempData["ErrorMessage"] = ReturnCode;
                                    return RedirectToAction("Index", "Home"); // successful tve activation                                    
                                }
                            }
                            else
                            {
                                SetNumberOfTriesForTFCEverywhereCookie();
                                if (String.Compare(response.StatusCode, "8", true) == 0)
                                    ReturnCode.StatusMessage = "Go to your Edit My Profile page to update the last name registered on your TFC.tv account.";
                                else
                                    ReturnCode.StatusMessage = response.StatusMessage;
                            }
                        }
                        else
                            ReturnCode.StatusMessage = "User does not exist.";
                    }
                    else
                        ReturnCode.StatusMessage = "You are not logged in.";
                }
                else
                    ReturnCode.StatusMessage = "Please fill in all required fields.";
                TempData["ErrorMessage"] = ReturnCode;
                url = Request.UrlReferrer.AbsolutePath;
            }
            catch (Exception e) { MyUtility.LogException(e); }
            return Redirect(url);
        }
Пример #28
0
        //private void Send()
        //{
        //    //Trace.WriteLine(context.Database.Connection.ConnectionString);
        //    try
        //    {
        //        var context = new IPTV2Entities();
        //        context.Database.Connection.ConnectionString = RoleEnvironment.GetConfigurationSettingValue("Iptv2Entities");
        //        Trace.TraceInformation("Fetching users for recurring...");
        //        DateTime dtRecur = registDt.Date.AddDays(Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("numOfDaysRecurringProcess")));
        //        var recurringBillings = context.RecurringBillings.Where(r => r.StatusId == 1 && r.NextRun < dtRecur);
        //        Trace.TraceInformation(String.Format("Total Users For Recurring: {0}", recurringBillings.Count()));

        //        if (recurringBillings != null)
        //        {                    
        //            var gomsService = new GomsTfcTv();

        //            //Set Goms Values via Azure                    
        //            gomsService.UserId = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvUserId");
        //            gomsService.Password = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvPassword");
        //            gomsService.ServiceUserId = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServiceUserId");
        //            gomsService.ServicePassword = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServicePassword");
        //            gomsService.ServiceUrl = RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServiceUrl");
        //            gomsService.ServiceId = Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("GomsTfcTvServiceId"));
        //            gomsService.GSapikey = RoleEnvironment.GetConfigurationSettingValue("GSapikey");
        //            gomsService.GSsecretkey = RoleEnvironment.GetConfigurationSettingValue("GSsecretkey");

        //            foreach (var i in recurringBillings)
        //            {
        //                Trace.TraceInformation(String.Format("Processing user {0} with productId {1}, endDate {2}", i.User.EMail, i.Product.Description, i.EndDate));
        //                try
        //                {
        //                    ProductPrice priceOfProduct = i.Product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == i.User.Country.CurrencyCode);
        //                    if (priceOfProduct == null)
        //                        priceOfProduct = i.Product.ProductPrices.FirstOrDefault(p => p.CurrencyCode == DefaultCurrencyCode);

        //                    Purchase purchase = CreatePurchase(registDt, "Payment via Credit Card");
        //                    i.User.Purchases.Add(purchase);

        //                    PurchaseItem item = CreatePurchaseItem(i.UserId, i.Product, priceOfProduct);
        //                    purchase.PurchaseItems.Add(item);

        //                    var cardType = i.User.CreditCards.LastOrDefault(c => c.StatusId == 1).CardType;
        //                    CreditCardPaymentTransaction transaction = new CreditCardPaymentTransaction()
        //                    {
        //                        Amount = priceOfProduct.Amount,
        //                        Currency = priceOfProduct.CurrencyCode,
        //                        Reference = cardType.ToUpper(),
        //                        Date = registDt,
        //                        Purchase = purchase,
        //                        OfferingId = offeringId,
        //                        StatusId = 1
        //                    };
        //                    var response = gomsService.CreateOrderViaRecurringPayment(context, i.UserId, transaction);
        //                    if (response.IsSuccess)
        //                    {
        //                        DateTime endDate = registDt;
        //                        item.SubscriptionProduct = (SubscriptionProduct)i.Product;
        //                        if (item.SubscriptionProduct is PackageSubscriptionProduct)
        //                        {
        //                            PackageSubscriptionProduct subscription = (PackageSubscriptionProduct)i.Product;

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

        //                                PackageEntitlement currentPackage = i.User.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId);

        //                                EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, i.Product, String.Format("{0}-{1}", "CC", cardType), response.TransactionId.ToString(), registDt);
        //                                if (currentPackage != null)
        //                                {
        //                                    request.StartDate = currentPackage.EndDate;
        //                                    currentPackage.EndDate = GetEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt));

        //                                    endDate = currentPackage.EndDate;
        //                                    currentPackage.LatestEntitlementRequest = request;
        //                                    request.EndDate = endDate;
        //                                }
        //                                else
        //                                {
        //                                    PackageEntitlement entitlement = CreatePackageEntitlement(request, subscription, package, registDt);
        //                                    request.EndDate = entitlement.EndDate;
        //                                    i.User.PackageEntitlements.Add(entitlement);
        //                                }
        //                                i.User.EntitlementRequests.Add(request);
        //                                item.EntitlementRequest = request; //UPDATED: November 22, 2012                                        
        //                            }

        //                            i.EndDate = endDate;
        //                            i.NextRun = endDate.AddDays(-3).Date;
        //                            i.UpdatedOn = registDt;

        //                        }
        //                    }
        //                    else
        //                        throw new Exception(response.StatusMessage);
        //                }
        //                catch (Exception e)
        //                {
        //                    Trace.TraceError(e.Message);
        //                    i.GomsRemarks = e.Message;
        //                    //    TFCTV.Helpers.MyUtility.LogException(e, "Recurring Billing Scheduled Task"); 
        //                }
        //            }
        //            context.SaveChanges();
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        //TFCTV.Helpers.MyUtility.LogException(e);
        //        Trace.TraceInformation("Error: " + e.Message);
        //        Trace.TraceInformation("Inner Exception: " + e.InnerException.Message);
        //    }
        //}


        private void Send()
        {
            //Trace.WriteLine(context.Database.Connection.ConnectionString);
            try
            {
                Trace.TraceInformation("Fetching users for recurring...");
                DateTime dtRecur = registDt.Date.AddDays(Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("numOfDaysRecurringProcess")));
                var recurringBillings = GetUsersEligibleForRenewal(dtRecur);
                Trace.TraceInformation(String.Format("Total Users For Recurring: {0}", recurringBillings.Count()));

                if (recurringBillings != null)
                {
                    using (var context = new IPTV2Entities())
                    {
                        context.Database.Connection.ConnectionString = RoleEnvironment.GetConfigurationSettingValue("Iptv2Entities");
                        var gomsService = new GomsTfcTv();
                        SetGomsServiceVariables(gomsService);
                        try
                        {
                            gomsService.TestConnect();
                            Console.WriteLine("Test Connect success");
                        }
                        catch (Exception) { Console.WriteLine("Test Connect failed."); }

                        foreach (var i in recurringBillings)
                        {
                            var user = context.Users.FirstOrDefault(u => u.UserId == i.UserId);
                            var recurringBilling = context.RecurringBillings.Find(i.RecurringBillingId);
                            var product = context.Products.Find(i.ProductId);
                            Trace.TraceInformation(String.Format("Processing user {0} with productId {1}, endDate {2}", user.EMail, product.Description, i.EndDate));
                            try
                            {
                                ProductPrice priceOfProduct = context.ProductPrices.FirstOrDefault(p => p.CurrencyCode == user.Country.CurrencyCode && p.ProductId == product.ProductId);
                                if (priceOfProduct == null)
                                    priceOfProduct = context.ProductPrices.FirstOrDefault(p => p.CurrencyCode == DefaultCurrencyCode && p.ProductId == product.ProductId);

                                Purchase purchase = CreatePurchase(registDt, "Payment via Credit Card");
                                user.Purchases.Add(purchase);

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

                                var cardType = user.CreditCards.LastOrDefault(c => c.StatusId == 1).CardType;
                                CreditCardPaymentTransaction transaction = new CreditCardPaymentTransaction()
                                {
                                    Amount = priceOfProduct.Amount,
                                    Currency = priceOfProduct.CurrencyCode,
                                    Reference = cardType.ToUpper(),
                                    Date = registDt,
                                    Purchase = purchase,
                                    OfferingId = offeringId,
                                    StatusId = 1
                                };

                                var response = gomsService.CreateOrderViaRecurringPayment(context, user.UserId, transaction);
                                if (response.IsSuccess)
                                {
                                    DateTime endDate = registDt;
                                    item.SubscriptionProduct = (SubscriptionProduct)product;
                                    if (item.SubscriptionProduct is PackageSubscriptionProduct)
                                    {
                                        PackageSubscriptionProduct subscription = (PackageSubscriptionProduct)product;

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

                                            PackageEntitlement currentPackage = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId);

                                            EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, product, String.Format("{0}-{1}", "CC", cardType), response.TransactionId.ToString(), registDt);
                                            if (currentPackage != null)
                                            {
                                                request.StartDate = currentPackage.EndDate;
                                                currentPackage.EndDate = GetEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt));

                                                endDate = currentPackage.EndDate;
                                                currentPackage.LatestEntitlementRequest = request;
                                                request.EndDate = endDate;
                                            }
                                            else
                                            {
                                                PackageEntitlement entitlement = CreatePackageEntitlement(request, subscription, package, registDt);
                                                request.EndDate = entitlement.EndDate;
                                                user.PackageEntitlements.Add(entitlement);
                                            }
                                            user.EntitlementRequests.Add(request);
                                            item.EntitlementRequest = request; //UPDATED: November 22, 2012                                        
                                        }

                                        recurringBilling.EndDate = endDate;
                                        recurringBilling.NextRun = endDate.AddDays(-3).Date;
                                        recurringBilling.UpdatedOn = registDt;
                                        recurringBilling.GomsRemarks = String.Empty;
                                        recurringBilling.NumberOfAttempts = 0;

                                    }
                                    Trace.TraceInformation(user.EMail + ": renewal process complete!");
                                }
                                else
                                {
                                    recurringBilling.GomsRemarks = response.StatusMessage;
                                    recurringBilling.NumberOfAttempts += 1;
                                    throw new Exception(user.EMail + ": " + response.StatusMessage);
                                }
                            }
                            catch (Exception e)
                            {
                                Trace.TraceError("INNER ERROR: " + e.Message);
                            }

                            if (context.SaveChanges() > 0)
                                Trace.TraceInformation("Saving changes...");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError("ERROR: " + e.Message);
            }
        }
Пример #29
0
        public JsonResult CancelRecurring(int? pid)
        {
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = String.Empty
            };

            DateTime registDt = DateTime.Now;
            try
            {
                if (pid == null)
                {
                    ReturnCode.StatusCode = (int)ErrorCodes.IsInvalidRequest;
                    ReturnCode.StatusMessage = "Request is not valid";
                    return this.Json(ReturnCode, JsonRequestBehavior.AllowGet);
                }
                if (!Request.IsAjaxRequest())
                {
                    ReturnCode.StatusCode = (int)ErrorCodes.IsInvalidRequest;
                    ReturnCode.StatusMessage = "Request is not valid";
                    return this.Json(ReturnCode, JsonRequestBehavior.AllowGet);
                }

                if (User.Identity.IsAuthenticated)
                {
                    var context = new IPTV2Entities();
                    var userId = new Guid(User.Identity.Name);
                    var user = context.Users.FirstOrDefault(u => u.UserId == userId);
                    if (user != null)
                    {
                        var product = context.Products.FirstOrDefault(p => p.ProductId == (int)pid);
                        if (product != null)
                        {
                            if (product is SubscriptionProduct)
                            {
                                var subscription_product = (SubscriptionProduct)product;
                                var packageIds = subscription_product.ProductGroup.GetPackageIds(true);
                                var CurrencyCode = GlobalConfig.DefaultCurrency;
                                try { CurrencyCode = user.Country.CurrencyCode; }
                                catch (Exception) { }
                                var rb = context.RecurringBillings.Where(r => r.UserId == user.UserId && r.StatusId == GlobalConfig.Visible && packageIds.Contains(r.PackageId));
                                if (rb != null)
                                {
                                    if (rb.Count() > 0)
                                    {
                                        var gomsService = new GomsTfcTv();
                                        foreach (var billing in rb)
                                        {
                                            string reference = String.Empty;
                                            bool serviceUpdateSuccess = false;
                                            string cancellation_remarks = String.Empty;
                                            if (billing is PaypalRecurringBilling)
                                            {
                                                try
                                                {
                                                    var paypalrbilling = (PaypalRecurringBilling)billing;
                                                    billing.StatusId = 0;
                                                    billing.UpdatedOn = registDt;
                                                    try
                                                    {
                                                        if (PaymentHelper.CancelPaypalRecurring(paypalrbilling.SubscriberId))
                                                        {
                                                            reference = String.Format("PayPal Payment Renewal id {0} cancelled", billing.RecurringBillingId);
                                                            String.Format("{0} - PayPal Recurring Billing Id cancelled", billing.RecurringBillingId);
                                                            serviceUpdateSuccess = true;
                                                        }
                                                    }
                                                    catch (Exception) { }
                                                }
                                                catch (Exception) { }
                                            }
                                            else
                                            {
                                                try
                                                {
                                                    var result = gomsService.CancelRecurringPayment(user, billing.Product);
                                                    if (result.IsSuccess)
                                                    {
                                                        billing.StatusId = 0;
                                                        billing.UpdatedOn = registDt;
                                                        reference = String.Format("Credit Card Payment Renewal {0} cancelled", billing.RecurringBillingId);
                                                        cancellation_remarks = String.Format("{0} - Credit Card Recurring Billing Id cancelled", billing.RecurringBillingId);
                                                        serviceUpdateSuccess = true;
                                                    }
                                                    else
                                                    {
                                                        ReturnCode.StatusMessage = result.StatusMessage;
                                                        throw new Exception(result.StatusMessage);
                                                    }

                                                }
                                                catch (Exception) { }
                                            }

                                            //serviceUpdateSuccess = true;
                                            if (serviceUpdateSuccess)
                                            {
                                                var transaction = new CancellationTransaction()
                                                {
                                                    Amount = 0,
                                                    Currency = CurrencyCode,
                                                    OfferingId = GlobalConfig.offeringId,
                                                    CancellationRemarks = cancellation_remarks,
                                                    OriginalTransactionId = -1,
                                                    GomsTransactionId = -1000,
                                                    Date = registDt,
                                                    Reference = reference,
                                                    StatusId = GlobalConfig.Visible
                                                };
                                                user.Transactions.Add(transaction);
                                            }
                                        }

                                        if (context.SaveChanges() > 0)
                                        {
                                            ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                            ReturnCode.StatusMessage = "We have disabled all your automatic payment renewal.";
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
                else
                {
                    ReturnCode.StatusCode = (int)ErrorCodes.NotAuthenticated;
                    ReturnCode.StatusMessage = "User is not authenticated";
                    return this.Json(ReturnCode, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception e) { MyUtility.LogException(e); }
            return this.Json(ReturnCode, JsonRequestBehavior.AllowGet);
        }
Пример #30
0
        public ActionResult _EnrollSmartPit(FormCollection fc)
        {
            Response.ContentType = "application/json";
            var ReturnCode = new TransactionReturnType()
            {
                StatusCode = (int)ErrorCodes.UnknownError,
                StatusMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError)
            };
            try
            {
                if (!Request.IsAjaxRequest())
                {
                    ReturnCode.StatusCode = (int)ErrorCodes.IsInvalidRequest;
                    ReturnCode.StatusMessage = "Your request is invalid.";
                    return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                }

                if (!GlobalConfig.IsSmartPitReloadEnabled)
                {
                    ReturnCode.StatusCode = (int)ReloadError.SMARTPIT_RELOAD_IS_DISABLED;
                    ReturnCode.StatusMessage = "SmartPit reloading is currently disabled.";
                    return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                }

                if (User.Identity.IsAuthenticated)
                {
                    var registDt = DateTime.Now;
                    var context = new IPTV2Entities();
                    System.Guid userId = new System.Guid(User.Identity.Name);
                    User user = context.Users.FirstOrDefault(u => u.UserId == userId);

                    Offering offering = context.Offerings.FirstOrDefault(o => o.OfferingId == GlobalConfig.offeringId);

                    if (user != null)
                    {
                        if (offering != null)
                        {
                            if (user.HasPendingGomsChangeCountryTransaction(offering))
                            {
                                ReturnCode.StatusCode = (int)ErrorCodes.HasPendingChangeCountryTransaction;
                                ReturnCode.StatusMessage = "We are processing your recent change in location. Please try again after a few minutes.";
                                return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                            }

                            if (user.HasExceededMaximumReloadTransactionsForTheDay(GlobalConfig.reloadTransactionMaximumThreshold, registDt))
                            {
                                ReturnCode.StatusCode = (int)ErrorCodes.MaximumTransactionsExceeded;
                                ReturnCode.StatusMessage = String.Format("You have exceeded the maximum number of transactions ({0}) allowed per day. Please try again later.", GlobalConfig.paymentTransactionMaximumThreshold);
                                return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                            }
                        }

                        if (String.Compare(user.CountryCode, GlobalConfig.JapanCountryCode, true) != 0)
                        {
                            ReturnCode.StatusCode = (int)ErrorCodes.UnauthorizedCountry;
                            ReturnCode.StatusMessage = "You are not allowed to use this feature.";
                            return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                        }

                        if (!String.IsNullOrEmpty(user.SmartPitId))
                        {
                            ReturnCode.StatusCode = (int)ErrorCodes.IsAlreadyEnrolledToSmartPit;
                            ReturnCode.StatusMessage = "You already have an enrolled SmartPit Card Number.";
                            return Json(ReturnCode, JsonRequestBehavior.AllowGet);
                        }


                        var SmartPitCardNumber = String.IsNullOrEmpty(fc["SmartPitCardNumber"]) ? String.Empty : fc["SmartPitCardNumber"];
                        string ErrorMessage = String.Empty;
                        var service = new GomsTfcTv();
                        try
                        {
                            var response = service.EnrollSmartPit(context, user.UserId, SmartPitCardNumber);

                            if (response.IsSuccess)
                            {
                                user.SmartPitId = response.SmartPitCardNo;
                                user.SmartPitRegistrationDate = registDt;
                                if (context.SaveChanges() > 0)
                                {
                                    ReturnCode.StatusCode = (int)ErrorCodes.Success;
                                    ReturnCode.StatusMessage = String.Format("You have successfully {0} a SmartPit Card Number.", String.IsNullOrEmpty(SmartPitCardNumber) ? "generated" : "enrolled");
                                    ReturnCode.info = response.SmartPitCardNo;
                                }
                                else
                                {
                                    ReturnCode.StatusCode = (int)ErrorCodes.EntityUpdateError;
                                    ReturnCode.StatusMessage = "The system encountered an unspecified error. Please contact Customer Support.";
                                }
                            }
                            else
                            {
                                ReturnCode.StatusCode = (int)ErrorCodes.UnknownError;
                                ReturnCode.StatusMessage = response.StatusMessage;
                            }
                        }
                        catch (Exception e)
                        {
                            MyUtility.LogException(e);
                            ReturnCode.StatusCode = (int)ErrorCodes.UnknownError;
                            ReturnCode.StatusMessage = e.Message;
                        }
                    }
                }
                else
                {
                    ReturnCode.StatusCode = (int)ErrorCodes.NotAuthenticated;
                    ReturnCode.StatusMessage = "Your session has expired. Please login again.";
                }
            }
            catch (Exception e)
            {
                MyUtility.LogException(e);
                ReturnCode.StatusCode = (int)ErrorCodes.UnknownError;
                ReturnCode.StatusMessage = e.Message;
            }
            return Json(ReturnCode, JsonRequestBehavior.AllowGet);
        }