/// <summary>
        /// Qualifies an order based on rules you set
        /// these are simple rules - override as needed
        /// </summary>
        public virtual void ValidateUse(Order order) {

            if (ExpiresOn < DateTime.Now)
                throw new InvalidOperationException("This coupon is Expired");

            if (order.SubTotal < MininumPurchase)
                throw new InvalidOperationException("There is a minimum of " + MininumPurchase.ToString("C") + " required");

            if (order.Items.Count < MinimumItems)
                throw new InvalidOperationException("There is a minimum of " + MinimumItems.ToString() + " items required");

            
            if (MustHaveProducts.Length > 0) {
                bool haveProduct=false;
                
                foreach (string productCode in MustHaveProducts) {
                    var item = order.Items.Where(x => x.Product.ProductCode == productCode).SingleOrDefault();
                    if (item != null) {
                        haveProduct = true;
                        break;
                    }

                }

                if (!haveProduct)
                    throw new InvalidOperationException("This coupon is not valid for the items you've selected");


            }


        }
        public void ApplyCoupon(Order order) {

            decimal discountRate = PercentOff / 100;
            order.DiscountAmount = order.SubTotal * discountRate;
            

        }
        public void SendOrderEmail(Order order, MailerType mailType) {
            //pull the mailer
            Mailer mailer = GetMailerForOrder(order, mailType);

            //no catches here - let bubble to caller
            Send(mailer);
        }
        public decimal CalculateTaxAmount(Order order)
        {
            decimal result = 0;

            //get the rates from the DB

            //sales tax is a tricky thing
            //you should speak to an accountant or CPA with regards to your needs
            //This sample tax calculator applies SalesTax by state
            //Sales tax is generally applied when you your business has a physical presence, or "Nexxus"
            //in the same location as the shipping address.
            //In the US, taxes are applied based on jurisdictions, which are address-based.
            //It is your responsibility to calculate taxes correctly

            //if the order's shipping address is located in the same state as our business
            //apply the tax
            
            //this assumes the input uses ISO 2-letter codes
            TaxRate rate = GetRate(order);

            if (rate != null)
            {
                result = rate.Rate * order.TaxableGoodsSubtotal;
            }

            return result;


        }
        public void VerifyOrder(Order order) {
            
            
            //set the order as submitted - this will "clear" the basket
            order.Status = OrderStatus.Submitted;
            _orderService.SaveOrder(order);


            //send thank you email
            _mailerService.SendOrderEmail(order, MailerType.CustomerOrderReceived);

            
            //validate shipping address
            _addressValidation.VerifyAddress(order.ShippingAddress);


            //authorize payment
            _paymentService.Authorize(order);


            //set order status to verified
            order.Status = OrderStatus.Verified;

            //save the order
            _orderService.SaveOrder(order);

            //adjust inventory
            foreach (OrderItem item in order.Items) {
                _inventoryService.IncrementInventory(item.Product.ID, -item.Quantity, "Adjustment for order " + order.ID);
            }

            //email admin RE new order
            _mailerService.SendOrderEmail(order, MailerType.AdminOrderReceived);

        }
        public void SendAdminEmail(Order order, string subject, string body) {

            string adminEmail = System.Configuration.ConfigurationManager.AppSettings["StoreEmail"];
            body = "Message RE Order " + order.OrderNumber + Environment.NewLine + body;
            MailMessage message = new MailMessage(adminEmail, adminEmail, subject, body);
            Send(message);

        }
Beispiel #7
0
        public void SendOrderEmail(Commerce.Data.Order order, Commerce.Data.MailerType mailType)
        {
            //pull the mailer
            Mailer mailer = GetMailerForOrder(order, mailType);

            //no catches here - let bubble to caller
            Send(mailer);
        }
        public IQueryable<ShippingMethod> GetRates(Order order)
        {
            var shipping = GetShippingMethods().ToList();
            foreach (ShippingMethod m in shipping)
                m.Cost = order.TotalWeightInPounds * m.RatePerPound;

            return shipping.AsQueryable();

        }
        public Transaction Capture(Order order)
        {

            //Refunding process - most gateways support this
            string authCode = "XYZ" + Guid.NewGuid().ToString().Substring(0, 10);


            return new Transaction(order.ID, order.Total, authCode, TransactionProcessor.FakePaymentProcessor);
        }
        public void Order_ShouldHave_ID_Number_Date_UserName_DiscountAmount_Items() {

            var o = new Order("1234", "rob");
            Assert.IsNotNull(o.ID);
            Assert.AreEqual("1234", o.OrderNumber);
            Assert.AreEqual("rob", o.UserName);
            Assert.IsNotNull(o.Items);

        }
        public IList<ShippingMethod> CalculateRates(Order order)
        {
            //pull the methods out
            var methods = _shippingRepository.GetRates(order);

            //their might be restrictions on the shipping
            //such as no ground delivery to HI...

            return methods.ToList();
        }
        public void ApplyCoupon(Order order) {
            decimal discountRate = PercentOff / 100;
            foreach (string productCode in ProductCodes) {
                OrderItem item = order.Items.Where(x => x.Product.ProductCode.Equals(productCode, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();
                if (item != null) {
                    order.DiscountAmount+=item.Product.Price * discountRate * item.Quantity;
                }
            }

        }
 Dictionary<string, object> GetCancelParams(Order order)
 {
     Dictionary<string, object> parameters = new Dictionary<string, object>();
     parameters.Add("PaymentServiceInterface", _paymentService);
     parameters.Add("OrderServiceInterface", _orderService);
     parameters.Add("MailerServiceInterface", _mailerService);
     parameters.Add("InventoryServiceInterface", _inventoryService);
     parameters.Add("CustomerOrder", order);
     return parameters;
 }
        public Dictionary<string, object> GetShippingParams(Order order, string trackingNumber, DateTime estimatedDelivery)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("OrderServiceInterface", _orderService);
            parameters.Add("MailerServiceInterface", _mailerService);
            parameters.Add("CustomerOrder", order);
            parameters.Add("TrackingNumber", trackingNumber);
            parameters.Add("EstimatedDelivery", estimatedDelivery);

            return parameters;

        }
        public void ChargeOrder(Order order) {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("PaymentServiceInterface", _paymentService);
            parameters.Add("OrderServiceInterface", _orderService);
            parameters.Add("MailerServiceInterface", _mailerService);
            parameters.Add("AddressValidationInterface", _addressValidation);
            parameters.Add("InventoryServiceInterface", _inventoryService);
            parameters.Add("CustomerOrder", order);

            WorkflowInstance instance = WFRuntimeInstance.CreateWorkflow(
                typeof(Commerce.Pipelines.ChargeWorkflow), parameters);

            instance.Start();
        }
        public TestOrderRepository() {
            _order = _order ?? new Order("TESTORDER", "testuser");
            _orders = new List<Order>();
            _orders.Add(_order);

            //create the items
            _orderItems = new List<OrderItem>();
            _addresses = new List<Address>();
            
            for (int i = 0; i < 2; i++)
            {
                var add = new Address("testuser", "first" + i, "last" + i, "email" + i,
                "street1" + i, "street2" + i, "city" + i,
                "stateprovince" + i, "zip" + i, "country" + i);
                add.IsDefault = i == 1;
                add.ID = i;
                if (!_addresses.Contains(add))
                    _addresses.Add(add);
            }

            TestCatalogRepository catalog = new TestCatalogRepository();

            for (int i = 0; i < 99; i++) {
                Order o = new Order("order" + i, "user" + 1);
                o.ID = Guid.NewGuid();


                for (int x = 1; x <= 5; x++) {
                    OrderItem item = new OrderItem(o.ID, catalog.GetProducts()
                        .Where(y=>y.ID==x).SingleOrDefault());
                    
                    item.Quantity = x == 5 ? 3 : 1;
                    
                    if(item.Quantity==1)
                        item.Quantity = x == 4 ? 2 : 1;

                    _orderItems.Add(item);
                    o.Items.Add(item);
                }

                o.ShippingAddress = GetAddresses().Take(1).Skip(1).SingleOrDefault();
                _orders.Add(o);
            }

        }
        TaxRate GetRate(Order order)
        {
            var rates = _taxRepository.GetTaxRates().ToList();

            //check the ZIP first - this allows zip-based overrides for places
            //like Universities, that may have 4% lower tax
            TaxRate result = (from r in rates
                              where r.Zip == order.ShippingAddress.Zip
                              select r).SingleOrDefault();

            if (result == null)
                result = (from rs in rates
                          where rs.Region == order.ShippingAddress.StateOrProvince &&
                          rs.Country == order.ShippingAddress.Country
                          select rs).SingleOrDefault();

            return result;

        }
        /// <summary>
        /// Processes a coupon for an order
        /// </summary>
        public void ProcessCoupon(string couponCode, Order order) {
            
            //get the incentive
            IIncentive i = GetIncentive(couponCode);

            if (i != null) {
                IIncentive check = order.IncentivesUsed.Where(x => x.Code.Equals(couponCode, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();
                if (check==null) {

                    //make sure it's valid
                    //this will throw
                    //let it
                    i.ValidateUse(order);
                    i.Coupon.ApplyCoupon(order);
                    order.IncentivesUsed.Add(i);
                    order.DiscountReason = "Coupon " + couponCode + " applied";
                }
            }
        }
        public Transaction Authorize(Order order)
        {
            

            //this is where you would structure a call to a payment processor
            //of your choice - like Verisign, PayPal, etc
            //an authorization is just that - not an actual movement of money
            //legally you are only allowed to transact money
            //when the shippable goods have been shipped

            
            //the credit card number and information is on the order
            CreditCard card = order.PaymentMethod as CreditCard;

            //run the auth here, with the data from the order, as needed

            string authCode = "XYZ" + Guid.NewGuid().ToString().Substring(0, 10);


            return new Transaction(order.ID, order.Total, authCode, TransactionProcessor.FakePaymentProcessor);

        }
        public void ChargeOrder(Order order)
        {

            //issue the capture order to the payment service
            //and add the transaction to the order
            //this gets saved on Submit
            if (order.Transactions == null)
                order.Transactions = new LazyList<Transaction>();

            //pull this order and make sure it's not already transacted/charged
            CheckOrderForPayments(order);

            Transaction t = _paymentService.Capture(order);
            CreateTransaction(order, t.AuthorizationCode, t.Amount, t.Processor);

            //set the status of the order to "Charged"
            order.Status = OrderStatus.Charged;

            _orderService.SaveOrder(order);

            
        }
        public Mailer GetMailerForOrder(Order order, MailerType mailType) {
            //pull the template
            Mailer mailer = GetMailer(mailType, order.UserLanguageCode);


            //format it
            //this will change, for sure
            //need some better injection method
            string storeName=System.Configuration.ConfigurationManager.AppSettings["StoreName"].ToString();
            string storeReplyTo=System.Configuration.ConfigurationManager.AppSettings["StoreEmail"].ToString();
            
            mailer.Body = mailer.Body.Replace("#STORENAME#", storeName)
                .Replace("#USERNAME#",order.ShippingAddress.FullName)
                .Replace("#ORDERLINK#",System.IO.Path.Combine(_orderAbsoluteRoot,order.ID.ToString()));

            mailer.FromEmailAddress = storeReplyTo;
            mailer.ToEmailAddress = order.ShippingAddress.Email;
            mailer.UserName = order.UserName;
            mailer.Status = MailerStatus.Queued;

            return mailer;
        }
 public void Order_Should_Have_OrderStatus_SetTo_NotCheckedOut_OnCreation() {
     Order order = new Order("testuser");
     Assert.AreEqual(OrderStatus.NotCheckoutOut, order.Status);
 }
 public void Order_Should_Have_Billing_And_Shipping_Addresses_SetTo_Null_OnCreation() {
     Order order = new Order("testuser");
     Assert.IsNull(order.ShippingAddress);
 }
        private static void CreateSqlOrder()
        {
            using (var uow = CommerceModelUnitOfWork.UnitOfWork()) {
                //lets grab up a few products.
                var products = new List<Product>();
                var asinList = new string[] {"B00000J1EQ",
                                        "B00002CF9M",
                                        "B00002S932",
                                        "B00004UE3D",
                                        "B00004XSAE" };

                foreach (var asin in asinList) {
                    var query = Query<Product>
                        .Where(item => item.Asin == asin);
                    var product = uow.Products.FirstOrDefault(item => item.Asin == asin);
                    products.Add(product);
                }

                var customer = new Customer() {
                    Address1 = "123 Main Street",
                    City = "Simpsonville",
                    Country = "US",
                    Email = "*****@*****.**",
                    FirstName = "John",
                    LastName = "Doe",
                    Phone = "555-867-5309",
                    StateOrProvince = "SC"
                };

                uow.Add(customer);

                var order = new Order() {
                    Customer = customer,
                    OrderDate = DateTime.Now,
                    ShipTo = customer,
                    Status = (int)OrderStatus.New
                };

                uow.Add(order);

                foreach (var product in products) {
                    var orderDetail = new OrderDetail() {
                        Order = order,
                        Product = product,
                        OrderedQuantity = 2,
                        Quantity = 2,
                        UnitPrice = 19.95m
                    };
                    uow.Add(orderDetail);
                }
                uow.SaveChanges();
            }
        }
        public void ShipOrder(Order order,
            string trackingNumber, DateTime estimatedDelivery) {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("OrderServiceInterface", _orderService);
            parameters.Add("MailerServiceInterface", _mailerService);
            parameters.Add("CustomerOrder", order);
            parameters.Add("TrackingNumber", trackingNumber);
            parameters.Add("EstimatedDelivery", estimatedDelivery);

            WorkflowInstance instance = WFRuntimeInstance.CreateWorkflow(
                typeof(Commerce.Pipelines.ShipOrderWorkflow), parameters);

            instance.Start();
        }
        public void ApplyCoupon(Order order) {

            //set the discount on the order
            order.DiscountAmount = AmountOff;

        }
        public void AcceptPalPayment(Order order, string transactionID, decimal payment) {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("OrderServiceInterface", _orderService);
            parameters.Add("MailerServiceInterface", _mailerService);
            parameters.Add("PaymentServiceInterface", _paymentService);
            parameters.Add("InventoryServiceInterface", _inventoryService);
            parameters.Add("CustomerOrder", order);
            parameters.Add("PayPalTransactionID", transactionID);
            parameters.Add("AmountPaid", payment);

            WorkflowInstance instance = WFRuntimeInstance.CreateWorkflow(
                typeof(Commerce.Pipelines.WindowsWorkflow.AcceptPayPalWorkflow), parameters);

            instance.Start();
        }
 public void SaveOrder(Order order)
 {
     _order = order;
 }
        ActionResult ValidateShippingAndRedirect(Order order) {
            
            bool isValid = false;
            
            try {
                _addressValidator.VerifyAddress(order.ShippingAddress);
                isValid = true;

            } catch {
                this.SetErrorMessage("Please check the address you've entered; it appears invalid");
            }

            if (isValid) {
                
                //put it in TempData
                PutTempOrder(order);
                //send them off...
                return RedirectToAction("CreditCard");
            
            } else {
                OrderData data = new OrderData();
                data.CurrentOrder = order;
                return View("Shipping", order);
            }

        }
 void PutTempOrder(Order order) {
     TempData["order"] = order;
 }
 public void SaveItems(Order order) {
     _order = order;
 }