public void GetAll_AllOrdersCanListed() { IOrderStatusService service = new OrderStatusManager(_mockOrderStatusDal.Object); List <OrderStatus> orderStatuses = service.GetAll().Data; Assert.AreEqual(2, orderStatuses.Count); }
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(); }
private bool ProcessFraudUpdate(IPayment payment, IOrderGroup orderGroup, ref string message) { if (payment.Properties[Common.Constants.FraudStatusPaymentField]?.ToString() == NotificationFraudStatus.FRAUD_RISK_ACCEPTED.ToString()) { payment.Status = PaymentStatus.Processed.ToString(); OrderStatusManager.ReleaseHoldOnOrder((PurchaseOrder)orderGroup); AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Klarna fraud risk accepted"); return(true); } else if (payment.Properties[Common.Constants.FraudStatusPaymentField]?.ToString() == NotificationFraudStatus.FRAUD_RISK_REJECTED.ToString()) { payment.Status = PaymentStatus.Failed.ToString(); AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Klarna fraud risk rejected"); return(false); } else if (payment.Properties[Common.Constants.FraudStatusPaymentField]?.ToString() == NotificationFraudStatus.FRAUD_RISK_STOPPED.ToString()) { //TODO Fraud status stopped payment.Status = PaymentStatus.Failed.ToString(); AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Klarna fraud risk stopped"); return(false); } message = $"Can't process authorization. Unknown fraud notitication: {payment.Properties[Common.Constants.FraudStatusPaymentField]} or no fraud notifications received so far."; return(false); }
private PaymentStepResult ProcessFraudUpdate(IPayment payment, IOrderGroup orderGroup) { var paymentStepResult = new PaymentStepResult(); if (payment.HasFraudStatus(NotificationFraudStatus.FRAUD_RISK_ACCEPTED)) { payment.Status = PaymentStatus.Processed.ToString(); OrderStatusManager.ReleaseHoldOnOrder((PurchaseOrder)orderGroup); AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Klarna fraud risk accepted"); paymentStepResult.Status = true; return(paymentStepResult); } if (payment.HasFraudStatus(NotificationFraudStatus.FRAUD_RISK_REJECTED)) { payment.Status = PaymentStatus.Failed.ToString(); OrderStatusManager.HoldOrder((PurchaseOrder)orderGroup); AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Klarna fraud risk rejected"); paymentStepResult.Status = true; return(paymentStepResult); } if (payment.HasFraudStatus(NotificationFraudStatus.FRAUD_RISK_STOPPED)) { payment.Status = PaymentStatus.Failed.ToString(); OrderStatusManager.HoldOrder((PurchaseOrder)orderGroup); AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Klarna fraud risk stopped"); paymentStepResult.Status = true; return(paymentStepResult); } paymentStepResult.Message = $"Can't process authorization. Unknown fraud notification: {payment.Properties[Common.Constants.FraudStatusPaymentField]} or no fraud notifications received so far."; return(paymentStepResult); }
private void SetOrderStatus(IPurchaseOrder purchaseOrder, IPayment payment) { if (payment.HasFraudStatus(FraudStatus.PENDING)) { OrderStatusManager.HoldOrder((PurchaseOrder)purchaseOrder); _orderRepository.Save(purchaseOrder); } }
public override void DataBind() { OrderGroup paymentPlanById; if (base.Request.QueryString["_v"].Equals("PaymentPlan-ObjectView")) { paymentPlanById = OrderHelper.GetPaymentPlanById(PrincipalInfo.CurrentPrincipal.GetContactId(), this.OrderGroupId); } else { paymentPlanById = OrderHelper.GetPurchaseOrderById(this.OrderGroupId); } OrderGroup orderGroup = paymentPlanById; Shipment dataItem = null; ObjectRepeaterDataItem objectRepeaterDataItem = this.DataItem as ObjectRepeaterDataItem; if (objectRepeaterDataItem != null && objectRepeaterDataItem.DataItem != null) { dataItem = (Shipment)objectRepeaterDataItem.DataItem; this._shipmentId = dataItem.Id; this.btnShipmentStatus.ContainerId = dataItem.Id.ToString(); this.btnShipmentStatus.DataBind(); this.ReturnExchangeButtonsHolder.ContainerId = dataItem.Id.ToString(); this.ReturnExchangeButtonsHolder.DataBind(); this.CompletePickupButton.ContainerId = dataItem.Id.ToString(); this.CompletePickupButton.DataBind(); } if (dataItem != null) { OrderShipmentStatus orderShipmentStatus = OrderStatusManager.GetOrderShipmentStatus(dataItem); this.lblShipStatus.Text = (string)base.GetGlobalResourceObject("OrderStrings", string.Concat(typeof(OrderShipmentStatus).Name, "_", orderShipmentStatus.ToString())); Currency currency = new Currency(orderGroup.BillingCurrency); decimal num = ((IEnumerable <ILineItem>)dataItem.LineItems.ToArray <ILineItem>()).Sum <ILineItem>((ILineItem x) => x.TryGetDiscountValue((ILineItemDiscountAmount y) => y.OrderAmount)); Label str = this.lblItemsSubTotal; Money money = new Money(dataItem.SubTotal + num, currency); //str.Text = money.ToString(); Label label = this.lblOrderLevelDiscount; money = new Money(num, currency); //label.Text = money.ToString(); Label str1 = this.lblOrderSubTotal; money = new Money(dataItem.SubTotal, currency); //str1.Text = money.ToString(); Label label1 = this.lblShippingCost; money = new Money(dataItem.ShippingSubTotal, currency); label1.Text = money.ToString(); Label str2 = this.lblShippingDiscount; money = new Money(dataItem.ShippingDiscountAmount, currency); str2.Text = money.ToString(); Label label2 = this.lblShippingTax; money = new Money(dataItem.ShippingTax, currency); label2.Text = money.ToString(); Label str3 = this.lblShipTotal; money = new Money(((dataItem.SubTotal + dataItem.ShippingSubTotal) + dataItem.ShippingTax) - dataItem.ShippingDiscountAmount, currency); str3.Text = money.ToString(); } }
private void SetOrderStatus(IPurchaseOrder purchaseOrder, IPayment payment) { var fraudStatus = payment.Properties[Common.Constants.FraudStatusPaymentField]?.ToString(); if (fraudStatus == FraudStatus.PENDING.ToString()) { OrderStatusManager.HoldOrder((PurchaseOrder)purchaseOrder); _orderRepository.Save(purchaseOrder); } }
public virtual IPurchaseOrder ProcessOnHoldOrder(int purchaseOrderId, string transaction_id) { var transaction = _requestsHelper.GetTransactionDetails(transaction_id); if (transaction == null) { Logger.Debug($"Unable to get Dintero transaction by id: {transaction_id}!"); } else { var purchaseOrder = PurchaseOrder.LoadByOrderGroupId(purchaseOrderId); Logger.Debug($"DinteroPaymentGateway.ProcessOnHoldOrder: Dintero transaction status: {transaction.Status}. Order status: {purchaseOrder.Status}."); if (transaction.Status == "FAILED") { OrderStatusManager.CancelOrder(purchaseOrder); } else if (transaction.Status == "AUTHORIZED") { Logger.Debug($"Releasing order and shipment {purchaseOrder.TrackingNumber}!"); OrderStatusManager.ReleaseHoldOnOrder(purchaseOrder); var order = (IPurchaseOrder)purchaseOrder; //order.OrderStatus = OrderStatus.InProgress; if (order.Forms != null && order.Forms.Any()) { var orderForm = order.Forms.FirstOrDefault(); if (orderForm != null) { foreach (var shipment in orderForm.Shipments) { if (shipment is Shipment s && CanHoldShipmentBeReleased(s)) { OrderStatusManager.PickForPackingOrderShipment(s); } } } } var orderRepository = ServiceLocator.Current.GetInstance <IOrderRepository>(); orderRepository.Save(purchaseOrder); PostProcessPayment.PostReleaseOnHold(purchaseOrder.TrackingNumber); Logger.Debug($"Order {purchaseOrder.TrackingNumber} was released!"); } purchaseOrder.AcceptChanges(); Logger.Debug("DinteroPaymentGateway.ProcessOnHoldOrder completed."); return(purchaseOrder); } return(null); }
private void BindCancelStatusesDropDown() { ddlCancelStatus.DataSource = OrderStatusManager.GetOrderStatus(); ddlCancelStatus.DataBind(); if (ddlCancelStatus.Items.Count == 0) { ddlCancelStatus.Items.Clear(); ddlCancelStatus.Items.Add(new ListItem(Mediachase.Ibn.Web.UI.WebControls.UtilHelper.GetResFileString("{OrderStrings:RecurringPayment_Select_CancelStatus}"), "")); } }
private void BindDefaultTransactionTypesDropDown() { ddlCancelStatus.DataSource = OrderStatusManager.GetDefinedOrderStatuses(); ddlCancelStatus.DataBind(); if (ddlCancelStatus.Items.Count == 0) { ddlCancelStatus.Items.Clear(); ddlCancelStatus.Items.Add(new ListItem(Mediachase.BusinessFoundation.UtilHelper.GetResFileString("{OrderStrings:RecurringPayment_Select_CancelStatus}"), "")); } }
/// <summary> /// Binds the root. /// </summary> private void BindRoot() { List <JsonTreeNode> nodes = new List <JsonTreeNode>(); nodes.Add(JsonTreeNode.CreateNode("OrderSearch", String.Empty, "Order Search", ModuleName, "OrderSearch-List", String.Empty, TreeListType.OrderSearch.ToString(), true)); // PurchaseOrders node JsonTreeNode poNode = JsonTreeNode.CreateNode("PurchaseOrders", String.Empty, "Purchase Orders", ModuleName, "Orders-List", String.Empty, TreeListType.PurchaseOrders.ToString()); poNode.icon = Mediachase.Commerce.Shared.CommerceHelper.GetAbsolutePath("~/Apps/Order/images/PurchaseOrders.png"); poNode.children = new List <JsonTreeNode>(); poNode.children.Add(JsonTreeNode.CreateNode("PO-TodayOrders", "Today", ModuleName, "Orders-List", "filter=today&class=PurchaseOrder", true)); poNode.children.Add(JsonTreeNode.CreateNode("PO-WeekOrders", "This Week", ModuleName, "Orders-List", "filter=thisweek&class=PurchaseOrder", true)); poNode.children.Add(JsonTreeNode.CreateNode("PO-MonthOrders", "This Month", ModuleName, "Orders-List", "filter=thismonth&class=PurchaseOrder", true)); poNode.children.Add(JsonTreeNode.CreateNode("PO-AllOrders", "All", ModuleName, "Orders-List", "filter=all&class=PurchaseOrder", true)); nodes.Add(poNode); // PurchaseOrdersByStatus node JsonTreeNode posNode = JsonTreeNode.CreateNode("PurchaseOrdersByStatus", String.Empty, "Purchase Orders By Status", ModuleName, "Orders-List", String.Empty, TreeListType.PurchaseOrdersByStatus.ToString()); posNode.children = new List <JsonTreeNode>(); OrderStatusDto statusDto = OrderStatusManager.GetOrderStatus(); foreach (OrderStatusDto.OrderStatusRow statusRow in statusDto.OrderStatus.Rows) { posNode.children.Add(JsonTreeNode.CreateNode("PO-Status-" + statusRow.OrderStatusId, statusRow.Name, ModuleName, "Orders-List", String.Format("status={0}", statusRow.Name), true)); } nodes.Add(posNode); // Carts node JsonTreeNode cartsNode = JsonTreeNode.CreateNode("Carts", "Carts", ModuleName, "Orders-List", "filter=all&class=ShoppingCart", false); cartsNode.children = new List <JsonTreeNode>(); cartsNode.children.Add(JsonTreeNode.CreateNode("CART-TodayOrders", "Today", ModuleName, "Orders-List", "filter=today&class=ShoppingCart", true)); cartsNode.children.Add(JsonTreeNode.CreateNode("CART-WeekOrders", "This Week", ModuleName, "Orders-List", "filter=thisweek&class=ShoppingCart", true)); cartsNode.children.Add(JsonTreeNode.CreateNode("CART-MonthOrders", "This Month", ModuleName, "Orders-List", "filter=thismonth&class=ShoppingCart", true)); cartsNode.children.Add(JsonTreeNode.CreateNode("CART-AllOrders", "All", ModuleName, "Orders-List", "filter=all&class=ShoppingCart", true)); nodes.Add(cartsNode); // PaymentPlans node JsonTreeNode ppNode = JsonTreeNode.CreateNode("PaymentPlans", "Payment Plans (recurring)", ModuleName, "Orders-List", "filter=all&class=PaymentPlan", false); ppNode.children = new List <JsonTreeNode>(); ppNode.children.Add(JsonTreeNode.CreateNode("PP-TodayOrders", "Today", ModuleName, "Orders-List", "filter=today&class=PaymentPlan", true)); ppNode.children.Add(JsonTreeNode.CreateNode("PP-WeekOrders", "This Week", ModuleName, "Orders-List", "filter=thisweek&class=PaymentPlan", true)); ppNode.children.Add(JsonTreeNode.CreateNode("PP-MonthOrders", "This Month", ModuleName, "Orders-List", "filter=thismonth&class=PaymentPlan", true)); ppNode.children.Add(JsonTreeNode.CreateNode("PP-AllOrders", "All", ModuleName, "Orders-List", "filter=all&class=PaymentPlan", true)); nodes.Add(ppNode); WriteArray(nodes); }
/// <summary> /// Binds the purchase orders by status. /// </summary> private void BindPurchaseOrdersByStatus() { List <JsonTreeNode> nodes = new List <JsonTreeNode>(); // PurchaseOrdersByStatus node OrderStatusDto statusDto = OrderStatusManager.GetOrderStatus(); foreach (OrderStatusDto.OrderStatusRow statusRow in statusDto.OrderStatus.Rows) { nodes.Add(JsonTreeNode.CreateNode("PO-Status-" + statusRow.OrderStatusId, statusRow.Name, ModuleName, "Orders-List", String.Format("status={0}", statusRow.Name), true)); } WriteArray(nodes); }
public void FinalizeOrder(string trackingNumber, IIdentity identity) { var order = _orderRepository.GetOrderByTrackingNumber(trackingNumber); // Create customer if anonymous CreateUpdateCustomer(order, identity); var shipment = order.OrderForms.First().Shipments.First(); OrderStatusManager.ReleaseOrderShipment(shipment); OrderStatusManager.PickForPackingOrderShipment(shipment); order.AcceptChanges(); }
public void Update_UpdateOrderStatus_ReturnTrueResult() { IOrderStatusService service = new OrderStatusManager(_mockOrderStatusDal.Object); OrderStatus orderStatus = new OrderStatus { Id = 1, Name = It.IsAny <string>(), CreateDate = DateTime.Now, Active = true }; var result = service.Update(orderStatus); Assert.IsTrue(result.Success); }
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { if (base.ReturnFormStatus == ReturnFormStatus.Complete) { //Need change ExchangeOrder from AvaitingCompletition to InProgress var exchangeOrder = ReturnExchangeManager.GetExchangeOrderForReturnForm(base.ReturnOrderForm); if (exchangeOrder != null && OrderStatusManager.GetOrderGroupStatus(exchangeOrder) == OrderStatus.AwaitingExchange) { OrderStatusManager.ProcessOrder(exchangeOrder); exchangeOrder.AcceptChanges(); } } // Retun the closed status indicating that this activity is complete. return(ActivityExecutionStatus.Closed); }
public OrderedProductModelProfile(OrderStatusManager orderStatusManager, IItemManager itemManager, IOrderedManager orderedManager) { this._itemManager = itemManager; this._orderStatusManager = orderStatusManager; this._orderedManager = orderedManager; CreateMap <OrderDTO, OrderedProductModel>() .ForMember(dest => dest.OrderID, scr => scr.MapFrom(p => p.OrderID)) .ForMember(dest => dest.Ordernumber, scr => scr.MapFrom(p => p.Ordernumber)) .ForMember(dest => dest.Date, scr => scr.MapFrom(p => p.Date)) .ForMember(dest => dest.UserID, scr => scr.MapFrom(p => p.UserID)) .ForMember(dest => dest.StatusName, scr => scr.MapFrom(p => GetItemStatus(p.StatusID))) .ForMember(dest => dest.ItemID, scr => scr.MapFrom(p => GetItemIdByOrderId(p.OrderID))) .ForMember(dest => dest.ItemTitle, scr => scr.MapFrom(p => GetItemTitleByOrderId(p.OrderID))) .ForMember(dest => dest.Amount, scr => scr.MapFrom(p => GetAmmountByOrderId(p.OrderID))); }
public PurchaseOrderModel QuickBuyOrder(QuickBuyModel model, Guid customerId) { var cart = _orderRepository.LoadOrCreateCart <Cart>(customerId, Constants.Order.Cartname.Quickbuy); var item = _orderGroupFactory.CreateLineItem(model.Sku, cart); item.Quantity = 1; cart.GetFirstShipment().LineItems.Add(item); cart.GetFirstShipment().ShippingAddress = CreateAddress(model, cart, "Shipping"); if (!string.IsNullOrEmpty(model.CouponCode)) { cart.GetFirstForm().CouponCodes.Add(model.CouponCode); } cart.ValidateOrRemoveLineItems(ProcessValidationIssue); cart.UpdatePlacedPriceOrRemoveLineItems(ProcessValidationIssue); cart.UpdateInventoryOrRemoveLineItems(ProcessValidationIssue); _promotionEngine.Run(cart); cart.GetFirstForm().Payments.Add(CreateQuickBuyPayment(model, cart)); cart.GetFirstForm().Payments.FirstOrDefault().BillingAddress = CreateAddress(model, cart, "Billing"); cart.ProcessPayments(); cart.OrderNumberMethod = cart1 => GetInvoiceNumber(); var orderRef = _orderRepository.SaveAsPurchaseOrder(cart); var order = _orderRepository.Load <PurchaseOrder>(orderRef.OrderGroupId); order[Constants.Metadata.PurchaseOrder.Frequency] = model.Frequency.ToString(); order[Constants.Metadata.PurchaseOrder.LatestDelivery] = DateTime.Now.AddDays(5); OrderStatusManager.CompleteOrderShipment(order.GetFirstShipment() as Shipment); _orderRepository.Save(order); return(MapToModel(order)); }
/// <summary> /// Loads the data and data bind. /// </summary> private void LoadDataAndDataBind() { OrderStatusDto statusDto = OrderStatusManager.GetOrderStatus(); OrderStatus.DataValueField = "Name"; OrderStatus.DataSource = statusDto.OrderStatus; OrderStatus.DataBind(); OrderStatus.Items.Insert(0, new ListItem("any", "")); DataRange.Items.Clear(); DataRange.Items.Add(new ListItem(SharedStrings.All, "")); DataRange.Items.Add(new ListItem(SharedStrings.Today, "today")); DataRange.Items.Add(new ListItem(SharedStrings.This_Week, "thisweek")); DataRange.Items.Add(new ListItem(SharedStrings.This_Month, "thismonth")); StringBuilder script = new StringBuilder("this.disabled = true;\r\n"); script.AppendFormat("__doPostBack('{0}', '');", btnSearch.UniqueID); btnSearch.OnClientClick = script.ToString(); }
public void Complete(IPurchaseOrder purchaseOrder) { if (purchaseOrder == null) { throw new ArgumentNullException(nameof(purchaseOrder)); } var orderForm = purchaseOrder.GetFirstForm(); var payment = orderForm?.Payments.FirstOrDefault(x => x.PaymentMethodName.Equals(Constants.KlarnaCheckoutSystemKeyword)); if (payment == null) { return; } if (payment.HasFraudStatus(FraudStatus.PENDING)) { OrderStatusManager.HoldOrder((PurchaseOrder)purchaseOrder); _orderRepository.Save(purchaseOrder); } }
protected override void DoCommand(IOrderGroup order, CommandParameters commandParameters) { try { var purchaseOrder = order as PurchaseOrder; 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.QuoteStatus] = Constant.Quote.RequestQuotationFinished; OrderStatusManager.ReleaseHoldOnOrder(purchaseOrder); AddNoteToOrder(purchaseOrder, "OrderNote_ChangeOrderStatusPattern", purchaseOrder.Status); SavePurchaseOrderChanges(purchaseOrder); } catch (Exception ex) { LogManager.GetLogger(GetType()).Error("Failed to process request quote approve.", ex); } }
public void CreateExchangePayments() { var origPurchaseOrder = ReturnOrderForm.Parent as PurchaseOrder; var origOrderForm = origPurchaseOrder.OrderForms[0]; var exchangeOrder = ReturnExchangeManager.GetExchangeOrderForReturnForm(ReturnOrderForm); if (exchangeOrder != null) { var exchangeOrderForm = exchangeOrder.OrderForms[0]; //Exchange payments //Credit exchange payment to original order decimal paymentTotal = Math.Min(ReturnOrderForm.Total, exchangeOrder.Total); ExchangePayment creditExchangePayment = CreateExchangePayment(TransactionType.Credit, paymentTotal); origOrderForm.Payments.Add(creditExchangePayment); //Debit exchange payment to exchange order ExchangePayment debitExchangePayment = CreateExchangePayment(TransactionType.Capture, paymentTotal); exchangeOrderForm.Payments.Add(debitExchangePayment); OrderStatusManager.RecalculatePurchaseOrder(exchangeOrder); exchangeOrder.AcceptChanges(); } }
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { try { if (base.ReturnFormStatus == ReturnFormStatus.Complete) { //Need change ExchangeOrder from AvaitingCompletition to InProgress var exchangeOrder = ReturnExchangeManager.GetExchangeOrderForReturnForm(base.ReturnOrderForm); if (exchangeOrder != null && OrderStatusManager.GetOrderGroupStatus(exchangeOrder) == OrderStatus.AwaitingExchange) { OrderStatusManager.ProcessOrder(exchangeOrder); exchangeOrder.AcceptChanges(); } } // Retun the closed status indicating that this activity is complete. return(ActivityExecutionStatus.Closed); } catch (Exception ex) { Logger.Error(GetType().Name + ": " + ex.Message, ex); // An unhandled exception occured. Throw it back to the WorkflowRuntime. throw; } }
/// <summary> /// Called by the workflow runtime to execute an activity. /// </summary> /// <param name="executionContext">The <see cref="T:Mediachase.Commerce.WorkflowCompatibility.ActivityExecutionContext"/> to associate with this <see cref="T:Mediachase.Commerce.WorkflowCompatibility.Activity"/> and execution.</param> /// <returns> /// The <see cref="T:Mediachase.Commerce.WorkflowCompatibility.ActivityExecutionStatus"/> of the run task, which determines whether the activity remains in the executing state, or transitions to the closed state. /// </returns> protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { // Check for multiple warehouses. In the default, we simply reject processing an order if the application has // multiple warehouses. Any corresponding fulfillment process is the responsibility of the client. CheckMultiWarehouse(); // Validate the properties at runtime ValidateRuntime(); // Return close status if order group is Payment Plan if (OrderGroup is PaymentPlan) { return(ActivityExecutionStatus.Closed); } var orderGroupStatus = OrderStatusManager.GetOrderGroupStatus(OrderGroup); var orderForms = OrderGroup.OrderForms.Where(o => !OrderForm.IsReturnOrderForm(o)); var inventoryRequests = new List <InventoryRequestItem>(); foreach (OrderForm orderForm in orderForms) { foreach (Shipment shipment in orderForm.Shipments) { if (!ValidateShipment(orderForm, shipment)) { continue; } var shipmentStatus = OrderStatusManager.GetOrderShipmentStatus(shipment); bool completingOrder = orderGroupStatus == OrderStatus.Completed || shipmentStatus == OrderShipmentStatus.Shipped; bool cancellingOrder = orderGroupStatus == OrderStatus.Cancelled || shipmentStatus == OrderShipmentStatus.Cancelled; _logger.Debug(string.Format("Adjusting inventory, got orderGroupStatus as {0} and shipmentStatus as {1}. completingOrder as {2} and cancellingOrder as {3}.", orderGroupStatus, shipmentStatus, completingOrder, cancellingOrder)); // When completing/cancelling an order or a shipment if (completingOrder || cancellingOrder) { var requestType = completingOrder ? InventoryRequestType.Complete : InventoryRequestType.Cancel; inventoryRequests.AddRange(GetRequestInventory(shipment, inventoryRequests.Count, requestType)); // When processed request, need to clear all operation keys from the shipment shipment.ClearOperationKeys(); } // When release a shipment, check if shipment contain a BackOrder then need to complete that BackOrder. else if (shipmentStatus == OrderShipmentStatus.Released) { foreach (LineItem lineItem in Shipment.GetShipmentLineItems(shipment)) { var lineItemIndex = orderForm.LineItems.IndexOf(lineItem); var completeBackOrderRequest = new List <InventoryRequestItem>(); var lineItemRequest = GetLineItemRequestInventory(shipment, lineItemIndex, 0, InventoryRequestType.Complete); // Only need to process complete BackOrder request type foreach (var request in lineItemRequest) { InventoryRequestType requestType; InventoryChange change; _operationKeySerializer.Service.TryDeserialize(request.OperationKey, out requestType, out change); if (requestType == InventoryRequestType.Backorder) { // Add BackOrder request to request list completeBackOrderRequest.Add(request); // Then remove BackOrder request operation key from shipment's operation key map shipment.RemoveOperationKey(lineItemIndex, request.OperationKey); } } // Storage the response operation keys from complete BackOrder mapping with line item index if (completeBackOrderRequest.Count > 0) { InventoryResponse response = _inventoryService.Service.Request(new InventoryRequest(DateTime.UtcNow, completeBackOrderRequest, null)); if (response != null && response.IsSuccess) { shipment.InsertOperationKeys(lineItemIndex, response.Items.Select(c => c.OperationKey)); } } } } else if (orderGroupStatus == OrderStatus.InProgress || orderGroupStatus == OrderStatus.AwaitingExchange) { // When placing an order or creating an exchange order bool placingOrder = shipmentStatus == OrderShipmentStatus.AwaitingInventory || shipmentStatus == OrderShipmentStatus.InventoryAssigned; if (placingOrder) { var lineItems = Shipment.GetShipmentLineItems(shipment); CancelOperationKeys(shipment); foreach (LineItem lineItem in lineItems) { RequestInventory(orderForm, shipment, lineItem); } } } } } if (inventoryRequests.Any()) { _inventoryService.Service.Request(new InventoryRequest(DateTime.UtcNow, inventoryRequests, null)); } // Retun the closed status indicating that this activity is complete. return(ActivityExecutionStatus.Closed); }
public void TestInitialize() { //instantiate private variables _orderStatusManager = new OrderStatusManager(); }
//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 })); }
/// <summary> /// Binds the form. /// </summary> private void BindForm() { /* * WorkflowList.DataSource = WorkflowConfiguration.Instance.Workflows; * WorkflowList.DataBind(); * */ // Bind Status OrderStatusList.DataSource = OrderStatusManager.GetOrderStatus(); OrderStatusList.DataBind(); // Bind Currency OrderCurrencyList.DataSource = CatalogContext.Current.GetCurrencyDto(); OrderCurrencyList.DataBind(); OrderGroup order = _order; if (order != null) { LoadAddresses(); ComboBoxItem item = CustomerName.Items.FindByValue(order.CustomerId.ToString()); if (item != null) { CustomerName.SelectedItem = item; } else { ComboBoxItem newItem = new ComboBoxItem(); newItem.Text = order.CustomerName; newItem.Value = order.CustomerId.ToString(); CustomerName.Items.Add(newItem); CustomerName.SelectedItem = newItem; } CustomerName.Text = order.CustomerName; //TrackingNo.Text = order.TrackingNumber; OrderSubTotal.Text = CurrencyFormatter.FormatCurrency(order.SubTotal, order.BillingCurrency); OrderTaxTotal.Text = CurrencyFormatter.FormatCurrency(order.TaxTotal, order.BillingCurrency); OrderShippingTotal.Text = CurrencyFormatter.FormatCurrency(order.ShippingTotal, order.BillingCurrency); OrderHandlingTotal.Text = CurrencyFormatter.FormatCurrency(order.HandlingTotal, order.BillingCurrency); OrderTotal.Text = CurrencyFormatter.FormatCurrency(order.Total, order.BillingCurrency); //OrderExpires.Value = order.ExpirationDate; if (_order.OrderForms.Count > 0) { if (AddressesList.Items.Count > 0) { ManagementHelper.SelectListItem(AddressesList, _order.OrderForms[0].BillingAddressId); } DiscountTotal.Text = CurrencyFormatter.FormatCurrency(order.OrderForms[0].DiscountAmount, order.BillingCurrency); } ManagementHelper.SelectListItem(OrderStatusList, order.Status); ManagementHelper.SelectListItem(OrderCurrencyList, order.BillingCurrency); /* * if (po.Status == OrderConfiguration.Instance.NewOrderStatus) * { * WorkflowDisabledDescription.Visible = false; * RunWorkflowButton.Enabled = true; * } * else * { * RunWorkflowButton.Enabled = false; * WorkflowDisabledDescription.Visible = true; * WorkflowDisabledDescription.Text = String.Format("Can only run workflow for orders with \"{0}\" status", OrderConfiguration.Instance.NewOrderStatus); * } * */ } else { ManagementHelper.SelectListItem(OrderCurrencyList, CommonSettingsManager.GetDefaultCurrency()); } }