コード例 #1
0
        public IActionResult TaxCategoryUpdate(Models.Tax.TaxCategoryModel model)
        {
            //ensure that Avalara tax provider is active
            if (!(_taxService.LoadActiveTaxProvider(_workContext.CurrentCustomer) is AvalaraTaxProvider))
            {
                return(new NullJsonResult());
            }

            if (!_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                return(AccessDeniedView());
            }

            if (!ModelState.IsValid)
            {
                return(Json(new DataSourceResult {
                    Errors = ModelState.SerializeErrors()
                }));
            }

            var taxCategory = _taxCategoryService.GetTaxCategoryById(model.Id);

            taxCategory = model.ToEntity(taxCategory);
            _taxCategoryService.UpdateTaxCategory(taxCategory);

            //save tax code type as generic attribute
            if (!string.IsNullOrEmpty(model.TypeId) && !model.TypeId.Equals(Guid.Empty.ToString()))
            {
                _genericAttributeService.SaveAttribute(taxCategory, AvalaraTaxDefaults.TaxCodeTypeAttribute, model.TypeId);
            }

            return(new NullJsonResult());
        }
コード例 #2
0
ファイル: TaxController.cs プロジェクト: huyhuana/grandnode-1
        public async Task<IActionResult> CategoryUpdate(TaxCategoryModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
            }

            var taxCategory = await _taxCategoryService.GetTaxCategoryById(model.Id);
            taxCategory = model.ToEntity(taxCategory);
            await _taxCategoryService.UpdateTaxCategory(taxCategory);

            return new NullJsonResult();
        }
コード例 #3
0
        public IActionResult CategoryUpdate(TaxCategoryModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Json(new DataSourceResult {
                    Errors = ModelState.SerializeErrors()
                }));
            }

            var taxCategory = _taxCategoryService.GetTaxCategoryById(model.Id);

            taxCategory = model.ToEntity(taxCategory);
            _taxCategoryService.UpdateTaxCategory(taxCategory);

            return(new NullJsonResult());
        }
コード例 #4
0
        public ActionResult CategoryUpdate(TaxCategoryModel model, GridCommand command)
        {
            if (!ModelState.IsValid)
            {
                var modelStateErrors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage);
                return(Content(modelStateErrors.FirstOrDefault()));
            }

            var taxCategory = _taxCategoryService.GetTaxCategoryById(model.Id);

            taxCategory = model.ToEntity(taxCategory);

            _taxCategoryService.UpdateTaxCategory(taxCategory);

            return(Categories(command));
        }
コード例 #5
0
        public override IActionResult CategoryDelete(int id)
        {
            //ensure that Avalara tax provider is active
            if (!_taxPluginManager.IsPluginActive(AvalaraTaxDefaults.SystemName))
            {
                return(new NullJsonResult());
            }

            if (!_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                return(AccessDeniedView());
            }

            //try to get a tax category with the specified id
            var taxCategory = _taxCategoryService.GetTaxCategoryById(id);

            if (taxCategory == null)
            {
                throw new ArgumentException("No tax category found with the specified id");
            }

            //delete generic attributes
            _genericAttributeService.SaveAttribute <string>(taxCategory, AvalaraTaxDefaults.TaxCodeDescriptionAttribute, null);
            _genericAttributeService.SaveAttribute <string>(taxCategory, AvalaraTaxDefaults.TaxCodeTypeAttribute, null);

            _taxCategoryService.DeleteTaxCategory(taxCategory);

            return(new NullJsonResult());
        }
        public IActionResult RatesByCountryStateZipList(ConfigurationModel searchModel)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                return(AccessDeniedDataTablesJson());
            }

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

            var gridModel = new CountryStateZipListModel().PrepareToGrid(searchModel, records, () =>
            {
                return(records.Select(record => new CountryStateZipModel
                {
                    Id = record.Id,
                    StoreId = record.StoreId,
                    StoreName = _storeService.GetStoreById(record.StoreId)?.Name ?? "*",
                    TaxCategoryId = record.TaxCategoryId,
                    TaxCategoryName = _taxCategoryService.GetTaxCategoryById(record.TaxCategoryId)?.Name ?? string.Empty,
                    CountryId = record.CountryId,
                    CountryName = _countryService.GetCountryById(record.CountryId)?.Name ?? "Unavailable",
                    StateProvinceId = record.StateProvinceId,
                    StateProvinceName = _stateProvinceService.GetStateProvinceById(record.StateProvinceId)?.Name ?? "*",
                    Zip = !string.IsNullOrEmpty(record.Zip) ? record.Zip : "*",
                    Percentage = record.Percentage
                }));
            });

            return(Json(gridModel));
        }
コード例 #7
0
        public IActionResult RatesByCountryStateZipList(DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                return(AccessDeniedKendoGridJson());
            }

            var records       = _taxRateService.GetAllTaxRates(command.Page - 1, command.PageSize);
            var taxRatesModel = records.Select(record => new CountryStateZipModel
            {
                Id                = record.Id,
                StoreId           = record.StoreId,
                StoreName         = _storeService.GetStoreById(record.StoreId)?.Name ?? "*",
                TaxCategoryId     = record.TaxCategoryId,
                TaxCategoryName   = _taxCategoryService.GetTaxCategoryById(record.TaxCategoryId)?.Name ?? string.Empty,
                CountryId         = record.CountryId,
                CountryName       = _countryService.GetCountryById(record.CountryId)?.Name ?? "Unavailable",
                StateProvinceId   = record.StateProvinceId,
                StateProvinceName = _stateProvinceService.GetStateProvinceById(record.StateProvinceId)?.Name ?? "*",
                Zip               = !string.IsNullOrEmpty(record.Zip) ? record.Zip : "*",
                Percentage        = record.Percentage,
            }).ToList();

            var gridModel = new DataSourceResult
            {
                Data  = taxRatesModel,
                Total = records.TotalCount
            };

            return(Json(gridModel));
        }
コード例 #8
0
        public ActionResult RatesByCountryStateZipList(DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                return(ErrorForKendoGridJson("Access denied"));
            }

            var records       = _taxRateService.GetAllTaxRates(command.Page - 1, command.PageSize);
            var taxRatesModel = records
                                .Select(x =>
            {
                var m = new WB_CountryStateZipModel
                {
                    Id              = x.Id,
                    StoreId         = x.StoreId,
                    TaxCategoryId   = x.TaxCategoryId,
                    CountryId       = x.CountryId,
                    StateProvinceId = x.StateProvinceId,
                    Zip             = x.Zip,
                    Percentage      = x.Percentage
                };
                //store
                var store   = _storeService.GetStoreById(x.StoreId);
                m.StoreName = store != null ? store.Name : "*";
                //tax category
                var tc            = _taxCategoryService.GetTaxCategoryById(x.TaxCategoryId);
                m.TaxCategoryName = tc != null ? tc.Name : "";
                //country
                var c         = _countryService.GetCountryById(x.CountryId);
                m.CountryName = c != null ? c.Name : "Unavailable";
                //state
                var s = _stateProvinceService.GetStateProvinceById(x.StateProvinceId);
                m.StateProvinceName = s != null ? s.Name : "*";
                //zip
                m.Zip = !string.IsNullOrEmpty(x.Zip) ? x.Zip : "*";
                return(m);
            }).ToList();

            var gridModel = new DataSourceResult
            {
                Data  = taxRatesModel,
                Total = records.TotalCount
            };

            return(Json(gridModel));
        }
コード例 #9
0
        public ActionResult CategoryUpdate(TaxCategoryModel model, GridCommand command)
        {
            if (_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                if (!ModelState.IsValid)
                {
                    var modelStateErrors = this.ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage);
                    return(Content(modelStateErrors.FirstOrDefault()));
                }

                var taxCategory = _taxCategoryService.GetTaxCategoryById(model.Id);
                taxCategory = model.ToEntity(taxCategory);

                _taxCategoryService.UpdateTaxCategory(taxCategory);
            }

            return(Categories(command));
        }
コード例 #10
0
        public virtual IActionResult CategoryUpdate(TaxCategoryModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                return(AccessDeniedView());
            }

            if (!ModelState.IsValid)
            {
                return(ErrorJson(ModelState.SerializeErrors()));
            }

            var taxCategory = _taxCategoryService.GetTaxCategoryById(model.Id);

            taxCategory = model.ToEntity(taxCategory);
            _taxCategoryService.UpdateTaxCategory(taxCategory);

            return(new NullJsonResult());
        }
コード例 #11
0
        public ActionResult CategoryUpdate(TaxCategoryModel model, GridCommand command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                return(AccessDeniedView());
            }

            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Categories"));
            }

            var taxCategory = _taxCategoryService.GetTaxCategoryById(model.Id);

            taxCategory = model.ToEntity(taxCategory);
            _taxCategoryService.UpdateTaxCategory(taxCategory);

            return(Categories(command));
        }
コード例 #12
0
        public async Task <IActionResult> RatesList(DataSourceRequest command)
        {
            if (!await _permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                return(Content("Access denied"));
            }

            var records = await _taxRateService.GetAllTaxRates(command.Page - 1, command.PageSize);

            var taxRatesModel = new List <TaxRateModel>();

            foreach (var x in records)
            {
                var m = new TaxRateModel
                {
                    Id              = x.Id,
                    StoreId         = x.StoreId,
                    TaxCategoryId   = x.TaxCategoryId,
                    CountryId       = x.CountryId,
                    StateProvinceId = x.StateProvinceId,
                    Zip             = x.Zip,
                    Percentage      = x.Percentage,
                };
                //store
                var store = await _storeService.GetStoreById(x.StoreId);

                m.StoreName = (store != null) ? store.Name : "*";
                //tax category
                var tc = await _taxCategoryService.GetTaxCategoryById(x.TaxCategoryId);

                m.TaxCategoryName = (tc != null) ? tc.Name : "";
                //country
                var c = await _countryService.GetCountryById(x.CountryId);

                m.CountryName = (c != null) ? c.Name : "Unavailable";
                //state
                var s = await _stateProvinceService.GetStateProvinceById(x.StateProvinceId);

                m.StateProvinceName = (s != null) ? s.Name : "*";
                //zip
                m.Zip = (!String.IsNullOrEmpty(x.Zip)) ? x.Zip : "*";
                taxRatesModel.Add(m);
            }

            var gridModel = new DataSourceResult
            {
                Data  = taxRatesModel,
                Total = records.TotalCount
            };

            return(Json(gridModel));
        }
コード例 #13
0
        public ActionResult RatesList(GridCommand command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                return(Content("Access denied"));
            }

            var records       = _taxRateService.GetAllTaxRates(command.Page - 1, command.PageSize);
            var taxRatesModel = records
                                .Select(x =>
            {
                var m = new TaxRateModel()
                {
                    Id              = x.Id,
                    StoreId         = x.StoreId,
                    TaxCategoryId   = x.TaxCategoryId,
                    CountryId       = x.CountryId,
                    StateProvinceId = x.StateProvinceId,
                    Zip             = x.Zip,
                    Percentage      = x.Percentage,
                };
                //store
                var store   = _storeService.GetStoreById(x.StoreId);
                m.StoreName = (store != null) ? store.Name : "*";
                //tax category
                var tc            = _taxCategoryService.GetTaxCategoryById(x.TaxCategoryId);
                m.TaxCategoryName = (tc != null) ? tc.Name : "";
                //country
                var c         = _countryService.GetCountryById(x.CountryId);
                m.CountryName = (c != null) ? c.Name : "Unavailable";
                //state
                var s = _stateProvinceService.GetStateProvinceById(x.StateProvinceId);
                m.StateProvinceName = (s != null) ? s.Name : "*";
                //zip
                m.Zip = (!String.IsNullOrEmpty(x.Zip)) ? x.Zip : "*";
                return(m);
            })
                                .ToList();
            var model = new GridModel <TaxRateModel>
            {
                Data  = taxRatesModel,
                Total = records.TotalCount
            };

            return(new JsonResult
            {
                Data = model
            });
        }
コード例 #14
0
        public async Task <IActionResult> RatesList(DataSourceRequest command)
        {
            var records = await _taxRateService.GetAllTaxRates(command.Page - 1, command.PageSize);

            var taxRatesModel = new List <TaxRateModel>();

            foreach (var x in records)
            {
                var m = new TaxRateModel
                {
                    Id              = x.Id,
                    StoreId         = x.StoreId,
                    TaxCategoryId   = x.TaxCategoryId,
                    CountryId       = x.CountryId,
                    StateProvinceId = x.StateProvinceId,
                    Zip             = x.Zip,
                    Percentage      = x.Percentage,
                };
                //store
                var store = await _storeService.GetStoreById(x.StoreId);

                m.StoreName = (store != null) ? store.Shortcut : "*";
                //tax category
                var tc = await _taxCategoryService.GetTaxCategoryById(x.TaxCategoryId);

                m.TaxCategoryName = (tc != null) ? tc.Name : "";
                //country
                var c = await _countryService.GetCountryById(x.CountryId);

                m.CountryName = (c != null) ? c.Name : "Unavailable";
                //state
                var s = c?.StateProvinces.FirstOrDefault(z => z.Id == x.StateProvinceId);
                m.StateProvinceName = (s != null) ? s.Name : "*";
                //zip
                m.Zip = (!String.IsNullOrEmpty(x.Zip)) ? x.Zip : "*";
                taxRatesModel.Add(m);
            }

            var gridModel = new DataSourceResult
            {
                Data  = taxRatesModel,
                Total = records.TotalCount
            };

            return(Json(gridModel));
        }
コード例 #15
0
        public ActionResult RatesList(GridCommand command)
        {
            var records       = _taxRateService.GetAllTaxRates(command.Page - 1, command.PageSize);
            var taxRatesModel = records
                                .Select(x =>
            {
                var m = new TaxRateModel()
                {
                    Id              = x.Id,
                    TaxCategoryId   = x.TaxCategoryId,
                    CountryId       = x.CountryId,
                    StateProvinceId = x.StateProvinceId,
                    Zip             = x.Zip,
                    Percentage      = x.Percentage,
                };
                var tc              = _taxCategoryService.GetTaxCategoryById(x.TaxCategoryId);
                m.TaxCategoryName   = (tc != null) ? tc.Name : "";
                var c               = _countryService.GetCountryById(x.CountryId);
                m.CountryName       = (c != null) ? c.Name : "Unavailable";
                var s               = _stateProvinceService.GetStateProvinceById(x.StateProvinceId);
                m.StateProvinceName = (s != null) ? s.Name : "*";
                m.Zip               = (!String.IsNullOrEmpty(x.Zip)) ? x.Zip : "*";
                return(m);
            })
                                .ToList();
            var model = new GridModel <TaxRateModel>
            {
                Data  = taxRatesModel,
                Total = records.TotalCount
            };

            return(new JsonResult
            {
                Data = model
            });
        }
コード例 #16
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            var address = calculateTaxRequest.Address;

            if (address == null || address.Country == null)
            {
                return new CalculateTaxResult {
                           Errors = new List <string> {
                               "Address is not set"
                           }
                }
            }
            ;

            var errors     = new List <string>();
            var taxRateKey = string.Format(ModelCacheEventConsumer.TAXRATE_KEY, address.Id, calculateTaxRequest.TaxCategoryId);

            var taxRate = _cacheManager.Get(taxRateKey, () =>
            {
                var tax = decimal.Zero;

                var taxCategory = _taxCategoryService.GetTaxCategoryById(calculateTaxRequest.TaxCategoryId);

                var taxCategoryName = taxCategory == null ? "Anything" : taxCategory.Name;
                taxCategoryName     = XmlHelper.XmlEncode(taxCategoryName);

                var fullName = string.Format("{0} {1}", address.FirstName, address.LastName);

                //create tax request
                var xml = String.Format(Properties.Resources.taxRequest,
                                        _exactorTaxSettings.MerchantId,
                                        _exactorTaxSettings.UserId,
                                        fullName,
                                        address.Address1,
                                        address.Address2 ?? String.Empty,
                                        address.City,
                                        address.StateProvince != null ? address.StateProvince.Name : String.Empty,
                                        address.ZipPostalCode,
                                        address.Country.Name,
                                        taxCategoryName,                    //description
                                                                            //Exactor does not return rate, only the amount of tax. The amount has limited accuracy in two digits,
                                                                            //so the price sent is obviously greater. Further it is converted into percentages with accuracy up to the fourth digit.
                                        10000,                              //gross amount
                                        DateTime.Now.ToString("yyyy-MM-dd") //sale date
                                        );

                string data;
                using (var client = new WebClient())
                {
                    try
                    {
                        data = client.UploadString(REQUEST_URL, xml);
                    }
                    catch (WebException ex)
                    {
                        errors.Add(ex.Message);
                        return(0);
                    }
                }

                var taxResponse = XDocument.Parse(data).Root;

                if (taxResponse == null)
                {
                    return(0);
                }

                //get XML namespace
                var ns = taxResponse.Name.ToString().Replace("TaxResponse", String.Empty);

                var invoiceResponse = taxResponse.Element(ns + "InvoiceResponse");
                var errorResponse   = taxResponse.Element(ns + "ErrorResponse");

                if (invoiceResponse == null && errorResponse == null)
                {
                    return(0);
                }

                if (errorResponse != null)
                {
                    errors.Add(String.Format("Line {0}: {1}", errorResponse.Element(ns + "LineNumber").Value, errorResponse.Element(ns + "ErrorDescription").Value));
                }
                else
                {
                    tax = Convert.ToDecimal(invoiceResponse.Element(ns + "TotalTaxAmount").Value, new CultureInfo("en-US"));
                }

                return(tax / 100);
            });

            if (errors.Any())
            {
                _cacheManager.Remove(taxRateKey);
            }

            return(new CalculateTaxResult {
                Errors = errors, TaxRate = taxRate
            });
        }
コード例 #17
0
 /// <summary>
 /// Gets a tax category
 /// </summary>
 /// <param name="taxCategoryId">Tax category identifier</param>
 /// <returns>Tax category</returns>
 public TaxCategory GetTaxCategoryById(int taxCategoryId)
 {
     return(_taxCategoryService.GetTaxCategoryById(taxCategoryId));
 }
        public IActionResult ExportProducts(string selectedIds)
        {
            //ensure that Avalara tax provider is active
            if (!_taxPluginManager.IsPluginActive(AvalaraTaxDefaults.SystemName))
            {
                return(RedirectToAction("List", "Product"));
            }

            if (!_permissionService.Authorize(StandardPermissionProvider.ManageTaxSettings))
            {
                return(AccessDeniedView());
            }

            //prepare exported items
            var productIds    = selectedIds?.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(id => Convert.ToInt32(id)).ToArray();
            var exportedItems = new List <ItemModel>();

            foreach (var product in _productService.GetProductsByIds(productIds))
            {
                //find product combinations
                var combinations = _productAttributeService.GetAllProductAttributeCombinations(product.Id)
                                   .Where(combination => !string.IsNullOrEmpty(combination.Sku));

                //export items with specified SKU only
                if (string.IsNullOrEmpty(product.Sku) && !combinations.Any())
                {
                    continue;
                }

                //prepare common properties
                var taxCategory = _taxCategoryService.GetTaxCategoryById(product.TaxCategoryId);
                var taxCode     = CommonHelper.EnsureMaximumLength(taxCategory?.Name, 25);
                var description = CommonHelper.EnsureMaximumLength(product.ShortDescription ?? product.Name, 255);

                //add the product as exported item
                if (!string.IsNullOrEmpty(product.Sku))
                {
                    exportedItems.Add(new ItemModel
                    {
                        createdDate = DateTime.UtcNow,
                        description = description,
                        itemCode    = CommonHelper.EnsureMaximumLength(product.Sku, 50),
                        taxCode     = taxCode
                    });
                }

                //add product combinations
                exportedItems.AddRange(combinations.Select(combination => new ItemModel
                {
                    createdDate = DateTime.UtcNow,
                    description = description,
                    itemCode    = CommonHelper.EnsureMaximumLength(combination.Sku, 50),
                    taxCode     = taxCode
                }));
            }

            //get existing items
            var existingItemCodes = _avalaraTaxManager.GetItems()?.Select(item => item.itemCode).ToList() ?? new List <string>();

            //remove duplicates
            exportedItems = exportedItems.Where(item => !existingItemCodes.Contains(item.itemCode)).Distinct().ToList();

            //export items
            if (exportedItems.Any())
            {
                //create items and get the result
                var result = _avalaraTaxManager.CreateItems(exportedItems)?.Count;

                //display results
                if (result.HasValue && result > 0)
                {
                    _notificationService.SuccessNotification(string.Format(_localizationService.GetResource("Plugins.Tax.Avalara.Items.Export.Success"), result));
                }
                else
                {
                    _notificationService.ErrorNotification(_localizationService.GetResource("PPlugins.Tax.Avalara.Items.Export.Error"));
                }
            }
            else
            {
                _notificationService.SuccessNotification(_localizationService.GetResource("Plugins.Tax.Avalara.Items.Export.AlreadyExported"));
            }

            return(RedirectToAction("List", "Product"));
        }
コード例 #19
0
        public ActionResult Configure()
        {
            var taxCategories = _taxCategoryService.GetAllTaxCategories();

            if (taxCategories.Count == 0)
            {
                return(Content("No tax categories can be loaded"));
            }

            var model = new TaxRateListModel();

            foreach (var tc in taxCategories)
            {
                model.AvailableTaxCategories.Add(new SelectListItem()
                {
                    Text = tc.Name, Value = tc.Id.ToString()
                });
            }
            var countries = _countryService.GetAllCountries(true);

            foreach (var c in countries)
            {
                model.AvailableCountries.Add(new SelectListItem()
                {
                    Text = c.Name, Value = c.Id.ToString()
                });
            }
            model.AvailableStates.Add(new SelectListItem()
            {
                Text = "*", Value = "0"
            });
            var states = _stateProvinceService.GetStateProvincesByCountryId(countries.FirstOrDefault().Id);

            if (states.Count > 0)
            {
                foreach (var s in states)
                {
                    model.AvailableStates.Add(new SelectListItem()
                    {
                        Text = s.Name, Value = s.Id.ToString()
                    });
                }
            }

            model.TaxRates = _taxRateService.GetAllTaxRates()
                             .Select(x =>
            {
                var m = new TaxRateModel()
                {
                    Id              = x.Id,
                    TaxCategoryId   = x.TaxCategoryId,
                    CountryId       = x.CountryId,
                    StateProvinceId = x.StateProvinceId,
                    Zip             = x.Zip,
                    Percentage      = x.Percentage,
                };
                var tc              = _taxCategoryService.GetTaxCategoryById(x.TaxCategoryId);
                m.TaxCategoryName   = (tc != null) ? tc.Name : "";
                var c               = _countryService.GetCountryById(x.CountryId);
                m.CountryName       = (c != null) ? c.Name : "Unavailable";
                var s               = _stateProvinceService.GetStateProvinceById(x.StateProvinceId);
                m.StateProvinceName = (s != null) ? s.Name : "*";
                m.Zip               = (!String.IsNullOrEmpty(x.Zip)) ? x.Zip : "*";
                return(m);
            })
                             .ToList();

            return(View("SmartStore.Plugin.Tax.CountryStateZip.Views.TaxCountryStateZip.Configure", model));
        }
コード例 #20
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            if (calculateTaxRequest.Address == null)
            {
                return new CalculateTaxResult {
                           Errors = new List <string>()
                           {
                               "Address is not set"
                           }
                }
            }
            ;

            string cacheKey = string.Format(TAXRATE_KEY,
                                            !string.IsNullOrEmpty(calculateTaxRequest.Address.Address1) ? calculateTaxRequest.Address.Address1 : string.Empty,
                                            !string.IsNullOrEmpty(calculateTaxRequest.Address.City) ? calculateTaxRequest.Address.City : string.Empty,
                                            calculateTaxRequest.Address.StateProvince != null ? calculateTaxRequest.Address.StateProvince.Id : 0,
                                            calculateTaxRequest.Address.Country != null ? calculateTaxRequest.Address.Country.Id : 0,
                                            !string.IsNullOrEmpty(calculateTaxRequest.Address.ZipPostalCode) ? calculateTaxRequest.Address.ZipPostalCode : string.Empty);

            // we don't use standard way _cacheManager.Get() due the need write errors to CalculateTaxResult
            if (_cacheManager.IsSet(cacheKey))
            {
                return new CalculateTaxResult {
                           TaxRate = _cacheManager.Get <decimal>(cacheKey)
                }
            }
            ;

            var address = new Address
            {
                AddressCode = calculateTaxRequest.Address.Id.ToString(),
                Line1       = calculateTaxRequest.Address.Address1,
                Line2       = calculateTaxRequest.Address.Address2,
                City        = calculateTaxRequest.Address.City,
                Region      = calculateTaxRequest.Address.StateProvince != null ? calculateTaxRequest.Address.StateProvince.Abbreviation : null,
                Country     = calculateTaxRequest.Address.Country != null ? calculateTaxRequest.Address.Country.TwoLetterIsoCode : null,
                PostalCode  = calculateTaxRequest.Address.ZipPostalCode
            };

            //information about product
            var taxCategory = _taxCategoryService.GetTaxCategoryById(calculateTaxRequest.TaxCategoryId);
            var line        = new Line
            {
                LineNo          = "1",
                DestinationCode = calculateTaxRequest.Address.Id.ToString(),
                OriginCode      = calculateTaxRequest.Address.Id.ToString(),
                ItemCode        = calculateTaxRequest.Product != null ? calculateTaxRequest.Product.Sku : null,
                Description     = calculateTaxRequest.Product != null ? calculateTaxRequest.Product.ShortDescription : null,
                TaxCode         = taxCategory != null ? taxCategory.Name : null,
                Qty             = 1,
                Amount          = calculateTaxRequest.Price
            };

            //tax exemption
            var exemptionReason = string.Empty;

            if (calculateTaxRequest.Product != null && calculateTaxRequest.Product.IsTaxExempt)
            {
                exemptionReason = string.Format("Exempt-product-{0}", calculateTaxRequest.Product.Sku);
            }
            else
            if (calculateTaxRequest.Customer != null)
            {
                if (calculateTaxRequest.Customer.IsTaxExempt)
                {
                    exemptionReason = string.Format("Exempt-customer-{0}", calculateTaxRequest.Customer.CustomerGuid.ToString());
                }
                else
                {
                    var exemptRole = calculateTaxRequest.Customer.CustomerRoles.FirstOrDefault(role => role.Active && role.TaxExempt);
                    exemptionReason = exemptRole != null?string.Format("Exempt-role-{0}", exemptRole.Name) : string.Empty;
                }
            }

            var taxRequest = new AvalaraTaxRequest
            {
                CustomerCode = calculateTaxRequest.Customer != null?calculateTaxRequest.Customer.CustomerGuid.ToString() : null,
                                   ExemptionNo = !string.IsNullOrEmpty(exemptionReason) ? exemptionReason : null,
                                   Addresses   = new [] { address },
                Lines = new [] { line }
            };

            var result = GetTaxResult(taxRequest);

            if (result == null)
            {
                return new CalculateTaxResult {
                           Errors = new List <string>()
                           {
                               "Bad request"
                           }
                }
            }
            ;

            if (result.ResultCode != SeverityLevel.Success)
            {
                return new CalculateTaxResult {
                           Errors = result.Messages.Select(message => message.Summary).ToList()
                }
            }
            ;

            var taxRate = result.TaxLines != null && result.TaxLines.Any() ? result.TaxLines[0].Rate * 100 : 0;

            _cacheManager.Set(cacheKey, taxRate, 60);
            return(new CalculateTaxResult {
                TaxRate = taxRate
            });
        }