public void createTaxLine() { getApiKey(); conekta.Api.version = "2.0.0"; Order order = new conekta.Order().create(@"{ ""currency"":""MXN"", ""customer_info"": { ""name"": ""Jul Ceballos"", ""phone"": ""+5215555555555"", ""email"": ""*****@*****.**"" }, ""line_items"": [{ ""name"": ""Box of Cohiba S1s"", ""unit_price"": 35000, ""quantity"": 1 }] }"); Assert.AreEqual(order.id.GetType().ToString(), "System.String"); order = new Order().find(order.id); TaxLine tax_line = order.createTaxLine(@"{ ""description"": ""IVA"", ""amount"": 600, ""metadata"": { ""random_key"": ""random_value"" } }"); Assert.AreEqual(tax_line.description, "IVA"); Assert.AreEqual(tax_line.amount, 600); }
public Invoice CreateBasedInOrder(Order order) { var invoice = new Invoice(order); var invoiceLines = new List <InvoiceLine>(); var taxLine = new TaxLine(); foreach (var line in order.OrderLines) { var currentTaxLine = taxLine.GetDefaultTaxes(line.TotalPrice); var invoiceLine = new InvoiceLine(orderLine: line, taxLine: currentTaxLine); invoiceLines.Add(invoiceLine); } foreach (var line in invoiceLines) { invoice.AddInvoiceLine(line); } if (!invoice.Valid) { return(invoice); } order.Bill(); _orderRepository.Update(order); _invoiceRepository.Create(invoice); _uow.Commit(); return(invoice); }
public static TaxEvaluationContext ToTaxEvalContext(this ShoppingCart cart, Store store) { var result = new TaxEvaluationContext(cart.StoreId) { Id = cart.Id, Code = cart.Name, Currency = cart.Currency, Type = "Cart", Customer = cart.Customer, StoreTaxCalculationEnabled = store.TaxCalculationEnabled, FixedTaxRate = store.FixedTaxRate }; foreach (var lineItem in cart.Items) { result.Lines.Add(new TaxLine(lineItem.Currency) { Id = lineItem.Id, Code = lineItem.Sku, Name = lineItem.Name, TaxType = lineItem.TaxType, //Special case when product have 100% discount and need to calculate tax for old value Amount = lineItem.ExtendedPrice.Amount > 0 ? lineItem.ExtendedPrice : lineItem.SalePrice }); } foreach (var shipment in cart.Shipments) { var totalTaxLine = new TaxLine(shipment.Currency) { Id = shipment.Id, Code = shipment.ShipmentMethodCode, Name = shipment.ShipmentMethodOption, TaxType = shipment.TaxType, //Special case when shipment have 100% discount and need to calculate tax for old value Amount = shipment.Total.Amount > 0 ? shipment.Total : shipment.Price }; result.Lines.Add(totalTaxLine); if (shipment.DeliveryAddress != null) { result.Address = shipment.DeliveryAddress; } } foreach (var payment in cart.Payments) { var totalTaxLine = new TaxLine(payment.Currency) { Id = payment.Id, Code = payment.PaymentGatewayCode, Name = payment.PaymentGatewayCode, TaxType = payment.TaxType, //Special case when shipment have 100% discount and need to calculate tax for old value Amount = payment.Total.Amount > 0 ? payment.Total : payment.Price }; result.Lines.Add(totalTaxLine); } return(result); }
protected virtual TaxSubTotal GetTaxSubTotal(TaxLine taxLine, TaxJurisdiction taxJurisdiction, string currencyCode) { Assert.ArgumentNotNull(taxLine, "taxLine"); Assert.ArgumentNotNull(taxJurisdiction, "taxJurisdiction"); Assert.ArgumentNotNullOrEmpty(currencyCode, "currencyCode"); var total = OrderFactory.CreateTaxSubTotal(); total.TaxableAmount = OrderFactory.CreateAmount(taxLine.TaxedAmount, currencyCode); total.TaxAmount = OrderFactory.CreateAmount(taxJurisdiction.Tax, currencyCode); total.TransactionCurrencyTaxAmount = OrderFactory.CreateAmount(taxJurisdiction.Tax, currencyCode); var category = OrderFactory.CreateTaxCategory(); category.ID = taxLine.ProductCode; // This will be either the actual product code for product tax, "SHIPPING" for shipping tax, or "HANDLING" for handling tax category.Name = taxLine.Type; // This will be populated for VAT, blank for North America tax category.Percent = taxJurisdiction.Rate * 100; category.BaseUnitMeasure = OrderFactory.CreateMeasure(); category.PerUnitAmount = OrderFactory.CreateAmount(0M, currencyCode); var scheme = OrderFactory.CreateTaxScheme(); scheme.CurrencyCode = currencyCode; scheme.ID = taxJurisdiction.Name; scheme.Name = taxJurisdiction.Name; scheme.TaxTypeCode = taxJurisdiction.Type; category.TaxScheme = scheme; total.TaxCategory = category; return(total); }
private static void AddToTaxItems(SalesTransaction transaction, IEnumerable <TaxLine> taxLines) { // Looping through each of the tax lines currently set to the ietm foreach (TaxLine saleLineTaxItem in taxLines) { // For every taxLine it is checked whether it has been added before to the transaction // If found, add the amount to the existing tax item. // If not a new taxItem is added to the transaction bool found = false; // Creating a new Tax item in case it needs to be added. TaxLine taxItem = new TaxLine(saleLineTaxItem); // Looping to see if tax group already exists foreach (TaxLine transTaxItem in transaction.TaxLines) { if ((transTaxItem.TaxCode != null) && (transTaxItem.TaxCode == saleLineTaxItem.TaxCode)) { transTaxItem.Amount += saleLineTaxItem.Amount; transTaxItem.TaxBasis += saleLineTaxItem.TaxBasis; found = true; break; } } if (!found) { transaction.TaxLines.Add(taxItem); } } }
public static TaxLine ToShopifyModel(this Storefront.Model.TaxDetail storefrontModel) { var shopifyModel = new TaxLine(); shopifyModel.Price = storefrontModel.Amount.Amount * 100; shopifyModel.Title = storefrontModel.Name; return(shopifyModel); }
public static TaxLine ToViewModel(this DataContracts.TaxDetail taxDetail) { var taxLineModel = new TaxLine(); taxLineModel.Price = taxDetail.Amount; taxLineModel.Rate = taxDetail.Rate; taxLineModel.Title = taxDetail.Name; return(taxLineModel); }
public static DataContracts.TaxDetail ToServiceModel(this TaxLine taxLineModel) { var taxDetail = new DataContracts.TaxDetail(); taxDetail.Amount = taxLineModel.Price; taxDetail.Name = taxLineModel.Title; taxDetail.Rate = taxLineModel.Rate; return(taxDetail); }
public virtual LineItemModel FromTaxLine(TaxLine taxLine) { number = taxLine.Id; itemCode = taxLine.Code; description = taxLine.Name; taxCode = taxLine.TaxType; amount = taxLine.Amount; quantity = taxLine.Quantity; return(this); }
public virtual TaxEvaluationContext ToTaxEvalContext(ShoppingCart cart) { var result = new TaxEvaluationContext(cart.StoreId); result.Id = cart.Id; result.Code = cart.Name; result.Currency = cart.Currency; result.Type = "Cart"; result.Customer = cart.Customer; foreach (var lineItem in cart.Items) { result.Lines.Add(new TaxLine(lineItem.Currency) { Id = lineItem.Id, Code = lineItem.Sku, Name = lineItem.Name, TaxType = lineItem.TaxType, Amount = lineItem.ExtendedPrice }); } foreach (var shipment in cart.Shipments) { var totalTaxLine = new TaxLine(shipment.Currency) { Id = shipment.Id, Code = shipment.ShipmentMethodCode, Name = shipment.ShipmentMethodOption, TaxType = shipment.TaxType, Amount = shipment.Total }; result.Lines.Add(totalTaxLine); if (shipment.DeliveryAddress != null) { result.Address = shipment.DeliveryAddress; } } foreach (var payment in cart.Payments) { var totalTaxLine = new TaxLine(payment.Currency) { Id = payment.Id, Code = payment.PaymentGatewayCode, Name = payment.PaymentGatewayCode, TaxType = payment.TaxType, Amount = payment.Total }; result.Lines.Add(totalTaxLine); } return(result); }
private void gridTaxLines_CurrentCellChanged(object sender, EventArgs e) { if (_currentRow != gridTaxLines.CurrentRowIndex) { _currentRow = gridTaxLines.CurrentRowIndex; if (_currentRow >= 0 && _getTaxResult.TaxLines.Count > 0) { TaxLine taxLine = _getTaxResult.TaxLines[_currentRow]; LoadTaxDetailData(taxLine); } } }
public static coreDto.TaxLine ToTaxLineDto(this TaxLine taxLine) { return(new coreDto.TaxLine { Id = taxLine.Id, Code = taxLine.Code, Name = taxLine.Name, Quantity = taxLine.Quantity, TaxType = taxLine.TaxType, Amount = (double)taxLine.Amount.Amount, Price = (double)taxLine.Price.Amount }); }
public void updateTaxLine() { conekta.Api.apiKey = "key_eYvWV7gSDkNYXsmr"; conekta.Api.version = "2.0.0"; Order order = new conekta.Order().create(@"{ ""currency"":""MXN"", ""customer_info"": { ""name"": ""Jul Ceballos"", ""phone"": ""+5215555555555"", ""email"": ""*****@*****.**"" }, ""line_items"": [{ ""name"": ""Box of Cohiba S1s"", ""unit_price"": 35000, ""quantity"": 1, ""metadata"": { ""random_key"": ""random value"" } }] }" ); Assert.AreEqual(order.id.GetType().ToString(), "System.String"); order = new Order().find(order.id); TaxLine tax_line = order.createTaxLine(@"{ ""description"": ""IVA"", ""amount"": 600, ""contextual_data"": { ""random_key"": ""random_value"" } }" ); order = new Order().find(order.id); //tax_line = order.tax_lines.at(0).update(@"{ // ""description"": ""IVA"", // ""amount"": 1000, // ""contextual_data"": { // ""random_key"": ""random_value"" // } //}"); //System.Console.WriteLine(tax_line.amount); //Assert.AreEqual(tax_line.description, "IVA"); //Assert.AreEqual(tax_line.amount, 1000); }
/// <summary> /// Calculates tax for this code for the line item. /// Updates the line item by adding a new Tax Item. /// </summary> /// <param name="codes">The collection of tax codes.</param> /// <param name="taxCodeAmountRounder">The current, accrued totals for this tax code.</param> /// <returns> /// The calculated amount of tax. /// </returns> public virtual decimal CalculateTaxAmount(ReadOnlyCollection <TaxCode> codes, TaxCodeAmountRounder taxCodeAmountRounder) { decimal taxAmount = decimal.Zero; this.TaxableEntity.ItemTaxGroupId = this.TaxGroup; var taxAmountNonRounded = this.TaxIncludedInPrice ? this.CalculateTaxIncluded(codes) : this.CalculateTaxExcluded(codes); string groupRoundingKey = string.Empty; if (this.TaxGroupRounding) { // tax codes already sorted for this taxable item. foreach (var code in codes) { groupRoundingKey += code.Code + "@:$"; } } else if (this.TaxLimitBase == TaxLimitBase.InvoiceWithoutVat) { // total tax required for whole invoice by this tax code only. groupRoundingKey = this.Code; } // rounding required when tax is not zero (not exempted). if (taxAmountNonRounded != decimal.Zero) { // Round per tax code or adjust tax code amount. taxAmount = taxCodeAmountRounder.Round(this.TaxContext, this, groupRoundingKey, taxAmountNonRounded); } // record amounts on line item TaxLine taxLine = new TaxLine { Amount = taxAmount, Percentage = this.Value, TaxCode = this.Code, TaxGroup = this.TaxGroup, IsExempt = this.Exempt, IsIncludedInPrice = this.TaxIncludedInPrice, TaxBasis = this.TaxBasis }; this.TaxableEntity.TaxLines.Add(taxLine); return(taxAmount); }
public TaxEvaluationContext ToTaxEvalContext(TaxEvaluationContext target) { target.Id = Id; target.Code = Number; target.Currency = Currency; target.Address = Addresses?.FirstOrDefault()?.ToTaxModel(AbstractTypeFactory <TaxModule.Core.Model.Address> .TryCreateInstance()); target.Type = GetType().Name; foreach (var quoteItem in Items) { var line = new TaxLine { Id = quoteItem.Id, Code = quoteItem.Sku, Name = quoteItem.Name, TaxType = quoteItem.TaxType, Amount = quoteItem.SelectedTierPrice.Price * quoteItem.SelectedTierPrice.Quantity }; target.Lines.Add(line); } return(target); }
public void LoadTaxDetailData(TaxLine taxLine) { //################################################### //### LOAD TAXDETAIL DATA FROM THE TAXLINE OBJECT ### //################################################### DataRow row; _dataDetails.Rows.Clear(); foreach (TaxDetail taxDetail in taxLine.TaxDetails) { row = _dataDetails.NewRow(); row[TaxDetailColumns.JurisType.ToString()] = taxDetail.JurisType.ToString(); row[TaxDetailColumns.JurisCode.ToString()] = taxDetail.JurisCode; row[TaxDetailColumns.Taxable.ToString()] = taxDetail.Taxable.ToString(); row[TaxDetailColumns.NonTaxable.ToString()] = taxDetail.NonTaxable.ToString(); row[TaxDetailColumns.Exemption.ToString()] = taxDetail.Exemption.ToString(); row[TaxDetailColumns.Rate.ToString()] = taxDetail.Rate.ToString(); row[TaxDetailColumns.Tax.ToString()] = taxDetail.Tax.ToString(); row[TaxDetailColumns.TaxType.ToString()] = taxDetail.TaxType.ToString(); row[TaxDetailColumns.TaxName.ToString()] = taxDetail.TaxName.ToString(); _dataDetails.Rows.Add(row); } }
/// <summary> /// Calculate the tax bases calculationBase and limitBase (which is zero for India). /// </summary> /// <param name="codes">The tax codes.</param> /// <param name="taxInStoreCurrency">If set to <c>true</c> [tax in store currency].</param> /// <param name="calculateBasePrice">If set to <c>true</c> [Calculate the base price].</param> /// <returns>The calculation base as Item1 and The limit base as Item2 in Tuple.</returns> protected override Tuple <decimal, decimal> GetBases(ReadOnlyCollection <TaxCode> codes, bool taxInStoreCurrency, bool calculateBasePrice) { const decimal LimitBase = decimal.Zero; decimal calculationBase; // For amount by unit calculation base is just the quantity. if (this.TaxBase == TaxBase.AmountByUnit) { calculationBase = this.TaxableEntity.Quantity; // If the tax is calculated in a different UOM, then convert if possible // this is only applicable for lineItem taxes. SalesLine salesLine = this.TaxableEntity as SalesLine; if (salesLine != null && !string.Equals(this.Unit, this.TaxableEntity.SalesOrderUnitOfMeasure, StringComparison.OrdinalIgnoreCase)) { ItemUnitConversion conversion = new ItemUnitConversion { FromUnitOfMeasure = this.TaxableEntity.SalesOrderUnitOfMeasure, ToUnitOfMeasure = this.Unit, ItemId = this.TaxableEntity.ItemId }; var conversions = new List <ItemUnitConversion>(); conversions.Add(conversion); var getUomConvertionDataRequest = new GetUnitOfMeasureConversionDataRequest(conversions, QueryResultSettings.SingleRecord); UnitOfMeasureConversion converter = this.RequestContext.Runtime .Execute <GetUnitOfMeasureConversionDataResponse>(getUomConvertionDataRequest, this.RequestContext).UnitConversions.SingleOrDefault(); calculationBase *= converter.GetFactorForQuantity(this.TaxableEntity.Quantity); } return(new Tuple <decimal, decimal>(calculationBase, LimitBase)); } // Determine the starting calculation base (includes the line price or not) switch (this.Formula.TaxableBasis) { case TaxableBasisIndia.LineAmount: calculationBase = this.TaxableEntity.NetAmountWithAllInclusiveTaxPerUnit; break; case TaxableBasisIndia.MaxRetailPrice: calculationBase = this.GetItemMaxRetailPrice(); break; default: calculationBase = decimal.Zero; break; } if (this.TaxIncludedInPrice) { calculationBase = GetBasePriceForTaxIncluded(calculationBase, codes, this.Formula, this.RequestContext); } calculationBase *= Math.Abs(this.TaxableEntity.Quantity); // Calculation expression is of the form: +[BCD]+[CVD]+[E-CESS_CVD]+[PE-C_CVD]+[SHE-C_CVD] // where the brackets are replaced with the delimiter char(164) // and BCD, CVD ... are tax codes. // The operator may be + - / *. string[] tokens = this.Formula.ParseExpression(); for (int index = 1; index < tokens.Length; index += 2) { TaxLine taxLine = (from line in this.TaxableEntity.TaxLines where line.TaxCode == tokens[index] select line).FirstOrDefault(); if (taxLine != null) { this.IsTaxOnTax = true; if (!this.taxCodesInFormula.Contains(taxLine.TaxCode)) { this.taxCodesInFormula.Add(taxLine.TaxCode); } } decimal amount = taxLine == null ? decimal.Zero : taxLine.Amount * Math.Sign(this.TaxableEntity.Quantity); int tokenNumber = index - 1; switch (tokens[tokenNumber]) { case "+": calculationBase += amount; break; case "-": calculationBase -= amount; break; case "*": calculationBase *= amount; break; case "/": calculationBase = amount == decimal.Zero ? calculationBase : calculationBase /= amount; break; default: RetailLogger.Log.CrtServicesTaxCodeIndiaTaxServiceInvalidOperatorFoundInBaseCalculation(tokens[tokenNumber]); break; } } // Knock any abatement off of the taxable basis calculationBase *= (100 - this.AbatementPercent) / 100; return(new Tuple <decimal, decimal>(calculationBase, LimitBase)); }
public CartMappingProfile() { CreateMap <CartModule.Core.Model.Address, TaxModule.Core.Model.Address>(); CreateMap <GiftReward, GiftItem>(); CreateMap <GiftItem, LineItem>(); CreateMap <CartProduct, LineItem>().ConvertUsing((cartProduct, lineItem, context) => { if (lineItem == null) { lineItem = AbstractTypeFactory <LineItem> .TryCreateInstance(); } //PT-5453: Add mapping to CartMappingProfile //lineItem.ValidationType //lineItem.IsReadOnly = newCartItem.CartProduct.Product.IsReadOnly; //lineItem.ShipmentMethodCode = newCartItem.CartProduct.Price.ShipmentMethodCode; //lineItem.ThumbnailImageUrl = newCartItem.CartProduct.Product.ThumbnailImageUrl; //lineItem.VolumetricWeight = newCartItem.CartProduct.Product.VolumetricWeight; lineItem.CatalogId = cartProduct.Product.CatalogId; lineItem.CategoryId = cartProduct.Product.CategoryId; if (cartProduct.Price != null) { lineItem.Currency = cartProduct.Price.Currency.Code; lineItem.DiscountAmount = cartProduct.Price.DiscountAmount.InternalAmount; lineItem.PriceId = cartProduct.Price.PricelistId; lineItem.SalePrice = cartProduct.Price.SalePrice.InternalAmount; lineItem.TaxDetails = cartProduct.Price.TaxDetails; lineItem.TaxPercentRate = cartProduct.Price.TaxPercentRate; lineItem.Discounts = cartProduct.Price.Discounts; } lineItem.Height = cartProduct.Product.Height; lineItem.ImageUrl = cartProduct.Product.ImgSrc; lineItem.Length = cartProduct.Product.Length; lineItem.ListPrice = cartProduct.Price.ListPrice.InternalAmount; lineItem.MeasureUnit = cartProduct.Product.MeasureUnit; lineItem.Name = cartProduct.Product.Name; lineItem.ProductId = cartProduct.Product.Id; lineItem.ProductType = cartProduct.Product.ProductType; lineItem.Sku = cartProduct.Product.Code; lineItem.TaxType = cartProduct.Product.TaxType; lineItem.Weight = cartProduct.Product.Weight; lineItem.WeightUnit = cartProduct.Product.WeightUnit; lineItem.Width = cartProduct.Product.Width; return(lineItem); }); CreateMap <Outline, Tools.Models.Outline>(); CreateMap <OutlineItem, Tools.Models.OutlineItem>(); CreateMap <SeoInfo, Tools.Models.SeoInfo>(); CreateMap <LineItem, IEnumerable <TaxLine> >().ConvertUsing((lineItem, taxLines, context) => { return(new[] { new TaxLine { Id = lineItem.Id, Code = lineItem.Sku, Name = lineItem.Name, TaxType = lineItem.TaxType, //Special case when product have 100% discount and need to calculate tax for old value Amount = lineItem.Price.List > 0 ? lineItem.Price.List : lineItem.Price.Sale ?? 0M } }); }); CreateMap <ShippingRate, IEnumerable <TaxLine> >().ConvertUsing((shipmentRate, taxLines, context) => { return(new[] { new TaxLine { Id = string.Join("&", shipmentRate.ShippingMethod.Code, shipmentRate.OptionName), Code = shipmentRate.ShippingMethod.Code, TaxType = shipmentRate.ShippingMethod.TaxType, Amount = shipmentRate.DiscountAmount > 0 ? shipmentRate.DiscountAmount : shipmentRate.Rate } }); }); CreateMap <PaymentMethod, IEnumerable <TaxLine> >().ConvertUsing((paymentMethod, taxLines, context) => { return(new[] { new TaxLine { Id = paymentMethod.Code, Code = paymentMethod.Code, TaxType = paymentMethod.TaxType, Amount = paymentMethod.Total > 0 ? paymentMethod.Total : paymentMethod.Price } }); }); CreateMap <CartAggregate, PriceEvaluationContext>().ConvertUsing((cartAggr, priceEvalContext, context) => { priceEvalContext = AbstractTypeFactory <PriceEvaluationContext> .TryCreateInstance(); priceEvalContext.Language = cartAggr.Cart.LanguageCode; priceEvalContext.StoreId = cartAggr.Cart.StoreId; priceEvalContext.CatalogId = cartAggr.Store.Catalog; priceEvalContext.Currency = cartAggr.Cart.Currency; var contact = cartAggr.Member; if (contact != null) { priceEvalContext.CustomerId = contact.Id; //priceEvalContext.GeoTimeZone = contact.TimeZome; var address = contact.Addresses.FirstOrDefault(x => x.AddressType == CoreModule.Core.Common.AddressType.Shipping) ?? contact.Addresses.FirstOrDefault(x => x.AddressType == CoreModule.Core.Common.AddressType.Billing); if (address != null) { priceEvalContext.GeoCity = address.City; priceEvalContext.GeoCountry = address.CountryCode; priceEvalContext.GeoState = address.RegionName; priceEvalContext.GeoZipCode = address.PostalCode; } if (contact.Groups != null) { priceEvalContext.UserGroups = contact.Groups.ToArray(); } } //if (pricelists != null) //{ // result.PricelistIds = pricelists.Select(p => p.Id).ToList(); //} //if (products != null) //{ // result.ProductIds = products.Select(p => p.Id).ToList(); //} return(priceEvalContext); }); CreateMap <LineItem, ProductPromoEntry>() .ConvertUsing((lineItem, productPromoEntry, context) => { if (productPromoEntry == null) { productPromoEntry = AbstractTypeFactory <ProductPromoEntry> .TryCreateInstance(); } //PT-5453: Add mapping to CartMappingProfile // productPromoEntry.InStockQuantity = lineItem.InStockQuantity; // productPromoEntry.Outline = lineItem.Product.Outline; // productPromoEntry.Variations = null; productPromoEntry.CatalogId = lineItem.CatalogId; productPromoEntry.CategoryId = lineItem.CategoryId; productPromoEntry.Code = lineItem.Sku; productPromoEntry.Discount = lineItem.DiscountTotal; //Use only base price for discount evaluation productPromoEntry.Price = lineItem.SalePrice; productPromoEntry.ProductId = lineItem.ProductId; productPromoEntry.Quantity = lineItem.Quantity; return(productPromoEntry); }); CreateMap <CartAggregate, PromotionEvaluationContext>().ConvertUsing((cartAggr, promoEvalcontext, context) => { if (promoEvalcontext == null) { promoEvalcontext = AbstractTypeFactory <PromotionEvaluationContext> .TryCreateInstance(); } promoEvalcontext.CartPromoEntries = new List <ProductPromoEntry>(); foreach (var lineItem in cartAggr.LineItems) { var promoEntry = context.Mapper.Map <ProductPromoEntry>(lineItem); var cartProduct = cartAggr.CartProducts[lineItem.ProductId]; if (cartProduct != null) { promoEntry.InStockQuantity = (int)(cartProduct.Inventory?.InStockQuantity ?? 0); promoEntry.Outline = cartProduct.Product.Outlines.Select(x => context.Mapper.Map <Tools.Models.Outline>(x)).GetOutlinePath(cartProduct.Product.CatalogId); } promoEvalcontext.CartPromoEntries.Add(promoEntry); } promoEvalcontext.CartTotal = cartAggr.Cart.SubTotal; promoEvalcontext.StoreId = cartAggr.Cart.StoreId; promoEvalcontext.Coupons = cartAggr.Cart.Coupons?.ToList(); promoEvalcontext.Currency = cartAggr.Cart.Currency; promoEvalcontext.CustomerId = cartAggr.Cart.CustomerId; promoEvalcontext.UserGroups = cartAggr.Member?.Groups.ToArray(); promoEvalcontext.IsRegisteredUser = !cartAggr.Cart.IsAnonymous; promoEvalcontext.Language = cartAggr.Cart.LanguageCode; //Set cart line items as default promo items promoEvalcontext.PromoEntries = promoEvalcontext.CartPromoEntries; if (!cartAggr.Cart.Shipments.IsNullOrEmpty()) { var shipment = cartAggr.Cart.Shipments.First(); promoEvalcontext.ShipmentMethodCode = shipment.ShipmentMethodCode; promoEvalcontext.ShipmentMethodOption = shipment.ShipmentMethodOption; promoEvalcontext.ShipmentMethodPrice = shipment.Price; } if (!cartAggr.Cart.Payments.IsNullOrEmpty()) { var payment = cartAggr.Cart.Payments.First(); promoEvalcontext.PaymentMethodCode = payment.PaymentGatewayCode; promoEvalcontext.PaymentMethodPrice = payment.Price; } promoEvalcontext.IsEveryone = true; //PT-5429: Map Is First time buyer //promoEvalcontext.IsFirstTimeBuyer = cartAggr.Member.IsFirstTimeBuyer; return(promoEvalcontext); }); //PT-5457: Need to think about extensibility for converters CreateMap <CartAggregate, TaxEvaluationContext>().ConvertUsing((cartAggr, taxEvalcontext, context) => { if (taxEvalcontext == null) { taxEvalcontext = AbstractTypeFactory <TaxEvaluationContext> .TryCreateInstance(); } taxEvalcontext.StoreId = cartAggr.Cart.StoreId; taxEvalcontext.Code = cartAggr.Cart.Name; taxEvalcontext.Type = "Cart"; taxEvalcontext.CustomerId = cartAggr.Cart.CustomerId; //map customer after PT-5425 foreach (var lineItem in cartAggr.LineItems ?? Array.Empty <LineItem>()) { taxEvalcontext.Lines.Add(new TaxLine() { //PT-5339: Add Currency to tax line Id = lineItem.Id, Code = lineItem.Sku, Name = lineItem.Name, TaxType = lineItem.TaxType, //Special case when product have 100% discount and need to calculate tax for old value Amount = lineItem.ExtendedPrice > 0 ? lineItem.ExtendedPrice : lineItem.SalePrice, Quantity = lineItem.Quantity, Price = lineItem.PlacedPrice, TypeName = "item" }); } foreach (var shipment in cartAggr.Cart.Shipments ?? Array.Empty <Shipment>()) { var totalTaxLine = new TaxLine { //PT-5339: Add Currency to tax line Id = shipment.Id, Code = shipment.ShipmentMethodCode, Name = shipment.ShipmentMethodOption, TaxType = shipment.TaxType, //Special case when shipment have 100% discount and need to calculate tax for old value Amount = shipment.Total > 0 ? shipment.Total : shipment.Price, TypeName = "shipment" }; taxEvalcontext.Lines.Add(totalTaxLine); if (shipment.DeliveryAddress != null) { taxEvalcontext.Address = context.Mapper.Map <TaxModule.Core.Model.Address>(shipment.DeliveryAddress); } } foreach (var payment in cartAggr.Cart.Payments ?? Array.Empty <Payment>()) { var totalTaxLine = new TaxLine { //PT-5339: Add Currency to tax line Id = payment.Id, Code = payment.PaymentGatewayCode, Name = payment.PaymentGatewayCode, TaxType = payment.TaxType, //Special case when shipment have 100% discount and need to calculate tax for old value Amount = payment.Total > 0 ? payment.Total : payment.Price, TypeName = "payment" }; taxEvalcontext.Lines.Add(totalTaxLine); } return(taxEvalcontext); }); CreateMap <IList <IFilter>, ShoppingCartSearchCriteria>() .ConvertUsing((terms, criteria, context) => { foreach (var term in terms.OfType <TermFilter>()) { term.MapTo(criteria); } return(criteria); }); }
public static Checkout AsCheckoutWebModel( this Data.ShoppingCart cart, VirtoCommerce.ApiClient.DataContracts.Orders.CustomerOrder order = null) { var checkoutModel = new Checkout(); checkoutModel.TaxLines = new List <TaxLine>(); if (cart.Addresses != null) { var billingAddress = cart.Addresses.FirstOrDefault(a => a.Type == AddressType.Billing); if (billingAddress != null) { checkoutModel.BillingAddress = billingAddress.AsCartWebModel(); checkoutModel.Email = billingAddress.Email; } var shippingAddress = cart.Addresses.FirstOrDefault(a => a.Type == AddressType.Shipping); if (shippingAddress != null) { checkoutModel.ShippingAddress = shippingAddress.AsCartWebModel(); checkoutModel.Email = shippingAddress.Email; } } checkoutModel.BuyerAcceptsMarketing = true; checkoutModel.Currency = cart.Currency; checkoutModel.CustomerId = cart.CustomerId; if (cart.Discounts != null) { checkoutModel.Discounts = new List <VirtoCommerce.Web.Models.Discount>(); foreach (var discount in cart.Discounts) { checkoutModel.Discounts.Add(new VirtoCommerce.Web.Models.Discount { Amount = (decimal)discount.DiscountAmount, Code = discount.PromotionId, Id = discount.Id }); } } checkoutModel.Email = ""; // TODO: Gift cards checkoutModel.Id = cart.Id; if (cart.Items != null) { checkoutModel.LineItems = new List <LineItem>(); foreach (var item in cart.Items) { checkoutModel.LineItems.Add(item.AsWebModel()); } var taxableItems = cart.Items;//.Where(i => i.TaxIncluded); if (taxableItems.Count() > 0) { var lineItemsTax = new TaxLine { Title = "Line items", Price = taxableItems.Sum(i => i.TaxTotal), Rate = taxableItems.Where(i => i.TaxDetails != null).Sum(i => i.TaxDetails.Sum(td => td.Rate)) }; if (checkoutModel.TaxLines == null) { checkoutModel.TaxLines = new List <TaxLine>(); } checkoutModel.TaxLines.Add(lineItemsTax); } } checkoutModel.Name = cart.Name; //checkoutModel.Note = cart.Note; if (order != null) { checkoutModel.Order = order.AsWebModel(); } if (cart.Payments != null) { var payment = cart.Payments.FirstOrDefault(); // Remake for multipayment if (payment != null) { checkoutModel.PaymentMethod = new Models.PaymentMethod { Code = payment.PaymentGatewayCode }; } } if (cart.Shipments != null) { var shipment = cart.Shipments.FirstOrDefault(); // Remake for multishipment if (shipment != null) { checkoutModel.ShippingMethod = new ShippingMethod { Handle = shipment.ShipmentMethodCode, Price = shipment.ShippingPrice, Title = shipment.ShipmentMethodCode, TaxTotal = shipment.TaxTotal, TaxType = shipment.TaxType }; } var taxableShipments = cart.Shipments;//.Where(s => s.TaxIncluded); if (taxableShipments.Count() > 0) { var shippingTax = new TaxLine { Title = "Shipping", Price = cart.Shipments.Sum(s => s.TaxTotal), Rate = taxableShipments.Where(s => s.TaxDetails != null).Sum(i => i.TaxDetails.Sum(td => td.Rate)) }; if (checkoutModel.TaxLines == null) { checkoutModel.TaxLines = new List <TaxLine>(); } checkoutModel.TaxLines.Add(shippingTax); } } // Transactions return(checkoutModel); }