Ejemplo n.º 1
0
        /// <returns>A task that represents the asynchronous operation</returns>
        public virtual async Task <IActionResult> StateEditPopup(int id)
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageCountries))
            {
                return(AccessDeniedView());
            }

            //try to get a state with the specified id
            var state = await _stateProvinceService.GetStateProvinceByIdAsync(id);

            if (state == null)
            {
                return(RedirectToAction("List"));
            }

            //try to get a country with the specified id
            var country = await _countryService.GetCountryByIdAsync(state.CountryId);

            if (country == null)
            {
                return(RedirectToAction("List"));
            }

            //prepare model
            var model = await _countryModelFactory.PrepareStateProvinceModelAsync(null, country, state);

            return(View(model));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> RatesByCountryStateZipList(ConfigurationModel searchModel)
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageTaxSettings))
            {
                return(await AccessDeniedDataTablesJson());
            }

            var records = await _taxRateService.GetAllTaxRatesAsync(searchModel.Page - 1, searchModel.PageSize);

            var gridModel = await new CountryStateZipListModel().PrepareToGridAsync(searchModel, records, () =>
            {
                return(records.SelectAwait(async record => new CountryStateZipModel
                {
                    Id = record.Id,
                    StoreId = record.StoreId,
                    StoreName = (await _storeService.GetStoreByIdAsync(record.StoreId))?.Name ?? "*",
                    TaxCategoryId = record.TaxCategoryId,
                    TaxCategoryName = (await _taxCategoryService.GetTaxCategoryByIdAsync(record.TaxCategoryId))?.Name ?? string.Empty,
                    CountryId = record.CountryId,
                    CountryName = (await _countryService.GetCountryByIdAsync(record.CountryId))?.Name ?? "Unavailable",
                    StateProvinceId = record.StateProvinceId,
                    StateProvinceName = (await _stateProvinceService.GetStateProvinceByIdAsync(record.StateProvinceId))?.Name ?? "*",

                    Zip = !string.IsNullOrEmpty(record.Zip) ? record.Zip : "*",
                    Percentage = record.Percentage
                }));
            });

            return(Json(gridModel));
        }
        /// <summary>
        /// Places order and returns the handover URL to redirect user when order is placed successful; otherwise returns null with the errors as <see cref="IList{string}"/>
        /// </summary>
        /// <param name="order">The order</param>
        /// <returns>The <see cref="Task"/> containing the handover URL to redirect user when order is placed successful; otherwise returns null with the errors as <see cref="IList{string}"/></returns>
        public virtual async Task <(string HandoverUrl, IList <string> Errors)> PlaceOrderAsync(Order order)
        {
            if (order is null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            var validationResult = await ValidateAsync();

            if (!validationResult.IsValid)
            {
                return(null, validationResult.Errors);
            }

            var errors = new List <string>();

            var shippingAddressId = order.PickupInStore ? order.PickupAddressId : order.ShippingAddressId;

            if (!shippingAddressId.HasValue)
            {
                errors.Add($"Cannot process payment for order {order.CustomOrderNumber}. The shipping address not found.");
                return(null, errors);
            }

            var shippingAddress = await _addressService.GetAddressByIdAsync(shippingAddressId.Value);

            if (shippingAddress == null)
            {
                errors.Add($"Cannot process payment for order {order.CustomOrderNumber}. The shipping address not found.");
                return(null, errors);
            }

            if (!shippingAddress.StateProvinceId.HasValue)
            {
                errors.Add($"Cannot process payment for order {order.CustomOrderNumber}. The state not found.");
                return(null, errors);
            }

            var shippingState = await _stateProvinceService.GetStateProvinceByIdAsync(shippingAddress.StateProvinceId.Value);

            if (shippingState == null)
            {
                errors.Add($"Cannot process payment for order {order.CustomOrderNumber}. The state not found.");
                return(null, errors);
            }

            var deliveryAddress = new CustomerAddress
            {
                Line1    = shippingAddress.Address1,
                Line2    = shippingAddress.Address2,
                Suburb   = shippingAddress.City ?? shippingAddress.County,
                PostCode = shippingAddress.ZipPostalCode,
                State    = shippingState.Abbreviation
            };

            var customer = await _customerService.GetCustomerByIdAsync(order.CustomerId);

            if (customer == null)
            {
                errors.Add($"Cannot process payment for order {order.CustomOrderNumber}. The customer not found.");
                return(null, errors);
            }

            var customerDetails = new PersonalDetails
            {
                Email           = shippingAddress.Email ?? customer.Email,
                DeliveryAddress = deliveryAddress
            };

            if (!string.IsNullOrWhiteSpace(shippingAddress.PhoneNumber))
            {
                customerDetails.PhoneNumber = shippingAddress.PhoneNumber;
            }
            else if (_customerSettings.PhoneEnabled)
            {
                customerDetails.PhoneNumber = await _genericAttributeService
                                              .GetAttributeAsync <string>(customer, NopCustomerDefaults.PhoneAttribute);
            }

            if (!order.PickupInStore && !string.IsNullOrWhiteSpace(shippingAddress.FirstName))
            {
                customerDetails.FirstName = shippingAddress.FirstName;
            }
            else
            {
                customerDetails.FirstName = _customerSettings.FirstNameEnabled
                    ? await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.FirstNameAttribute)
                    : _customerSettings.UsernamesEnabled ? customer.Username : customer.Email;
            }

            if (!order.PickupInStore && !string.IsNullOrWhiteSpace(shippingAddress.LastName))
            {
                customerDetails.FamilyName = shippingAddress.LastName;
            }
            else
            {
                customerDetails.FamilyName = _customerSettings.LastNameEnabled
                    ? await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.LastNameAttribute)
                    : _customerSettings.UsernamesEnabled ? customer.Username : customer.Email;
            }

            // billing address not required
            var billingAddress = await _addressService.GetAddressByIdAsync(order.BillingAddressId);

            if (billingAddress != null)
            {
                var billingState = await _stateProvinceService.GetStateProvinceByIdAsync(billingAddress.StateProvinceId.Value);

                if (billingState != null)
                {
                    customerDetails.ResidentialAddress = new CustomerAddress
                    {
                        Line1    = billingAddress.Address1,
                        Line2    = billingAddress.Address2,
                        Suburb   = billingAddress.City ?? billingAddress.County,
                        PostCode = billingAddress.ZipPostalCode,
                        State    = billingState.Abbreviation
                    };

                    if (string.IsNullOrEmpty(customerDetails.PhoneNumber))
                    {
                        customerDetails.PhoneNumber = billingAddress.PhoneNumber;
                    }
                }
            }

            var currentRequestProtocol = _webHelper.GetCurrentRequestProtocol();
            var urlHelper   = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);
            var callbackUrl = urlHelper.RouteUrl(Defaults.SuccessfulPaymentWebhookRouteName, null, currentRequestProtocol);
            var failUrl     = urlHelper.RouteUrl(Defaults.OrderDetailsRouteName, new { orderId = order.Id }, currentRequestProtocol);

            var customerJourney = new CustomerJourney
            {
                Origin = "Online",
                Online = new OnlineJourneyDetails
                {
                    CallbackUrl      = callbackUrl,
                    CancelUrl        = failUrl,
                    FailUrl          = failUrl,
                    CustomerDetails  = customerDetails,
                    PlanCreationType = "pending",
                    DeliveryMethod   = order.PickupInStore ? "Pickup" : "Delivery"
                }
            };

            var createOrderRequest = new CreateOrderRequest
            {
                PurchasePrice   = (int)(order.OrderTotal * 100),
                CustomerJourney = customerJourney,
                RetailerOrderNo = order.Id.ToString()
            };

            var orderItems = await _orderService.GetOrderItemsAsync(order.Id);

            if (orderItems?.Any() == true)
            {
                var cartItems = new List <CartItem>();
                foreach (var item in orderItems)
                {
                    var product = await _productService.GetProductByIdAsync(item.ProductId);

                    if (product == null)
                    {
                        errors.Add($"Cannot process payment for order {order.CustomOrderNumber}. Cannot get the product by id '{item.ProductId}'.");
                        return(null, errors);
                    }

                    var productName = string.Empty;
                    if (string.IsNullOrEmpty(item.AttributesXml))
                    {
                        productName = product.Name;
                    }
                    else
                    {
                        var attributeInfo = await _productAttributeFormatter.FormatAttributesAsync(product, item.AttributesXml, customer, ", ");

                        productName = $"{product.Name} ({attributeInfo})";
                    }

                    var cartItem = new CartItem
                    {
                        Name      = productName,
                        Code      = product.Id.ToString(),
                        Quantity  = item.Quantity.ToString(),
                        UnitPrice = (int)(item.UnitPriceInclTax * 100),
                        Charge    = (int)(item.PriceInclTax * 100)
                    };

                    cartItems.Add(cartItem);
                }

                createOrderRequest.CartItems = cartItems.ToArray();
            }

            try
            {
                var openPayOrder = await _openPayApi.CreateOrderAsync(createOrderRequest);

                var formPost = openPayOrder?.NextAction?.FormPost;
                if (!string.IsNullOrEmpty(formPost?.FormPostUrl) && formPost?.FormFields?.Any() == true)
                {
                    // add query directly to eliminate character escaping
                    var redirectUrl = $"{formPost?.FormPostUrl}?{string.Join("&", formPost.FormFields.Select(field => $"{field.Name}={field.Value}"))}";

                    return(redirectUrl, errors);
                }

                errors.Add($"Cannot process payment for order {order.CustomOrderNumber}. Cannot get the handover URL to redirect user to OpenPay gateway.");
            }
            catch (ApiException ex)
            {
                errors.Add(ex.Message);
            }

            return(null, errors);
        }
        /// <returns>A task that represents the asynchronous operation</returns>
        public async Task <IActionResult> RateByWeightByTotalList(ConfigurationModel searchModel, ConfigurationModel filter)
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageShippingSettings))
            {
                return(await AccessDeniedDataTablesJson());
            }

            //var records = _shippingByWeightService.GetAll(command.Page - 1, command.PageSize);
            var records = await _shippingByWeightService.FindRecordsAsync(
                pageIndex : searchModel.Page - 1,
                pageSize : searchModel.PageSize,
                storeId : filter.SearchStoreId,
                warehouseId : filter.SearchWarehouseId,
                countryId : filter.SearchCountryId,
                stateProvinceId : filter.SearchStateProvinceId,
                zip : filter.SearchZip,
                shippingMethodId : filter.SearchShippingMethodId,
                weight : null,
                orderSubtotal : null
                );

            var gridModel = await new ShippingByWeightByTotalListModel().PrepareToGridAsync(searchModel, records, () =>
            {
                return(records.SelectAwait(async record =>
                {
                    var model = new ShippingByWeightByTotalModel
                    {
                        Id = record.Id,
                        StoreId = record.StoreId,
                        StoreName = (await _storeService.GetStoreByIdAsync(record.StoreId))?.Name ?? "*",
                        WarehouseId = record.WarehouseId,
                        WarehouseName = (await _shippingService.GetWarehouseByIdAsync(record.WarehouseId))?.Name ?? "*",
                        ShippingMethodId = record.ShippingMethodId,
                        ShippingMethodName = (await _shippingService.GetShippingMethodByIdAsync(record.ShippingMethodId))?.Name ?? "Unavailable",
                        CountryId = record.CountryId,
                        CountryName = (await _countryService.GetCountryByIdAsync(record.CountryId))?.Name ?? "*",
                        StateProvinceId = record.StateProvinceId,
                        StateProvinceName = (await _stateProvinceService.GetStateProvinceByIdAsync(record.StateProvinceId))?.Name ?? "*",
                        WeightFrom = record.WeightFrom,
                        WeightTo = record.WeightTo,
                        OrderSubtotalFrom = record.OrderSubtotalFrom,
                        OrderSubtotalTo = record.OrderSubtotalTo,
                        AdditionalFixedCost = record.AdditionalFixedCost,
                        PercentageRateOfSubtotal = record.PercentageRateOfSubtotal,
                        RatePerWeightUnit = record.RatePerWeightUnit,
                        LowerWeightLimit = record.LowerWeightLimit,
                        Zip = !string.IsNullOrEmpty(record.Zip) ? record.Zip : "*"
                    };

                    var htmlSb = new StringBuilder("<div>");
                    htmlSb.AppendFormat("{0}: {1}",
                                        await _localizationService.GetResourceAsync("Plugins.Shipping.FixedByWeightByTotal.Fields.WeightFrom"),
                                        model.WeightFrom);
                    htmlSb.Append("<br />");
                    htmlSb.AppendFormat("{0}: {1}",
                                        await _localizationService.GetResourceAsync("Plugins.Shipping.FixedByWeightByTotal.Fields.WeightTo"),
                                        model.WeightTo);
                    htmlSb.Append("<br />");
                    htmlSb.AppendFormat("{0}: {1}",
                                        await _localizationService.GetResourceAsync("Plugins.Shipping.FixedByWeightByTotal.Fields.OrderSubtotalFrom"),
                                        model.OrderSubtotalFrom);
                    htmlSb.Append("<br />");
                    htmlSb.AppendFormat("{0}: {1}",
                                        await _localizationService.GetResourceAsync("Plugins.Shipping.FixedByWeightByTotal.Fields.OrderSubtotalTo"),
                                        model.OrderSubtotalTo);
                    htmlSb.Append("<br />");
                    htmlSb.AppendFormat("{0}: {1}",
                                        await _localizationService.GetResourceAsync("Plugins.Shipping.FixedByWeightByTotal.Fields.AdditionalFixedCost"),
                                        model.AdditionalFixedCost);
                    htmlSb.Append("<br />");
                    htmlSb.AppendFormat("{0}: {1}",
                                        await _localizationService.GetResourceAsync("Plugins.Shipping.FixedByWeightByTotal.Fields.RatePerWeightUnit"),
                                        model.RatePerWeightUnit);
                    htmlSb.Append("<br />");
                    htmlSb.AppendFormat("{0}: {1}",
                                        await _localizationService.GetResourceAsync("Plugins.Shipping.FixedByWeightByTotal.Fields.LowerWeightLimit"),
                                        model.LowerWeightLimit);
                    htmlSb.Append("<br />");
                    htmlSb.AppendFormat("{0}: {1}",
                                        await _localizationService.GetResourceAsync("Plugins.Shipping.FixedByWeightByTotal.Fields.PercentageRateOfSubtotal"),
                                        model.PercentageRateOfSubtotal);

                    htmlSb.Append("</div>");
                    model.DataHtml = htmlSb.ToString();

                    return model;
                }));
            });

            return(Json(gridModel));
        }