Ejemplo n.º 1
0
        public RespCreateOrder CreateOrderViaCreditCard(IPTV2Entities context, System.Guid userId, CreditCardPaymentTransaction transaction, CreditCardInfo cardInfo, int FreeTrialConvertedDays)
        {
            RespCreateOrder result = null;

            InitializeServiceClient();

            try
            {
                // validate credit card information
                cardInfo.Validate();
                if (!cardInfo.IsValid)
                {
                    throw new GomsInvalidCreditCardException();
                }

                // Validate User
                GomsException validationResult = UserValidation(context, userId);
                if (!(validationResult is GomsSuccess))
                {
                    throw validationResult;
                }
                var user = context.Users.Find(userId);

                if (transaction == null)
                {
                    throw new GomsInvalidTransactionException();
                }
                else
                {
                    // check purchase items
                    if ((transaction.Purchase == null) || (transaction.Purchase.PurchaseItems.Count() <= 0))
                    {
                        throw new GomsInvalidTransactionException();
                    }
                }

                var paymentMethod = context.GomsPaymentMethods.FirstOrDefault(p => (p.GomsSubsidiaryId == user.GomsSubsidiaryId) && (p.Name == cardInfo.CardTypeString));
                if (paymentMethod == null)
                {
                    throw new GomsCreditCardTypeInvalidException();
                }

                var req = new ReqCreateOrder
                {
                    UID = ServiceUserId,
                    PWD = ServicePassword,
                    Email = user.EMail,
                    CustomerId = (int)user.GomsCustomerId,
                    ServiceId = (int)user.GomsServiceId,
                    SubsidiaryId = (int)user.GomsSubsidiaryId,
                    OrderType = 2,
                    PhoenixId = (int)(DateTime.Now.Ticks - int.MaxValue),
                    // CurrencyId = (int)context.Currencies.Find(transaction.Currency).GomsId,
                    CurrencyId = (int)context.Currencies.Find(user.Country.CurrencyCode).GomsId,
                    CCName = cardInfo.Name,
                    CCNumber = cardInfo.Number,
                    CCSecurityCode = cardInfo.CardSecurityCode,
                    CCExpiry = cardInfo.ExpiryDate,
                    CCPostalCode = cardInfo.PostalCode,
                    CCStreet = cardInfo.StreetAddress,
                    PaymentMethod = paymentMethod.PaymentMethodId,
                };

                // build order items

                OrderItem[] oi = new OrderItem[transaction.Purchase.PurchaseItems.Count()];
                int i = 0;
                foreach (var item in transaction.Purchase.PurchaseItems)
                {
                    // look for user's entitlment of purchased product
                    Entitlement userEntitlement = Entitlement.GetUserProductEntitlement(context, userId, item.ProductId);

                    //var package = context.ProductPackages.FirstOrDefault(p => p.ProductId == item.ProductId);
                    //if (package == null)
                    //    throw new Exception(String.Format("Cannot locate package for product Id {0}", item.ProductId));

                    //var entitlement = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId);
                    //if (entitlement == null)
                    //    throw new Exception(String.Format("Cannot locate entitlement for product Id {0}, package id {1}", item.ProductId, package.PackageId));

                    DateTime startDate = DateTime.Now;
                    if (userEntitlement != null)
                        startDate = userEntitlement.EndDate > DateTime.Now ? userEntitlement.EndDate : DateTime.Now;

                    //var startDate = (userEntitlement == null) || (userEntitlement.EndDate > DateTime.Now) ? userEntitlement.EndDate : DateTime.Now;

                    var newEndDate = getEntitlementEndDate(item.SubscriptionProduct.Duration, item.SubscriptionProduct.DurationType, startDate);

                    /**** EARLY BIRD ****/
                    if (FreeTrialConvertedDays > 0)
                        newEndDate = newEndDate.AddDays(FreeTrialConvertedDays);

                    oi[i] = new OrderItem
                    {
                        ItemId = (int)item.SubscriptionProduct.GomsProductId,
                        Quantity = (int)item.SubscriptionProduct.GomsProductQuantity,
                        AmountLocalCurrency = (double)item.Price,
                        EndDate = newEndDate.ToString("MM/dd/yyyy"),
                        StartDate = startDate.ToString("MM/dd/yyyy"),
                    };
                    if (item.RecipientUserId != userId)
                    {
                        req.OrderType = 3;
                        User recipient = context.Users.Find(item.RecipientUserId);
                        if (recipient == null)
                        {
                            throw new GomsInvalidRecipientException();
                        }
                        if (!recipient.IsGomsRegistered)
                        {
                            //var registerResult = RegisterUser(context, item.RecipientUserId);
                            var registerResult = RegisterUser2(context, item.RecipientUserId);
                            if (!registerResult.IsSuccess)
                            {
                                throw new GomsRegisterUserException(registerResult.StatusMessage);
                            }
                        }
                        req.Recipient = (int)recipient.GomsCustomerId;
                        req.RecipientServiceId = (int)recipient.GomsServiceId;
                    }
                    i++;
                }
                req.OrderItems = oi;
                var log = new GomsLogs() { email = user.EMail, phoenixid = req.PhoenixId };
                try
                {


                    // _serviceClient.InnerChannel.OperationTimeout = TimeSpan.FromMinutes(5);
                    var startTime = DateTime.Now;
                    result = _serviceClient.CreateOrder(req);
                    var endTime = DateTime.Now;
                    var timeDifference = endTime - startTime;

                    if (result.IsSuccess)
                    {
                        transaction.Reference += "-" + result.TransactionId.ToString();
                        transaction.GomsTransactionId = result.TransactionId;
                        transaction.GomsTransactionDate = DateTime.Now;
                        user.Transactions.Add(transaction);
                        //context.SaveChanges();

                        log.transactionid = transaction.TransactionId;
                        log.transactiondate = transaction.GomsTransactionDate.Value.ToString("yyyy-MM-dd hh:mm:ss");
                        //log.message = String.Format("{0} - {1}", result.IsSuccess, result.StatusMessage);                        
                        //log.statuscode = result.StatusCode;
                        //log.statusmessage = result.StatusMessage;
                        //log.issuccess = result.IsSuccess;
                        //log.gomstransactionid = result.TransactionId;

                    }
                    else
                    {
                        log.transactionid = 0;
                        log.transactiondate = String.Empty;
                        //log.message = String.Format("{0} - {1}", result.IsSuccess, result.StatusMessage);
                    }

                    log.message = String.Format("{0} - {1}", result.IsSuccess, result.StatusMessage);
                    log.statuscode = result.StatusCode;
                    log.statusmessage = result.StatusMessage;
                    log.issuccess = result.IsSuccess;
                    log.gomstransactionid = result.TransactionId;
                }
                catch (Exception e)
                {
                    log.message = e.Message;
                    LogToGigya("glogs", log);
                    throw new GomsServiceCallException(e.Message);

                }
                finally
                {
                    LogToGigya("glogs", log);
                }
            }
            catch (GomsException e)
            {
                result = new RespCreateOrder { IsSuccess = false, StatusCode = e.StatusCode, StatusMessage = e.StatusMessage };
            }

            return (result);
        }
Ejemplo n.º 2
0
        public RespCreateOrder CreateOrder(IPTV2Entities context, System.Guid userId, int transactionId)
        {
            RespCreateOrder result = null;

            InitializeServiceClient();

            try
            {
                // validate user
                GomsException validationResult = UserValidation(context, userId);
                if (!(validationResult is GomsSuccess))
                {
                    throw validationResult;
                }
                var user = context.Users.Find(userId);

                // validate transaction
                validationResult = TransactionValidation(context, transactionId, true);
                if (!(validationResult is GomsSuccess))
                {
                    throw validationResult;
                }
                var transaction = user.Transactions.FirstOrDefault(t => t.TransactionId == transactionId);

                int currencyId = 0;
                string curr = transaction.Currency;
                if (transaction.Currency == "---")
                {
                    if (transaction is WalletPaymentTransaction)
                    {
                        currencyId = (int)((WalletPaymentTransaction)transaction).UserWallet.WalletCurrency.GomsId;
                        curr = ((WalletPaymentTransaction)transaction).UserWallet.Currency;
                    }
                    else if (transaction is PpcPaymentTransaction)
                    {
                        currencyId = (int)((PpcPaymentTransaction)transaction).User.Country.Currency.GomsId;
                        curr = ((PpcPaymentTransaction)transaction).User.Country.CurrencyCode;
                    }
                }
                else
                {
                    //if (!(transaction is PaypalPaymentTransaction))
                    currencyId = (int)context.Currencies.Find(transaction.Currency).GomsId;
                }
                if (currencyId == 0)
                {
                    currencyId = (int)context.Currencies.Find(user.Country.CurrencyCode).GomsId;
                    curr = user.Country.CurrencyCode;
                }

                var paymentTransaction = (PaymentTransaction)transaction;
                var req = new ReqCreateOrder
                {
                    UID = ServiceUserId,
                    PWD = ServicePassword,
                    Email = user.EMail,
                    CustomerId = (int)user.GomsCustomerId,
                    ServiceId = (int)user.GomsServiceId,
                    SubsidiaryId = (int)user.GomsSubsidiaryId,
                    OrderType = 2,
                    PhoenixId = transaction.TransactionId,
                    //CurrencyId = (int)context.Currencies.Find(transaction.Currency).GomsId
                    CurrencyId = currencyId,
                    //ExchangeRate = (double)Forex.Convert(context, curr, "USD", 1)
                    ExchangeRate = (double)Forex.Convert(context, "USD", curr, 1)
                };

                bool updateExchangeRate = false;

                GomsPaymentMethod paymentMethod = null;

                if (paymentTransaction is PpcPaymentTransaction)
                {
                    paymentMethod = context.GomsPaymentMethods.FirstOrDefault(p => (p.GomsSubsidiaryId == user.GomsSubsidiaryId) && (p.Name == "Prepaid Card"));
                    if (paymentMethod == null)
                    {
                        throw new GomsPaymentMethodIdInvalidException();
                    }

                    req.PaymentMethod = paymentMethod.PaymentMethodId;
                    // TODO: validate if consume prepaid card still needs to be called
                    var resultUsePpc = UsePrepaidCard(context, userId, transaction);
                    if (!resultUsePpc.IsSuccess)
                    {
                        throw new GomsException { StatusCode = resultUsePpc.StatusCode, StatusMessage = resultUsePpc.StatusMessage };
                    }
                    else
                    {
                        result = new RespCreateOrder { IsSuccess = resultUsePpc.IsSuccess, StatusCode = resultUsePpc.StatusCode, StatusMessage = resultUsePpc.StatusMessage, TransactionId = resultUsePpc.TransactionId };
                    }
                }
                else if (paymentTransaction is PaypalPaymentTransaction)
                {
                    req.PaypalReferenceNo = transaction.Reference;
                    paymentMethod = context.GomsPaymentMethods.FirstOrDefault(p => (p.GomsSubsidiaryId == user.GomsSubsidiaryId) && (p.Name == "PayPal"));
                    if (paymentMethod != null)
                    {
                        req.PaymentMethod = paymentMethod.PaymentMethodId;
                    }
                    else
                    {
                        throw new GomsPaymentMethodIdInvalidException();
                    }

                    //if (String.Compare(user.Country.CurrencyCode, "USD", true) == 0)
                    //    req.ExchangeRate = (double)Forex.Convert(context, user.Country.CurrencyCode, "USD", 1);
                    //else
                    //    req.ExchangeRate = (double)Forex.Convert(context, "USD", user.Country.CurrencyCode, 1);
                }
                else if (paymentTransaction is WalletPaymentTransaction)
                {
                    paymentMethod = context.GomsPaymentMethods.FirstOrDefault(p => (p.GomsSubsidiaryId == user.GomsSubsidiaryId) && (p.Name == "E-Wallet"));
                    if (paymentMethod != null)
                    {
                        req.PaymentMethod = paymentMethod.PaymentMethodId;
                    }
                    else
                    {
                        throw new GomsPaymentMethodIdInvalidException();
                    }
                }
                else
                {
                    throw new GomsInvalidTransactionTypeException();
                }

                if (!(paymentTransaction is PpcPaymentTransaction))
                {
                    // build order items
                    OrderItem[] oi = new OrderItem[paymentTransaction.Purchase.PurchaseItems.Count()];
                    int i = 0;
                    foreach (var item in paymentTransaction.Purchase.PurchaseItems)
                    {
                        if (item.SubscriptionProduct.GomsProductId == null)
                            throw new GomsMissingGomsProductId();

                        var endDate = item.EntitlementRequest.EndDate;
                        var startDate = endDate;
                        switch (item.SubscriptionProduct.DurationType.ToUpper())
                        {
                            case "D":
                                {
                                    startDate = endDate.AddDays(item.SubscriptionProduct.Duration * -1);
                                    break;
                                };
                            case "M":
                                {
                                    startDate = endDate.AddMonths(item.SubscriptionProduct.Duration * -1);
                                    break;
                                };
                            case "Y":
                                {
                                    startDate = endDate.AddYears(item.SubscriptionProduct.Duration * -1);
                                    break;
                                };
                            default:
                                {
                                    break;
                                }
                        }

                        if (transaction is PaypalPaymentTransaction)
                        {
                            //if (String.Compare(user.Country.CurrencyCode, "USD", true) == 0)
                            //{
                            //    oi[i] = new OrderItem
                            //    {
                            //        ItemId = (int)item.SubscriptionProduct.GomsProductId,
                            //        Quantity = (int)item.SubscriptionProduct.GomsProductQuantity,
                            //        AmountLocalCurrency = (double)item.Price,
                            //        AmountBaseCurrency = (double)Forex.Convert(context, user.Country.CurrencyCode, "USD", item.Price),
                            //        StartDate = startDate.ToString("MM/dd/yyyy"),
                            //        EndDate = endDate.ToString("MM/dd/yyyy")
                            //    };
                            //}
                            //else
                            //{
                            //    oi[i] = new OrderItem
                            //    {
                            //        ItemId = (int)item.SubscriptionProduct.GomsProductId,
                            //        Quantity = (int)item.SubscriptionProduct.GomsProductQuantity,
                            //        AmountLocalCurrency = (double)Forex.Convert(context, "USD", user.Country.CurrencyCode, item.Price),
                            //        AmountBaseCurrency = (double)item.Price,
                            //        StartDate = startDate.ToString("MM/dd/yyyy"),
                            //        EndDate = endDate.ToString("MM/dd/yyyy")
                            //    };
                            //}

                            if (String.Compare(user.Country.CurrencyCode, transaction.Currency) != 0) //Check first if transaction currency is not the same as user's country currency
                            {
                                var userCountryProductPrice = item.SubscriptionProduct.ProductPrices.FirstOrDefault(c => c.CurrencyCode == user.Country.CurrencyCode); //Retrieves the currency of product based on user's country currency
                                if (userCountryProductPrice != null) // ProductPrice found based on user's country currency
                                {
                                    oi[i] = new OrderItem
                                    {
                                        ItemId = (int)item.SubscriptionProduct.GomsProductId,
                                        Quantity = (int)item.SubscriptionProduct.GomsProductQuantity,
                                        AmountLocalCurrency = (double)userCountryProductPrice.Amount,
                                        AmountBaseCurrency = (double)Forex.Convert(context, userCountryProductPrice.CurrencyCode, "USD", userCountryProductPrice.Amount),
                                        StartDate = startDate.ToString("MM/dd/yyyy"),
                                        EndDate = endDate.ToString("MM/dd/yyyy")
                                    };

                                    if (!updateExchangeRate)
                                    {
                                        req.CurrencyId = (int)context.Currencies.Find(userCountryProductPrice.CurrencyCode).GomsId;
                                        req.ExchangeRate = (double)Forex.Convert(context, "USD", userCountryProductPrice.CurrencyCode, 1);
                                        updateExchangeRate = true;
                                    }
                                }
                                else
                                {
                                    oi[i] = new OrderItem
                                    {
                                        ItemId = (int)item.SubscriptionProduct.GomsProductId,
                                        Quantity = (int)item.SubscriptionProduct.GomsProductQuantity,
                                        AmountLocalCurrency = (double)item.Price,
                                        AmountBaseCurrency = (double)Forex.Convert(context, transaction.Currency, "USD", item.Price),
                                        StartDate = startDate.ToString("MM/dd/yyyy"),
                                        EndDate = endDate.ToString("MM/dd/yyyy")
                                    };

                                    if (!updateExchangeRate)
                                    {
                                        req.CurrencyId = (int)context.Currencies.Find(transaction.Currency).GomsId;
                                        req.ExchangeRate = (double)Forex.Convert(context, "USD", transaction.Currency, 1);
                                        updateExchangeRate = true;
                                    }
                                }
                            }
                            else
                            {
                                oi[i] = new OrderItem
                                {
                                    ItemId = (int)item.SubscriptionProduct.GomsProductId,
                                    Quantity = (int)item.SubscriptionProduct.GomsProductQuantity,
                                    AmountLocalCurrency = (double)item.Price,
                                    AmountBaseCurrency = (double)Forex.Convert(context, user.Country.CurrencyCode, "USD", item.Price),
                                    StartDate = startDate.ToString("MM/dd/yyyy"),
                                    EndDate = endDate.ToString("MM/dd/yyyy")
                                };
                            }
                        }
                        else
                        {
                            oi[i] = new OrderItem
                            {
                                ItemId = (int)item.SubscriptionProduct.GomsProductId,
                                Quantity = (int)item.SubscriptionProduct.GomsProductQuantity,
                                AmountLocalCurrency = (double)item.Price,
                                AmountBaseCurrency = (double)Forex.Convert(context, user.Country.CurrencyCode, "USD", item.Price),
                                StartDate = startDate.ToString("MM/dd/yyyy"),
                                EndDate = endDate.ToString("MM/dd/yyyy")
                            };
                        }

                        if (item.RecipientUserId != userId)
                        {
                            req.OrderType = 3;
                            User recipient = context.Users.Find(item.RecipientUserId);
                            if (recipient != null)
                            {
                                if (!recipient.IsGomsRegistered)
                                {
                                    //var registerResult = RegisterUser(context, item.RecipientUserId);
                                    var registerResult = RegisterUser2(context, item.RecipientUserId);
                                    if (!registerResult.IsSuccess)
                                    {
                                        throw new GomsRegisterUserException(registerResult.StatusMessage);
                                    }
                                }
                                req.Recipient = (int)recipient.GomsCustomerId;
                                req.RecipientServiceId = (int)recipient.GomsServiceId;
                            }
                            else
                            {
                                throw new GomsInvalidRecipientException();
                            }
                        }
                        i++;
                    }
                    req.OrderItems = oi;

                    try
                    {
                        result = _serviceClient.CreateOrder(req);

                        if (result.IsSuccess)
                        {
                            transaction.GomsTransactionId = result.TransactionId;
                            transaction.GomsTransactionDate = DateTime.Now;
                            transaction.GomsRemarks = null;
                            context.SaveChanges();
                        }
                        else
                        {
                            var match = System.Text.RegularExpressions.Regex.Match(result.StatusMessage, "DUP_RCRD", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            if (match.Success)
                            {
                                transaction.GomsTransactionId = -10; // Duplicate record                                
                                transaction.GomsRemarks = result.StatusMessage;
                                context.SaveChanges();
                            }
                            else
                                throw new GomsException { StatusCode = result.StatusCode, StatusMessage = result.StatusMessage };
                        }
                    }
                    catch (Exception e)
                    {
                        throw new GomsServiceCallException(e.Message);
                    }
                }
            }
            catch (GomsException e)
            {
                result = new RespCreateOrder { IsSuccess = false, StatusCode = e.StatusCode, StatusMessage = e.StatusMessage };
            }
            return (result);
        }