Exemplo n.º 1
0
        public IActionResult ImportTaxCodes()
        {
            //ensure that Avalara tax provider is active
            if (!(_taxService.LoadActiveTaxProvider(_workContext.CurrentCustomer) is AvalaraTaxProvider))
            {
                return(List());
            }

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

            //get Avalara pre-defined system tax codes (only active)
            var systemTaxCodes = _avalaraTaxManager.GetSystemTaxCodes(true);

            if (!systemTaxCodes?.Any() ?? true)
            {
                ErrorNotification(_localizationService.GetResource("Plugins.Tax.Avalara.TaxCodes.Import.Error"));
                return(List());
            }

            //get existing tax categories
            var existingTaxCategories = _taxCategoryService.GetAllTaxCategories().Select(taxCategory => taxCategory.Name).ToList();

            //remove duplicates
            var taxCodesToImport = systemTaxCodes.Where(taxCode => !existingTaxCategories.Contains(taxCode.taxCode)).ToList();

            var importedTaxCodesNumber = 0;

            foreach (var taxCode in taxCodesToImport)
            {
                if (string.IsNullOrEmpty(taxCode?.taxCode))
                {
                    continue;
                }

                //create new tax category
                var taxCategory = new TaxCategory {
                    Name = taxCode.taxCode
                };
                _taxCategoryService.InsertTaxCategory(taxCategory);

                //save description and type
                if (!string.IsNullOrEmpty(taxCode.description))
                {
                    _genericAttributeService.SaveAttribute(taxCategory, AvalaraTaxDefaults.TaxCodeDescriptionAttribute, taxCode.description);
                }
                if (!string.IsNullOrEmpty(taxCode.taxCodeTypeId))
                {
                    _genericAttributeService.SaveAttribute(taxCategory, AvalaraTaxDefaults.TaxCodeTypeAttribute, taxCode.taxCodeTypeId);
                }

                importedTaxCodesNumber++;
            }

            //successfully imported
            var successMessage = _localizationService.GetResource("Plugins.Tax.Avalara.TaxCodes.Import.Success");

            SuccessNotification(string.Format(successMessage, importedTaxCodesNumber));

            return(List());
        }