public void OrderSystem_GetPurchaseOrderTest() { Cart cart = CreateShoppingCart(); cart.OrderForms[0].LineItems[0].Discounts.Add(OrderHelper.CreateLineItemDiscount()); ShipmentDiscount discount = new ShipmentDiscount(); discount.DiscountAmount = 10; discount.DiscountId = 1; discount.DiscountName = "asas"; discount.DiscountValue = 10; discount.DisplayMessage = "asdasd"; ShipmentDiscount discount2 = new ShipmentDiscount(); discount2.DiscountAmount = 10; discount2.DiscountId = 2; discount2.DiscountName = "asas"; discount2.DiscountValue = 10; discount2.DisplayMessage = "asdasd"; cart.OrderForms[0].Shipments[0].Discounts.Add(discount); cart.OrderForms[0].Shipments[0].Discounts.Add(discount2); int cartLineItemDiscountCount = cart.OrderForms[0].LineItems[0].Discounts.Count; PurchaseOrder po = cart.SaveAsPurchaseOrder(); po.AcceptChanges(); // Reload cart from database PurchaseOrder po2 = OrderContext.Current.GetPurchaseOrder(po.CustomerId, po.OrderGroupId); int po1ShipmentDiscountsCount = po.OrderForms[0].Shipments[0].Discounts.Count; int po2ShipmentDiscountsCount = po2.OrderForms[0].Shipments[0].Discounts.Count; int po2LineItemDiscountCount = po2.OrderForms[0].LineItems[0].Discounts.Count; // Now remove discounts and add them again foreach (ShipmentDiscount dis in po2.OrderForms[0].Shipments[0].Discounts) { dis.Delete(); } po2.OrderForms[0].Shipments[0].Discounts.Add(discount); po2.OrderForms[0].Shipments[0].Discounts.Add(discount2); po2.AcceptChanges(); // Remove created stuff cart.Delete(); cart.AcceptChanges(); po2.Delete(); po2.AcceptChanges(); Assert.AreEqual(po1ShipmentDiscountsCount, po2ShipmentDiscountsCount); Assert.AreEqual(cartLineItemDiscountCount, po2LineItemDiscountCount); }
public void CreateUpdateCustomer(PurchaseOrder order, IIdentity identity) { // try catch so this does not interrupt the order process. try { var billingAddress = order.OrderAddresses.FirstOrDefault(x => x.Name == Constants.Order.BillingAddressName); var shippingAddress = order.OrderAddresses.FirstOrDefault(x => x.Name == Constants.Order.ShippingAddressName); // create customer if anonymous, or update join customer club and selected values on existing user MembershipUser user = null; if (!identity.IsAuthenticated) { string email = null; if (billingAddress != null) { email = billingAddress.Email.Trim(); user = Membership.GetUser(email); } if (user == null) { var customer = CreateCustomer(email, Guid.NewGuid().ToString(), billingAddress.DaytimePhoneNumber, billingAddress, shippingAddress, false, createStatus => Log.Error("Failed to create user during order completion. " + createStatus.ToString())); if (customer != null) { order.CustomerId = Guid.Parse(customer.PrimaryKeyId.Value.ToString()); order.CustomerName = customer.FirstName + " " + customer.LastName; order.AcceptChanges(); SetExtraCustomerProperties(order, customer); _emailService.SendWelcomeEmail(billingAddress.Email); } } else { var customer = CustomerContext.Current.GetContactForUser(user); order.CustomerName = customer.FirstName + " " + customer.LastName; order.CustomerId = Guid.Parse(customer.PrimaryKeyId.Value.ToString()); order.AcceptChanges(); SetExtraCustomerProperties(order, customer); } } else { user = Membership.GetUser(identity.Name); var customer = CustomerContext.Current.GetContactForUser(user); SetExtraCustomerProperties(order, customer); } } catch (Exception ex) { // Log here Log.Error("Error during creating / update user", ex); } }
protected void OnPaymentComplete(PurchaseOrder order) { // Create customer if anonymous CreateUpdateCustomer(order, User.Identity); var shipment = order.OrderForms.First().Shipments.First(); OrderStatusManager.ReleaseOrderShipment(shipment); OrderStatusManager.PickForPackingOrderShipment(shipment); order.AcceptChanges(); // Send Email receipt bool sendOrderReceiptResult = SendOrderReceipt(order); _log.Debug("Sending receipt e-mail - " + (sendOrderReceiptResult ? "success" : "failed")); try { // Not extremely important that this succeeds. // Stocks are continually adjusted from ERP. AdjustStocks(order); } catch (Exception e) { _log.Error("Error adjusting inventory after purchase.", e); } ForwardOrderToErp(order); }
public void CompleteShipment(int purchaseOrderId) { PurchaseOrder order = OrderContext.Current.GetPurchaseOrderById(purchaseOrderId); if (order == null || order.OrderForms.Count == 0) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); } if (order.OrderForms.Count > 1) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotImplemented) { ReasonPhrase = "Orderform contains more than one form, this is not supported by the API." }); } ShipmentCollection shipments = order.OrderForms[0].Shipments; if (shipments.Count > 1) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotImplemented) { ReasonPhrase = "Orderform contains more than one shipment, this is not supported by the API." }); } // Set status and run workflows OrderStatusManager.CompleteOrderShipment(shipments[0]); // Workflows could have changed the order order.AcceptChanges(); }
/// <summary> /// Creates a purchase order with the given order number and deletes the cart /// </summary> /// <param name="cart">Cart</param> /// <param name="payment">Payment</param> /// <param name="orderNumber">orderNumber</param> /// <returns>Boolean indicating success or failure</returns> private bool CreatePurchaseOrder(Cart cart, Payment payment, string orderNumber) { try { using (TransactionScope scope = new TransactionScope()) { PaymentStatusManager.ProcessPayment(payment); cart.OrderNumberMethod = c => orderNumber; PurchaseOrder purchaseOrder = cart.SaveAsPurchaseOrder(); cart.Delete(); cart.AcceptChanges(); purchaseOrder.AcceptChanges(); scope.Complete(); } return(true); } catch (Exception e) { // Add your own logging return(false); } }
public void OrderSystem_UnitTest_Payments_GiftCardSucceed() { // Creating cart fails Cart cart = OrderHelper.CreateCartSimple(Guid.NewGuid()); cart.OrderForms[0].Payments.Clear(); cart.OrderForms[0].Payments.Add(OrderHelper.CreateGiftCardPayment()); cart.AcceptChanges(); cart.RunWorkflow("CartValidate"); cart.RunWorkflow("CartPrepare"); cart.OrderForms[0].Payments[0].Amount = cart.Total; cart.RunWorkflow("CartCheckout"); cart.AcceptChanges(); PurchaseOrder po = cart.SaveAsPurchaseOrder(); po = OrderContext.Current.GetPurchaseOrder(po.CustomerId, po.OrderGroupId); // Validate purchase order Assert.AreEqual(po.OrderForms[0].Payments.Count, 1); // Delete PO po.Delete(); po.AcceptChanges(); // Assert that PO is deleted Assert.IsTrue(po.ObjectState == MetaObjectState.Deleted); // Delete cart cart.Delete(); cart.AcceptChanges(); // Assert that cart is deleted Assert.IsTrue(cart.ObjectState == MetaObjectState.Deleted); }
/// <summary> /// Sends the order noticfication and confirmation. /// </summary> /// <param name="order">The order.</param> /// <param name="email">The email.</param> /// <returns></returns> protected bool SendOrderNotificationAndConfirmation(PurchaseOrder order, string email) { try { // Add input parameter var dic = new Dictionary <string, object>() { { "OrderGroup", order } }; // Send out emails // Create smtp client var client = new SmtpClient(); var msg = new MailMessage(); msg.From = new MailAddress(_storeEmail, _storeTitle); msg.IsBodyHtml = true; // Send confirmation email msg.Subject = String.Format("{0}: Order Confirmation for {1}", _storeTitle, order.CustomerName); msg.To.Add(new MailAddress(email, order.CustomerName)); msg.Body = TemplateService.Process("order-purchaseorder-confirm", Thread.CurrentThread.CurrentCulture, dic); // send email client.Send(msg); AddNoteToPurchaseOrder("Order notification send to {0}", order, email); order.AcceptChanges(); return(true); } catch (Exception ex) { log.LogManager.GetLogger(this.GetType()).Error(ex.Message, ex); return(false); } }
public int PlaceCartForQuoteById(int orderId, Guid userId) { PurchaseOrder purchaseOrder = null; try { var referedOrder = _orderRepository.Load <IPurchaseOrder>(orderId); var cart = _orderRepository.LoadOrCreateCart <ICart>(userId, "RequstQuoteFromOrder"); foreach (var lineItem in referedOrder.GetFirstForm().GetAllLineItems()) { var newLineItem = lineItem; newLineItem.Properties[Constant.Quote.PreQuotePrice] = lineItem.PlacedPrice; cart.AddLineItem(newLineItem); } cart.Currency = referedOrder.Currency; cart.MarketId = referedOrder.MarketId; var orderReference = _orderRepository.SaveAsPurchaseOrder(cart); purchaseOrder = _orderRepository.Load <PurchaseOrder>(orderReference.OrderGroupId); if (purchaseOrder != null) { _ = int.TryParse(ConfigurationManager.AppSettings[Constant.Quote.QuoteExpireDate], out var quoteExpireDays); purchaseOrder[Constant.Quote.QuoteExpireDate] = string.IsNullOrEmpty(ConfigurationManager.AppSettings[Constant.Quote.QuoteExpireDate]) ? DateTime.Now.AddDays(30) : DateTime.Now.AddDays(quoteExpireDays); purchaseOrder[Constant.Quote.PreQuoteTotal] = purchaseOrder.Total; purchaseOrder[Constant.Quote.QuoteStatus] = Constant.Quote.RequestQuotation; purchaseOrder.Status = OrderStatus.OnHold.ToString(); if (string.IsNullOrEmpty(purchaseOrder[Constant.Customer.CustomerFullName]?.ToString())) { if (CustomerContext.Current != null && CustomerContext.Current.CurrentContact != null) { var contact = CustomerContext.Current.CurrentContact; purchaseOrder[Constant.Customer.CustomerFullName] = contact.FullName; purchaseOrder[Constant.Customer.CustomerEmailAddress] = contact.Email; var org = _organizationService.GetCurrentFoundationOrganization(); if (org != null) { purchaseOrder[Constant.Customer.CurrentCustomerOrganization] = org.Name; } } } } purchaseOrder.AcceptChanges(); _orderRepository.Delete(cart.OrderLink); } catch (Exception ex) { LogManager.GetLogger(GetType()).Error("Failed to process request quote request.", ex); } return(purchaseOrder?.Id ?? 0); }
public void CreateUpdateCustomer(PurchaseOrder order, IIdentity identity) { // try catch so this does not interrupt the order process. try { var billingAddress = order.OrderAddresses.FirstOrDefault(x => x.Name == Constants.Order.BillingAddressName); var shippingAddress = order.OrderAddresses.FirstOrDefault(x => x.Name == Constants.Order.ShippingAddressName); // create customer if anonymous, or update join customer club and selected values on existing user MembershipUser user = null; if (!identity.IsAuthenticated) { string email = billingAddress.Email.Trim(); user = Membership.GetUser(email); if (user == null) { var customer = CreateCustomer(email, Guid.NewGuid().ToString(), billingAddress.DaytimePhoneNumber, billingAddress, shippingAddress, false, createStatus => Log.Error("Failed to create user during order completion. " + createStatus.ToString())); if (customer != null) { order.CustomerId = Guid.Parse(customer.PrimaryKeyId.Value.ToString()); order.CustomerName = customer.FirstName + " " + customer.LastName; order.AcceptChanges(); SetExtraCustomerProperties(order, customer); _emailService.SendWelcomeEmail(billingAddress.Email); } } else { var customer = CustomerContext.Current.GetContactForUser(user); order.CustomerName = customer.FirstName + " " + customer.LastName; order.CustomerId = Guid.Parse(customer.PrimaryKeyId.Value.ToString()); order.AcceptChanges(); SetExtraCustomerProperties(order, customer); } } else { user = Membership.GetUser(identity.Name); var customer = CustomerContext.Current.GetContactForUser(user); SetExtraCustomerProperties(order, customer); } } catch (Exception ex) { // Log here Log.Error("Error during creating / update user", ex); } }
/// <summary> /// Copy notes from cart to purchse order /// </summary> /// <param name="purchaseOrder"></param> /// <param name="cart"></param> private void CopyNotesFromCartToPurchaseOrder(PurchaseOrder purchaseOrder, Mediachase.Commerce.Orders.Cart cart) { foreach (var note in cart.OrderNotes.OrderByDescending(n => n.Created)) { OrderNote on = purchaseOrder.OrderNotes.AddNew(); on.Detail = note.Detail; on.Title = note.Title; on.Type = OrderNoteTypes.System.ToString(); on.Created = note.Created; on.CustomerId = note.CustomerId; } purchaseOrder.AcceptChanges(); }
public void OrderSystem_CreateRandomOrder() { Cart cart = OrderContext.Current.GetCart(Cart.DefaultName, Guid.NewGuid()); String customerFullName = _customerNames[_random.Next(0, _customerNames.Length - 1)]; int space = customerFullName.IndexOf(' '); String customerFirstName = customerFullName.Substring(0, space); String customerLastName = customerFullName.Substring(space + 1); //String customerHomeId = customerFullName + "\'s " + "Home"; cart.CustomerName = customerFullName; cart.BillingCurrency = CommonSettingsManager.GetDefaultCurrency(); cart.OrderAddresses.Add(OrderHelper.CreateAddress()); cart.OrderAddresses[0].Name = "Home"; cart.OrderAddresses[0].FirstName = customerFirstName; cart.OrderAddresses[0].LastName = customerLastName; OrderForm orderForm = new OrderForm(); orderForm.Name = "default"; // Randomly pick a shipping method. Mediachase.Commerce.Orders.Dto.ShippingMethodDto smd = Mediachase.Commerce.Orders.Managers.ShippingManager.GetShippingMethods("en-us"); int shippingMethod = _random.Next(smd.ShippingMethod.Count); Guid shippingMethodId = smd.ShippingMethod[shippingMethod].ShippingMethodId; String shippingMethodName = smd.ShippingMethod[shippingMethod].Name; // Add line items // Random number of line items in an order int itemNum = _random.Next(3, 10); for (int i = 0; i < itemNum; i++) { orderForm.LineItems.Add(createLineItem(_random, shippingMethodId, shippingMethodName)); } // Add payments // Pay by phone orderForm.Payments.Add(OrderHelper.CreateInvoicePayment()); // Pay by credit card (sends out emails) //orderForm.Payments.Add(OrderHelper.CreateCreditCardPayment()); // Add discounts orderForm.Discounts.Add(OrderHelper.CreateOrderFormDiscount()); cart.OrderForms.Add(orderForm); cart.OrderForms[0].BillingAddressId = cart.OrderAddresses[0].Name; cart.RunWorkflow("CartValidate"); cart.RunWorkflow("CartPrepare"); cart.OrderForms[0].Payments[0].Amount = cart.Total; cart.RunWorkflow("CartCheckout"); // Last step PurchaseOrder po = cart.SaveAsPurchaseOrder(); // Randomize created date and time po.OrderForms[0].Created = randomDate(); // Randomize order status po.Status = randomStatus(); po.AcceptChanges(); }
//Exercise (E2) Do CheckOut public ActionResult CheckOut(CheckOutViewModel model) { // ToDo: declare a variable for CartHelper CartHelper ch = new CartHelper(Cart.DefaultName); int orderAddressId = 0; // ToDo: Addresses (an If-Else) if (CustomerContext.Current.CurrentContact == null) { // Anonymous... one way of "doing it"... for example, if no other address exist orderAddressId = ch.Cart.OrderAddresses.Add( new OrderAddress { CountryCode = "SWE", CountryName = "Sweden", Name = "SomeCustomerAddress", DaytimePhoneNumber = "123456", FirstName = "John", LastName = "Smith", Email = "*****@*****.**", }); } else { // Logged in if (CustomerContext.Current.CurrentContact.PreferredShippingAddress == null) { // no pref. address set... so we set one for the contact CustomerAddress newCustAddress = CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId); newCustAddress.AddressType = CustomerAddressTypeEnum.Shipping; // mandatory newCustAddress.ContactId = CustomerContext.Current.CurrentContact.PrimaryKeyId; newCustAddress.CountryCode = "SWE"; newCustAddress.CountryName = "Sweden"; newCustAddress.Name = "new customer address"; // mandatory newCustAddress.DaytimePhoneNumber = "123456"; newCustAddress.FirstName = CustomerContext.Current.CurrentContact.FirstName; newCustAddress.LastName = CustomerContext.Current.CurrentContact.LastName; newCustAddress.Email = "*****@*****.**"; // note: Line1 & City is what is shown in CM at a few places... not the Name CustomerContext.Current.CurrentContact.AddContactAddress(newCustAddress); CustomerContext.Current.CurrentContact.SaveChanges(); // ... needs to be in this order CustomerContext.Current.CurrentContact.PreferredShippingAddress = newCustAddress; CustomerContext.Current.CurrentContact.SaveChanges(); // need this ...again // then, for the cart orderAddressId = ch.Cart.OrderAddresses.Add(new OrderAddress(newCustAddress)); } else { // there is a preferred address set (and, a fourth alternative exists... do later ) OrderAddress orderAddress = new OrderAddress(CustomerContext.Current.CurrentContact.PreferredShippingAddress); // then, for the cart orderAddressId = ch.Cart.OrderAddresses.Add(orderAddress); } } // Depending how it was created... OrderAddress address = ch.FindAddressById(orderAddressId.ToString()); // ToDo: Define Shipping ShippingMethodDto.ShippingMethodRow theShip = ShippingManager.GetShippingMethod(model.SelectedShipId).ShippingMethod.First(); int shippingId = ch.Cart.OrderForms[0].Shipments.Add( new Shipment { // ...removing anything? ShippingAddressId = address.Name, // note: use no custom prefixes ShippingMethodId = theShip.ShippingMethodId, ShippingMethodName = theShip.Name, ShipmentTotal = theShip.BasePrice, ShipmentTrackingNumber = "My tracking number", }); // get the Shipping ... check to see if the Shipping knows about the LineItem Shipment firstOrderShipment = ch.Cart.OrderForms[0].Shipments.FirstOrDefault(); // First (and only) OrderForm LineItemCollection lineItems = ch.Cart.OrderForms[0].LineItems; // ...basic now... one OrderForm - one Shipping foreach (LineItem lineItem in lineItems) { int index = lineItems.IndexOf(lineItem); if ((firstOrderShipment != null) && (index != -1)) { firstOrderShipment.AddLineItemIndex(index, lineItem.Quantity); } } // Execute the "Shipping & Taxes - WF" (CartPrepare) ... and take care of the return object WorkflowResults resultPrepare = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartPrepareWorkflowName); List <string> wfMessagesPrepare = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultPrepare)); // ToDo: Define Shipping PaymentMethodDto.PaymentMethodRow thePay = PaymentManager.GetPaymentMethod(model.SelectedPayId).PaymentMethod.First(); Payment firstOrderPayment = ch.Cart.OrderForms[0].Payments.AddNew(typeof(OtherPayment)); // ... need both below firstOrderPayment.Amount = firstOrderShipment.SubTotal + firstOrderShipment.ShipmentTotal; // will change... firstOrderPayment.BillingAddressId = address.Name; firstOrderPayment.PaymentMethodId = thePay.PaymentMethodId; firstOrderPayment.PaymentMethodName = thePay.Name; // ch.Cart.CustomerName = "John Smith"; // ... this line overwrites what´s in there, if logged in // Execute the "Payment activation - WF" (CartCheckout) ... and take care of the return object // ...activates the gateway (same for shipping) WorkflowResults resultCheckout = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartCheckOutWorkflowName, false); List <string> wfMessagesCheckout = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultCheckout)); //ch.RunWorkflow("CartValidate") ... can see this (or variations) string trackingNumber = String.Empty; PurchaseOrder purchaseOrder = null; // Add a transaction scope and convert the cart to PO using (var scope = new Mediachase.Data.Provider.TransactionScope()) { purchaseOrder = ch.Cart.SaveAsPurchaseOrder(); ch.Cart.Delete(); ch.Cart.AcceptChanges(); trackingNumber = purchaseOrder.TrackingNumber; scope.Complete(); } // Housekeeping below (Shipping release, OrderNotes and save the order) OrderStatusManager.ReleaseOrderShipment(purchaseOrder.OrderForms[0].Shipments[0]); OrderNotesManager.AddNoteToPurchaseOrder(purchaseOrder, DateTime.UtcNow.ToShortDateString() + " released for shipping", OrderNoteTypes.System, CustomerContext.Current.CurrentContactId); purchaseOrder.ExpirationDate = DateTime.UtcNow.AddDays(30); purchaseOrder.Status = OrderStatus.InProgress.ToString(); purchaseOrder.AcceptChanges(); // need this here, else no "order-note" persisted // Final steps, navigate to the order confirmation page StartPage home = _contentLoader.Service.Get <StartPage>(ContentReference.StartPage); ContentReference orderPageReference = home.Settings.orderPage; string passingValue = trackingNumber; return(RedirectToAction("Index", new { node = orderPageReference, passedAlong = passingValue })); }