示例#1
0
        public void Can_Package_A_Basket_Using_Basket_ExtensionMethod()
        {
            //// Arrange
            var notShippable = PreTestDataWorker.MakeExistingProduct(false);
            _basket.AddItem(notShippable);

            var destination = new Address()
            {
                Name = "San Diego Zoo",
                Address1 = "2920 Zoo Dr",
                Locality = "San Diego",
                Region = "CA",
                PostalCode = "92101",
                CountryCode = "US"
            };

            //// Act
            var shipments = _basket.PackageBasket(MerchelloContext.Current, destination);

            //// Assert
            Assert.NotNull(shipments);
            Assert.AreEqual(1, shipments.Count());

            Assert.AreEqual(4, shipments.First().Items.Count);
        }
示例#2
0
        public void Default_BasketPackagingStrategy_Returns_A_Shipment()
        {
            //// Arrange
            var notShippable = PreTestDataWorker.MakeExistingProduct(false);
            _basket.AddItem(notShippable);

            var destination = new Address()
            {
                Name = "San Diego Zoo",
                Address1 = "2920 Zoo Dr",
                Locality = "San Diego",
                Region = "CA",
                PostalCode = "92101",
                CountryCode = "US"
            };

            _basket.AddItem(notShippable);

            //// Act
            var strategy = new DefaultWarehousePackagingStrategy(MerchelloContext.Current, _basket.Items, destination, Guid.NewGuid());
            var shipments = strategy.PackageShipments();

            //// Assert
            Assert.NotNull(shipments);
            Assert.AreEqual(1, shipments.Count());
            Assert.AreEqual(4, shipments.First().Items.Count);
        }
        public void Can_Add_Invoices_To_Collections()
        {
            //// Arrange
            var billTo = new Address() { Address1 = "test", CountryCode = "US", PostalCode = "11111" };

            var invoice = _invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);
            invoice.SetBillingAddress(billTo);
            _invoiceService.Save(invoice);

            var invoice2 = _invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);
            invoice2.SetBillingAddress(billTo);
            _invoiceService.Save(invoice2);

            var invoice3 = _invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);
            _invoiceService.Save(invoice3);
            invoice3.SetBillingAddress(billTo);

            var invoice4 = _invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);
            invoice4.SetBillingAddress(billTo);
            _invoiceService.Save(invoice4);

            var collection1 = _entityCollectionService.CreateEntityCollectionWithKey(
                EntityType.Invoice,
                _providerKey,
                "Invoice Collection1");

            var provider1 = collection1.ResolveProvider<StaticInvoiceCollectionProvider>();
            Assert.NotNull(provider1);
            Assert.AreEqual(typeof(StaticInvoiceCollectionProvider), provider1.GetType());

            var collection2 = _entityCollectionService.CreateEntityCollectionWithKey(
                EntityType.Invoice,
                _providerKey,
                "Invoice Collection2");

            var provider2 = collection2.ResolveProvider<StaticInvoiceCollectionProvider>();
            Assert.NotNull(provider2);
            Assert.AreEqual(typeof(StaticInvoiceCollectionProvider), provider2.GetType());

            invoice.AddToCollection(collection1);
            invoice2.AddToCollection(collection1);
            invoice3.AddToCollection(collection1);
            invoice4.AddToCollection(collection1);

            invoice3.AddToCollection(collection2);
            invoice4.AddToCollection(collection2);

            //// Assert
            var c1Invoices = collection1.GetEntities<IInvoice>().ToArray();
            var c2Invoices = collection2.GetEntities<IInvoice>().ToArray();
            Assert.IsTrue(c1Invoices.Any());
            Assert.IsTrue(c2Invoices.Any());

            Assert.Greater(c1Invoices.Count(), c2Invoices.Count());

            var i1 = c1Invoices.First();
            Assert.IsTrue(i1.GetCollectionsContaining().Any());
        }
        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;
        }
示例#5
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");
        }
示例#6
0
        public void Can_Get_Simple_First_And_LastNames_From_IAddress()
        {
            //// Arrange
            var address = new Address() { Name = "John Doe" };

            //// Act
            var firstName = address.TrySplitFirstName();
            var lastName = address.TrySplitLastName();

            //// Assert
            Assert.AreEqual("John", firstName);
            Assert.AreEqual("Doe", lastName);
        }
示例#7
0
        public void Can_Get_A_Multiple_Word_LastName()
        {
            //// Arrange
            var address = new Address() { Name = "John El Macho" };

            //// Act
            var firstName = address.TrySplitFirstName();
            var lastName = address.TrySplitLastName();

            //// Assert
            Assert.AreEqual("John", firstName);
            Assert.AreEqual("El Macho", lastName);
        }
示例#8
0
        public void Can_Prove_LastName_Is_Empty_If_Not_Provided()
        {
            //// Arrange
            var address = new Address() { Name = "John" };

            //// Act
            var firstName = address.TrySplitFirstName();
            var lastName = address.TrySplitLastName();

            //// Assert
            Assert.AreEqual("John", firstName);
            Assert.IsEmpty(lastName);
        }
示例#9
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>());
        }
示例#10
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");
        }
示例#11
0
        public void Can_Detect_A_ShipmentStatusChange()
        {
            //// Arrange
            var address = new Address()
                              {
                                  Address1 = "111 Somewhere St.",
                                  Locality = "Bellingham",
                                  Region = "WA",
                                  PostalCode = "98225",
                                  CountryCode = "US",
                                  Name = "Merchello"
                              };

            var invoice = MockInvoiceDataMaker.GetMockInvoiceForTaxation();

            var payment = new Payment(PaymentMethodType.Cash, invoice.Total) { Collected = true, Authorized = true };

            MerchelloContext.Current.Services.PaymentService.Save(payment);

            MerchelloContext.Current.Services.InvoiceService.Save(invoice);

            var appliedPaymentService = ((ServiceContext)(MerchelloContext.Current.Services)).AppliedPaymentService;

            var appliedPayment = appliedPaymentService.CreateAppliedPaymentWithKey(
                payment.Key,
                invoice.Key,
                AppliedPaymentType.Debit,
                "Payment applied",
                payment.Amount);

            invoice = MerchelloContext.Current.Services.InvoiceService.GetByKey(invoice.Key);

            Assert.NotNull(invoice);

            var order = invoice.PrepareOrder();

            MerchelloContext.Current.Services.OrderService.Save(order);

            var builder = new ShipmentBuilderChain(MerchelloContext.Current, order, order.Items.Select(x => x.Key), Guid.NewGuid(), Constants.DefaultKeys.ShipmentStatus.Packaging, "Track");

            var attempt = builder.Build();

            Assert.IsTrue(attempt.Success);
        }
        public void Init()
        {
            var address = new Address()
            {
                Name = "Mindfly",
                Address1 = "114 W. Magnolia St.",
                Address2 = "Suite 300",
                Locality = "Bellingham",
                Region = "WA",
                PostalCode = "98225",
                Email = "*****@*****.**",
                Phone = "555-555-5555"
            };

            _invoice = MockInvoiceDataMaker.InvoiceForInserting(address, 599.99M);
            ((Invoice) _invoice).InvoiceNumber = 123;
            _invoice.Items.Add(new InvoiceLineItem(LineItemType.Product, "Xbox One", "Xbox1", 1, 486M));
            _invoice.Items.Add(new InvoiceLineItem(LineItemType.Product, "Xbox One TitanFall", "XB1-TitanFall", 2, 49.99M));
            _invoice.Items.Add(new InvoiceLineItem(LineItemType.Shipping, "Shipping", "Shipping", 1, 30.00M));
            _invoice.Items.Add(new InvoiceLineItem(LineItemType.Tax, "Sales Tax", "Tax", 1, 14.01M));

            _message
                = @"{{BillToName}}
            Your address
            {{BillToAddress1}}
            {{BillToAddress2}}
            {{BillToLocality}}, {{BillToRegion}} {{BillToPostalCode}}

            Email : {{BillToEmail}}
            Phone : {{BillToPhone}}

            Invoice Number : {{InvoiceNumber}}

            Items Purchased:

            {{IterationStart[Invoice.Items]}}
            + {{Item.Name}} -> {{Item.Sku}} -> {{Item.UnitPrice}} -> {{Item.Quantity}} -> {{Item.TotalPrice}}
            {{IterationEnd[Invoice.Items]}}

            Thanks for the order.
            ";
        }
示例#13
0
        public void Can_Package_A_Basket_Using_Basket_ExtensionMethod()
        {
            //// Arrange
            var destination = new Address()
            {
                Name = "San Diego Zoo",
                Address1 = "2920 Zoo Dr",
                Locality = "San Diego",
                Region = "CA",
                PostalCode = "92101",
                CountryCode = "US"
            };

            //// Act
            var shipments = _basket.PackageBasket(MerchelloContext, destination);

            //// Assert
            Assert.NotNull(shipments);
            Assert.AreEqual(1, shipments.Count());
        }
示例#14
0
        public void Default_BasketPackagingStrategy_Returns_A_Shipment()
        {
            //// Arrange
            var destination = new Address()
            {
                Name = "San Diego Zoo",
                Address1 = "2920 Zoo Dr",
                Locality = "San Diego",
                Region = "CA",
                PostalCode = "92101",
                CountryCode = "US"
            };

            //// Act
            var strategy = new DefaultWarehousePackagingStrategy(MerchelloContext, _basket.Items, destination, Guid.NewGuid());
            var shipments = strategy.PackageShipments();

            //// Assert
            Assert.NotNull(shipments);
            Assert.AreEqual(1, shipments.Count());
        }
示例#15
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");
        }
示例#16
0
        public void Can_Get_Tax_Result_With_IInvoice_Data()
        {
            //// Arrange
            var storeAddress = new Address()
                {
                    Name = "Mindfly, Inc.",
                    Address1 = "114 W. Magnolia St. Suite 300",
                    Locality = "Bellingham",
                    Region = "WA",
                    PostalCode = "98225",
                    CountryCode = "US"
                };

            var taxRequest = Invoice.AsTaxRequest(storeAddress.ToTaxAddress());
            taxRequest.DocCode = "INV-DT-" + Guid.NewGuid().ToString();
            Assert.NotNull(taxRequest);

            var result = AvaTaxService.GetTax(taxRequest);

            //// Assert
            Assert.NotNull(result);

            if (result.ResultCode != SeverityLevel.Success)
            if (result.Messages.Any()) 
                foreach(var message in result.Messages) Console.WriteLine(message.Details);

            Assert.AreEqual(result.ResultCode, SeverityLevel.Success);
        }
        public void Can_Remove_Invoices_From_A_Collection()
        {
            //// Arrange
            //// Arrange
            var billTo = new Address() { Address1 = "test", CountryCode = "US", PostalCode = "11111" };

            var invoice = _invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);
            invoice.SetBillingAddress(billTo);
            _invoiceService.Save(invoice);

            var invoice2 = _invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);
            invoice2.SetBillingAddress(billTo);
            _invoiceService.Save(invoice2);

            var invoice3 = _invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);
            _invoiceService.Save(invoice3);
            invoice3.SetBillingAddress(billTo);

            var invoice4 = _invoiceService.CreateInvoice(Core.Constants.DefaultKeys.InvoiceStatus.Unpaid);
            invoice4.SetBillingAddress(billTo);
            _invoiceService.Save(invoice4);

            var collection1 = _entityCollectionService.CreateEntityCollectionWithKey(
              EntityType.Invoice,
              _providerKey,
              "Invoice Collection1");

            invoice.AddToCollection(collection1);
            invoice2.AddToCollection(collection1);
            invoice3.AddToCollection(collection1);
            invoice4.AddToCollection(collection1);
            var provider = collection1.ResolveProvider<StaticInvoiceCollectionProvider>();
            Assert.NotNull(provider);

            //// Act

            var cinvoices = collection1.GetEntities<IInvoice>().ToArray();
            Assert.AreEqual(4, cinvoices.Count());

            var remove = cinvoices.First();
            var key = remove.Key;

            remove.RemoveFromCollection(collection1);

            //// Assert
            var afterRemove = collection1.GetEntities<IInvoice>().ToArray();
            Assert.AreEqual(3, afterRemove.Count());
            Assert.False(afterRemove.Any(x => x.Key == key));
            Assert.IsFalse(collection1.Exists(remove));
            Assert.IsFalse(remove.GetCollectionsContaining().Any());
        }
示例#18
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
        }
        public void Can_Complete_Simple_Checkout_Scenario()
        {
            // The basket is empty
            WriteBasketInfoToConsole();

            #region Customer Does Basket Operations

            // -------------------------
            // Add a couple of products
            // -------------------------
            Console.WriteLine("Adding 10 'Product1' to the Basket");
            CurrentCustomer.Basket().AddItem(_product1, 10);

            Console.WriteLine("Adding 2 'Product2' to the Basket");
            CurrentCustomer.Basket().AddItem(_product2, 2);
            CurrentCustomer.Basket().Save();

            WriteBasketInfoToConsole();
            Assert.AreEqual(12, CurrentCustomer.Basket().TotalQuantityCount);
            Assert.AreEqual(14, CurrentCustomer.Basket().TotalBasketPrice);
            Assert.AreEqual(2, CurrentCustomer.Basket().TotalItemCount);

            // -------------------------
            // Add another product2
            // -------------------------
            Console.WriteLine("Adding another 'Product2' to the Basket");
            CurrentCustomer.Basket().AddItem(_product2);
            CurrentCustomer.Basket().Save();

            WriteBasketInfoToConsole();
            Assert.AreEqual(13, CurrentCustomer.Basket().TotalQuantityCount);
            Assert.AreEqual(16, CurrentCustomer.Basket().TotalBasketPrice);
            Assert.AreEqual(2, CurrentCustomer.Basket().TotalItemCount);

            // -------------------------
            // Add products - product3 and product4
            // -------------------------
            Console.WriteLine("Adding 2 'Product4' to the Basket");
            CurrentCustomer.Basket().AddItem(_product4, 2);

            WriteBasketInfoToConsole();
            Assert.AreEqual(15, CurrentCustomer.Basket().TotalQuantityCount);
            Assert.AreEqual(24, CurrentCustomer.Basket().TotalBasketPrice);
            Assert.AreEqual(3, CurrentCustomer.Basket().TotalItemCount);

            Console.WriteLine("Adding 1 'Product3' to the Basket");
            CurrentCustomer.Basket().AddItem(_product3, 1);
            CurrentCustomer.Basket().Save();

            WriteBasketInfoToConsole();
            Assert.AreEqual(16, CurrentCustomer.Basket().TotalQuantityCount);
            Assert.AreEqual(27, CurrentCustomer.Basket().TotalBasketPrice);
            Assert.AreEqual(4, CurrentCustomer.Basket().TotalItemCount);

            // -------------------------
            // Update Product4's quantity to 1
            // -------------------------
            CurrentCustomer.Basket().Items.First(x => x.Sku == _product4.Sku).Quantity = 1;
            CurrentCustomer.Basket().Save();

            WriteBasketInfoToConsole();
            Assert.AreEqual(15, CurrentCustomer.Basket().TotalQuantityCount);
            Assert.AreEqual(23, CurrentCustomer.Basket().TotalBasketPrice);
            Assert.AreEqual(4, CurrentCustomer.Basket().TotalItemCount);

            // -------------------------
            // Remove Product3 from the basket
            // -------------------------
            CurrentCustomer.Basket().RemoveItem(_product3.Sku);
            CurrentCustomer.Basket().Save();

            WriteBasketInfoToConsole();
            Assert.AreEqual(14, CurrentCustomer.Basket().TotalQuantityCount);
            Assert.AreEqual(20, CurrentCustomer.Basket().TotalBasketPrice);
            Assert.AreEqual(3, CurrentCustomer.Basket().TotalItemCount);

            #endregion

            #region CheckOut

            // ------------- Customer Shipping Address Entry -------------------------

            // Customer enters the destination shipping address
            var destination = new Address()
                {
                    Name = "Mindfly Web Design Studio",
                    Address1 = "115 W. Magnolia St.",
                    Address2 = "Suite 504",
                    Locality = "Bellingham",
                    Region = "WA",
                    PostalCode = "98225",
                    CountryCode = "US"
                };

            // Assume customer selects billing address is same as shipping address
            CurrentCustomer.Basket().SalePreparation().SaveBillToAddress(destination);

            // --------------- ShipMethod Selection ----------------------------------

            // Package the shipments
            //
            // This should return a collection containing a single shipment
            //
            var shipments = CurrentCustomer.Basket().PackageBasket(destination).ToArray();

            Assert.IsTrue(shipments.Any());
            Assert.AreEqual(1, shipments.Count());

            var shipment = shipments.First();

            // Get a shipment rate quote
            //
            // This should return a collection containing 2 shipment rate quotes (for US)
            //
            var shipRateQuotes = shipment.ShipmentRateQuotes().ToArray();

            foreach (var srq in shipRateQuotes)
            {
                WriteShipRateQuote(srq);
            }

            // Customer chooses the cheapest shipping rate
            var approvedShipRateQuote = shipRateQuotes.FirstOrDefault();

            // start the Checkout process
            Assert.AreEqual(CurrentCustomer.Basket().TotalItemCount, CurrentCustomer.Basket().SalePreparation().ItemCache.Items.Count);

            CurrentCustomer.Basket().SalePreparation().SaveShipmentRateQuote(approvedShipRateQuote);

            // Customer changes their mind and adds Product 5 to the basket
            CurrentCustomer.Basket().AddItem(_product5);
            CurrentCustomer.Basket().Save();

            WriteBasketInfoToConsole();
            Assert.AreEqual(15, CurrentCustomer.Basket().TotalQuantityCount);
            Assert.AreEqual(25, CurrentCustomer.Basket().TotalBasketPrice);
            Assert.AreEqual(4, CurrentCustomer.Basket().TotalItemCount);

            // This should have cleared the CheckoutPreparation and reconstructed so that it matches the basket again
            Assert.AreEqual(CurrentCustomer.Basket().TotalItemCount, CurrentCustomer.Basket().SalePreparation().ItemCache.Items.Count(x => x.LineItemType == LineItemType.Product));
            Console.WriteLine("OrderPrepartion was cleared!");

            // Because the customer went back and added another item the checkout workflow needs to
            // be restarted

            // User is finally finished and going to checkout
            #region Final Checkout Prepartion

            #region Shipping information

            // Save the billing information (again - the same as shipping information)
            CurrentCustomer.Basket().SalePreparation().SaveBillToAddress(destination);

            shipments = CurrentCustomer.Basket().PackageBasket(destination).ToArray();
            Assert.IsTrue(shipments.Any());

            shipment = shipments.First();

            // shipment should have all four items packaged in it since they all were marked shippable
            Assert.AreEqual(CurrentCustomer.Basket().TotalItemCount, shipment.Items.Count, "Shipment did not contain all of the items");

            var shipmentRateQuotes = shipment.ShipmentRateQuotes().ToArray();
            Assert.AreEqual(2, shipmentRateQuotes.Count());

            // customer picks faster delivery so picks the more expensive rate from a drop down
            var dropDownListValue = shipmentRateQuotes.Last().ShipMethod.Key.ToString();

            var approvedShipmentRateQuote = shipment.ShipmentRateQuoteByShipMethod(dropDownListValue);

            // The shipment in the rate quote should have all four items packaged in it since they all were marked shippable
            Assert.AreEqual(CurrentCustomer.Basket().Items.Count, approvedShipmentRateQuote.Shipment.Items.Count);

            Assert.NotNull(approvedShipRateQuote);
            WriteShipRateQuote(approvedShipmentRateQuote);

            // save the rate quote
            CurrentCustomer.Basket().SalePreparation().SaveShipmentRateQuote(approvedShipmentRateQuote);

            #endregion // end shipping info round 2

            // generate an invoice to preview
            var isReadytoInvoice = CurrentCustomer.Basket().SalePreparation().IsReadyToInvoice();

            Assert.IsTrue(isReadytoInvoice);

            var invoice = CurrentCustomer.Basket().SalePreparation().PrepareInvoice();
            WriteInvoiceInfoToConsole(invoice);

            var paymentMethods = CurrentCustomer.Basket().SalePreparation().GetPaymentGatewayMethods();

            var paymentResult = CurrentCustomer.Basket().SalePreparation().AuthorizePayment(paymentMethods.FirstOrDefault());

            Assert.IsTrue(paymentResult.Payment.Success);
            Assert.IsTrue(CurrentCustomer.Basket().IsEmpty);

            #endregion // completed checkout preparation

            // capture the payment
            invoice.CapturePayment(paymentResult.Payment.Result, paymentMethods.FirstOrDefault(), invoice.Total);

            Assert.AreEqual(Constants.DefaultKeys.InvoiceStatus.Paid, invoice.InvoiceStatusKey);

            if (paymentResult.ApproveOrderCreation)
            {
                MerchelloContext.Current.Services.OrderService.Save(invoice.PrepareOrder());
            }

            #endregion
        }
示例#20
0
        public virtual void Init()
        {
            Customer = PreTestDataWorker.MakeExistingAnonymousCustomer();
            Basket = Web.Workflow.Basket.GetBasket(MerchelloContext, Customer);

            var odd = true;
            for (var i = 0; i < ProductCount; i++)
            {

                var product = PreTestDataWorker.MakeExistingProduct(true, WeightPerProduct, PricePerProduct);
                product.AddToCatalogInventory(PreTestDataWorker.WarehouseCatalog);
                product.CatalogInventories.First().Count = 10;
                product.TrackInventory = true;
                PreTestDataWorker.ProductService.Save(product);
                Basket.AddItem(product, 2);

                odd = !odd;
            }

            BillingAddress = new Address()
            {
                Name = "Out there",
                Address1 = "some street",
                Locality = "some city",
                Region = "ST",
                PostalCode = "98225",
                CountryCode = "US"
            };

            var origin = new Address()
            {
                Name = "Somewhere",
                Address1 = "origin street",
                Locality = "origin city",
                Region = "ST",
                PostalCode = "98225",
                CountryCode = "US"
            };

            PreTestDataWorker.DeleteAllItemCaches();
            PreTestDataWorker.DeleteAllInvoices();

            Customer.ExtendedData.AddAddress(BillingAddress, AddressType.Billing);
            ItemCache = new Core.Models.ItemCache(Customer.EntityKey, ItemCacheType.Checkout);

            PreTestDataWorker.ItemCacheService.Save(ItemCache);

            foreach (var item in Basket.Items)
            {
                ItemCache.AddItem(item.AsLineItemOf<ItemCacheLineItem>());
            }

            // setup the checkout
            SalePreparationMock = new SalePreparationMock(MerchelloContext, ItemCache, Customer);

            // add the shipment rate quote
            var shipment = Basket.PackageBasket(MerchelloContext, BillingAddress).First();
            var shipRateQuote = shipment.ShipmentRateQuotes(MerchelloContext).FirstOrDefault();

            //_checkoutMock.ItemCache.Items.Add(shipRateQuote.AsLineItemOf<InvoiceLineItem>());
            SalePreparationMock.SaveShipmentRateQuote(shipRateQuote);
        }