コード例 #1
0
        /// <returns>A task that represents the asynchronous operation</returns>
        public override async Task <IActionResult> Categories(TaxCategorySearchModel searchModel)
        {
            //ensure that Avalara tax provider is active
            if (!await _taxPluginManager.IsPluginActiveAsync(AvalaraTaxDefaults.SystemName))
            {
                return(await base.Categories(searchModel));
            }

            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageTaxSettings))
            {
                return(await AccessDeniedDataTablesJson());
            }

            //get tax categories
            var taxCategories = (await _taxCategoryService.GetAllTaxCategoriesAsync()).ToPagedList(searchModel);

            //get tax types and define the default value
            var cacheKey = _cacheManager.PrepareKeyForDefaultCache(AvalaraTaxDefaults.TaxCodeTypesCacheKey);
            var taxTypes = (await _cacheManager.GetAsync(cacheKey, async() => await _avalaraTaxManager.GetTaxCodeTypesAsync()))
                           ?.Select(taxType => new { Id = taxType.Key, Name = taxType.Value });
            var defaultType = taxTypes
                              ?.FirstOrDefault(taxType => taxType.Name.Equals("Unknown", StringComparison.InvariantCultureIgnoreCase))
                              ?? taxTypes?.FirstOrDefault();

            //prepare grid model
            var model = await new Models.Tax.TaxCategoryListModel().PrepareToGridAsync(searchModel, taxCategories, () =>
            {
                //fill in model values from the entity
                return(taxCategories.SelectAwait(async taxCategory =>
                {
                    //fill in model values from the entity
                    var taxCategoryModel = new Models.Tax.TaxCategoryModel
                    {
                        Id = taxCategory.Id,
                        Name = taxCategory.Name,
                        DisplayOrder = taxCategory.DisplayOrder
                    };

                    //try to get previously saved tax code type and description
                    var taxCodeType = (await taxTypes?.FirstOrDefaultAwaitAsync(async type =>
                                                                                type.Id.Equals((await _genericAttributeService.GetAttributeAsync <string>(taxCategory, AvalaraTaxDefaults.TaxCodeTypeAttribute)) ?? string.Empty)))
                                      ?? defaultType;
                    taxCategoryModel.Type = taxCodeType?.Name ?? string.Empty;
                    taxCategoryModel.TypeId = taxCodeType?.Id ?? Guid.Empty.ToString();
                    taxCategoryModel.Description = (await _genericAttributeService
                                                    .GetAttributeAsync <string>(taxCategory, AvalaraTaxDefaults.TaxCodeDescriptionAttribute)) ?? string.Empty;

                    return taxCategoryModel;
                }));
            });

            return(Json(model));
        }
コード例 #2
0
        /// <summary>
        /// Uninstall plugin
        /// </summary>
        /// <returns>A task that represents the asynchronous operation</returns>
        public override async Task UninstallAsync()
        {
            //settings
            await _settingService.DeleteSettingAsync <FixedOrByCountryStateZipTaxSettings>();

            //fixed rates
            var fixedRates = await(await _taxCategoryService.GetAllTaxCategoriesAsync())
                             .SelectAwait(async taxCategory => await _settingService.GetSettingAsync(string.Format(FixedOrByCountryStateZipDefaults.FixedRateSettingsKey, taxCategory.Id)))
                             .Where(setting => setting != null).ToListAsync();
            await _settingService.DeleteSettingsAsync(fixedRates);

            //locales
            await _localizationService.DeleteLocaleResourcesAsync("Plugins.Tax.FixedOrByCountryStateZip");

            await base.UninstallAsync();
        }
コード例 #3
0
        /// <summary>
        /// Prepare paged tax category list model
        /// </summary>
        /// <param name="searchModel">Tax category search model</param>
        /// <returns>Tax category list model</returns>
        public virtual async Task <TaxCategoryListModel> PrepareTaxCategoryListModelAsync(TaxCategorySearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get tax categories
            var taxCategories = (await _taxCategoryService.GetAllTaxCategoriesAsync()).ToPagedList(searchModel);

            //prepare grid model
            var model = new TaxCategoryListModel().PrepareToGrid(searchModel, taxCategories, () =>
            {
                //fill in model values from the entity
                return(taxCategories.Select(taxCategory => taxCategory.ToModel <TaxCategoryModel>()));
            });

            return(model);
        }
コード例 #4
0
        private async Task <bool> IsCustomerInTaxableStateAsync(Customer customer)
        {
            var taxCategory     = (await _taxCategoryService.GetAllTaxCategoriesAsync()).FirstOrDefault(x => x.Name == "Warranties");
            var shippingAddress = customer.ShippingAddressId.HasValue ?
                                  await _addressService.GetAddressByIdAsync(customer.ShippingAddressId.Value) :
                                  null;

            if (shippingAddress == null)
            {
                return(false);
            }

            return(await _abcTaxService.GetAbcTaxRateAsync(
                       // for now this should be fine, since all rates apply to all stores
                       0,
                       taxCategory?.Id ?? 0,
                       shippingAddress
                       ) != null);
        }
コード例 #5
0
        public async Task CanExportProductsToXlsx()
        {
            var replacePairs = new Dictionary <string, string>
            {
                { "ProductId", "Id" },
                { "ProductType", "ProductTypeId" },
                { "GiftCardType", "GiftCardTypeId" },
                { "Vendor", "VendorId" },
                { "ProductTemplate", "ProductTemplateId" },
                { "DeliveryDate", "DeliveryDateId" },
                { "TaxCategory", "TaxCategoryId" },
                { "ManageInventoryMethod", "ManageInventoryMethodId" },
                { "ProductAvailabilityRange", "ProductAvailabilityRangeId" },
                { "LowStockActivity", "LowStockActivityId" },
                { "BackorderMode", "BackorderModeId" },
                { "BasepriceUnit", "BasepriceUnitId" },
                { "BasepriceBaseUnit", "BasepriceBaseUnitId" },
                { "SKU", "Sku" },
                { "DownloadActivationType", "DownloadActivationTypeId" },
                { "RecurringCyclePeriod", "RecurringCyclePeriodId" },
                { "RentalPricePeriod", "RentalPricePeriodId" }
            };

            var ignore = new List <string> {
                "Categories", "Manufacturers", "AdminComment",
                "ProductType", "BackorderMode", "DownloadActivationType", "GiftCardType", "LowStockActivity",
                "ManageInventoryMethod", "RecurringCyclePeriod", "RentalPricePeriod", "ProductCategories",
                "ProductManufacturers", "ProductPictures", "ProductReviews", "ProductSpecificationAttributes",
                "ProductTags", "ProductAttributeMappings", "ProductAttributeCombinations", "TierPrices",
                "AppliedDiscounts", "ProductWarehouseInventory", "ApprovedRatingSum", "NotApprovedRatingSum",
                "ApprovedTotalReviews", "NotApprovedTotalReviews", "SubjectToAcl", "LimitedToStores", "Deleted",
                "DownloadExpirationDays", "HasTierPrices", "HasDiscountsApplied", "AvailableStartDateTimeUtc",
                "AvailableEndDateTimeUtc", "DisplayOrder", "CreatedOnUtc", "UpdatedOnUtc", "ProductProductTagMappings",
                "DiscountProductMappings", "EntityCacheKey"
            };

            ignore.AddRange(replacePairs.Values);

            var product = _productRepository.Table.ToList().First();

            var excelData = await _exportManager.ExportProductsToXlsxAsync(new[] { product });

            var worksheet = GetWorksheets(excelData);
            var manager   = GetPropertyManager <Product>(worksheet);

            manager.SetSelectList("ProductType", await ProductType.SimpleProduct.ToSelectListAsync(useLocalization: false));
            manager.SetSelectList("GiftCardType", await GiftCardType.Virtual.ToSelectListAsync(useLocalization: false));
            manager.SetSelectList("DownloadActivationType", await DownloadActivationType.Manually.ToSelectListAsync(useLocalization: false));
            manager.SetSelectList("ManageInventoryMethod", await ManageInventoryMethod.DontManageStock.ToSelectListAsync(useLocalization: false));
            manager.SetSelectList("LowStockActivity", await LowStockActivity.Nothing.ToSelectListAsync(useLocalization: false));
            manager.SetSelectList("BackorderMode", await BackorderMode.NoBackorders.ToSelectListAsync(useLocalization: false));
            manager.SetSelectList("RecurringCyclePeriod", await RecurringProductCyclePeriod.Days.ToSelectListAsync(useLocalization: false));
            manager.SetSelectList("RentalPricePeriod", await RentalPricePeriod.Days.ToSelectListAsync(useLocalization: false));

            var vendors = await _vendorService.GetAllVendorsAsync(showHidden : true);

            manager.SetSelectList("Vendor", vendors.Select(v => v as BaseEntity).ToSelectList(p => (p as Vendor)?.Name ?? string.Empty));
            var templates = await _productTemplateService.GetAllProductTemplatesAsync();

            manager.SetSelectList("ProductTemplate", templates.Select(pt => pt as BaseEntity).ToSelectList(p => (p as ProductTemplate)?.Name ?? string.Empty));
            var dates = await _dateRangeService.GetAllDeliveryDatesAsync();

            manager.SetSelectList("DeliveryDate", dates.Select(dd => dd as BaseEntity).ToSelectList(p => (p as DeliveryDate)?.Name ?? string.Empty));
            var availabilityRanges = await _dateRangeService.GetAllProductAvailabilityRangesAsync();

            manager.SetSelectList("ProductAvailabilityRange", availabilityRanges.Select(range => range as BaseEntity).ToSelectList(p => (p as ProductAvailabilityRange)?.Name ?? string.Empty));
            var categories = await _taxCategoryService.GetAllTaxCategoriesAsync();

            manager.SetSelectList("TaxCategory", categories.Select(tc => tc as BaseEntity).ToSelectList(p => (p as TaxCategory)?.Name ?? string.Empty));
            var measureWeights = await _measureService.GetAllMeasureWeightsAsync();

            manager.SetSelectList("BasepriceUnit", measureWeights.Select(mw => mw as BaseEntity).ToSelectList(p => (p as MeasureWeight)?.Name ?? string.Empty));
            manager.SetSelectList("BasepriceBaseUnit", measureWeights.Select(mw => mw as BaseEntity).ToSelectList(p => (p as MeasureWeight)?.Name ?? string.Empty));

            manager.Remove("ProductTags");

            manager.ReadFromXlsx(worksheet, 2);

            AreAllObjectPropertiesPresent(product, manager, ignore.ToArray());
            PropertiesShouldEqual(product, manager, replacePairs);
        }
コード例 #6
0
        public async Task <IActionResult> Configure(bool showtour = false)
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageTaxSettings))
            {
                return(AccessDeniedView());
            }

            var taxCategories = await _taxCategoryService.GetAllTaxCategoriesAsync();

            if (!taxCategories.Any())
            {
                var errorModel = new ConfigurationModel
                {
                    TaxCategoriesCanNotLoadedError = string.Format(
                        await _localizationService.GetResourceAsync(
                            "Plugins.Tax.FixedOrByCountryStateZip.TaxCategoriesCanNotLoaded"),
                        Url.Action("Categories", "Tax"))
                };

                return(View("~/Plugins/Tax.FixedOrByCountryStateZip/Views/Configure.cshtml", errorModel));
            }

            var model = new ConfigurationModel {
                CountryStateZipEnabled = _countryStateZipSettings.CountryStateZipEnabled
            };

            //stores
            model.AvailableStores.Add(new SelectListItem {
                Text = "*", Value = "0"
            });
            var stores = await _storeService.GetAllStoresAsync();

            foreach (var s in stores)
            {
                model.AvailableStores.Add(new SelectListItem {
                    Text = s.Name, Value = s.Id.ToString()
                });
            }
            //tax categories
            foreach (var tc in taxCategories)
            {
                model.AvailableTaxCategories.Add(new SelectListItem {
                    Text = tc.Name, Value = tc.Id.ToString()
                });
            }
            //countries
            var countries = await _countryService.GetAllCountriesAsync(showHidden : true);

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

            if (defaultCountry != null)
            {
                var states = await _stateProvinceService.GetStateProvincesByCountryIdAsync(defaultCountry.Id);

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

            //show configuration tour
            if (showtour)
            {
                var customer = await _workContext.GetCurrentCustomerAsync();

                var hideCard = await _genericAttributeService.GetAttributeAsync <bool>(customer, NopCustomerDefaults.HideConfigurationStepsAttribute);

                var closeCard = await _genericAttributeService.GetAttributeAsync <bool>(customer, NopCustomerDefaults.CloseConfigurationStepsAttribute);

                if (!hideCard && !closeCard)
                {
                    ViewBag.ShowTour = true;
                }
            }

            return(View("~/Plugins/Tax.FixedOrByCountryStateZip/Views/Configure.cshtml", model));
        }
コード例 #7
0
        public async Task <Product> UpsertAbcMattressProductAsync(AbcMattressModel abcMattressModel)
        {
            var entries = _abcMattressEntryService.GetAbcMattressEntriesByModelId(
                abcMattressModel.Id
                );

            var     hasExistingProduct = abcMattressModel.ProductId != null;
            Product product            = hasExistingProduct ?
                                         await _productService.GetProductByIdAsync(abcMattressModel.ProductId.Value) :
                                         new Product();

            product.Name = await GetProductNameAsync(abcMattressModel);

            // So I'd like to only use this once we totally migrate off of
            // old mattresses
            product.Sku = $"M{abcMattressModel.Name}";
            product.AllowCustomerReviews = false;
            product.Published            = entries.Any();
            product.CreatedOnUtc         = DateTime.UtcNow;
            product.VisibleIndividually  = true;
            product.ProductType          = ProductType.SimpleProduct;
            product.OrderMinimumQuantity = 1;
            product.OrderMaximumQuantity = 10000;
            product.IsShipEnabled        = true;
            product.Price = await CalculatePriceAsync(abcMattressModel, entries);

            product.TaxCategoryId = (await _taxCategoryService.GetAllTaxCategoriesAsync())
                                    .Where(tc => tc.Name == "Everything")
                                    .Select(tc => tc.Id)
                                    .FirstOrDefault();

            await MapProductToStoreAsync(product);

            if (hasExistingProduct)
            {
                await _productService.UpdateProductAsync(product);
            }
            else
            {
                await _productService.InsertProductAsync(product);
            }


            await _urlRecordService.SaveSlugAsync(product, await _urlRecordService.ValidateSeNameAsync(
                                                      product,
                                                      string.Empty,
                                                      product.Name,
                                                      false),
                                                  0
                                                  );

            if (!hasExistingProduct)
            {
                abcMattressModel.ProductId = product.Id;
                await _abcMattressService.UpdateAbcMattressModelAsync(abcMattressModel);
            }
            if (!string.IsNullOrWhiteSpace(abcMattressModel.Sku))
            {
                await _genericAttributeService.SaveAttributeAsync <string>(
                    product,
                    "MattressSku",
                    abcMattressModel.Sku
                    );

                await _genericAttributeService.SaveAttributeAsync <string>(
                    product,
                    "PowerReviewsSku",
                    abcMattressModel.Sku
                    );
            }

            // add information relating to Synchrony payments
            await SyncSynchronyPaymentsDataAsync(product, abcMattressModel);


            var plpDescription = await _genericAttributeService.GetAttributeAsync <string>(
                product,
                "PLPDescription"
                );

            // Add description for PowerReviews
            await _genericAttributeService.SaveAttributeAsync <string>(
                product,
                "PowerReviewsDescription",
                plpDescription
                );

            return(product);
        }