Ejemplo n.º 1
0
        public void Init()
        {
            _address = new Address()
            {
                Name        = "Mindfly Web Design Studio",
                Address1    = "114 W. Magnolia St.  Suite 504",
                Locality    = "Bellingham",
                Region      = "WA",
                PostalCode  = "98225",
                CountryCode = "US"
            };

            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("merchProductKey", Guid.NewGuid().ToString());
            extendedData.SetValue("merchProductVariantKey", Guid.NewGuid().ToString());
            extendedData.SetValue("merchWeight", "12");

            var lineItemCollection = new LineItemCollection()
            {
                { new ItemCacheLineItem(LineItemType.Product, "Product1", "Sku1", 1, 10, extendedData) },
                { new ItemCacheLineItem(LineItemType.Product, "Product2", "Sku2", 2, 12, extendedData) },
                { new ItemCacheLineItem(LineItemType.Product, "Product3", "Sku3", 3, 14, extendedData) },
            };

            _shipment = new Shipment(_address, _address, lineItemCollection);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProductTaxCalculationResult"/> class.
        /// </summary>
        /// <param name="taxMethodName">
        /// The tax method name
        /// </param>
        /// <param name="originalPrice">
        /// The original price.
        /// </param>
        /// <param name="modifiedPrice">
        /// The modified price.
        /// </param>
        /// <param name="originalSalePrice">
        /// The original sale price.
        /// </param>
        /// <param name="modifiedSalePrice">
        /// The modified sale price.
        /// </param>
        /// <param name="baseTaxRate">
        /// The base tax rate
        /// </param>
        public ProductTaxCalculationResult(
            string taxMethodName,
            decimal originalPrice,
            decimal modifiedPrice,
            decimal originalSalePrice,
            decimal modifiedSalePrice,
            decimal? baseTaxRate = null)
        {
            var edprice = new ExtendedDataCollection();
            var edsaleprice = new ExtendedDataCollection();

             var taxRate = baseTaxRate != null ? 
                 baseTaxRate > 1  ? 
                    baseTaxRate.Value / 100M : baseTaxRate.Value :
                    0M;

            if (baseTaxRate != null)
            {
                edprice.SetValue(Core.Constants.ExtendedDataKeys.BaseTaxRate, baseTaxRate.Value.ToString(CultureInfo.InvariantCulture));
                edsaleprice.SetValue(Core.Constants.ExtendedDataKeys.BaseTaxRate, baseTaxRate.Value.ToString(CultureInfo.InvariantCulture));
            }

            edprice.SetValue(Constants.ExtendedDataKeys.ProductPriceNoTax, originalPrice.ToString(CultureInfo.InvariantCulture));
            edprice.SetValue(Constants.ExtendedDataKeys.ProductPriceTaxAmount, modifiedPrice.ToString(CultureInfo.InvariantCulture));
            edsaleprice.SetValue(Constants.ExtendedDataKeys.ProductSalePriceNoTax, originalSalePrice.ToString(CultureInfo.InvariantCulture));
            edsaleprice.SetValue(Constants.ExtendedDataKeys.ProductSalePriceTaxAmount, modifiedSalePrice.ToString(CultureInfo.InvariantCulture));

            PriceResult = new TaxCalculationResult(taxMethodName, taxRate, modifiedPrice, edprice);
            SalePriceResult = new TaxCalculationResult(taxMethodName, taxRate, modifiedSalePrice, edsaleprice);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ProductTaxCalculationResult"/> class.
        /// </summary>
        /// <param name="taxMethodName">
        /// The tax method name
        /// </param>
        /// <param name="originalPrice">
        /// The original price.
        /// </param>
        /// <param name="modifiedPrice">
        /// The modified price.
        /// </param>
        /// <param name="originalSalePrice">
        /// The original sale price.
        /// </param>
        /// <param name="modifiedSalePrice">
        /// The modified sale price.
        /// </param>
        /// <param name="baseTaxRate">
        /// The base tax rate
        /// </param>
        public ProductTaxCalculationResult(
            string taxMethodName,
            decimal originalPrice,
            decimal modifiedPrice,
            decimal originalSalePrice,
            decimal modifiedSalePrice,
            decimal?baseTaxRate = null)
        {
            var edprice     = new ExtendedDataCollection();
            var edsaleprice = new ExtendedDataCollection();

            var taxRate = baseTaxRate != null ?
                          baseTaxRate > 1  ?
                          baseTaxRate.Value / 100M : baseTaxRate.Value :
                          0M;

            if (baseTaxRate != null)
            {
                edprice.SetValue(Core.Constants.ExtendedDataKeys.BaseTaxRate, baseTaxRate.Value.ToString(CultureInfo.InvariantCulture));
                edsaleprice.SetValue(Core.Constants.ExtendedDataKeys.BaseTaxRate, baseTaxRate.Value.ToString(CultureInfo.InvariantCulture));
            }

            edprice.SetValue(Constants.ExtendedDataKeys.ProductPriceNoTax, originalPrice.ToString(CultureInfo.InvariantCulture));
            edprice.SetValue(Constants.ExtendedDataKeys.ProductPriceTaxAmount, modifiedPrice.ToString(CultureInfo.InvariantCulture));
            edsaleprice.SetValue(Constants.ExtendedDataKeys.ProductSalePriceNoTax, originalSalePrice.ToString(CultureInfo.InvariantCulture));
            edsaleprice.SetValue(Constants.ExtendedDataKeys.ProductSalePriceTaxAmount, modifiedSalePrice.ToString(CultureInfo.InvariantCulture));

            PriceResult     = new TaxCalculationResult(taxMethodName, taxRate, modifiedPrice, edprice);
            SalePriceResult = new TaxCalculationResult(taxMethodName, taxRate, modifiedSalePrice, edsaleprice);
        }
Ejemplo n.º 4
0
        public ActionResult AddItem(AddItemFormModel model)
        {
            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            var product = Services.ProductService.GetByKey(model.ProductKey);

            if (model.OptionChoices != null && model.OptionChoices.Any())
            {
                var variant = Services.ProductVariantService.GetProductVariantWithAttributes(product, model.OptionChoices);

                extendedData.SetValue("isVariant", "true");

                Basket.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                Basket.AddItem(product, product.Name, 1, extendedData);
            }

            Basket.Save();

            return(RedirectToCurrentUmbracoPage());
        }
Ejemplo n.º 5
0
        public static IInvoice GetMockInvoiceForTaxation()
        {
            var origin = new Address()
            {
                Organization = "Mindfly Web Design Studios",
                Address1     = "114 W. Magnolia St. Suite 300",
                Locality     = "Bellingham",
                Region       = "WA",
                PostalCode   = "98225",
                CountryCode  = "US",
                Email        = "*****@*****.**",
                Phone        = "555-555-5555"
            };

            var billToShipTo = new Address()
            {
                Name        = "Space Needle",
                Address1    = "400 Broad St",
                Locality    = "Seattle",
                Region      = "WA",
                PostalCode  = "98109",
                CountryCode = "US",
            };


            var invoiceService = GetServiceContext().InvoiceService;

            var invoice = invoiceService.CreateInvoice(Core.Constants.InvoiceStatus.Unpaid);

            invoice.SetBillingAddress(billToShipTo);


            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.Taxable, true.ToString());

            // make up some line items
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 10, 1, extendedData);
            var l2 = new InvoiceLineItem(LineItemType.Product, "Item 2", "I2", 2, 40, extendedData);

            invoice.Items.Add(l1);
            invoice.Items.Add(l2);

            var shipment = new ShipmentMock(origin, billToShipTo, invoice.Items);

            var shipmethod = new ShipMethodMock();

            var quote = new ShipmentRateQuote(shipment, shipmethod)
            {
                Rate = 16.22M
            };

            invoice.Items.Add(quote.AsLineItemOf <InvoiceLineItem>());

            invoice.Total = invoice.Items.Sum(x => x.TotalPrice);

            return(invoice);
        }
Ejemplo n.º 6
0
        private void MakeInvoice()
        {
            var origin = new Address()
            {
                Organization = "Mindfly Web Design Studios",
                Address1     = "114 W. Magnolia St. Suite 300",
                Locality     = "Bellingham",
                Region       = "WA",
                PostalCode   = "98225",
                CountryCode  = "US",
                Email        = "*****@*****.**",
                Phone        = "555-555-5555"
            };

            var billToShipTo = new Address()
            {
                Name        = "The President of the United States",
                Address1    = "1600 Pennsylvania Ave NW",
                Locality    = "Washington",
                Region      = "DC",
                PostalCode  = "20500",
                CountryCode = "US",
            };

            var invoiceService = new InvoiceService();

            Invoice = invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);

            Invoice.SetBillingAddress(billToShipTo);

            Invoice.Total = 120M;
            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.Taxable, true.ToString());

            // make up some line items
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 10, 1, extendedData);
            var l2 = new InvoiceLineItem(LineItemType.Product, "Item 2", "I2", 2, 40, extendedData);

            Invoice.Items.Add(l1);
            Invoice.Items.Add(l2);

            var shipment = new ShipmentMock(origin, billToShipTo, Invoice.Items);

            var shipmethod = new ShipMethodMock();

            var quote = new ShipmentRateQuote(shipment, shipmethod)
            {
                Rate = 16.22M
            };

            Invoice.Items.Add(quote.AsLineItemOf <InvoiceLineItem>());
        }
Ejemplo n.º 7
0
        public static IInvoice GetMockInvoiceForTaxation()
        {
            var origin = new Address()
            {
                Organization = "Mindfly Web Design Studios",
                Address1 = "114 W. Magnolia St. Suite 300",
                Locality = "Bellingham",
                Region = "WA",
                PostalCode = "98225",
                CountryCode = "US",
                Email = "*****@*****.**",
                Phone = "555-555-5555"
            };

            var billToShipTo = new Address()
            {
                Name = "Space Needle",
                Address1 = "400 Broad St",
                Locality = "Seattle",
                Region = "WA",
                PostalCode = "98109",
                CountryCode = "US",
            };

            var invoiceService = new InvoiceService();

            var invoice = invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);

            invoice.SetBillingAddress(billToShipTo);

            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.Taxable, true.ToString());

            // make up some line items
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 10, 1, extendedData);
            var l2 = new InvoiceLineItem(LineItemType.Product, "Item 2", "I2", 2, 40, extendedData);

            invoice.Items.Add(l1);
            invoice.Items.Add(l2);

            var shipment = new ShipmentMock(origin, billToShipTo, invoice.Items);

            var shipmethod = new ShipMethodMock();

            var quote = new ShipmentRateQuote(shipment, shipmethod) { Rate = 16.22M };
            invoice.Items.Add(quote.AsLineItemOf<InvoiceLineItem>());

            invoice.Total = invoice.Items.Sum(x => x.TotalPrice);

            return invoice;
        }
Ejemplo n.º 8
0
        private void MakeInvoice()
        {
            var origin = new Address()
            {
                Organization = "Mindfly Web Design Studios",
                Address1 = "114 W. Magnolia St. Suite 300",
                Locality = "Bellingham",
                Region = "WA",
                PostalCode = "98225",
                CountryCode = "US",
                Email = "*****@*****.**",
                Phone = "555-555-5555"
            };

            var billToShipTo = new Address()
                {
                    Name = "The President of the United States",
                    Address1 = "1600 Pennsylvania Ave NW",
                    Locality = "Washington",
                    Region = "DC",
                    PostalCode = "20500",
                    CountryCode = "US",
                };

            var invoiceService = new InvoiceService();

            Invoice = invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);

            Invoice.SetBillingAddress(billToShipTo);

            Invoice.Total = 120M;
            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.Taxable, true.ToString());

            // make up some line items
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 10, 1, extendedData);
            var l2 = new InvoiceLineItem(LineItemType.Product, "Item 2", "I2", 2, 40, extendedData);

            Invoice.Items.Add(l1);
            Invoice.Items.Add(l2);

            var shipment = new ShipmentMock(origin, billToShipTo, Invoice.Items);

            var shipmethod = new ShipMethodMock();

            var quote = new ShipmentRateQuote(shipment, shipmethod) { Rate = 16.22M };
            Invoice.Items.Add(quote.AsLineItemOf<InvoiceLineItem>());
        }
        public void ContainsAny_Returns_False_When_Keys_DoNot_Exist()
        {
            //// Arrange
            var ed = new ExtendedDataCollection();
            ed.SetValue("one", "value");
            ed.SetValue("two", "value");
            ed.SetValue("three", "value");

            //// Act
            var found = ed.ContainsAny(new[] { "six", "five" });

            //// Assert
            Assert.IsFalse(found);
        }
Ejemplo n.º 10
0
        public void ContainsAny_Returns_False_When_Keys_DoNot_Exist()
        {
            //// Arrange
            var ed = new ExtendedDataCollection();

            ed.SetValue("one", "value");
            ed.SetValue("two", "value");
            ed.SetValue("three", "value");

            //// Act
            var found = ed.ContainsAny(new[] { "six", "five" });

            //// Assert
            Assert.IsFalse(found);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Calculates tax for invoice.
        /// </summary>
        /// <param name="invoice">
        /// The invoice.
        /// </param>
        /// <param name="taxAddress">
        /// The tax address.
        /// </param>
        /// <returns>
        /// The <see cref="ITaxCalculationResult"/>.
        /// </returns>
        public override ITaxCalculationResult CalculateTaxForInvoice(IInvoice invoice, IAddress taxAddress)
        {
            decimal amount = 0m;
            foreach (var item in invoice.Items)
            {
                // can I use?: https://github.com/Merchello/Merchello/blob/5706b8c9466f7417c41fdd29de7930b3e8c4dd2d/src/Merchello.Core/Models/ExtendedDataExtensions.cs#L287-L295
                if (item.ExtendedData.GetTaxableValue())
                    amount = amount + item.TotalPrice;
            }

            TaxRequest taxRequest = new TaxRequest();
            taxRequest.Amount = amount;
            taxRequest.Shipping = invoice.TotalShipping();
            taxRequest.ToCity = taxAddress.Locality;
            taxRequest.ToCountry = taxAddress.CountryCode;
            taxRequest.ToState = taxAddress.Region;
            taxRequest.ToZip = taxAddress.PostalCode;

            Models.TaxResult taxResult = _taxjarService.GetTax(taxRequest);

            if (taxResult.Success)
            {
                var extendedData = new ExtendedDataCollection();

                extendedData.SetValue(Core.Constants.ExtendedDataKeys.TaxTransactionResults, JsonConvert.SerializeObject(taxResult));

                return new TaxCalculationResult(TaxMethod.Name, taxResult.Rate, taxResult.TotalTax, extendedData);
            }

            throw new Exception("TaxJar.com error");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Calculates tax for invoice.
        /// </summary>
        /// <param name="invoice">
        /// The invoice.
        /// </param>
        /// <param name="taxAddress">
        /// The tax address.
        /// </param>
        /// <returns>
        /// The <see cref="ITaxCalculationResult"/>.
        /// </returns>
        public override ITaxCalculationResult CalculateTaxForInvoice(IInvoice invoice, IAddress taxAddress)
        {
            decimal amount = 0m;

            foreach (var item in invoice.Items)
            {
                // can I use?: https://github.com/Merchello/Merchello/blob/5706b8c9466f7417c41fdd29de7930b3e8c4dd2d/src/Merchello.Core/Models/ExtendedDataExtensions.cs#L287-L295
                if (item.ExtendedData.GetTaxableValue())
                {
                    amount = amount + item.TotalPrice;
                }
            }

            TaxRequest taxRequest = new TaxRequest();

            taxRequest.Amount    = amount;
            taxRequest.Shipping  = invoice.TotalShipping();
            taxRequest.ToCity    = taxAddress.Locality;
            taxRequest.ToCountry = taxAddress.CountryCode;
            taxRequest.ToState   = taxAddress.Region;
            taxRequest.ToZip     = taxAddress.PostalCode;

            Models.TaxResult taxResult = _taxjarService.GetTax(taxRequest);

            if (taxResult.Success)
            {
                var extendedData = new ExtendedDataCollection();

                extendedData.SetValue(Core.Constants.ExtendedDataKeys.TaxTransactionResults, JsonConvert.SerializeObject(taxResult));

                return(new TaxCalculationResult(TaxMethod.Name, taxResult.Rate, taxResult.TotalTax, extendedData));
            }

            throw new Exception("TaxJar.com error");
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Computes the invoice tax result
        /// </summary>
        /// <returns>
        /// The <see cref="ITaxCalculationResult"/>
        /// </returns>
        public override Attempt <ITaxCalculationResult> CalculateTaxesForInvoice()
        {
            var extendedData = new ExtendedDataCollection();

            try
            {
                var baseTaxRate = _taxMethod.PercentageTaxRate;

                extendedData.SetValue(Core.Constants.ExtendedDataKeys.BaseTaxRate, baseTaxRate.ToString(CultureInfo.InvariantCulture));

                if (_taxMethod.HasProvinces)
                {
                    baseTaxRate = AdjustedRate(baseTaxRate, _taxMethod.Provinces.FirstOrDefault(x => x.Code == TaxAddress.Region), extendedData);
                }

                var visitor = new TaxableLineItemVisitor(baseTaxRate / 100);

                Invoice.Items.Accept(visitor);

                var totalTax = visitor.TaxableLineItems.Sum(x => decimal.Parse(x.ExtendedData.GetValue(Core.Constants.ExtendedDataKeys.LineItemTaxAmount)));

                return(Attempt <ITaxCalculationResult> .Succeed(
                           new TaxCalculationResult(_taxMethod.Name, baseTaxRate, totalTax, extendedData)));
            }
            catch (Exception ex)
            {
                return(Attempt <ITaxCalculationResult> .Fail(ex));
            }
        }
Ejemplo n.º 14
0
        public ActionResult AddToBasket(AddItemModel model)
        {
            // This is an example of using the ExtendedDataCollection to add some custom functionality.
            // In this case, we are creating a direct reference to the content (Product Detail Page) so
            // that we can provide a link, thumbnail and description in the cart per this design.  In other
            // designs, there may not be thumbnails or descriptions and the link could be to a completely
            // different website.
            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            var product = this.MerchelloServices.ProductService.GetByKey(model.Product.Key);

            // In the event the product has options we want to add the "variant" to the basket.
            // -- If a product that has variants is defined, the FIRST variant will be added to the cart.
            // -- This was done so that we did not have to throw an error since the Master variant is no
            // -- longer valid for sale.
            if (model.OptionChoices != null && model.OptionChoices.Any())
            {
                var variant = this.MerchelloServices.ProductVariantService.GetProductVariantWithAttributes(product, model.OptionChoices);
                this.Basket.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                this.Basket.AddItem(product, product.Name, 1, extendedData);
            }

            this.Basket.Save();

            return(this.RedirectToUmbracoPage(model.BasketPageId));
        }
Ejemplo n.º 15
0
        public ActionResult AddItem(Guid productKey, int contentId, Guid[] optionKeys = null)
        {
            var merchelloContext = MerchelloContext.Current;
            var basket           = GetBasket();

            // Get requested product
            var product = merchelloContext.Services.ProductService.GetByKey(productKey);

            // Save content Id along with line item
            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("umbracoContentId", contentId.ToString());

            // Add product to basket
            if (optionKeys.IsAndAny())
            {
                // If options provided, work out the content variant that has been requested
                var variant = merchelloContext.Services.ProductVariantService.GetProductVariantWithAttributes(product, optionKeys);
                basket.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                basket.AddItem(product, product.Name, 1, extendedData);
            }

            basket.Save();

            return(RedirectToBasketPage());
        }
Ejemplo n.º 16
0
        public ActionResult AddToBasket(AddItemModel model)
        {
            // This is an example of using the ExtendedDataCollection to add some custom functionality.
            // In this case, we are creating a direct reference to the content (Product Detail Page) so
            // that we can provide a link, thumbnail and description in the cart per this design.  In other
            // designs, there may not be thumbnails or descriptions and the link could be to a completely
            // different website.
            var extendedData = new ExtendedDataCollection();
            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            var product = Services.ProductService.GetByKey(model.ProductKey);

            // In the event the product has options we want to add the "variant" to the basket.
            // -- If a product that has variants is defined, the FIRST variant will be added to the cart.
            // -- This was done so that we did not have to throw an error since the Master variant is no
            // -- longer valid for sale.
            if (model.OptionChoices != null && model.OptionChoices.Any())
            {
                var variant = Services.ProductVariantService.GetProductVariantWithAttributes(product, model.OptionChoices);
                Basket.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                Basket.AddItem(product, product.Name, 1, extendedData);
            }

            Basket.Save();

            return RedirectToUmbracoPage(GetContentIdByContentName(BasketPage));
        }
        /// <summary>
        /// Computes the invoice tax result
        /// </summary>
        /// <returns>
        /// The <see cref="ITaxCalculationResult"/>
        /// </returns>
        public override Attempt<ITaxCalculationResult> CalculateTaxesForInvoice()
        {
            var extendedData = new ExtendedDataCollection();

            try
            {                
                var baseTaxRate = _taxMethod.PercentageTaxRate;

                extendedData.SetValue(Core.Constants.ExtendedDataKeys.BaseTaxRate, baseTaxRate.ToString(CultureInfo.InvariantCulture));

                if (_taxMethod.HasProvinces)
                {
                    baseTaxRate = AdjustedRate(baseTaxRate, _taxMethod.Provinces.FirstOrDefault(x => x.Code == TaxAddress.Region), extendedData);
                }
                
                var visitor = new TaxableLineItemVisitor(baseTaxRate / 100);

                Invoice.Items.Accept(visitor);

                var totalTax = visitor.TaxableLineItems.Sum(x => decimal.Parse(x.ExtendedData.GetValue(Core.Constants.ExtendedDataKeys.LineItemTaxAmount)));

                return Attempt<ITaxCalculationResult>.Succeed(
                    new TaxCalculationResult(_taxMethod.Name, baseTaxRate, totalTax, extendedData));
            }
            catch (Exception ex)
            {
                return Attempt<ITaxCalculationResult>.Fail(ex);
            }                                   
        }
Ejemplo n.º 18
0
        public void Can_Create_An_Invoice_With_A_CustomLineItem()
        {
            //// Arrange
            var invoice = MockInvoiceDataMaker.GetMockInvoiceForTaxation();

            Assert.NotNull(invoice, "Invoice is null");

            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue(Constants.ExtendedDataKeys.Taxable, false.ToString());

            var typeField = EnumTypeFieldConverter.LineItemType.Custom("CcFee");

            //// Act
            var ccFee = new InvoiceLineItem(
                typeField.TypeKey,
                "CC Fee",
                "ccfee",
                1,
                1.0m,
                extendedData);

            invoice.Items.Add(ccFee);

            Assert.IsTrue(invoice.CustomLineItems().Any());
        }
Ejemplo n.º 19
0
        public void Can_Map_An_Invoice_With_A_Custom_LineItemType_To_InvoiceDisplay()
        {
            //// Arrange
            var invoice = MockInvoiceDataMaker.GetMockInvoiceForTaxation();

            Assert.NotNull(invoice, "Invoice is null");

            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue(Constants.ExtendedDataKeys.Taxable, false.ToString());

            var typeField = EnumTypeFieldConverter.LineItemType.Custom("CcFee");

            //// Act
            var ccFee = new InvoiceLineItem(
                typeField.TypeKey,
                "CC Fee",
                "ccfee",
                1,
                1.0m,
                extendedData);

            invoice.Items.Add(ccFee);

            var display = invoice.ToInvoiceDisplay();

            //// Assert
            Assert.NotNull(display);
            Assert.IsFalse(display.Items.Any(x => x.LineItemTypeField == null), "One or more of the LineItemTypeFields where null");
        }
        public ActionResult AddToBasket(AddToBasket model)
        {
            // Disable VAT in initial lookup so we don't double tax
            var merchello = new MerchelloHelper(false);

            // we want to include VAT
            Basket.EnableDataModifiers = true;

            var product = merchello.Query.Product.GetByKey(model.ProductKey);

            if (model.OptionChoice != Guid.Empty)
            {
                var extendedData = new ExtendedDataCollection();
                var variant = product.GetProductVariantDisplayWithAttributes(new[] { model.OptionChoice });
                //// serialize the attributes here as they are need in the design
                extendedData.SetValue(Constants.ExtendedDataKeys.BasketItemAttributes, JsonConvert.SerializeObject(variant.Attributes));
                Basket.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                Basket.AddItem(product, product.Name, 1);
            }

            Basket.Save();

            if (Request.IsAjaxRequest())
            {
                // this would be the partial for the pop window
                return Content("Form submitted");
            }

            return RedirectToUmbracoPage(ContentResolver.Instance.GetBasketContent());
        }
        /// <summary>
        /// Adds a <see cref="LineItemCollection"/> to the <see cref="ExtendedDataCollection"/>
        /// </summary>
        /// <param name="extendedData">
        /// The extended Data.
        /// </param>
        /// <param name="lineItemCollection">
        /// The line Item Collection.
        /// </param>
        public static void AddLineItemCollection(this ExtendedDataCollection extendedData, LineItemCollection lineItemCollection)
        {
            using (var sw = new StringWriter())
            {
                var settings = new XmlWriterSettings()
                {
                    OmitXmlDeclaration = true
                };

                using (var writer = XmlWriter.Create(sw, settings))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement(Constants.ExtendedDataKeys.LineItemCollection);

                    foreach (var lineItem in lineItemCollection)
                    {
                        ////writer.WriteStartElement(Constants);
                        writer.WriteRaw(((LineItemBase)lineItem).SerializeToXml());
                    }

                    writer.WriteEndElement(); // ExtendedData
                    writer.WriteEndDocument();
                }
                extendedData.SetValue(Constants.ExtendedDataKeys.LineItemCollection, sw.ToString());
            }
        }
 /// <summary>
 /// Adds a <see cref="IShipment"/> to the extended data collection
 /// </summary>
 /// <param name="extendedData">
 /// The extended Data.
 /// </param>
 /// <param name="shipment">
 /// The shipment.
 /// </param>
 public static void AddShipment(this ExtendedDataCollection extendedData, IShipment shipment)
 {
     extendedData.AddAddress(shipment.GetOriginAddress(), Constants.ExtendedDataKeys.ShippingOriginAddress);
     extendedData.AddAddress(shipment.GetDestinationAddress(), Constants.ExtendedDataKeys.ShippingDestinationAddress);
     extendedData.SetValue(Constants.ExtendedDataKeys.ShipMethodKey, shipment.ShipMethodKey.ToString());
     extendedData.AddLineItemCollection(shipment.Items);
 }
        /// <summary>
        /// Adds an <see cref="IAddress"/> to extended data.  This is intended for shipment addresses
        /// </summary>
        /// <param name="extendedData">
        /// The extended Data.
        /// </param>
        /// <param name="address">
        /// The <see cref="IAddress"/> to be added to extended data
        /// </param>
        /// <param name="dictionaryKey">
        /// The dictionary key used to reference the serialized <see cref="IAddress"/>
        /// </param>
        public static void AddAddress(this ExtendedDataCollection extendedData, IAddress address, string dictionaryKey)
        {
            var addressXml = SerializationHelper.SerializeToXml(address as Address);

            ////var addressJson = JsonConvert.SerializeObject(address);

            extendedData.SetValue(dictionaryKey, addressXml);
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Adjusts the rate of the quote based on the province
 /// </summary>
 /// <param name="baseRate">The base (unadjusted) rate</param>
 /// <param name="province">The <see cref="ITaxProvince"/> associated with the <see cref="ITaxMethod"/></param>
 /// <param name="extendedData">The <see cref="ExtendedDataCollection"/></param>
 /// <returns>The tax adjustment</returns>
 private static decimal AdjustedRate(decimal baseRate, ITaxProvince province, ExtendedDataCollection extendedData)
 {
     if (province == null)
     {
         return(baseRate);
     }
     extendedData.SetValue(Core.Constants.ExtendedDataKeys.ProviceTaxRate, province.PercentAdjustment.ToString(CultureInfo.InvariantCulture));
     return(province.PercentAdjustment + baseRate);
 }
        /// <summary>
        /// Utility extension to quickly serialize <see cref="BraintreeProviderSettings"/> to an extended data value
        /// </summary>
        /// <param name="extendedData">
        /// The extended data.
        /// </param>
        /// <param name="settings">
        /// The <see cref="BraintreeProviderSettings"/>
        /// </param>
        public static void SaveProviderSettings(this ExtendedDataCollection extendedData, BraintreeProviderSettings settings)
        {
            var jsonSerializerSettings = new JsonSerializerSettings {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            var json = JsonConvert.SerializeObject(settings, Formatting.None, jsonSerializerSettings);

            extendedData.SetValue(Constants.ExtendedDataKeys.BraintreeProviderSettings, json);
        }
Ejemplo n.º 26
0
        public ActionResult AddToBasket(AddItemModel model)
        {
            // This is an example of using the ExtendedDataCollection to add some custom functionality.
            // In this case, we are creating a direct reference to the content (Product Detail Page) so
            // that we can provide a link, thumbnail and description in the cart per this design.  In other
            // designs, there may not be thumbnails or descriptions and the link could be to a completely
            // different website.
            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            var product = Services.ProductService.GetByKey(model.ProductKey);

            // check if content has sample shipper property - isOverWeight
            // if yes, set basket item extended property
            var content = Umbraco.Content(model.ContentId.ToString(CultureInfo.InvariantCulture));

            if (content.HasProperty("IsOverweight") && content.HasValue("IsOverweight"))
            {
                extendedData.SetValue("IsOverweight", "true");
            }
            else
            {
                extendedData.SetValue("IsOverweight", "false");
            }

            // In the event the product has options we want to add the "variant" to the basket.
            // -- If a product that has variants is defined, the FIRST variant will be added to the cart.
            // -- This was done so that we did not have to throw an error since the Master variant is no
            // -- longer valid for sale.
            if (model.OptionChoices != null && model.OptionChoices.Any())
            {
                var variant = Services.ProductVariantService.GetProductVariantWithAttributes(product, model.OptionChoices);
                Basket.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                Basket.AddItem(product, product.Name, 1, extendedData);
            }

            Basket.Save();

            return(RedirectToUmbracoPage(GetContentIdByContentName(BasketPage)));
        }
Ejemplo n.º 27
0
        public void Init()
        {
            var billTo = new Address()
            {
                Organization = "Mindfly Web Design Studios",
                Address1     = "114 W. Magnolia St. Suite 504",
                Locality     = "Bellingham",
                Region       = "WA",
                PostalCode   = "98225",
                CountryCode  = "US",
                Email        = "*****@*****.**",
                Phone        = "555-555-5555"
            };

            // create an invoice
            var invoiceService = new InvoiceService();

            _invoice = invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);

            _invoice.SetBillingAddress(billTo);

            _invoice.Total = 120M;
            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");

            // make up some line items
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 10, 1, extendedData);
            var l2 = new InvoiceLineItem(LineItemType.Product, "Item 2", "I2", 2, 40, extendedData);
            var l3 = new InvoiceLineItem(LineItemType.Shipping, "Shipping", "shipping", 1, 10M, extendedData);
            var l4 = new InvoiceLineItem(LineItemType.Tax, "Tax", "tax", 1, 10M, extendedData);

            _invoice.Items.Add(l1);
            _invoice.Items.Add(l2);
            _invoice.Items.Add(l3);
            _invoice.Items.Add(l4);

            var processorSettings = new AuthorizeNetProcessorSettings
            {
                LoginId        = ConfigurationManager.AppSettings["xlogin"],
                TransactionKey = ConfigurationManager.AppSettings["xtrankey"],
                UseSandbox     = true
            };

            Provider.GatewayProviderSettings.ExtendedData.SaveProcessorSettings(processorSettings);

            if (Provider.PaymentMethods.Any())
            {
                return;
            }
            var resource = Provider.ListResourcesOffered().ToArray();

            Provider.CreatePaymentMethod(resource.First(), "Credit Card", "Credit Card");
        }
Ejemplo n.º 28
0
    private void SalePreparationBaseOnInvoicePrepared(SalePreparationBase sender, SalesPreparationEventArgs <IInvoice> e)
    {
        // custom line items
        var ed1 = new ExtendedDataCollection();

        ed1.SetValue(Merchello.Core.Constants.ExtendedDataKeys.Taxable, false.ToString());
        ed1.SetValue(Merchello.Core.Constants.ExtendedDataKeys.Shippable, false.ToString());

        var typeField = EnumTypeFieldConverter.LineItemType.Custom("CcFee");

        //// Act
        var ccFee = new InvoiceLineItem(
            typeField.TypeKey,
            "CC Fee",
            "ccfee",
            1,
            1.0m,
            ed1);

        e.Entity.Items.Add(ccFee);
        e.Entity.Total += 1.0m;

        var ed2 = new ExtendedDataCollection();
        var shippingLineItem = e.Entity.ShippingLineItems().FirstOrDefault();

        if (shippingLineItem != null)
        {
            ////
            if (shippingLineItem.Price >= 30)
            {
                var shipping10Off = new InvoiceLineItem(
                    EnumTypeFieldConverter.LineItemType.Discount.TypeKey,
                    "10 Off Shipping",
                    "BreakOnShipping",
                    1,
                    10M,
                    ed2);
                e.Entity.Items.Add(shipping10Off);
                e.Entity.Total -= 10M;
            }
        }
    }
        /// <summary>
        /// Gets a extended data collection stored within an extended data collection.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <returns>
        /// The <see cref="ExtendedDataCollection"/>.
        /// </returns>
        internal static ExtendedDataCollection AsExtendedDataCollection(this IEnumerable <KeyValuePair <string, string> > source)
        {
            var ed = new ExtendedDataCollection();

            foreach (var item in source.ToArray())
            {
                ed.SetValue(item.Key, item.Value);
            }

            return(ed);
        }
Ejemplo n.º 30
0
        public void Init()
        {
            var billTo = new Address()
            {
                Organization = "Flightpath",
                Address1     = "36 West 25th Street",
                Locality     = "New York",
                Region       = "NY",
                PostalCode   = "10010",
                CountryCode  = "US",
                Email        = "*****@*****.**",
                Phone        = "212-555-5555"
            };

            // create an invoice
            var invoiceService = new InvoiceService();

            _invoice = invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);

            _invoice.SetBillingAddress(billTo);

            _invoice.Total = 120M;
            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");

            // make up some line items
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 10, 1, extendedData);
            var l2 = new InvoiceLineItem(LineItemType.Product, "Item 2", "I2", 2, 40, extendedData);
            var l3 = new InvoiceLineItem(LineItemType.Shipping, "Shipping", "shipping", 1, 10M, extendedData);
            var l4 = new InvoiceLineItem(LineItemType.Tax, "Tax", "tax", 1, 10M, extendedData);

            _invoice.Items.Add(l1);
            _invoice.Items.Add(l2);
            _invoice.Items.Add(l3);
            _invoice.Items.Add(l4);

            var processorSettings = new StripeProcessorSettings
            {
                ApiKey = ConfigurationManager.AppSettings["stripeApiKey"]
            };

            Provider.GatewayProviderSettings.ExtendedData.SaveProcessorSettings(processorSettings);

            if (Provider.PaymentMethods.Any())
            {
                return;
            }
            var resource = Provider.ListResourcesOffered().ToArray();

            Provider.CreatePaymentMethod(resource.First(), "Credit Card", "Credit Card");
        }
Ejemplo n.º 31
0
        public void Init()
        {

            var billTo = new Address()
            {
                Organization = "Mindfly Web Design Studios",
                Address1 = "114 W. Magnolia St. Suite 504",
                Locality = "Bellingham",
                Region = "WA",
                PostalCode = "98225",
                CountryCode = "US",
                Email = "*****@*****.**",
                Phone = "555-555-5555"
            };

            // create an invoice
            var invoiceService = new InvoiceService();

            _invoice = invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);

            _invoice.SetBillingAddress(billTo);

            _invoice.Total = 120M;
            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");
            
            // make up some line items
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 10, 1, extendedData);
            var l2 = new InvoiceLineItem(LineItemType.Product, "Item 2", "I2", 2, 40, extendedData);
            var l3 = new InvoiceLineItem(LineItemType.Shipping, "Shipping", "shipping", 1, 10M, extendedData);
            var l4 = new InvoiceLineItem(LineItemType.Tax, "Tax", "tax", 1, 10M, extendedData);

            _invoice.Items.Add(l1);
            _invoice.Items.Add(l2);
            _invoice.Items.Add(l3);
            _invoice.Items.Add(l4);

            var processorSettings = new AuthorizeNetProcessorSettings
            {
                LoginId = ConfigurationManager.AppSettings["xlogin"],
                TransactionKey = ConfigurationManager.AppSettings["xtrankey"],
                UseSandbox = true
            };

            Provider.GatewayProviderSettings.ExtendedData.SaveProcessorSettings(processorSettings);

            if (Provider.PaymentMethods.Any()) return;
            var resource = Provider.ListResourcesOffered().ToArray();
            Provider.CreatePaymentMethod(resource.First(), "Credit Card", "Credit Card");
        }
Ejemplo n.º 32
0
        public void Init()
        {
            _origin = new Address()
            {
                Name         = "Mindfly Web Design Studio",
                Address1     = "114 W. Magnolia St.  Suite 504",
                Locality     = "Bellingham",
                Region       = "WA",
                PostalCode   = "98225",
                CountryCode  = "US",
                IsCommercial = true
            };

            _destination = new Address()
            {
                Name         = "Stratosphere Casino, Hotel & Tower",
                Address1     = "2000 S Las Vegas Blvd",
                Locality     = "Las Vegas",
                Region       = "NV",
                PostalCode   = "89104",
                CountryCode  = "US",
                IsCommercial = true
            };

            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("merchProductKey", Guid.NewGuid().ToString());
            extendedData.SetValue("merchProductVariantKey", Guid.NewGuid().ToString());
            extendedData.SetValue("merchWeight", "12");

            var lineItemCollection = new LineItemCollection()
            {
                { new ItemCacheLineItem(LineItemType.Product, "Product1", "Sku1", 1, 10, extendedData) },
                { new ItemCacheLineItem(LineItemType.Product, "Product2", "Sku2", 2, 12, extendedData) },
                { new ItemCacheLineItem(LineItemType.Product, "Product3", "Sku3", 3, 14, extendedData) },
            };

            _shipment = new Shipment(new ShipmentStatusMock(), _origin, _destination, lineItemCollection);
        }
Ejemplo n.º 33
0
        public void Init()
        {
            _origin = new Address()
            {
                Name = "Mindfly Web Design Studio",
                Address1 = "114 W. Magnolia St.  Suite 504",
                Locality = "Bellingham",
                Region = "WA",
                PostalCode = "98225",
                CountryCode = "US",
                IsCommercial = true
            };

            _destination = new Address()
                {
                    Name = "Stratosphere Casino, Hotel & Tower",
                    Address1 = "2000 S Las Vegas Blvd",
                    Locality = "Las Vegas",
                    Region = "NV",
                    PostalCode = "89104",
                    CountryCode = "US",
                    IsCommercial = true
                };

            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("merchProductKey", Guid.NewGuid().ToString());
            extendedData.SetValue("merchProductVariantKey", Guid.NewGuid().ToString());
            extendedData.SetValue("merchWeight", "12");

            var lineItemCollection = new LineItemCollection()
            {
                {new ItemCacheLineItem(LineItemType.Product, "Product1", "Sku1", 1, 10, extendedData)},
                {new ItemCacheLineItem(LineItemType.Product, "Product2", "Sku2", 2, 12, extendedData)},
                {new ItemCacheLineItem(LineItemType.Product, "Product3", "Sku3", 3, 14, extendedData)},
            };

            _shipment = new Shipment(_origin, _destination, lineItemCollection);
        }
Ejemplo n.º 34
0
        public ActionResult AddToBasket(AddItemModel model)
        {
            // This is an example of using the ExtendedDataCollection to add some custom functionality.
            // In this case, we are creating a direct reference to the content (Product Detail Page) so
            // that we can provide a link, thumbnail and description in the cart per this design.  In other
            // designs, there may not be thumbnails or descriptions and the link could be to a completely
            // different website.
            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            // NEW IN 1.9.1
            // We've added some data modifiers that can handle such things as including taxes in product
            // pricing.  The data modifiers can either get executed when the item is added to the basket or
            // as a result from a MerchelloHelper query - you just don't want them to execute twice.

            // Calls directly to the ProductService are not modified
            // var product = this.MerchelloServices.ProductService.GetByKey(model.Product.Key);

            // Calls to using the MerchelloHelper WILL be modified
            // var merchello = new MerchelloHelper();
            //
            // if you want to do this you should tell the basket not to modify the data again when adding the item
            //this.Basket.EnableDataModifiers = false;

            // In this case we want to get the product without any data modification
            var merchello = new MerchelloHelper(false);

            var product = merchello.Query.Product.GetByKey(model.Product.Key);

            // In the event the product has options we want to add the "variant" to the basket.
            // -- If a product that has variants is defined, the FIRST variant will be added to the cart.
            // -- This was done so that we did not have to throw an error since the Master variant is no
            // -- longer valid for sale.
            if (model.OptionChoices != null && model.OptionChoices.Any())
            {
                // NEW in 1.9.1
                // ProductDisplay and ProductVariantDisplay classes can be added directly to the Basket
                // so you don't have to query the service.
                var variant = product.GetProductVariantDisplayWithAttributes(model.OptionChoices);
                this.Basket.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                this.Basket.AddItem(product, product.Name, 1, extendedData);
            }

            this.Basket.Save();

            return(this.RedirectToUmbracoPage(model.BasketPageId));
        }
Ejemplo n.º 35
0
        public void Init()
        {

            var billTo = new Address()
            {
                Organization = "Flightpath",
                Address1 = "36 West 25th Street",
                Locality = "New York",
                Region = "NY",
                PostalCode = "10010",
                CountryCode = "US",
                Email = "*****@*****.**",
                Phone = "212-555-5555"
            };

            // create an invoice
            var invoiceService = new InvoiceService();

            _invoice = invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);

            _invoice.SetBillingAddress(billTo);

            _invoice.Total = 120M;
            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");
            
            // make up some line items
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 10, 1, extendedData);
            var l2 = new InvoiceLineItem(LineItemType.Product, "Item 2", "I2", 2, 40, extendedData);
            var l3 = new InvoiceLineItem(LineItemType.Shipping, "Shipping", "shipping", 1, 10M, extendedData);
            var l4 = new InvoiceLineItem(LineItemType.Tax, "Tax", "tax", 1, 10M, extendedData);

            _invoice.Items.Add(l1);
            _invoice.Items.Add(l2);
            _invoice.Items.Add(l3);
            _invoice.Items.Add(l4);

            var processorSettings = new StripeProcessorSettings
            {
                ApiKey = ConfigurationManager.AppSettings["stripeApiKey"]
            };

            Provider.GatewayProviderSettings.ExtendedData.SaveProcessorSettings(processorSettings);

            if (Provider.PaymentMethods.Any()) return;
            var resource = Provider.ListResourcesOffered().ToArray();
            Provider.CreatePaymentMethod(resource.First(), "Credit Card", "Credit Card");
        }
 /// <summary>
 /// Merges the modifier extend data(s) into the extended data
 /// </summary>
 /// <param name="extendedData">
 /// The extended data.
 /// </param>
 /// <param name="modifier">
 /// The modifier.
 /// </param>
 public static void MergeDataModifierLogs(this ExtendedDataCollection extendedData, IDataModifierData modifier)
 {
     if (modifier.ModifiedDataLogs == null)
     {
         return;
     }
     foreach (var log in modifier.ModifiedDataLogs)
     {
         foreach (var item in log.ExtendedData)
         {
             extendedData.SetValue(item.Key, item.Value);
         }
     }
 }
        public ActionResult AddToBasket(AddItemModel model)
        {
            // This is an example of using the ExtendedDataCollection to add some custom functionality.
            // In this case, we are creating a direct reference to the content (Product Detail Page) so
            // that we can provide a link, thumbnail and description in the cart per this design.  In other
            // designs, there may not be thumbnails or descriptions and the link could be to a completely
            // different website.
            var extendedData = new ExtendedDataCollection();
            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            // NEW IN 1.9.1
            // We've added some data modifiers that can handle such things as including taxes in product
            // pricing.  The data modifiers can either get executed when the item is added to the basket or
            // as a result from a MerchelloHelper query - you just don't want them to execute twice.

            // Calls directly to the ProductService are not modified
            // var product = this.MerchelloServices.ProductService.GetByKey(model.Product.Key);

            // Calls to using the MerchelloHelper WILL be modified
            // var merchello = new MerchelloHelper();
            //
            // if you want to do this you should tell the basket not to modify the data again when adding the item
            //this.Basket.EnableDataModifiers = false;

            // In this case we want to get the product without any data modification
            var merchello = new MerchelloHelper(false);

            var product = merchello.Query.Product.GetByKey(model.Product.Key);

            // In the event the product has options we want to add the "variant" to the basket.
            // -- If a product that has variants is defined, the FIRST variant will be added to the cart.
            // -- This was done so that we did not have to throw an error since the Master variant is no
            // -- longer valid for sale.
            if (model.OptionChoices != null && model.OptionChoices.Any())
            {
                // NEW in 1.9.1
                // ProductDisplay and ProductVariantDisplay classes can be added directly to the Basket
                // so you don't have to query the service.
                var variant = product.GetProductVariantDisplayWithAttributes(model.OptionChoices);
                this.Basket.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                this.Basket.AddItem(product, product.Name, 1, extendedData);
            }

            this.Basket.Save();

            return this.RedirectToUmbracoPage(model.BasketPageId);
        }
 /// <summary>
 /// Sets an object value into an extended data collection
 /// </summary>
 /// <param name="extendedData">
 /// The extended data.
 /// </param>
 /// <param name="key">
 /// The key.
 /// </param>
 /// <param name="model">
 /// The model.
 /// </param>
 /// <typeparam name="T">
 /// The type of object to be serialized
 /// </typeparam>
 public static void SetValue <T>(this ExtendedDataCollection extendedData, string key, T model) where T : class, new()
 {
     try
     {
         var value = JsonConvert.SerializeObject(model);
         extendedData.SetValue(key, value);
     }
     catch (Exception ex)
     {
         var logData = MultiLogger.GetBaseLoggingData();
         logData.AddCategory("ExtendedData");
         MultiLogHelper.WarnWithException(typeof(Extensions), "Failed to serialize value. Proceding with operation.", ex, logData);
     }
 }
        public ActionResult AddToBasket(AddItemModel model)
        {
            // This is an example of using the ExtendedDataCollection to add some custom functionality.
            // In this case, we are creating a direct reference to the content (Product Detail Page) so
            // that we can provide a link, thumbnail and description in the cart per this design.  In other
            // designs, there may not be thumbnails or descriptions and the link could be to a completely
            // different website.
            var extendedData = new ExtendedDataCollection();
            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            var product = _merchelloContext.Services.ProductService.GetByKey(model.ProductKey);

            // In the event the product has options we want to add the "variant" to the basket.
            // -- If a product that has variants is defined, the FIRST variant will be added to the cart.
            // -- This was done so that we did not have to throw an error since the Master variant is no
            // -- longer valid for sale.
            if (model.OptionChoices != null && model.OptionChoices.Any())
            {

                var variant = _merchelloContext.Services.ProductVariantService.GetProductVariantWithAttributes(product, model.OptionChoices);

                // TODO : This is an error in the back office ... name should already include the variant info
                // Begin fix -------------------------------------------------------------------------------------------
                // We need to save the variant name (T-Shirt - blue, large) instead of (T-Shirt).  This is done in the
                // ProductVariantService CreateProductVariantWithKey ... but obviously we're not using that method
                // and must be doing it himself in the Back Office before he sends it to the server - likely just
                // calling save.  http://issues.merchello.com/youtrack/issue/M-153
                var name = product.Name;
                foreach (var att in variant.Attributes)
                {
                    if (name == product.Name) name += " - ";
                    else
                        name += ", ";
                    name += " " + att.Name;
                }
                // end fix ----------------------------------------------------------------------------------------------

                _basket.AddItem(variant, name, 1, extendedData);
            }
            else
            {

                _basket.AddItem(product, product.Name, 1, extendedData);
            }
            _basket.Save();

            // redirect to the cart page - this is a quick and dirty and should be done differently in
            // practice
            return RedirectToUmbracoPage(BasketContentId);
        }
Ejemplo n.º 40
0
        /// <summary>
        /// The calculate tax for invoice.
        /// </summary>
        /// <param name="invoice">
        /// The invoice.
        /// </param>
        /// <param name="taxAddress">
        /// The tax address.
        /// </param>
        /// <param name="quoteOnly">
        /// A value indicating whether or not this is a tax quote or a formal tax submission
        /// </param>
        /// <returns>
        /// The <see cref="ITaxCalculationResult"/>.
        /// </returns>
        public ITaxCalculationResult CalculateTaxForInvoice(IInvoice invoice, IAddress taxAddress, bool quoteOnly)
        {
            var defaultStoreAddress = _settings.DefaultStoreAddress;

            string prefix = invoice.InvoiceNumberPrefix;

            if (quoteOnly)
            {
                invoice.InvoiceNumberPrefix = string.Format("Quote-{0}", Guid.NewGuid());
            }

            var request = invoice.AsTaxRequest(defaultStoreAddress, quoteOnly);

            if (quoteOnly)
            {
                invoice.InvoiceNumberPrefix = prefix;
            }

            request.CompanyCode = _settings.CompanyCode;

            var avaTaxResult = _avaTaxService.GetTax(request);

            if (avaTaxResult.ResultCode == SeverityLevel.Success)
            {
                var extendedData = new ExtendedDataCollection();

                extendedData.SetValue(Core.Constants.ExtendedDataKeys.TaxTransactionResults, JsonConvert.SerializeObject(avaTaxResult));

                return(new TaxCalculationResult(TaxMethod.Name, -1, avaTaxResult.TotalTax, extendedData));
            }

            IEnumerable <ApiResponseMessage> messages;

            try
            {
                messages = avaTaxResult.Messages;
            }
            catch (Exception)
            {
                messages = Enumerable.Empty <ApiResponseMessage>();
            }

            var exception = new AvaTaxApiException(string.Format("AvaTax returned result code: {0}.  {1}", avaTaxResult.ResultCode, string.Join(Environment.NewLine, messages.Select(x => x.Details))));

            LogHelper.Error <AvaTaxTaxationGatewayMethod>("AvaTax API returned an exception", exception);

            throw exception;
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Adds the AVS and CVV data to the payment so it can be displayed in the back office
        /// </summary>
        /// <param name="extendedData"></param>
        /// <param name="transaction"></param>
        public static void SetAvsCvvData(this ExtendedDataCollection extendedData, Transaction transaction)
        {
            // Pull out all the AVS and CVV Data as we need to display this
            var sb = new StringBuilder();

            if (!string.IsNullOrEmpty(transaction.AvsErrorResponseCode))
            {
                sb.AppendFormat("AvsErrorResponseCode: {0} | ", transaction.AvsErrorResponseCode);
            }
            sb.AppendFormat("AvsPostalCodeResponseCode: {0} | ", transaction.AvsPostalCodeResponseCode);
            sb.AppendFormat("AvsStreetAddressResponseCode: {0} | ", transaction.AvsStreetAddressResponseCode);
            sb.AppendFormat("CvvResponseCode: {0}", transaction.CvvResponseCode);

            // Set it into the Extended data
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.AvsCvvData, sb.ToString());
        }
Ejemplo n.º 42
0
        public ActionResult AddToBasket(AddItemModel model)
        {
            // Add to Logical Basket

            // add Umbraco content id to Merchello Product extended properties
            var extendedData = new ExtendedDataCollection();
            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            // get Merchello product
            var product = Services.ProductService.GetByKey(model.ProductKey);

            // add a single item of the Product to the logical Basket
            Basket.AddItem(product, product.Name, 1, extendedData);

            // Save to Database tables: merchItemCache, merchItemCacheItem
            Basket.Save();

            return RedirectToUmbracoPage(BasketContentId);
        }
Ejemplo n.º 43
0
        public ActionResult AddToBasket(AddItemModel model)
        {
            // Add to Logical Basket
            // add Umbraco content id to Merchello Product extended data
            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            // get Merchello product
            var product = Services.ProductService.GetByKey(model.ProductKey);

            // add a single item of the Product to the logical Basket
            Basket.AddItem(product, product.Name, model.OrderAmount, extendedData);

            // Save to Database tables: merchItemCache, merchItemCacheItem
            Basket.Save();

            return(RedirectToUmbracoPage(BasketContentId));
        }
Ejemplo n.º 44
0
        public ActionResult AddToWishList(AddItemModel model)
        {
            var extendedData = new ExtendedDataCollection();
            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            var product = this.MerchelloServices.ProductService.GetByKey(model.Product.Key);
            if (model.OptionChoices != null && model.OptionChoices.Any())
            {
                var variant = this.MerchelloServices.ProductVariantService.GetProductVariantWithAttributes(product, model.OptionChoices);
                _wishList.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                _wishList.AddItem(product, product.Name, 1, extendedData);
            }

            _wishList.Save();

            return this.RedirectToUmbracoPage(model.WishListPageId);
        }
Ejemplo n.º 45
0
        public ActionResult AddToWishList(AddItemModel model)
        {
            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("umbracoContentId", model.ContentId.ToString(CultureInfo.InvariantCulture));

            var product = this.MerchelloServices.ProductService.GetByKey(model.Product.Key);

            if (model.OptionChoices != null && model.OptionChoices.Any())
            {
                var variant = this.MerchelloServices.ProductVariantService.GetProductVariantWithAttributes(product, model.OptionChoices);
                _wishList.AddItem(variant, variant.Name, 1, extendedData);
            }
            else
            {
                _wishList.AddItem(product, product.Name, 1, extendedData);
            }

            _wishList.Save();

            return(this.RedirectToUmbracoPage(model.WishListPageId));
        }
Ejemplo n.º 46
0
        public void Init()
        {
            var billTo = new Address()
            {
                Organization = "Proworks",
                Address1 = "777 NE 2nd St.",
                Locality = "Corvallis",
                Region = "OR",
                PostalCode = "97330",
                CountryCode = "US",
                Email = "*****@*****.**",
                Phone = "555-555-5555"
            };

            // create an invoice
            var invoiceService = new InvoiceService();

            _invoice = invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);
                                                  
            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");

            var processorSettings = new ChaseProcessorSettings
            {
                MerchantId = ConfigurationManager.AppSettings["merchantId"],
                Bin = ConfigurationManager.AppSettings["bin"],
                Username = ConfigurationManager.AppSettings["username"],
                Password = ConfigurationManager.AppSettings["password"]
            };

            Provider.GatewayProviderSettings.ExtendedData.SaveProcessorSettings(processorSettings);

            if (Provider.PaymentMethods.Any()) return;
            var resource = new GatewayResource("CreditCard", "Credit Card");
            _payment = Provider.CreatePaymentMethod(resource, "Credit Card", "Credit Card");
        }
Ejemplo n.º 47
0
        public void Can_Create_An_Invoice_With_A_CustomLineItem()
        {
            //// Arrange
            var invoice = MockInvoiceDataMaker.GetMockInvoiceForTaxation();
            Assert.NotNull(invoice, "Invoice is null");

            var extendedData = new ExtendedDataCollection();
            extendedData.SetValue(Constants.ExtendedDataKeys.Taxable, false.ToString());

            var typeField = EnumTypeFieldConverter.LineItemType.Custom("CcFee");

            //// Act
            var ccFee = new InvoiceLineItem(
                typeField.TypeKey,
                "CC Fee",
                "ccfee",
                1,
                1.0m,
                extendedData);

            invoice.Items.Add(ccFee);

            Assert.IsTrue(invoice.CustomLineItems().Any());
        }
Ejemplo n.º 48
0
        public void TestCaseNumber_3_Section_C_MasterCard_AuthCapture()
        {
            //Arrange            
            const string cardType = "MasterCard";
            const string card = "5454545454545454";
            const string cardCode = "333";
            const string postalCode = "44444";
            const int amount = 41;
            const string aav = "Asju1ljfl86bAAAAAACm9zU6aqY";
            const string eci = "5";

            // Setup extended data for invoice
            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");

            _invoice.BillToPostalCode = postalCode;

            // Set the total value for the invoice.
            _invoice.Total = amount;

            // make up some line items for the invoice                                                    
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 1, amount, extendedData);

            _invoice.Items.Add(l1);

            var creditCardMethod = Provider.GetPaymentGatewayMethodByPaymentCode("CreditCard");
            Assert.NotNull(creditCardMethod);

            var ccEntry = TestHelper.GetCreditCardFormData(cardType, card, cardCode);
            ccEntry.AuthenticationVerification = aav;
            ccEntry.AuthenticationVerificationEci = eci;

            // Act                                                                                         
            var result = _payment.AuthorizeCapturePayment(_invoice, amount, ccEntry.AsProcessorArgumentCollection());
            // Assert

            Assert.IsTrue(result.Payment.Success);
            Assert.IsTrue(result.ApproveOrderCreation);

            // Log Results for certification       
            TestHelper.LogInformation("Test 3 Section C MasterCard Auth Capture", result);
        }
Ejemplo n.º 49
0
        public void TestCaseNumber_24_Section_A_A_And_B()
        {
            //Arrange       
            const string cardType = "VISA";
            const string card = "4055011111111111";
            const string cardCode = "333";
            const string postalCode = "22222";
            const int amount = 90;
            const int taxAmount = 10;

            // Setup extended data for invoice
            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");
            
            _invoice.BillToPostalCode = postalCode;
            
            // Set the total value for the invoice.
            _invoice.Total = amount + taxAmount;
            _invoice.PoNumber = "PW0001";
            
            // make up some line items for the invoice                                                    
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 1, amount - taxAmount, extendedData);
            var l2 = new InvoiceLineItem(LineItemType.Tax, "Item 2", "I2", 1, taxAmount, extendedData);
            
            _invoice.Items.Add(l1);
            _invoice.Items.Add(l2);

            var creditCardMethod = Provider.GetPaymentGatewayMethodByPaymentCode("CreditCard");
            Assert.NotNull(creditCardMethod);

            var ccEntry = TestHelper.GetCreditCardFormData(cardType, card, cardCode);
            
            // Act
            var result = _payment.AuthorizePayment(_invoice, ccEntry.AsProcessorArgumentCollection());
            var result2 = _payment.CapturePayment(_invoice, result.Payment.Result, amount, ccEntry.AsProcessorArgumentCollection());

            // Assert                 
            Assert.IsTrue(result.Payment.Success);
            Assert.IsTrue(result.ApproveOrderCreation);

            Assert.IsTrue(result2.Payment.Success);
            Assert.IsTrue(result2.ApproveOrderCreation);

            // Log Results for certification
            TestHelper.LogInformation("Test 24A Section A", result);
            TestHelper.LogInformation("Test 24B Section A", result2);
        }
Ejemplo n.º 50
0
        public void TestCaseNumber_3_Section_B()
        {
            //Arrange            
            const string cardType = "VISA";
            const string card = "4788250000028291";
            const string cardCode = "";
            const string postalCode = "11111";
            const decimal amount = 38.01M;

            // Setup extended data for invoice
            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");

            _invoice.BillToPostalCode = postalCode;

            // Set the total value for the invoice.
            _invoice.Total = amount;

            // make up some line items for the invoice                                                    
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 1, amount, extendedData);

            _invoice.Items.Add(l1);

            var creditCardMethod = Provider.GetPaymentGatewayMethodByPaymentCode("CreditCard");
            Assert.NotNull(creditCardMethod);

            var ccEntry = TestHelper.GetCreditCardFormData(cardType, card, cardCode);

            // Act                                                                                                        
            var result = _payment.AuthorizeCapturePayment(_invoice, amount, ccEntry.AsProcessorArgumentCollection());
            // Assert

            Assert.IsFalse(result.Payment.Success);
            Assert.IsFalse(result.ApproveOrderCreation);

            // Log Results for certification       
            TestHelper.LogInformation("Test 3 Section B", result);
        }                             
Ejemplo n.º 51
0
        public void Init()
        {
            _address = new Address()
            {
                Name = "Mindfly Web Design Studio",
                Address1 = "114 W. Magnolia St.  Suite 504",
                Locality = "Bellingham",
                Region = "WA",
                PostalCode = "98225",
                CountryCode = "US"
            };

            var extendedData = new ExtendedDataCollection();

            extendedData.SetValue("merchProductKey", Guid.NewGuid().ToString());
            extendedData.SetValue("merchProductVariantKey", Guid.NewGuid().ToString());
            extendedData.SetValue("merchWeight", "12");

            var lineItemCollection = new LineItemCollection()
            {
                {new ItemCacheLineItem(LineItemType.Product, "Product1", "Sku1", 1, 10, extendedData)},
                {new ItemCacheLineItem(LineItemType.Product, "Product2", "Sku2", 2, 12, extendedData)},
                {new ItemCacheLineItem(LineItemType.Product, "Product3", "Sku3", 3, 14, extendedData)},
            };

            _shipment = new Shipment(new ShipmentStatusMock(), _address, _address, lineItemCollection);
        }
Ejemplo n.º 52
0
        public void TestCaseNumber_6_Section_B_A_And_B()
        {
            //Arrange            
            const string cardType = "MasterCard";
            const string card = "5454545454545454";
            const string cardCode = "";
            const string postalCode = "L6L2X9";
            const int amount = 41;

            // Setup extended data for invoice
            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");

            _invoice.BillToPostalCode = postalCode;

            // Set the total value for the invoice.
            _invoice.Total = amount;

            // make up some line items for the invoice                                                    
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 1, amount, extendedData);

            _invoice.Items.Add(l1);

            var creditCardMethod = Provider.GetPaymentGatewayMethodByPaymentCode("CreditCard");
            Assert.NotNull(creditCardMethod);

            var ccEntry = TestHelper.GetCreditCardFormData(cardType, card, cardCode);

            // Act                                                                                                        
            var result = _payment.AuthorizeCapturePayment(_invoice, amount, ccEntry.AsProcessorArgumentCollection());
            var result2 = _payment.VoidPayment(_invoice, result.Payment.Result, ccEntry.AsProcessorArgumentCollection());
            // Assert

            Assert.IsTrue(result.Payment.Success);
            Assert.IsTrue(result.ApproveOrderCreation);

            Assert.AreEqual("0", result2.Payment.Result.ExtendedData.GetValue(Constants.ExtendedDataKeys.VoidProcStatus));

            // Log Results for certification       
            TestHelper.LogInformation("Test 6A Section B", result);
            TestHelper.LogInformation("Test 6B Section B", result2);
        }
Ejemplo n.º 53
0
        public void TestCaseNumber_5_Section_C_Visa_AuthCapture()
        {
            //Arrange            
            const string cardType = "Visa";
            const string card = "4788250000028291";
            const string cardCode = "111";
            const string postalCode = "55555";
            const int amount = 1055;
            const string cavv = "CAAQCZkRERI0VniQEhERAAAAAAA=";
            //const string cavv = "BwABA4kRERI0VniQEhERAAAAAAA=";
            const string eci = "6";

            // Setup extended data for invoice
            var extendedData = new ExtendedDataCollection();

            // this is typically added automatically in the checkout workflow
            extendedData.SetValue(Core.Constants.ExtendedDataKeys.CurrencyCode, "USD");

            _invoice.BillToPostalCode = postalCode;

            // Set the total value for the invoice.
            _invoice.Total = amount;

            // make up some line items for the invoice                                                    
            var l1 = new InvoiceLineItem(LineItemType.Product, "Item 1", "I1", 1, amount, extendedData);

            _invoice.Items.Add(l1);

            var creditCardMethod = Provider.GetPaymentGatewayMethodByPaymentCode("CreditCard");
            Assert.NotNull(creditCardMethod);

            var ccEntry = TestHelper.GetCreditCardFormData(cardType, card, cardCode);
            ccEntry.AuthenticationVerification = cavv;
            ccEntry.AuthenticationVerificationEci = eci;

            // Act                                                                                          
            var result = _payment.AuthorizeCapturePayment(_invoice, amount, ccEntry.AsProcessorArgumentCollection());
            // Assert

            Assert.IsTrue(result.Payment.Success);
            Assert.IsTrue(result.ApproveOrderCreation);

            // Log Results for certification       
            TestHelper.LogInformation("Test 5 Section C Visa Auth Capture", result);
        }
 /// <summary>
 /// Adjusts the rate of the quote based on the province 
 /// </summary>
 /// <param name="baseRate">The base (unadjusted) rate</param>
 /// <param name="province">The <see cref="ITaxProvince"/> associated with the <see cref="ITaxMethod"/></param>
 /// <param name="extendedData">The <see cref="ExtendedDataCollection"/></param>
 /// <returns>The tax adjustment</returns>
 private static decimal AdjustedRate(decimal baseRate, ITaxProvince province, ExtendedDataCollection extendedData)
 {
     if (province == null) return baseRate;
     extendedData.SetValue(Core.Constants.ExtendedDataKeys.ProviceTaxRate, province.PercentAdjustment.ToString(CultureInfo.InvariantCulture));
     return province.PercentAdjustment + baseRate;
 }
Ejemplo n.º 55
0
        public void Can_Map_An_Invoice_With_A_Custom_LineItemType_To_InvoiceDisplay()
        {
            //// Arrange
            var invoice = MockInvoiceDataMaker.GetMockInvoiceForTaxation();
            Assert.NotNull(invoice, "Invoice is null");

            var extendedData = new ExtendedDataCollection();
            extendedData.SetValue(Constants.ExtendedDataKeys.Taxable, false.ToString());

            var typeField = EnumTypeFieldConverter.LineItemType.Custom("CcFee");

            //// Act
            var ccFee = new InvoiceLineItem(
                typeField.TypeKey,
                "CC Fee",
                "ccfee",
                1,
                1.0m,
                extendedData);

            invoice.Items.Add(ccFee);

            var display = invoice.ToInvoiceDisplay();

            //// Assert
            Assert.NotNull(display);
            Assert.IsFalse(display.Items.Any(x => x.LineItemTypeField == null), "One or more of the LineItemTypeFields where null");
        }
Ejemplo n.º 56
0
        public void Can_Create_A_Customer_Invoice_And_Order()
        {
            // Adding the shipmethod is typically done in the back office through the UI.
            // Interested in the use case to dynamically add theses?
            var key = Constants.ProviderKeys.Shipping.FixedRateShippingProviderKey;
            var defaultCatalogKey = Constants.DefaultKeys.Warehouse.DefaultWarehouseCatalogKey;

            // this would have to be done through the back office as it uses an internal service
            var us = MerchelloContext.Current.Services.StoreSettingService.GetCountryByCode("US");
            var usCountry = new ShipCountry(defaultCatalogKey, us);
            ((ServiceContext)MerchelloContext.Current.Services).ShipCountryService.Save(usCountry);

            // we can use this later.
            var rateTableProvider = (FixedRateShippingGatewayProvider)MerchelloContext.Current.Gateways.Shipping.GetProviderByKey(key);

            // again usually done in the back office
            if (!rateTableProvider.ShipMethods.Any())
            {
                // creates the rate table for ship rate quotes
                var gwShipmeMethod = (FixedRateShippingGatewayMethod)rateTableProvider.CreateShipMethod(FixedRateShippingGatewayMethod.QuoteType.VaryByWeight, usCountry, "Ground (Vary by Weight)");
                gwShipmeMethod.RateTable.AddRow(0, 10, 5);
                gwShipmeMethod.RateTable.AddRow(10, 15, 10); // total weight should be 10M so we should hit this tier
                gwShipmeMethod.RateTable.AddRow(15, 25, 25);
                gwShipmeMethod.RateTable.AddRow(25, 10000, 100);
                rateTableProvider.SaveShippingGatewayMethod(gwShipmeMethod);
            }

            // Get the persisted customer
            const string loginName = "rusty";

            var customerService = MerchelloContext.Current.Services.CustomerService;

            var customer = customerService.GetByLoginName(loginName)
                           ?? customerService.CreateCustomerWithKey(loginName, "Rusty", "Swayne", "*****@*****.**");

            // I'll use this for billing and shipping
            var billingAddress = new Address()
                                     {
                                         Name = "Mindfly Web Design Studio",
                                         Address1 = "114 W. Magnolia St. Suite 300",
                                         Locality = "Bellingham",
                                         Region = "WA",
                                         PostalCode = "98225",
                                         CountryCode = "US"
                                     };

            // Most of the time this information is brought in from the IProductVariant - but the idea is you can
            // describe things on the fly
            var extendedData = new ExtendedDataCollection();
            // this is used to determine where a shipment originates
            extendedData.SetValue(Constants.ExtendedDataKeys.WarehouseCatalogKey, defaultCatalogKey.ToString());
            // items set to shippable
            extendedData.SetValue(Constants.ExtendedDataKeys.TrackInventory, "false");
            extendedData.SetValue(Constants.ExtendedDataKeys.Shippable, "true");
            extendedData.SetValue(Constants.ExtendedDataKeys.Weight, "1.25");
            extendedData.SetValue(Constants.ExtendedDataKeys.CurrencyCode, "USD");

            var item = new InvoiceLineItem(LineItemType.Product, "My product", "mySku", 2, 10M, extendedData);

            var invoiceService = MerchelloContext.Current.Services.InvoiceService;

            var invoice = invoiceService.CreateInvoice(Constants.DefaultKeys.InvoiceStatus.Unpaid);
            // I'd say we need to add a parameter to the service so we don't have to do this
            // http://issues.merchello.com/youtrack/issue/M-434
            ((Invoice)invoice).CustomerKey = customer.Key;

            // The version key is useful in some cases to invalidate shipping quotes or taxation calculations
            invoice.VersionKey = Guid.NewGuid();

            invoice.Items.Add(item);

            // at this point the invoice is not saved and we don't have an invoice number
            // however, we may want to quote shipping so we need a shipment

            // Shipment Statuses are new in 1.5.0
            var warehouse = MerchelloContext.Current.Services.WarehouseService.GetDefaultWarehouse();

            var shipmentStatus =
                MerchelloContext.Current.Services.ShipmentService.GetShipmentStatusByKey(
                    Constants.DefaultKeys.ShipmentStatus.Quoted);

            // since we know all the items in the invoice will be shipped we don't need to filter
            var shipment = new Shipment(shipmentStatus, warehouse.AsAddress(), billingAddress, invoice.Items);

            // since we already know the shipping provider we want from above we can do
            var quotes = rateTableProvider.QuoteShippingGatewayMethodsForShipment(shipment);

            // if we wanted Merchello to get quotes from all shipping providers we'd do the following
            // var quotes = shipment.ShipmentRateQuotes();

            if (quotes.Any())
            {
                // this check makes certain a quote was returned.  For example if the collection of items was outside the allowable
                // weight range, the provider would not return a quote.

                // Add the first quote to the invoice.

                invoice.Items.Add(quotes.FirstOrDefault().AsLineItemOf<InvoiceLineItem>());
            }

            // you do need to update the total ... this is usually done in the InvoiceBuilder in
            // instantiated by a SalesPreparation sub class
            var charges = invoice.Items.Where(x => x.LineItemType != LineItemType.Discount).Sum(x => x.TotalPrice);
            var discounts = invoice.Items.Where(x => x.LineItemType == LineItemType.Discount).Sum(x => x.TotalPrice);

            // total the invoice
            decimal converted;
            invoice.Total = decimal.TryParse((charges - discounts).ToString(CultureInfo.InvariantCulture), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture.NumberFormat, out converted) ? converted : 0;

            // Now we save the invoice since we have to have a real record of something to collect a payment against
            // This also generates the invoice number
            invoiceService.Save(invoice);

            Console.WriteLine(invoice.InvoiceNumber);

            // cash payment method
            var cashProvider = MerchelloContext.Current.Gateways.Payment.GetProviderByKey(Constants.ProviderKeys.Payment.CashPaymentProviderKey);

            if (cashProvider != null)
            {
                var cash = cashProvider.PaymentMethods.FirstOrDefault(); // default install has a single payment method "Cash"

                // I usually Authorize a cash payment if taken online since we don't really see the money.  Capture is used
                // when the money comes in.  In your inquiry, it looks like you are assuming the money is in hand at the
                // time of the purchase, so we'll use AuthorizeCapture straight away.

                var attempt = invoice.AuthorizeCapturePayment(cash.Key);

                if (! attempt.Payment.Success)
                {
                    // handle the error
                }

                // otherwise you'll notice
                var approved = attempt.ApproveOrderCreation; // equals true

                // the order will be automatically created by the event handler in Merchello.Core.Gateways.GatewayEvents

                // however in this test I don't have the event wired up so I have to do it manuall
                if (approved)
                {
                   var order = invoice.PrepareOrder();
                   MerchelloContext.Current.Services.OrderService.Save(order);

                    var items = order.Items;
                }
            }
            // Cash provider is not active
        }
Ejemplo n.º 57
0
        /// <summary>
        /// The calculate tax for invoice.
        /// </summary>
        /// <param name="invoice">
        /// The invoice.
        /// </param>
        /// <param name="taxAddress">
        /// The tax address.
        /// </param>
        /// <param name="quoteOnly">
        /// A value indicating whether or not this is a tax quote or a formal tax submission
        /// </param>
        /// <returns>
        /// The <see cref="ITaxCalculationResult"/>.
        /// </returns>
        public ITaxCalculationResult CalculateTaxForInvoice(IInvoice invoice, IAddress taxAddress, bool quoteOnly)
        {
            var defaultStoreAddress = _settings.DefaultStoreAddress;

            string prefix = invoice.InvoiceNumberPrefix;

            if (quoteOnly)
            {                
                invoice.InvoiceNumberPrefix = string.Format("Quote-{0}", Guid.NewGuid());
            }

            var request = invoice.AsTaxRequest(defaultStoreAddress, quoteOnly);
            if (quoteOnly) invoice.InvoiceNumberPrefix = prefix;

            request.CompanyCode = _settings.CompanyCode;

            var avaTaxResult = _avaTaxService.GetTax(request);

            if (avaTaxResult.ResultCode == SeverityLevel.Success)
            {
                var extendedData = new ExtendedDataCollection();

                extendedData.SetValue(Core.Constants.ExtendedDataKeys.TaxTransactionResults, JsonConvert.SerializeObject(avaTaxResult));

                return new TaxCalculationResult(TaxMethod.Name, -1, avaTaxResult.TotalTax, extendedData);
            }

            IEnumerable<ApiResponseMessage> messages;
            try
            {
                messages = avaTaxResult.Messages;
            }
            catch (Exception)
            {                    
                messages = Enumerable.Empty<ApiResponseMessage>();
            }
        
            var exception = new AvaTaxApiException(string.Format("AvaTax returned result code: {0}.  {1}", avaTaxResult.ResultCode, string.Join(Environment.NewLine, messages.Select(x => x.Details))));

            LogHelper.Error<AvaTaxTaxationGatewayMethod>("AvaTax API returned an exception", exception);

            throw exception;
        }