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

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

            //prepare tax codes to export
            var taxCodesToExport = _taxCategoryService.GetAllTaxCategories().Select(taxCategory => new TaxCodeModel
            {
                createdDate   = DateTime.UtcNow,
                description   = CommonHelper.EnsureMaximumLength(taxCategory.Name, 255),
                isActive      = true,
                taxCode       = CommonHelper.EnsureMaximumLength(taxCategory.Name, 25),
                taxCodeTypeId = CommonHelper.EnsureMaximumLength(_genericAttributeService
                                                                 .GetAttribute <string>(taxCategory, AvalaraTaxDefaults.TaxCodeTypeAttribute) ?? "P", 2)
            }).Where(taxCode => !string.IsNullOrEmpty(taxCode.taxCode)).ToList();

            //get existing tax codes (only active)
            var existingTaxCodes = _avalaraTaxManager.GetTaxCodes(true)?.Select(taxCode => taxCode.taxCode).ToList() ?? new List <string>();

            //add Avalara pre-defined system tax codes
            var systemTaxCodes = _avalaraTaxManager.GetSystemTaxCodes(true)?.Select(taxCode => taxCode.taxCode).ToList() ?? new List <string>();

            existingTaxCodes.AddRange(systemTaxCodes);

            //remove duplicates
            taxCodesToExport = taxCodesToExport.Where(taxCode => !existingTaxCodes.Contains(taxCode.taxCode)).Distinct().ToList();

            //export tax codes
            if (taxCodesToExport.Any())
            {
                //create tax codes and get the result
                var result = _avalaraTaxManager.CreateTaxCodes(taxCodesToExport)?.Count;

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

            return(List());
        }