Exemplo n.º 1
0
        private int GetTaxCategoryId(string taxCategory)
        {
            CatalogTaxDto taxes = CatalogTaxManager.GetTaxCategories();

            if (taxes.TaxCategory != null)
            {
                DataRow[] drws          = null;
                int       taxCategoryId = 0;
                if (Int32.TryParse(taxCategory, out taxCategoryId))
                {
                    drws = taxes.TaxCategory.Select(String.Format("TaxCategoryId = '{0}'", taxCategoryId));
                    if (drws.Length > 0)
                    {
                        return(taxCategoryId);
                    }
                }
                else
                {
                    drws = taxes.TaxCategory.Select(String.Format("Name LIKE '{0}'", taxCategory.Replace("'", "''")));
                    if (drws.Length > 0)
                    {
                        return(((CatalogTaxDto.TaxCategoryRow)drws[0]).TaxCategoryId);
                    }
                }
            }
            return(0);
        }
Exemplo n.º 2
0
        public virtual int GetDefaultTaxCategoryId()
        {
            var taxDto         = CatalogTaxManager.GetTaxCategoryByName(DefaultTaxCategoryName);
            var taxCategoryRow = taxDto?.TaxCategory.FirstOrDefault();

            return(taxCategoryRow?.TaxCategoryId ?? 1);
        }
Exemplo n.º 3
0
        private static void AdjustPriceAndTaxes(Currency currency, ILineItem lineItem,
            DinteroOrderLine dinteroItem, IOrderAddress orderAddress)
        {
            var amount = lineItem.GetExtendedPrice(currency).Amount;
            double vat = 0;

            var entryDto = CatalogContext.Current.GetCatalogEntryDto(lineItem.Code,
                new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryFull));
            if (entryDto.CatalogEntry.Count > 0)
            {
                CatalogEntryDto.VariationRow[] variationRows = entryDto.CatalogEntry[0].GetVariationRows();
                if (variationRows.Length > 0)
                {
                    var taxCategory = CatalogTaxManager.GetTaxCategoryNameById(variationRows[0].TaxCategoryId);
                    var taxes = OrderContext.Current.GetTaxes(Guid.Empty, taxCategory,
                        Thread.CurrentThread.CurrentCulture.Name, orderAddress).ToList();

                    foreach (var tax in taxes)
                    {
                        if (tax.TaxType == TaxType.SalesTax)
                        {
                            vat = tax.Percentage;
                        }
                    }
                }
            }

            dinteroItem.Amount = CurrencyHelper.CurrencyToInt(amount, currency.CurrencyCode);
            dinteroItem.Vat = Convert.ToInt32(vat);
            dinteroItem.VatAmount = GetVatAmount(amount, vat, currency.CurrencyCode);
        }
Exemplo n.º 4
0
        public Money GetShippingTaxTotal(IShipment shipment, IMarket market, Currency currency)
        {
            if (shipment.ShippingAddress == null)
            {
                return(new Money(0m, currency));
            }

            var shippingTaxes = new List <ITaxValue>();

            foreach (var item in shipment.LineItems)
            {
                //get the variation entry that the item is associated with
                var reference = _referenceConverter.GetContentLink(item.Code);
                var entry     = _contentRepository.Get <VariationContent>(reference);
                if (entry == null || !entry.TaxCategoryId.HasValue)
                {
                    continue;
                }

                //get the tax values applicable for the entry. If not taxes found then continue with next line item.
                var taxCategory = CatalogTaxManager.GetTaxCategoryNameById(entry.TaxCategoryId.Value);

                var taxes = GetTaxValues(taxCategory, market.DefaultLanguage.Name, shipment.ShippingAddress).ToList();
                if (taxes.Count <= 0)
                {
                    continue;
                }

                shippingTaxes.AddRange(
                    taxes.Where(x => x.TaxType == TaxType.ShippingTax &&
                                !shippingTaxes.Any(y => y.Name.Equals(x.Name))));
            }

            return(new Money(CalculateShippingTax(shippingTaxes, shipment, market, currency), currency));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Binds the lists.
        /// </summary>
        private void BindLists()
        {
            // bind shipment packages
            if (PackageList.Items.Count <= 1)
            {
                ShippingMethodDto shippingDto = ShippingManager.GetShippingPackages();
                if (shippingDto.Package != null)
                {
                    foreach (ShippingMethodDto.PackageRow row in shippingDto.Package.Rows)
                    {
                        PackageList.Items.Add(new ListItem(row.Name, row.PackageId.ToString()));
                    }
                }
                PackageList.DataBind();
            }

            // bind warehouses
            if (WarehouseList.Items.Count <= 1)
            {
                WarehouseDto dto = WarehouseManager.GetWarehouseDto();
                if (dto.Warehouse != null)
                {
                    foreach (WarehouseDto.WarehouseRow row in dto.Warehouse.Rows)
                    {
                        WarehouseList.Items.Add(new ListItem(row.Name, row.WarehouseId.ToString()));
                    }
                }

                WarehouseList.DataBind();
            }

            // bind merchants
            if (MerchantList.Items.Count <= 1)
            {
                CatalogEntryDto merchants = CatalogContext.Current.GetMerchantsDto();
                if (merchants.Merchant != null)
                {
                    foreach (CatalogEntryDto.MerchantRow row in merchants.Merchant.Rows)
                    {
                        MerchantList.Items.Add(new ListItem(row.Name, row.MerchantId.ToString()));
                    }
                }
                MerchantList.DataBind();
            }

            // bind tax categories
            if (TaxList.Items.Count <= 1)
            {
                CatalogTaxDto taxes = CatalogTaxManager.GetTaxCategories();
                if (taxes.TaxCategory != null)
                {
                    foreach (CatalogTaxDto.TaxCategoryRow row in taxes.TaxCategory.Rows)
                    {
                        TaxList.Items.Add(new ListItem(row.Name, row.TaxCategoryId.ToString()));
                    }
                }
                TaxList.DataBind();
            }
        }
Exemplo n.º 6
0
        public Money GetTaxTotal(IOrderForm orderForm, IMarket market, Currency currency)
        {
            var formTaxes = 0m;

            //calculate tax for each shipment
            foreach (var shipment in orderForm.Shipments.Where(x => x.ShippingAddress != null))
            {
                var shippingTaxes = new List <ITaxValue>();
                foreach (var item in shipment.LineItems)
                {
                    //get the variation entry that the item is associated with
                    var reference = _referenceConverter.GetContentLink(item.Code);
                    var entry     = _contentRepository.Get <VariationContent>(reference);
                    if (entry == null || !entry.TaxCategoryId.HasValue)
                    {
                        continue;
                    }

                    //get the tax values applicable for the entry. If not taxes found then continue with next line item.
                    var taxCategory = CatalogTaxManager.GetTaxCategoryNameById(entry.TaxCategoryId.Value);
                    var taxes       = GetTaxValues(taxCategory, market.DefaultLanguage.Name, shipment.ShippingAddress).ToList();
                    if (taxes.Count <= 0)
                    {
                        continue;
                    }

                    //calculate the line item price, excluding tax
                    var lineItem = (LineItem)item;
                    var lineItemPricesExcludingTax = item.PlacedPrice - (lineItem.OrderLevelDiscountAmount + lineItem.LineItemDiscountAmount) / item.Quantity;
                    var quantity = 0m;

                    if (orderForm.Name.Equals(OrderForm.ReturnName))
                    {
                        quantity = item.ReturnQuantity;
                    }
                    else
                    {
                        quantity = item.Quantity;
                    }

                    formTaxes += taxes.Where(x => x.TaxType == TaxType.SalesTax).Sum(x => lineItemPricesExcludingTax * (decimal)x.Percentage * 0.01m) * quantity;

                    //add shipping taxes for later tax calculation
                    shippingTaxes.AddRange(
                        taxes.Where(x => x.TaxType == TaxType.ShippingTax &&
                                    !shippingTaxes.Any(y => y.Name.Equals(x.Name))));
                }

                //sum the calculated tax for each shipment
                formTaxes += CalculateShippingTax(shippingTaxes, shipment, market, currency);
            }

            return(new Money(currency.Round(formTaxes), currency));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Calculates the sale taxes.
        /// </summary>
        private void CalculateSaleTaxes()
        {
            // Get the property, since it is expensive process, make sure to get it once
            OrderGroup order = OrderGroup;

            foreach (OrderForm form in order.OrderForms)
            {
                decimal totalTaxes = 0;
                foreach (Shipment shipment in form.Shipments)
                {
                    List <LineItem> items = GetSplitShipmentLineItems(shipment);

                    // Calculate sales and shipping taxes per items
                    foreach (LineItem item in items)
                    {
                        // Try getting an address
                        OrderAddress address = GetAddressByName(form, shipment.ShippingAddressId);
                        if (address != null) // no taxes if there is no address
                        {
                            // Try getting an entry
                            CatalogEntryDto entryDto = CatalogContext.Current.GetCatalogEntryDto(item.CatalogEntryId, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryFull));
                            if (entryDto.CatalogEntry.Count > 0) // no entry, no tax category, no tax
                            {
                                CatalogEntryDto.VariationRow[] variationRows = entryDto.CatalogEntry[0].GetVariationRows();
                                if (variationRows.Length > 0)
                                {
                                    string     taxCategory = CatalogTaxManager.GetTaxCategoryNameById(variationRows[0].TaxCategoryId);
                                    IMarket    market      = ServiceLocator.Current.GetInstance <IMarketService>().GetMarket(order.MarketId);
                                    TaxValue[] taxes       = OrderContext.Current.GetTaxes(Guid.Empty, taxCategory, market.DefaultLanguage.Name, address.CountryCode, address.State, address.PostalCode, address.RegionCode, String.Empty, address.City);

                                    if (taxes.Length > 0)
                                    {
                                        foreach (TaxValue tax in taxes)
                                        {
                                            if (tax.TaxType == TaxType.SalesTax)
                                            {
                                                var taxFactor = 1 + ((decimal)tax.Percentage / 100);

                                                totalTaxes += item.ExtendedPrice - (item.ExtendedPrice / taxFactor);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                form.TaxTotal = Math.Round(totalTaxes, 2);
            }
        }
Exemplo n.º 8
0
        // ...still what's used in the "newer calculators"
        public TaxValue[] GetTaxes(int taxCategoryId)
        {
            TaxValue[] taxes = null;

            // get the cat-string
            string taxCategory = CatalogTaxManager.GetTaxCategoryNameById(taxCategoryId);

            taxes = OrderContext.Current.GetTaxes
                        (Guid.Empty, taxCategory, GetLanguageName(), GetCountryCode()
                        , String.Empty, String.Empty, String.Empty, String.Empty
                        , String.Empty);

            return(taxes);
        }
Exemplo n.º 9
0
 private void ProcessCommand()
 {
     if (CurrentDto != null && CurrentDto.TaxCategory.Count > 0)
     {
         // update tax category
         CurrentDto.TaxCategory[0].Name = TaxCategoryName.Text;
         CatalogTaxManager.SaveTaxCategory(CurrentDto);
     }
     else
     {
         // create new tax category
         CatalogTaxManager.CreateTaxCategory(TaxCategoryName.Text, false);
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// Loads the data and data bind.
        /// </summary>
        /// <param name="sortExpression">The sort expression.</param>
        private void LoadDataAndDataBind(string sortExpression)
        {
            CatalogTaxDto dto = CatalogTaxManager.GetTaxCategories();

            if (dto.TaxCategory != null)
            {
                DataView view = dto.TaxCategory.DefaultView;
                view.Sort             = sortExpression;
                MyListView.DataSource = view;
            }

            MyListView.CurrentListView.PrimaryKeyId = EcfListView.MakePrimaryKeyIdString("TaxCategoryId");
            MyListView.DataBind();
        }
Exemplo n.º 11
0
        private Money GetTaxOldSchool(DemoMarketsViewModel viewModel, IOrderAddress orderAddress)
        {
            string taxCategory = CatalogTaxManager.GetTaxCategoryNameById((int)viewModel.Shirt.TaxCategoryId);

            viewModel.Taxes = OrderContext.Current.GetTaxes(Guid.Empty, taxCategory,
                                                            viewModel.SelectedMarket.DefaultLanguage.TwoLetterISOLanguageName, orderAddress);

            decimal decTaxTotal = (decimal)(from x in viewModel.Taxes
                                            where x.TaxType == TaxType.SalesTax
                                            select x).Sum((ITaxValue x) => x.Percentage);

            decimal itemPrice = viewModel.Shirt.GetDefaultPrice().UnitPrice;

            return(new Money(itemPrice * decTaxTotal / 100m, viewModel.SelectedMarket.DefaultCurrency));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Checks if entered tax category name is unique.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
        public void TaxCategoryNameCheck(object sender, ServerValidateEventArgs args)
        {
            // load tax category by name
            CatalogTaxDto dto = CatalogTaxManager.GetTaxCategoryByName(args.Value);

            // check if tax category with specified name is loaded
            if (dto != null && dto.TaxCategory.Count > 0 &&
                dto.TaxCategory[0].TaxCategoryId != TaxCategoryId)
            {
                args.IsValid = false;
                return;
            }

            args.IsValid = true;
        }
        //Injected<ReferenceConverter> _refConv;
        public override void SetDefaultValues(ContentType contentType)
        {
            base.SetDefaultValues(contentType);

            CatalogContentBase myParent = _loader.Service.Get <CatalogContentBase>(this.ParentLink);

            // Changed so the ServiceAPI works
            if (myParent.GetOriginalType() == typeof(NodeContent))
            {
                FashionNode fashionNode = (FashionNode)myParent;

                // sooo much easier now
                this.TaxCategoryId  = int.Parse(fashionNode.TaxCategories);
                this.theTaxCategory = CatalogTaxManager.GetTaxCategoryNameById(Int16.Parse(fashionNode.TaxCategories));
            }
        }
        public IEnumerable <ISelectItem> GetSelections(ExtendedMetadata md)
        {
            CatalogTaxDto      dto = CatalogTaxManager.GetTaxCategories();
            List <ISelectItem> listOfSelectItems = new List <ISelectItem>();

            foreach (var item in dto.TaxCategory)
            {
                SelectItem theItem = new SelectItem()
                {
                    Text = item.Name, Value = item.TaxCategoryId
                };
                listOfSelectItems.Add(theItem);
            }

            return(listOfSelectItems.ToArray());
        }
Exemplo n.º 15
0
        /// <summary>
        /// Processes the delete command.
        /// </summary>
        /// <param name="items">The items.</param>
        void ProcessDeleteCommand(string[] items)
        {
            for (int i = 0; i < items.Length; i++)
            {
                string[] keys = EcfListView.GetPrimaryKeyIdStringItems(items[i]);
                if (keys != null)
                {
                    int id = Int32.Parse(keys[0]);

                    CatalogTaxDto dto = CatalogTaxManager.GetTaxCategoryByTaxCategoryId(id);
                    if (dto != null && dto.TaxCategory.Count > 0)
                    {
                        dto.TaxCategory[0].Delete();
                        CatalogTaxManager.SaveTaxCategory(dto);
                    }
                }
            }
        }
Exemplo n.º 16
0
        public Money GetSalesTax(ILineItem lineItem, IMarket market, IOrderAddress shippingAddress, Money basePrice)
        {
            if (market.MarketId.Value == "sv" && shippingAddress.City == "Stockholm")
            {
                Decimal decPrice              = 0;
                string  taxCategory           = CatalogTaxManager.GetTaxCategoryNameById((int)lineItem.TaxCategoryId);
                IEnumerable <ITaxValue> taxes = OrderContext.Current.GetTaxes(Guid.Empty, taxCategory, "sv", shippingAddress);

                foreach (var tax in taxes)
                {
                    decPrice += (decimal)(tax.Percentage + 0.10) * (lineItem.PlacedPrice * lineItem.Quantity);
                }
                return(new Money(decPrice, basePrice.Currency) / 100);
            }
            else
            {
                return(_defaultTaxCalculator.GetSalesTax(lineItem, market, shippingAddress, basePrice));
            }
        }
        private decimal CalculateLineItemSaleTaxes(LineItem lineItem, string shipmentAddressId)
        {
            decimal retVal = 0;
            // Try getting an address
            OrderAddress address = GetAddressByName(base.ReturnOrderForm, shipmentAddressId);

            if (address == null)             // no taxes if there is no address
            {
                return(0m);
            }
            // Try getting an entry
            CatalogEntryDto entryDto = CatalogContext.Current.GetCatalogEntryDto(lineItem.CatalogEntryId, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryFull));

            if (entryDto.CatalogEntry.Count == 0)             // no entry, no tax category, no tax
            {
                return(0m);
            }
            CatalogEntryDto.VariationRow[] variationRows = entryDto.CatalogEntry[0].GetVariationRows();
            if (variationRows.Length == 0)
            {
                return(0m);
            }
            string taxCategory = CatalogTaxManager.GetTaxCategoryNameById(variationRows[0].TaxCategoryId);

            TaxValue[] taxes = OrderContext.Current.GetTaxes(Guid.Empty, taxCategory, Thread.CurrentThread.CurrentCulture.Name, address.CountryCode, address.State, address.PostalCode, address.RegionCode, String.Empty, address.City);
            if (taxes.Length == 0)
            {
                return(0m);
            }

            foreach (TaxValue tax in taxes)
            {
                if (tax.TaxType == TaxType.SalesTax)
                {
                    var taxFactor = 1 + ((decimal)tax.Percentage / 100);

                    retVal += lineItem.ExtendedPrice - (lineItem.ExtendedPrice / taxFactor);
                    //	retVal += lineItem.ExtendedPrice * ((decimal)tax.Percentage / 100);
                }
            }
            return(retVal);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Binds the tax categories.
        /// </summary>
        private void BindTaxCategories()
        {
            CatalogTaxDto taxCategoriesDto = CatalogTaxManager.GetTaxCategories();

            var query = from taxCategory in taxCategoriesDto.TaxCategory
                        orderby taxCategory.Name
                        select taxCategory;

            foreach (CatalogTaxDto.TaxCategoryRow taxCategoryRow in query)
            {
                ListItem li = new ListItem(taxCategoryRow.Field <string>("Name"));

                if (!TaxCategoriesList.Items.Contains(li))
                {
                    TaxCategoriesList.Items.Add(li);
                }
            }

            TaxCategoriesList.DataBind();
        }
Exemplo n.º 19
0
        private static bool TryGetTaxValues(IMarket market, IShipment shipment, int taxCategoryId, out ITaxValue[] taxValues)
        {
            if (shipment.ShippingAddress == null)
            {
                taxValues = Enumerable.Empty <ITaxValue>().ToArray();

                return(false);
            }

            var taxValueCollection = OrderContext.Current.GetTaxes(Guid.Empty, CatalogTaxManager.GetTaxCategoryNameById(taxCategoryId), market.DefaultLanguage.Name, shipment.ShippingAddress);

            if (taxValueCollection == null)
            {
                taxValues = Enumerable.Empty <ITaxValue>().ToArray();

                return(false);
            }

            taxValues = taxValueCollection.ToArray();

            return(taxValues.Any());
        }
Exemplo n.º 20
0
        public void Dump()
        {
            var languageBranch = _languageBranchRepository.ListAll().First();

            var taxCategory = CatalogTaxManager.CreateTaxCategory("Tax category", true);

            CatalogTaxManager.SaveTaxCategory(taxCategory);

            var jurisdictionDto = new JurisdictionDto();
            var applicationId   = AppContext.Current.ApplicationId;

            jurisdictionDto.Jurisdiction.AddJurisdictionRow("Jurisdiction", null, languageBranch.LanguageID, (int)JurisdictionManager.JurisdictionType.Tax, null, null, null, null, null, null, applicationId, "ABC");
            jurisdictionDto.JurisdictionGroup.AddJurisdictionGroupRow(applicationId, "Group", (int)JurisdictionManager.JurisdictionType.Tax, "ABC");
            JurisdictionManager.SaveJurisdiction(jurisdictionDto);

            var taxDto = new TaxDto();

            taxDto.Tax.AddTaxRow((int)TaxType.SalesTax, "Tax", 1, applicationId);
            taxDto.TaxValue.AddTaxValueRow(20d, taxDto.Tax[0], "Tax category", jurisdictionDto.JurisdictionGroup[0].JurisdictionGroupId, DateTime.Now, Guid.Empty);
            TaxManager.SaveTax(taxDto);

            var currentMarket = _currentMarket.GetCurrentMarket();
            var market        = (MarketImpl)_marketService.GetMarket(currentMarket.MarketId);

            market.DefaultCurrency = Currency.EUR;
            market.DefaultLanguage = languageBranch.Culture;
            _marketService.UpdateMarket(market);

            var rootLink = _referenceConverter.GetRootLink();
            var catalog  = _contentRepository.GetDefault <CatalogContent>(rootLink, languageBranch.Culture);

            catalog.Name             = "Catalog";
            catalog.DefaultCurrency  = market.DefaultCurrency;
            catalog.CatalogLanguages = new ItemCollection <string> {
                languageBranch.LanguageID
            };
            catalog.DefaultLanguage = "en";
            catalog.WeightBase      = "kg";
            catalog.LengthBase      = "cm";
            var catalogRef = _contentRepository.Save(catalog, SaveAction.Publish, AccessLevel.NoAccess);

            var category = _contentRepository.GetDefault <NodeContent>(catalogRef);

            category.Name        = "Category";
            category.DisplayName = "Category";
            category.Code        = "category";
            var categoryRef = _contentRepository.Save(category, SaveAction.Publish, AccessLevel.NoAccess);

            var product = _contentRepository.GetDefault <ProductContent>(categoryRef);

            product.Name        = "Product";
            product.DisplayName = "Product";
            product.Code        = "product";
            var productRef = _contentRepository.Save(product, SaveAction.Publish, AccessLevel.NoAccess);

            var variant = _contentRepository.GetDefault <VariationContent>(productRef);

            variant.Name          = "Variant";
            variant.DisplayName   = "Variant";
            variant.Code          = Constants.VariationCode;
            variant.TaxCategoryId = taxCategory.TaxCategory.First().TaxCategoryId;
            variant.MinQuantity   = 1;
            variant.MaxQuantity   = 100;
            _contentRepository.Save(variant, SaveAction.Publish, AccessLevel.NoAccess);

            var price = new PriceValue
            {
                UnitPrice       = new Money(100, market.DefaultCurrency),
                CatalogKey      = new CatalogKey(applicationId, variant.Code),
                MarketId        = market.MarketId,
                ValidFrom       = DateTime.Today.AddYears(-1),
                ValidUntil      = DateTime.Today.AddYears(1),
                CustomerPricing = CustomerPricing.AllCustomers,
                MinQuantity     = 0
            };

            _priceService.SetCatalogEntryPrices(price.CatalogKey, new[] { price });

            var campaign = _contentRepository.GetDefault <SalesCampaign>(SalesCampaignFolder.CampaignRoot);

            campaign.Name       = "QuickSilver";
            campaign.Created    = DateTime.UtcNow.AddHours(-1);
            campaign.IsActive   = true;
            campaign.ValidFrom  = DateTime.Today;
            campaign.ValidUntil = DateTime.Today.AddYears(1);
            var campaignRef = _contentRepository.Save(campaign, SaveAction.Publish, AccessLevel.NoAccess);

            var promotion = _contentRepository.GetDefault <BuyFromCategoryGetItemDiscount>(campaignRef);

            promotion.IsActive            = true;
            promotion.Name                = "25 % off";
            promotion.Category            = categoryRef;
            promotion.Discount.UseAmounts = false;
            promotion.Discount.Percentage = 25m;
            _contentRepository.Save(promotion, SaveAction.Publish, AccessLevel.NoAccess);

            var paymentDto = new PaymentMethodDto();
            var created    = DateTime.UtcNow.AddHours(-1);

            paymentDto.PaymentMethod.AddPaymentMethodRow(Constants.PaymentMethodId, "Payment", "Payment", languageBranch.LanguageID, "Keyword", true, true, typeof(GenericPaymentGateway).AssemblyQualifiedName, typeof(OtherPayment).AssemblyQualifiedName, false, 1, created, created, applicationId);
            paymentDto.MarketPaymentMethods.AddMarketPaymentMethodsRow(market.MarketId.Value, paymentDto.PaymentMethod[0]);
            PaymentManager.SavePayment(paymentDto);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Imports the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="applicationId">The application id.</param>
        /// <param name="baseFilePath">The base file path.</param>
        public void Import(string pathToCsvFile, Guid applicationId, Guid?siteId, char delimiter)
        {
            CultureInfo currentCultureInfo = GetImportExportCulture();

            int totalImportSteps = GetTotalImportSteps();

            OnEvent("Starting import...", 0);

            string fileName = Path.GetFileName(pathToCsvFile);

            // 1. Parse csv file
            OnEvent("Start parsing csv file", GetProgressPercent((int)ImportSteps.StartParseFile, totalImportSteps));

            CsvIncomingDataParser parser = new CsvIncomingDataParser(Path.GetDirectoryName(pathToCsvFile), true, delimiter);

            DataSet taxDataSet = parser.Parse(fileName, null);

            OnEvent("Finished parsing csv file", GetProgressPercent((int)ImportSteps.EndParseFile, totalImportSteps));

            // 2. Create Dtos from parsed DataSet
            if (taxDataSet.Tables[fileName] == null)
            {
                throw new OrdersImportExportException(String.Format("Unknown problem with parsing file {0}.", fileName));
            }

            OnEvent("Start processing parsed rows", GetProgressPercent((int)ImportSteps.StartImport, totalImportSteps));

            int totalRowCount = taxDataSet.Tables[fileName].Rows.Count;

            JurisdictionDto currentJurisdictionDto = JurisdictionManager.GetJurisdictions(Mediachase.Commerce.Orders.Managers.JurisdictionManager.JurisdictionType.Tax);
            TaxDto          currentTaxDto          = TaxManager.GetTaxDto(TaxType.SalesTax);

            JurisdictionDto jurisdictionDto = new JurisdictionDto();
            TaxDto          taxDto          = new TaxDto();

            for (int i = 0; i <= totalRowCount - 1; i++)
            {
                DataRow currentRow = taxDataSet.Tables[fileName].Rows[i];

                #region Import Jurisdictions
                #region JurisdictionDto
                string jurisdictionCode = currentRow.ItemArray.GetValue(9).ToString();

                JurisdictionDto.JurisdictionRow jRow = null;

                JurisdictionDto.JurisdictionRow[] jRows = (JurisdictionDto.JurisdictionRow[])currentJurisdictionDto.Jurisdiction.Select(String.Format("Code='{0}'", jurisdictionCode));

                // check if row has already been imported
                // (to support multiple values for the same jurisdiction need to check if jurisdiction with the given name already exists in jurisdictionDto)
                JurisdictionDto.JurisdictionRow[] jRows2 = (JurisdictionDto.JurisdictionRow[])jurisdictionDto.Jurisdiction.Select(String.Format("Code='{0}'", jurisdictionCode));
                bool jurisdictionExists = jRows2 != null && jRows2.Length > 0;

                if (jurisdictionExists)
                {
                    jRow = jRows2[0];
                }
                else
                {
                    if (jRows != null && jRows.Length > 0)
                    {
                        jurisdictionDto.Jurisdiction.ImportRow(jRows[0]);
                        jRow = jurisdictionDto.Jurisdiction[jurisdictionDto.Jurisdiction.Count - 1];
                    }
                    else
                    {
                        jRow = jurisdictionDto.Jurisdiction.NewJurisdictionRow();
                        jRow.ApplicationId    = applicationId;
                        jRow.JurisdictionType = Mediachase.Commerce.Orders.Managers.JurisdictionManager.JurisdictionType.Tax.GetHashCode();
                    }
                }

                jRow.DisplayName        = currentRow.ItemArray.GetValue(0).ToString();
                jRow.StateProvinceCode  = GetStringValue(currentRow.ItemArray.GetValue(1));
                jRow.CountryCode        = currentRow.ItemArray.GetValue(2).ToString();
                jRow.ZipPostalCodeStart = GetStringValue(currentRow.ItemArray.GetValue(3));
                jRow.ZipPostalCodeEnd   = GetStringValue(currentRow.ItemArray.GetValue(4));
                jRow.City     = GetStringValue(currentRow.ItemArray.GetValue(5));
                jRow.District = GetStringValue(currentRow.ItemArray.GetValue(6));
                jRow.County   = GetStringValue(currentRow.ItemArray.GetValue(7));
                jRow.GeoCode  = GetStringValue(currentRow.ItemArray.GetValue(8));
                jRow.Code     = jurisdictionCode;

                if (jRow.RowState == DataRowState.Detached)
                {
                    jurisdictionDto.Jurisdiction.Rows.Add(jRow);
                }
                #endregion

                #region JurisdictionGroupDto

                string jurisdictionGroupCode = currentRow.ItemArray.GetValue(11).ToString();

                JurisdictionDto.JurisdictionGroupRow jGroupRow = null;

                JurisdictionDto.JurisdictionGroupRow[] jGroupRows = (JurisdictionDto.JurisdictionGroupRow[])currentJurisdictionDto.JurisdictionGroup.Select(String.Format("Code='{0}'", jurisdictionGroupCode));

                // check if row has already been imported
                // (to support multiple values for the same jurisdiction need to check if jurisdiction with the given name already exists in jurisdictionDto)
                JurisdictionDto.JurisdictionGroupRow[] jGroupRows2 = (JurisdictionDto.JurisdictionGroupRow[])jurisdictionDto.JurisdictionGroup.Select(String.Format("Code='{0}'", jurisdictionGroupCode));
                bool jurisdictionGroupExists = jGroupRows2 != null && jGroupRows2.Length > 0;

                if (jurisdictionGroupExists)
                {
                    jGroupRow = jGroupRows2[0];
                }
                else
                {
                    if (jGroupRows != null && jGroupRows.Length > 0)
                    {
                        jurisdictionDto.JurisdictionGroup.ImportRow(jGroupRows[0]);
                        jGroupRow = jurisdictionDto.JurisdictionGroup[jurisdictionDto.JurisdictionGroup.Count - 1];
                    }
                    else
                    {
                        jGroupRow = jurisdictionDto.JurisdictionGroup.NewJurisdictionGroupRow();
                        jGroupRow.ApplicationId    = applicationId;
                        jGroupRow.JurisdictionType = Mediachase.Commerce.Orders.Managers.JurisdictionManager.JurisdictionType.Tax.GetHashCode();
                    }
                }

                jGroupRow.DisplayName = currentRow.ItemArray.GetValue(10).ToString();
                jGroupRow.Code        = jurisdictionGroupCode;

                if (jGroupRow.RowState == DataRowState.Detached)
                {
                    jurisdictionDto.JurisdictionGroup.Rows.Add(jGroupRow);
                }
                #endregion

                #region JurisdictionRelationDto
                JurisdictionDto.JurisdictionRelationRow jRelationRow = null;
                if (jRow.JurisdictionId > 0 && jGroupRow.JurisdictionGroupId > 0)
                {
                    // check if relation already exists
                    JurisdictionDto.JurisdictionRelationRow[] jRelationRows = (JurisdictionDto.JurisdictionRelationRow[])currentJurisdictionDto.JurisdictionRelation.Select(String.Format("JurisdictionId={0} AND JurisdictionGroupId={1}", jRow.JurisdictionId, jGroupRow.JurisdictionGroupId));
                    if (jRelationRows != null && jRelationRows.Length > 0)
                    {
                        jurisdictionDto.JurisdictionRelation.ImportRow(jRelationRows[0]);
                        jRelationRow = jurisdictionDto.JurisdictionRelation[jurisdictionDto.JurisdictionRelation.Count - 1];
                    }
                }
                if (jRelationRow == null)
                {
                    // create new relation
                    jRelationRow = jurisdictionDto.JurisdictionRelation.NewJurisdictionRelationRow();
                    jRelationRow.JurisdictionId      = jRow.JurisdictionId;
                    jRelationRow.JurisdictionGroupId = jGroupRow.JurisdictionGroupId;
                    jurisdictionDto.JurisdictionRelation.Rows.Add(jRelationRow);
                }
                #endregion

                // save jurisdictionDto
                if (jurisdictionDto.HasChanges())
                {
                    JurisdictionManager.SaveJurisdiction(jurisdictionDto);
                }
                #endregion

                #region Import Taxes
                #region TaxDto
                TaxDto.TaxRow taxRow = null;

                string taxName = currentRow.ItemArray.GetValue(13).ToString();

                // check if row already exists
                TaxDto.TaxRow[] taxRows = (TaxDto.TaxRow[])currentTaxDto.Tax.Select(String.Format("Name='{0}'", taxName));

                // check if row has already been imported
                TaxDto.TaxRow[] taxRows2  = (TaxDto.TaxRow[])taxDto.Tax.Select(String.Format("Name='{0}'", taxName));
                bool            taxExists = taxRows2 != null && taxRows2.Length > 0;

                if (taxExists)
                {
                    taxRow = taxRows2[0];
                }
                else
                {
                    #region if tax is not in the destination dto
                    if (taxRows != null && taxRows.Length > 0)
                    {
                        taxDto.Tax.ImportRow(taxRows[0]);
                        taxRow = taxDto.Tax[taxDto.Tax.Count - 1];
                    }
                    else
                    {
                        taxRow = taxDto.Tax.NewTaxRow();
                        taxRow.ApplicationId = applicationId;
                        taxRow.TaxType       = TaxType.SalesTax.GetHashCode();
                        taxRow.Name          = taxName;
                    }
                    #endregion
                }

                taxRow.SortOrder = Int32.Parse(currentRow.ItemArray.GetValue(14).ToString());

                if (taxRow.RowState == DataRowState.Detached)
                {
                    taxDto.Tax.Rows.Add(taxRow);
                }
                #endregion

                #region TaxLanguageDto
                TaxDto.TaxLanguageRow taxLanguageRow = null;

                string langCode = currentRow.ItemArray.GetValue(15).ToString();

                // check if row already exists
                TaxDto.TaxLanguageRow[] taxLanguageRows = (TaxDto.TaxLanguageRow[])currentTaxDto.TaxLanguage.Select(String.Format("LanguageCode='{0}' and TaxId={1}", langCode, taxRow.TaxId));

                // check if row has already been imported
                TaxDto.TaxLanguageRow[] taxLanguageRows2 = (TaxDto.TaxLanguageRow[])taxDto.TaxLanguage.Select(String.Format("LanguageCode='{0}' and TaxId={1}", langCode, taxRow.TaxId));
                bool taxLanguageExists = taxLanguageRows2 != null && taxLanguageRows2.Length > 0;

                string displayName = currentRow.ItemArray.GetValue(12).ToString();

                if (taxLanguageExists)
                {
                    taxLanguageRow = taxLanguageRows2[0];
                }
                else
                {
                    #region if tax is not in the destination dto
                    if (taxLanguageRows != null && taxLanguageRows.Length > 0)
                    {
                        taxDto.TaxLanguage.ImportRow(taxLanguageRows[0]);
                        taxLanguageRow = taxDto.TaxLanguage[taxDto.TaxLanguage.Count - 1];
                    }
                    else
                    {
                        taxLanguageRow = taxDto.TaxLanguage.NewTaxLanguageRow();
                        taxLanguageRow.LanguageCode = langCode;
                        taxLanguageRow.TaxId        = taxRow.TaxId;
                    }
                    #endregion
                }

                taxLanguageRow.DisplayName = displayName;

                if (taxLanguageRow.RowState == DataRowState.Detached)
                {
                    taxDto.TaxLanguage.Rows.Add(taxLanguageRow);
                }
                #endregion

                #region TaxValueDto
                TaxDto.TaxValueRow taxValueRow = null;

                // check if row already exists
                TaxDto.TaxValueRow[] taxValueRows = null;
                if (siteId.HasValue)
                {
                    taxValueRows = (TaxDto.TaxValueRow[])currentTaxDto.TaxValue.Select(String.Format("TaxId={0} and SiteId={1} and JurisdictionGroupId={2}", taxRow.TaxId, siteId.Value, jRelationRow.JurisdictionGroupId));
                }
                else
                {
                    taxValueRows = (TaxDto.TaxValueRow[])currentTaxDto.TaxValue.Select(String.Format("TaxId={0} and JurisdictionGroupId={1}", taxRow.TaxId, jRelationRow.JurisdictionGroupId));
                }

                // check if row has already been imported
                TaxDto.TaxValueRow[] taxValueRows2 = null;
                if (siteId.HasValue)
                {
                    taxValueRows2 = (TaxDto.TaxValueRow[])taxDto.TaxValue.Select(String.Format("TaxId={0} and SiteId={1} and JurisdictionGroupId={2}", taxRow.TaxId, siteId.Value, jRelationRow.JurisdictionGroupId));
                }
                else
                {
                    taxValueRows2 = (TaxDto.TaxValueRow[])taxDto.TaxValue.Select(String.Format("TaxId={0} and JurisdictionGroupId={1}", taxRow.TaxId, jRelationRow.JurisdictionGroupId));
                }

                bool taxValueExists = taxValueRows2 != null && taxValueRows2.Length > 0;

                if (taxValueExists)
                {
                    taxValueRow = taxValueRows2[0];
                }
                else
                {
                    if (taxValueRows != null && taxValueRows.Length > 0)
                    {
                        taxDto.TaxValue.ImportRow(taxValueRows[0]);
                        taxValueRow = taxDto.TaxValue[taxDto.TaxValue.Count - 1];
                    }
                    else
                    {
                        taxValueRow       = taxDto.TaxValue.NewTaxValueRow();
                        taxValueRow.TaxId = taxRow.TaxId;
                    }
                }

                // assign tax values
                taxValueRow.JurisdictionGroupId = jGroupRow.JurisdictionGroupId;
                taxValueRow.TaxCategory         = currentRow.ItemArray.GetValue(16).ToString();
                taxValueRow.Percentage          = float.Parse(currentRow.ItemArray.GetValue(17).ToString(), currentCultureInfo);
                taxValueRow.AffectiveDate       = DateTime.Parse(currentRow.ItemArray.GetValue(18).ToString(), currentCultureInfo);
                if (siteId.HasValue)
                {
                    taxValueRow.SiteId = siteId.Value;
                }

                // add row to dto, if needed
                if (taxValueRow.RowState == DataRowState.Detached)
                {
                    taxDto.TaxValue.Rows.Add(taxValueRow);
                }

                // create tax category, if it doesn't exist yet
                CatalogTaxManager.CreateTaxCategory(taxValueRow.TaxCategory, true);
                #endregion

                if (taxDto.HasChanges())
                {
                    TaxManager.SaveTax(taxDto);
                }
                #endregion

                if ((i + 1) % 20 == 0)
                {
                    OnEvent(String.Format("Processed {0} of {1} rows", i + 1, totalRowCount), GetProgressPercent((int)ImportSteps.StartImport, totalImportSteps));
                }
            }

            OnEvent(String.Format("Finished processing parsed rows. Total processed: {0}", totalRowCount), GetProgressPercent((int)ImportSteps.Finish, totalImportSteps));

            OnEvent("CSV file successfully imported.", 100);
        }
        // Extra tax for Stockholm
        protected override Money CalculateTaxTotal(
            IOrderGroup orderGroup
            , IMarket market
            , Currency currency)
        {
            // may have use of this
            // could have Cart/PO-property like ... "CheckTaxStandAlone" for forking code (used with the bogus-cart)
            this._orderGroup = orderGroup;
            decimal d = 0;

            if (market.MarketId.Value == "sv")
            {
                // need the shipment with the new stuff... else coding against the old stuff manually
                IShipment        ship      = orderGroup.GetFirstShipment();
                List <ITaxValue> taxValues = new List <ITaxValue>();

                // Could have a generic "sv"-tax and... and onther higher for Stockholm (address.city)
                // .. but then the below is not needed
                // could set the City, Country etc. based on a IP-LookUp or something Market-wise
                // Could have the "Stockholm Market" where taxes and prices are higher

                // ...just for testing
                if (ship.ShippingAddress == null)
                {
                    this.address        = _orderGroupFactory.Service.CreateOrderAddress(orderGroup);
                    address.CountryCode = "sv";
                    address.CountryName = "sv";

                    // Like The Netherlands tourist accommodation tax ... differs between cities
                    // when you set the city in CM-->Admin-->Taxes ... it gets excluded
                    // and no tax is applied... have to find a "WorkAround"
                    // the rest works...
                    address.City         = "Stockholm";
                    address.Id           = "DummyAddress";
                    ship.ShippingAddress = address;
                }

                if (ship.ShippingAddress.City == "Stockholm")
                {
                    //
                    this.peopleFromStockholm = true;
                }

                // Extra tax ...
                if (ship.ShippingAddress.City == "Stockholm")
                {
                    foreach (var item in orderGroup.GetAllLineItems())
                    {
                        ContentReference contentLink = _referenceConverter.GetContentLink(item.Code);

                        IPricing pricing = _contentRepository.Get <EntryContentBase>(contentLink) as IPricing;
                        int      i       = (int)pricing.TaxCategoryId;

                        // An address have to be there if using this ... so we can match the different properties
                        taxValues.AddRange(GetTaxValues(CatalogTaxManager.GetTaxCategoryNameById(i), "sv", address));

                        foreach (var item2 in taxValues)
                        {
                            // extra tax when shipped to Stockholm 10% more
                            d += (decimal)(item2.Percentage + 0.10) * (item.PlacedPrice * item.Quantity);
                        }
                    }
                    //var liAmount = orderGroup.Forms.Sum(x => x.GetAllLineItems().Sum(l => l.PlacedPrice * l.Quantity));
                }
                else
                {
                    foreach (var item in orderGroup.GetAllLineItems())
                    {
                        ContentReference contentLink = _referenceConverter.GetContentLink(item.Code);

                        IPricing pricing = _contentRepository.Get <EntryContentBase>(contentLink) as IPricing;
                        int      i       = (int)pricing.TaxCategoryId;

                        // An address have to be there
                        taxValues.AddRange(GetTaxValues(CatalogTaxManager.GetTaxCategoryNameById(i), "sv", address));

                        foreach (var item2 in taxValues)
                        {
                            // not Stockholm, so no extra tax
                            d += (decimal)(item2.Percentage) * (item.PlacedPrice * item.Quantity);
                        }
                    }
                }

                return(new Money(d, market.DefaultCurrency) / 100);
            }
            else
            {
                return(base.CalculateTaxTotal(orderGroup, market, currency));
            }
        }
Exemplo n.º 23
0
        private void BindDataType()
        {
            DataRow   dr;
            DataTable dt = new DataTable();

            dt.Columns.Add(new DataColumn("key", typeof(string)));
            dt.Columns.Add(new DataColumn("name", typeof(string)));
            dt.Columns.Add(new DataColumn("Type", typeof(string)));
            dt.Columns.Add(new DataColumn("IsSystemDictionary", typeof(bool)));
            dt.Columns.Add(new DataColumn("AllowNulls", typeof(bool)));
            dt.Columns.Add(new DataColumn("IsConstant", typeof(bool)));

            MappingMetaClass mmc = null;

            MetaDataPlus.Import.Rule mapping = null;
            string MetaClassName             = ddlMetaClass.SelectedValue;
            string language = ddlLanguage.SelectedValue;

            switch (ddlTypeData.SelectedValue)
            {
            case "Category":
                CatalogContext.MetaDataContext.UseCurrentUICulture = false;
                CatalogContext.MetaDataContext.Language            = language;

                if (!String.IsNullOrEmpty(MetaClassName))
                {
                    mmc = new CategoryMappingMetaClass(CatalogContext.MetaDataContext, MetaClassName, -1);
                }
                else
                {
                    mmc = new CategoryMappingMetaClass(CatalogContext.MetaDataContext, -1);
                }

                CatalogContext.MetaDataContext.UseCurrentUICulture = true;

                mapping = mmc.CreateClassRule();
                mapping.Attribute.Add("TypeName", "Category");

                if (!String.IsNullOrEmpty(language))
                {
                    mapping.Attribute.Add("Language", language);
                }
                break;

            case "Entry":
                CatalogContext.MetaDataContext.UseCurrentUICulture = false;
                CatalogContext.MetaDataContext.Language            = language;

                if (!String.IsNullOrEmpty(MetaClassName))
                {
                    mmc = new EntryMappingMetaClass(CatalogContext.MetaDataContext, MetaClassName, -1);
                }
                else
                {
                    mmc = new EntryMappingMetaClass(CatalogContext.MetaDataContext, -1);
                }

                CatalogContext.MetaDataContext.UseCurrentUICulture = true;

                mapping = mmc.CreateClassRule();
                mapping.Attribute.Add("TypeName", "Entry");

                if (!String.IsNullOrEmpty(language))
                {
                    mapping.Attribute.Add("Language", language);
                }
                break;

            case "EntryRelation":
                mmc     = new EntryRelationMappingMetaClass(CatalogContext.MetaDataContext, -1);
                mapping = mmc.CreateClassRule();
                mapping.Attribute.Add("TypeName", "EntryRelation");
                break;

            case "EntryAssociation":
                mmc     = new EntryAssociationMappingMetaClass(CatalogContext.MetaDataContext, -1);
                mapping = mmc.CreateClassRule();
                mapping.Attribute.Add("TypeName", "EntryAssociation");
                break;

            case "Variation":
                mmc     = new VariationMappingMetaClass(CatalogContext.MetaDataContext, -1);
                mapping = mmc.CreateClassRule();
                mapping.Attribute.Add("TypeName", "Variation");
                break;

            case "SalePrice":
                mmc     = new PricingMappingMetaClass(CatalogContext.MetaDataContext, -1);
                mapping = mmc.CreateClassRule();
                mapping.Attribute.Add("TypeName", "SalePrice");
                break;

            default:
                return;
            }
            mapping.Attribute.Add("Delimiter", this.ddlDelimiter.SelectedValue);
            mapping.Attribute.Add("TextQualifier", this.ddlTextQualifier.SelectedValue);
            foreach (ColumnInfo ci in mmc.ColumnInfos)
            {
                dr = dt.NewRow();
                if (ci.Field.IsSystem)
                {
                    dr["key"]  = ci.FieldName;
                    dr["name"] = (ci.FieldFriendlyName != null) ? ci.FieldFriendlyName : ci.FieldName;
                }
                else
                {
                    dr["key"]  = ci.FieldName;
                    dr["name"] = ci.FieldFriendlyName;
                }

                if (ci.Field.MultiLanguageValue && !String.IsNullOrEmpty(language))
                {
                    dr["name"] += String.Format(" ({0})", language);
                }

                dr["Type"] = ci.Field.DataType.ToString();
                dr["IsSystemDictionary"] = ci.IsSystemDictionary;
                dr["AllowNulls"]         = ci.Field.AllowNulls;
                dr["IsConstant"]         = false;
                dt.Rows.Add(dr);
                mapping.Add(new RuleItem(ci.Field, MetaDataPlus.Import.FillType.NotUse));
            }
            grdFields.Columns[0].HeaderText = RM.GetString("IMPORT_MAPPING_TITLE_FIELDS");
            grdFields.Columns[1].HeaderText = RM.GetString("IMPORT_MAPPING_TITLE_COLUMN_HEADERS");
            grdFields.Columns[2].HeaderText = "Custom values";
            grdFields.DataSource            = dt;
            grdFields.DataBind();
            this.ClassRule = mapping;

            if (ddlDataFiles.SelectedIndex > 0)
            {
                IIncomingDataParser parser  = null;
                DataSet             rawData = null;
                try
                {
                    char chTextQualifier = (this.ddlTextQualifier.SelectedValue == "") ? '\0' : char.Parse(this.ddlTextQualifier.SelectedValue);
                    parser  = new CsvIncomingDataParser(SourcePath, true, char.Parse(this.ddlDelimiter.SelectedValue), chTextQualifier, true, GetEncoding(this.ddlEncoding.SelectedValue));
                    rawData = parser.Parse(ddlDataFiles.SelectedItem.Text, null);
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex.Message);
                    return;
                }
                DataTable dtSource = rawData.Tables[0];

                DataTable dtColumns = new DataTable();
                dtColumns.Columns.Add(new DataColumn("Text", typeof(string)));
                dtColumns.Columns.Add(new DataColumn("Value", typeof(string)));

                foreach (DataColumn dc in dtSource.Columns)
                {
                    dr          = dtColumns.NewRow();
                    dr["Text"]  = "Column " + (dc.Ordinal + 1) + " - " + dc.ColumnName;
                    dr["Value"] = dc.ColumnName;
                    dtColumns.Rows.Add(dr);
                }

                foreach (DataGridItem dgi in grdFields.Items)
                {
                    DropDownList ddl           = (DropDownList)dgi.FindControl("ddlFields");
                    TextBox      tbCustomValue = (TextBox)dgi.FindControl("tbCustomValue");
                    DropDownList ddlValues     = (DropDownList)dgi.FindControl("ddlValues");

                    string sKey  = dgi.Cells[3].Text;
                    string sType = dgi.Cells[4].Text;
                    bool   sIsSystemDictionary = bool.Parse(dgi.Cells[5].Text);
                    bool   allowNulls          = bool.Parse(dgi.Cells[6].Text);
                    bool   IsConstant          = bool.Parse(dgi.Cells[7].Text);

                    bool useDictionaryControl = GetUseDictionaryFlag(dgi);

                    if (!IsConstant)
                    {
                        if (ddl != null)
                        {
                            ddl.DataSource     = dtColumns;
                            ddl.DataTextField  = "Text";
                            ddl.DataValueField = "Value";
                            ddl.DataBind();

                            if (sIsSystemDictionary)
                            {
                                ddl.Items.Insert(0, new ListItem("<" + RM.GetString("IMPORT_TYPE_VALUES_DICTIONARY_VALUE") + ">", "CustomValue"));
                            }
                            else
                            {
                                ddl.Items.Insert(0, new ListItem("<" + RM.GetString("IMPORT_TYPE_VALUES_CUSTOM_VALUE") + ">", "CustomValue"));
                            }

                            if (allowNulls)
                            {
                                ddl.Items.Insert(0, new ListItem("", ""));
                            }
                            else
                            {
                                ddl.Items.Insert(0, new ListItem("<" + RM.GetString("IMPORT_TYPE_VALUES_NOT_SET") + ">", "NotSet"));
                            }

                            string customControlID = useDictionaryControl ? ddlValues.ClientID : tbCustomValue.ClientID;

                            string jsDllOnChange = String.Format("ddlOnChange(this, 'CustomValue', '{0}')", customControlID);
                            ddl.Attributes.Add("OnChange", jsDllOnChange);
                        }
                    }

                    //fill custom or dictionary controls
                    ddlValues.Visible     = useDictionaryControl;
                    tbCustomValue.Visible = !ddlValues.Visible;

                    if (sType.Equals(MetaDataType.Boolean.ToString()) || sType.Equals(MetaDataType.Bit.ToString()))
                    {
                        ddlValues.Items.Clear();
                        ddlValues.Items.Add("True");
                        ddlValues.Items.Add("False");
                    }

                    if (sKey.Equals("sys_RowAction"))
                    {
                        ddlValues.Items.Clear();
                        ddlValues.Items.Add(RowAction.Default.ToString());
                        ddlValues.Items.Add(RowAction.Insert.ToString());
                        ddlValues.Items.Add(RowAction.Update.ToString());
                        ddlValues.Items.Add(RowAction.Delete.ToString());
                    }

                    switch (ddlTypeData.SelectedValue)
                    {
                    case "Category":
                        if (sKey == "TemplateName")
                        {
                            TemplateDto templates = DictionaryManager.GetTemplateDto();
                            if (templates.main_Templates.Count > 0)
                            {
                                DataView view = templates.main_Templates.DefaultView;
                                view.RowFilter           = "TemplateType = 'node'";
                                ddlValues.DataTextField  = "FriendlyName";
                                ddlValues.DataValueField = "Name";
                                ddlValues.DataSource     = view;
                                ddlValues.DataBind();
                            }
                        }
                        break;

                    case "Entry":
                        if (sKey == "ClassTypeId")
                        {
                            ddlValues.Items.Clear();
                            ddlValues.Items.Add(new ListItem("Product", EntryType.Product));
                            ddlValues.Items.Add(new ListItem("Variation/Sku", EntryType.Variation));
                            ddlValues.Items.Add(new ListItem("Package", EntryType.Package));
                            ddlValues.Items.Add(new ListItem("Bundle", EntryType.Bundle));
                            ddlValues.Items.Add(new ListItem("Dynamic Package", EntryType.DynamicPackage));
                        }

                        if (sKey == "TemplateName")
                        {
                            TemplateDto templates = DictionaryManager.GetTemplateDto();
                            if (templates.main_Templates.Count > 0)
                            {
                                DataView view = templates.main_Templates.DefaultView;
                                view.RowFilter           = "TemplateType = 'entry'";
                                ddlValues.DataTextField  = "FriendlyName";
                                ddlValues.DataValueField = "Name";
                                ddlValues.DataSource     = view;
                                ddlValues.DataBind();
                            }
                        }
                        break;

                    case "EntryAssociation":
                        if (sKey == "AssociationType")
                        {
                            ddlValues.Items.Clear();
                            CatalogAssociationDto dto = CatalogContext.Current.GetCatalogAssociationDto(0);
                            if (dto.AssociationType.Count > 0)
                            {
                                ddlValues.DataTextField  = "Description";
                                ddlValues.DataValueField = "AssociationTypeId";
                                ddlValues.DataSource     = dto.AssociationType;
                                ddlValues.DataBind();
                            }
                        }
                        break;

                    case "Variation":
                        if (sKey == "TaxCategoryId")
                        {
                            CatalogTaxDto taxes = CatalogTaxManager.GetTaxCategories();
                            if (taxes.TaxCategory != null)
                            {
                                ddlValues.DataTextField  = "Name";
                                ddlValues.DataValueField = "TaxCategoryId";
                                ddlValues.DataSource     = taxes.TaxCategory.Rows;
                                ddlValues.DataBind();
                            }
                        }
                        if (sKey == "MerchantId")
                        {
                            CatalogEntryDto merchants = CatalogContext.Current.GetMerchantsDto();
                            if (merchants.Merchant != null)
                            {
                                ddlValues.DataTextField  = "Name";
                                ddlValues.DataValueField = "MerchantId";
                                ddlValues.DataSource     = merchants.Merchant.Rows;
                                ddlValues.DataBind();
                            }
                        }
                        if (sKey == "WarehouseId")
                        {
                            WarehouseDto warehouses = WarehouseManager.GetWarehouseDto();
                            if (warehouses.Warehouse != null)
                            {
                                ddlValues.DataTextField  = "Name";
                                ddlValues.DataValueField = "WarehouseId";
                                ddlValues.DataSource     = warehouses.Warehouse.Rows;
                                ddlValues.DataBind();
                            }
                        }
                        if (sKey == "PackageId")
                        {
                            ShippingMethodDto shippingDto = ShippingManager.GetShippingPackages();
                            if (shippingDto.Package != null)
                            {
                                ddlValues.DataTextField  = "Name";
                                ddlValues.DataValueField = "PackageId";
                                ddlValues.DataSource     = shippingDto.Package.Rows;
                                ddlValues.DataBind();
                            }
                        }

                        break;

                    case "SalePrice":
                        if (sKey == "SaleType")
                        {
                            ddlValues.Items.Clear();
                            foreach (SalePriceTypeDefinition element in CatalogConfiguration.Instance.SalePriceTypes)
                            {
                                ListItem li = new ListItem(UtilHelper.GetResFileString(element.Description), element.Value.ToString());
                                ddlValues.Items.Add(li);
                            }
                        }
                        if (sKey == "Currency")
                        {
                            CurrencyDto dto = CatalogContext.Current.GetCurrencyDto();
                            ddlValues.DataTextField  = "Name";
                            ddlValues.DataValueField = "CurrencyCode";
                            ddlValues.DataSource     = dto.Currency;
                            ddlValues.DataBind();
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
        }
Exemplo n.º 24
0
    /// <summary>
    /// Binds the batch control.
    /// </summary>
    private void BindData()
    {
        CatalogEntryDto.VariationRow[] variationRows = null;

        CatalogEntryDto.CatalogEntryRow item = (CatalogEntryDto.CatalogEntryRow)DataItem;

        if (IsMetaField)
        {
            int             MetaClassId = item.MetaClassId;
            int             ObjectId    = item.CatalogEntryId;
            MetaDataContext MDContext   = CatalogContext.MetaDataContext;

            MetaControls.EnableViewState = false;
            if (MetaControls.Controls.Count > 0)
            {
                return;
            }

            MetaControls.Controls.Clear();

            MetaClass mc = MetaClass.Load(MDContext, MetaClassId);

            if (mc == null)
            {
                return;
            }

            MDContext.UseCurrentUICulture = false;
            MDContext.Language            = LanguageCode;

            MetaObject metaObj = null;
            if (ObjectId > 0)
            {
                metaObj = MetaObject.Load(MDContext, ObjectId, mc);
                if (metaObj == null)
                {
                    metaObj = MetaObject.NewObject(MDContext, ObjectId, MetaClassId, FrameworkContext.Current.Profile.UserName);
                    metaObj.AcceptChanges(MDContext);
                }
            }
            MDContext.UseCurrentUICulture = true;


            MetaField mf = MetaField.Load(MDContext, FieldName);
            if (mf.IsUser)
            {
                string  controlName = ResolveMetaControl(mc, mf);
                Control ctrl        = MetaControls.FindControl(mf.Name);

                if (ctrl == null)
                {
                    ctrl = Page.LoadControl(controlName);
                    MetaControls.Controls.Add(ctrl);
                }


                CoreBaseUserControl coreCtrl = ctrl as CoreBaseUserControl;
                if (coreCtrl != null)
                {
                    coreCtrl.MDContext = MDContext;
                }

                //ctrl.ID = String.Format("{0}-{1}", mf.Name, index.ToString());

                ((IMetaControl)ctrl).MetaField = mf;
                if (metaObj != null && metaObj[mf.Name] != null)
                {
                    ((IMetaControl)ctrl).MetaObject = metaObj;
                }

                ((IMetaControl)ctrl).LanguageCode    = LanguageCode;
                ((IMetaControl)ctrl).ValidationGroup = String.Empty;

                ctrl.DataBind();
            }
        }
        else
        {
            switch (FieldName)
            {
            case "Name":
            case "Code":
                tbItem.Visible = true;
                tbItem.Text    = (string)item[FieldName];
                break;

            case "StartDate":
            case "EndDate":
                cdpItem.Visible = true;
                cdpItem.Value   = (DateTime)item[FieldName];
                break;

            case "TemplateName":
                ddlItem.Visible = true;
                TemplateDto templates = DictionaryManager.GetTemplateDto();
                if (templates.main_Templates.Count > 0)
                {
                    DataView view = templates.main_Templates.DefaultView;
                    view.RowFilter         = "TemplateType = 'entry'";
                    ddlItem.DataTextField  = "FriendlyName";
                    ddlItem.DataValueField = "Name";
                    ddlItem.DataSource     = view;
                    ddlItem.DataBind();
                }
                ManagementHelper.SelectListItem2(ddlItem, item.TemplateName);
                break;

            case "SortOrder":
                tbItem.Visible = true;
                CatalogRelationDto relationDto = CatalogContext.Current.GetCatalogRelationDto(item.CatalogId, CatalogNodeId, item.CatalogEntryId, String.Empty, new CatalogRelationResponseGroup(CatalogRelationResponseGroup.ResponseGroup.NodeEntry));
                if (relationDto.NodeEntryRelation.Count > 0)
                {
                    tbItem.Text = relationDto.NodeEntryRelation[0].SortOrder.ToString();
                }
                break;

            case "IsActive":
                becItem.Visible    = true;
                becItem.IsSelected = item.IsActive;
                break;

            case "ListPrice":
                tbItem.Visible = true;
                variationRows  = item.GetVariationRows();
                if (variationRows.Length > 0)
                {
                    tbItem.Text = variationRows[0].ListPrice.ToString("#0.00");
                }
                break;

            case "TaxCategoryId":
                ddlItem.Visible = true;
                ddlItem.Items.Add(new ListItem(Resources.CatalogStrings.Entry_Select_Tax_Category, "0"));
                CatalogTaxDto taxes = CatalogTaxManager.GetTaxCategories();
                if (taxes.TaxCategory != null)
                {
                    foreach (CatalogTaxDto.TaxCategoryRow row in taxes.TaxCategory.Rows)
                    {
                        ddlItem.Items.Add(new ListItem(row.Name, row.TaxCategoryId.ToString()));
                    }
                }
                ddlItem.DataBind();
                variationRows = item.GetVariationRows();
                if (variationRows.Length > 0)
                {
                    ManagementHelper.SelectListItem2(ddlItem, variationRows[0].TaxCategoryId);
                }
                break;

            case "TrackInventory":
                becItem.Visible = true;
                variationRows   = item.GetVariationRows();
                if (variationRows.Length > 0)
                {
                    becItem.IsSelected = variationRows[0].TrackInventory;
                }
                break;

            case "MerchantId":
                ddlItem.Visible = true;
                ddlItem.Items.Insert(0, new ListItem(Resources.CatalogStrings.Entry_Select_Merchant, ""));
                CatalogEntryDto merchants = CatalogContext.Current.GetMerchantsDto();
                if (merchants.Merchant != null)
                {
                    foreach (CatalogEntryDto.MerchantRow row in merchants.Merchant.Rows)
                    {
                        ddlItem.Items.Add(new ListItem(row.Name, row.MerchantId.ToString()));
                    }
                }
                ddlItem.DataBind();
                variationRows = item.GetVariationRows();
                if (variationRows.Length > 0 && !variationRows[0].IsMerchantIdNull())
                {
                    ManagementHelper.SelectListItem2(ddlItem, variationRows[0].MerchantId);
                }
                break;

            case "WarehouseId":
                ddlItem.Visible = true;
                ddlItem.Items.Insert(0, new ListItem(Resources.CatalogStrings.Entry_Select_Warehouse, "0"));
                WarehouseDto warehouses = WarehouseManager.GetWarehouseDto();
                if (warehouses.Warehouse != null)
                {
                    foreach (WarehouseDto.WarehouseRow row in warehouses.Warehouse.Rows)
                    {
                        ddlItem.Items.Add(new ListItem(row.Name, row.WarehouseId.ToString()));
                    }
                }
                ddlItem.DataBind();
                variationRows = item.GetVariationRows();
                if (variationRows.Length > 0)
                {
                    ManagementHelper.SelectListItem2(ddlItem, variationRows[0].WarehouseId);
                }
                break;

            case "PackageId":
                ddlItem.Visible = true;
                ddlItem.Items.Insert(0, new ListItem(Resources.CatalogStrings.Entry_Select_Package, "0"));
                ShippingMethodDto shippingDto = ShippingManager.GetShippingPackages();
                if (shippingDto.Package != null)
                {
                    foreach (ShippingMethodDto.PackageRow row in shippingDto.Package.Rows)
                    {
                        ddlItem.Items.Add(new ListItem(row.Name, row.PackageId.ToString()));
                    }
                }
                ddlItem.DataBind();
                variationRows = item.GetVariationRows();
                if (variationRows.Length > 0)
                {
                    ManagementHelper.SelectListItem2(ddlItem, variationRows[0].PackageId);
                }
                break;

            case "Weight":
            case "MinQuantity":
            case "MaxQuantity":
                tbItem.Visible = true;
                variationRows  = item.GetVariationRows();
                if (variationRows.Length > 0 && variationRows[0][FieldName] != DBNull.Value)
                {
                    tbItem.Text = variationRows[0][FieldName].ToString();
                }
                break;

            case "InStockQuantity":
            case "ReservedQuantity":
            case "ReorderMinQuantity":
            case "PreorderQuantity":
            case "BackorderQuantity":
                tbItem.Visible = true;
                if (item.InventoryRow != null && item.InventoryRow[FieldName] != DBNull.Value)
                {
                    tbItem.Text = item.InventoryRow[FieldName].ToString();
                }
                break;

            case "AllowBackorder":
            case "AllowPreorder":
                becItem.Visible = true;
                if (item.InventoryRow != null)
                {
                    becItem.IsSelected = (bool)item.InventoryRow[FieldName];
                }
                break;

            case "InventoryStatus":
                ddlItem.Visible = true;
                ddlItem.Items.Insert(0, new ListItem(Resources.SharedStrings.Disabled, "0"));
                ddlItem.Items.Insert(0, new ListItem(Resources.SharedStrings.Enabled, "1"));
                ddlItem.Items.Insert(0, new ListItem(Resources.SharedStrings.Ignored, "2"));
                ddlItem.DataBind();
                if (item.InventoryRow != null)
                {
                    ManagementHelper.SelectListItem2(ddlItem, item.InventoryRow.InventoryStatus);
                }
                break;

            case "PreorderAvailabilityDate":
            case "BackorderAvailabilityDate":
                cdpItem.Visible = true;
                if (item.InventoryRow != null)
                {
                    cdpItem.Value = (DateTime)item.InventoryRow[FieldName];
                }
                break;
            }
        }
    }
        //Injected<ReferenceConverter> _refConv;
        public override void SetDefaultValues(ContentType contentType)
        {
            #region JustChecking - prob. no demo of "What is my parent"

            //contentType = ID = 27, Name = "SomeVariation"


            #region Used to check


            //CatalogContentBase theOut0 = null;
            //var stuff0 = _loader.Service.TryGet<CatalogContentBase>(this.ParentLink, out theOut0); // could use this
            //// this gives the product if created on the Product
            //// gets the shirt node if created direct in the node

            //EntryContentBase theOut00 = null;
            //var stuff00 = _loader.Service.TryGet<EntryContentBase>(this.ParentLink, out theOut00); // could use this
            //                                                                                       // SameSame when doing on the Product
            //                                                                                       // gets null if created direct in the node...of course
            //                                                                                       // gets the Product if assigent to one

            #endregion

            //var cat = theOut00.Categories; // seems to be CMS-categories ... error if created in the node directly
            // no error if done at the product

            //var cat1 = theOut00.GetNodeRelations(); // gets the relations... error if created in the node
            //var t = cat1.GetEnumerator().Current.Target; gets error

            //var t = theOut0.GetOriginalType();
            //var v = this.ParentLink;

            // Changed i 9 (triggers twice now, not four times)
            // ...see the ReadMe.txt in NumberNine ECF-8.17 for more info...
            // 1073741825, SomeNode is "TheParentNode"... gets that when "outside" of a product
            // Need to walk up the hierarchy to find the node ... when "doing it" on a Product

            #endregion

            base.SetDefaultValues(contentType);

            #region Old garbage

            // ...For the lab (if any), Added a null-check if the editor did not choose any category
            //CatalogContentBase theOut = null; // would like more flexibility here
            //var stuff2 = _loader.Service.TryGet<CatalogContentBase>(this.ParentLink, out theOut); // cannot use this
            // Gets null for the above
            //var c = this.GetCategories();
            //var xx = this.ParentLink.GetOriginalType();
            //var yy = stuff2.GetOriginalType();


            //var relations = this.GetNodeRelations(); // error if done on the node
            //var stuff3 = _loader.Service.TryGet<ProductContent>(this.ParentLink, out onProduct); // could use this

            // could do a check if node or product
            // NodeEntryrelation have IsPrimary
            // just checking the parent... could have several levels of products
            // check if NodeEntryRelation is set here

            //NodeEntryRelation 11.2 & ServiceAPI is different with this thing

            /*
             * var rels = this.GetNodeRelations(); // not set yet, unusable
             * foreach (var item in rels)
             * {
             *  NodeEntryRelation r = (NodeEntryRelation)item;
             *  if (r.IsPrimary)
             *  {
             *      var id = r.Child.ID;
             *  }
             * }
             */

            //CatalogContentBase theOut4 = null; // would like more flexibility here

            #endregion

            CatalogContentBase myParent = _loader.Service.Get <CatalogContentBase>(this.ParentLink); //

            // just checking, used in "old garbage"
            //IEnumerable<IContent> ans = _loader.Service.GetAncestors(myCategory.ContentLink);

            #region More old garbage
            //List<IContent> ans2 =

            //var z = this.Categories; // nothing, but some other category
            //var zz = this.GetCategories(); // nothing, not set yet

            //string taxCat = String.Empty;
            //ContentReference ccref = null;

            #endregion

            // Changed so the ServiceAPI works
            if (myParent.GetOriginalType() == typeof(NodeContent))
            {
                FashionNode fashionNode = (FashionNode)myParent;

                // sooo much easier now
                this.TaxCategoryId  = int.Parse(fashionNode.TaxCategories);
                this.theTaxCategory = CatalogTaxManager.GetTaxCategoryNameById(Int16.Parse(fashionNode.TaxCategories));
            }

            #region Oldest garbage

            //foreach (var item in ans) // Nodes
            //{
            //    if (item.GetOriginalType() == typeof(FashionNode)) // so it doesn't crash in the catalog
            //    {
            //        var item2 = (FashionNode)item;
            //        if (item2.TaxCategories != "")
            //        {
            //            taxCat = item2.TaxCategories;
            //            ccref = item2.ContentLink;
            //            break;
            //        }

            //    }

            //}


            //var a = ans.GetEnumerator().Current;
            //var aa = ans.GetEnumerator().MoveNext().GetOriginalType();


            //ContentReference ppp = null;
            //var ccc = ans.GetEnumerator();
            //ccc.MoveNext();
            //var c = ccc.Current.ContentLink;
            //while (ccc.Current.GetOriginalType() == typeof(EntryContentBase))
            //{
            //    ppp = ccc.Current.ContentLink;
            //}

            //var daStuff = _loader.Service.Get<FashionNode>(ccref);
            //var t = daStuff.TaxCategories;

            //if (daStuff != null) // in other words we got the "right thing"
            //{
            //    FashionNode node = (FashionNode)daStuff;
            //    if (node.TaxCategories != null) // need to check this
            //    {
            //        //we have the parent node
            //        this.TaxCategoryId = Int16.Parse(node.TaxCategories); // change this to int in the model
            //        // ...have a look if the Tax-drop-down in pricing dialog changes to the string... yes it does
            //        this.theTaxCategory = CatalogTaxManager.GetTaxCategoryNameById(Int16.Parse(node.TaxCategories));
            //        this.MainBody = new XhtmlString(theOut.Name);
            //    }
            //}

            //do
            //{

            //    //CatalogContentBase theOut3 = null; // would like more flexibility here
            //    //pp = _loader.Service.Get<CatalogContentBase>(pp.ParentLink); // cannot use this
            //    p.ParentLink.GetOriginalType();
            //    var check = typeof(EntryContentBase);
            //    if (p.GetOriginalType() == typeof(FashionNode))
            //    {
            //        b = true;
            //        p = _loader.Service.

            //    }
            //    FashionNode theOut4 = null;
            //    var pp = _loader.Service.TryGet<FashionNode>(stuff4.ParentLink, out theOut4);

            //} while (b);


            // Original
            //if (stuff2) // in other words we got the "right thing"
            //{
            //    FashionNode node = (FashionNode)theOut;
            //    if (node.TaxCategories != null) // need to check this
            //    {
            //        //we have the parent node
            //        this.TaxCategoryId = Int16.Parse(node.TaxCategories); // change this to int in the model
            //        // ...have a look if the Tax-drop-down in pricing dialog changes to the string... yes it does
            //        this.theTaxCategory = CatalogTaxManager.GetTaxCategoryNameById(Int16.Parse(node.TaxCategories));
            //        this.MainBody = new XhtmlString(theOut.Name);
            //    }
            //}

            #endregion
        }
Exemplo n.º 26
0
 public string GetTaxCategoryNameById(int id)
 {
     return(CatalogTaxManager.GetTaxCategoryNameById(id));
 }