private void CheckInventory() { string warehouseCode = "Test"; string entryCode = "PriceTest_1"; int quantity = 2; List <InventoryRequestItem> requestItems = new List <InventoryRequestItem>(); // holds the "items" InventoryRequestItem requestItem = new InventoryRequestItem(); // The one we use now requestItem.CatalogEntryCode = entryCode; requestItem.Quantity = quantity; requestItem.WarehouseCode = warehouseCode; requestItem.RequestType = InventoryRequestType.Purchase; // reserve for now requestItems.Add(requestItem); InventoryRequest inventoryRequest = new InventoryRequest(DateTime.UtcNow, requestItems, null); InventoryResponse inventoryResponse = invSrvs.Service.Request(inventoryRequest); bool theBool = false; if (inventoryResponse.IsSuccess) { theBool = inventoryResponse.IsSuccess; } else { InventoryResponseItem iii = inventoryResponse.Items.FirstOrDefault(); InventoryResponseTypeInfo typeInfo = iii.ResponseTypeInfo; } /* * * */ }
public async Task <InventoryResponse> ParseInventoryResponse(JArray inventoryResponse) { var domInventory = new InventoryResponse(); try { // Parse response into a list of dictionaries foreach (var inventoryContent in inventoryResponse.Children <JObject>()) { var branchNumAndQuantityDict = new Dictionary <string, string>(); foreach (var inventoryLine in inventoryContent.Properties()) { branchNumAndQuantityDict.TryAdd(inventoryLine.Name, inventoryLine.Value.ToString()); } domInventory.InventoryData.Add(branchNumAndQuantityDict); } } catch (Exception ex) { var title = "Error in ParseInventoryResponse"; var teamsMessage = new TeamsMessage(title, $"Error message: {ex.Message}. Stacktrace: {ex.StackTrace}", "red", SourcingEngineFunctions.errorLogsUrl); teamsMessage.LogToTeams(teamsMessage); } return(domInventory); }
/// <summary> /// Fetches the inventory for the given Steam ID using the Steam API. /// </summary> /// <returns>The give users inventory.</returns> /// <param name='steamId'>Steam identifier.</param> /// <param name='apiKey'>The needed Steam API key.</param> public static Inventory FetchInventory (ulong steamId, string apiKey) { var url = "http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/?key=" + apiKey + "&steamid=" + steamId; string response = SteamWeb.Fetch (url, "GET", null, null, false); InventoryResponse result = JsonConvert.DeserializeObject<InventoryResponse>(response); return new Inventory(result.result); }
/// <summary> /// Create an url to the inventory with the steamID, appID and contextID /// Deserialize the response to an object so we can ease the work /// /// If we have more than 5000 items, page the request with the extension "start_assetid" and the last assetid from the previous request /// Make another request, if there are more pages set the variable of the default object so we can make a new request /// Add the items and the descriptions to the default inventoryresponse object /// /// Finally return the inventoryobject with all items from the inventory /// </summary> /// <param name="_steamID"></param> /// <param name="_appID"></param> /// <param name="_contextID"></param> /// <returns></returns> public async Task <InventoryResponse> GetInventory(ulong _steamID, int _appID, int _contextID) { try { string url = $"http://{m_steamWeb.m_SteamCommunityHost}/inventory/{_steamID}/{_appID}/{_contextID}?l=english&trading=1&count=5000"; string response = await m_steamWeb.m_WebHelper.GetStringFromRequest(url).ConfigureAwait(false); InventoryResponse inventoryResponse = JsonConvert.DeserializeObject <InventoryResponse>(response); while (inventoryResponse.More == 1) { url += $"&start_assetid={inventoryResponse.LastAssetID}"; response = await m_steamWeb.m_WebHelper.GetStringFromRequest(url).ConfigureAwait(false); InventoryResponse inventoryResponseMore = JsonConvert.DeserializeObject <InventoryResponse>(response); inventoryResponse.More = inventoryResponseMore.More; inventoryResponse.LastAssetID = inventoryResponseMore.LastAssetID; inventoryResponse.Assets.AddRange(inventoryResponseMore.Assets); inventoryResponse.ItemsDescriptions.AddRange(inventoryResponseMore.ItemsDescriptions); } return(inventoryResponse); } catch (Exception e) { Console.WriteLine($"GetInventory : {e}"); } return(new InventoryResponse()); }
public async Task GivenAnInventoryUpdateRequestForAnExistingProduct() { _existingInventory = await _inventoryManagementClient.PostAsync(new InventoryPostRequest { Quantity = 10 }); _request = new InventoryUpdateRequest { ProductId = _existingInventory.ProductId }; }
private void PopulateQuestions() { foreach (InventoryQuestion question in Questions) { InventoryResponse response = new InventoryResponse(question); tableLayoutPanelQuestions.Controls.Add(response); } }
public void BeforeEachTest() { //Arrange var request = new InventoryRequest { Items = new[] {"098138"} }; //Act _theResponse = _client.GetInventory(request); }
CSGOInventory(InventoryResponse inventory) { if (inventory == null) { throw new ArgumentNullException(); } this.inventory = inventory; this.classIdToId = inventory.rgInventory.ToLookup(pair => pair.Value.classid, pair => pair.Key); this.marketNameToId = inventory.rgDescriptions .SelectMany(pair => classIdToId[pair.Value.classid].Select(id => new KeyValuePair <string, string>(pair.Value.market_name, id))) .ToLookup(pair => pair.Key, pair => pair.Value); }
/// <summary> /// Fetches the inventory for the given Steam ID using the Steam API. /// </summary> /// <returns>The give users inventory.</returns> /// <param name='steamId'>Steam identifier.</param> /// <param name='apiKey'>The needed Steam API key.</param> /// <param name="steamWeb">The SteamWeb instance for this Bot</param> public static Dota2Inventory FetchInventory(ulong steamId, string apiKey, SteamWeb steamWeb) { var url = "http://api.steampowered.com/IEconItems_570/GetPlayerItems/v0001/?key=" + apiKey + "&steamid=" + steamId; string response = steamWeb.Fetch(url, "GET", null, false); InventoryResponse result = JsonConvert.DeserializeObject <InventoryResponse>(response); if (result.result != null) { return(new Dota2Inventory(result.result) as Dota2Inventory); } return(null); }
/// <summary> /// Fetches the inventory for the given Steam ID using the Steam API. /// </summary> /// <returns>The give users inventory.</returns> /// <param name='steamId'>Steam identifier.</param> /// <param name='apiKey'>The needed Steam API key.</param> /// <param name="steamWeb">The SteamWeb instance for this Bot</param> public static Inventory FetchInventory(ulong steamId, string apiKey, SteamWeb steamWeb, Action <string> chatMessage) { int attempts = 1; InventoryResponse result = null; while (result == null || result.result?.items == null) { try { var url = "http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/?key=" + apiKey + "&steamid=" + steamId; string response = steamWeb.Fetch(url, "GET", null, false); result = JsonConvert.DeserializeObject <InventoryResponse>(response); } catch (WebException e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("ERROR IN INVENTORY.FETCHINVENTORY: " + e.ToString()); Console.ForegroundColor = ConsoleColor.White; result = null; Thread.Sleep(500); } attempts++; if (attempts == 4) { attempts = 0; if (_failedFetch) { //Console.ForegroundColor = ConsoleColor.Red; //Console.WriteLine("Fetch Failing already. Aborting."); //Thread.CurrentThread.Abort(); } if (chatMessage != null) { _failedFetch = true; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Unable to fetch inventory of user #{0}. Giving up.", steamId.ToString()); Console.ForegroundColor = ConsoleColor.White; //chatMessage("I am currently encountering issues connecting to Steam. Please try again in a few minutes."); return(null); } } } return(new Inventory(result.result)); }
/// <summary> /// Fetches the inventory for the given Steam ID using the Steam API. /// </summary> /// <returns>The give users inventory.</returns> /// <param name='steamId'>Steam identifier.</param> /// <param name='apiKey'>The needed Steam API key.</param> /// <param name="steamWeb">The SteamWeb instance for this Bot</param> public static Inventory FetchInventory(ulong steamId, string apiKey, SteamWeb steamWeb) { int attempts = 1; InventoryResponse result = null; while ((result == null || result.result.items == null) && attempts <= 3) { var url = "https://api.steampowered.com/IEconItems_570/GetPlayerItems/v0001/?key=" + apiKey + "&steamid=" + steamId; string response = steamWeb.Fetch(url, "GET", null, false); result = JsonConvert.DeserializeObject <InventoryResponse>(response); attempts++; } return(new Inventory(result.result)); }
public async Task Get_WithNonExistingProductId_ReturnsNotFound() { var productId = 1; InventoryResponse inventoryResponse = null; var expectedObjectResult = new NotFoundResult(); _inventoryRepository.Get(productId).Returns(inventoryResponse); var sut = CreateSut(); var actual = sut.Get(productId); actual.As <NotFoundResult>().Should().BeEquivalentTo(expectedObjectResult); }
/// <summary> /// Fetches the inventory for the given Steam ID using the Steam API. /// </summary> /// <returns>The give users inventory.</returns> /// <param name='steamId'>Steam identifier.</param> /// <param name='apiKey'>The needed Steam API key.</param> /// <param name="appid"></param> public Inventory FetchInventory(ulong steamId, string apiKey, int appid) { var attempts = 1; InventoryResponse result = null; while ((result?.result.Items == null) && attempts <= 3) { var url = $"http://api.steampowered.com/IEconItems_{appid}/GetPlayerItems/v0001/?key={apiKey}&steamid={steamId}"; var response = SteamWeb.Request(url, "GET", data: null, referer: "http://api.steampowered.com"); result = JsonConvert.DeserializeObject <InventoryResponse>(response); attempts++; } return(new Inventory(result?.result)); }
public async Task Get_WithExistingProductId_ReturnsResult() { var productId = 1; var expected = new InventoryResponse { ProductId = productId, Quantity = 2 }; var expectedObjectResult = new OkObjectResult(expected); _inventoryRepository.Get(productId).Returns(expected); var sut = CreateSut(); var actual = sut.Get(productId); actual.As <OkObjectResult>().Should().BeEquivalentTo(expectedObjectResult); }
public void Update_QuantityCanBeDiscounted_ReturnsDiscountedInventoryResponse() { const int existingQuantity = 2; const int quantityToDiscount = -1; var sut = CreateSut(); var addedInventory = sut.Add(existingQuantity); var expected = new InventoryResponse { ProductId = addedInventory.ProductId, Quantity = existingQuantity + quantityToDiscount }; var actual = sut.Update(addedInventory.ProductId, quantityToDiscount); actual.Should().BeEquivalentTo(expected); }
public async Task Consume(ConsumeContext <OrderCreated> context) { _logger.LogInformation("Got order created"); var numberOfRowsAffected = await _inventoryUpdatorProvider.UpdateAsync(context.Message.ProductId, context.Message.Quantity); var inventoryResponse = new InventoryResponse { OrderId = context.Message.OrderId, IsSuccess = numberOfRowsAffected > 0 }; _logger.LogInformation("Sending/publishing a message: {InventoryResponse}", inventoryResponse); await _publishEndpoint.Publish <InventoryResponse>(inventoryResponse); }
public async Task Put_WithNonExistingProductId_ReturnsNotFound() { var productId = 1; var quantity = 2; InventoryUpdateRequest request = new InventoryUpdateRequest { ProductId = productId, Quantity = quantity }; InventoryResponse inventoryResponse = null; var expectedObjectResult = new NotFoundResult(); _inventoryRepository.Update(productId, quantity).Returns(inventoryResponse); var sut = CreateSut(); var actual = sut.Put(request); actual.As <NotFoundResult>().Should().BeEquivalentTo(expectedObjectResult); }
private bool SendNotification(InventoryResponse inventoryResponse) { var newestItem = inventoryResponse.Descriptions.FirstOrDefault(); if (newestItem != null) { var message = new NotificationMessage(newestItem.Name, newestItem.MarketHashName, newestItem.IconHash, DateTime.Now); var notificationError = _notifier.Notify(message); var isSuccessful = string.IsNullOrEmpty(notificationError); if (!isSuccessful) { MessageBox.Show(notificationError); } return(isSuccessful); } return(false); }
/// <summary> /// Fetches the inventory for the given Steam ID using the Steam API. /// </summary> /// <returns>The give users inventory.</returns> /// <param name='steamId'>Steam identifier.</param> /// <param name='apiKey'>The needed Steam API key.</param> /// <param name="steamWeb">The SteamWeb instance for this Bot</param> public static CSGOInventory FetchInventory(ulong steamId, string apiKey, SteamWeb steamWeb) { var url = "http://api.steampowered.com/IEconItems_730/GetPlayerItems/v0001/?key=" + apiKey + "&steamid=" + steamId; for (int i = 0; i < 100; i++) { try { string response = steamWeb.Fetch(url, "GET", null, false); InventoryResponse result = JsonConvert.DeserializeObject <InventoryResponse>(response); if (result.result != null) { return(new CSGOInventory(result.result) as CSGOInventory); } } catch (System.Net.WebException we) { } } throw new InventoryException("Failed to load CSGO inventory."); }
public async Task Post_WithRequest_ReturnsResult() { var productId = 1; var quantity = 2; InventoryPostRequest request = new InventoryPostRequest { Quantity = quantity }; InventoryResponse inventoryResponse = new InventoryResponse { ProductId = productId, Quantity = quantity }; var expectedObjectResult = new OkObjectResult(inventoryResponse); _inventoryRepository.Add(quantity).Returns(inventoryResponse); var sut = CreateSut(); var actual = sut.Post(request); actual.As <OkObjectResult>().Should().BeEquivalentTo(expectedObjectResult); }
private void RequestInventory(OrderForm orderForm, Shipment shipment, LineItem lineItem) { var lineItemIndex = orderForm.LineItems.IndexOf(lineItem); InventoryRequest request; InventoryResponse response = null; // If item is out of stock then delete item. if (GetNewLineItemQty(lineItem, new List <string>(), shipment) <= 0) { Warnings.Add("LineItemRemoved-" + lineItem.LineItemId.ToString(), string.Format("Item \"{0}\" has been removed from the cart because there is not enough available quantity.", lineItem.DisplayName)); PurchaseOrderManager.RemoveLineItemFromShipment(orderForm.Parent, lineItem.LineItemId, shipment); ValidateShipment(orderForm, shipment); return; } // Else try to allocate quantity request = AdjustStockItemQuantity(shipment, lineItem); if (request != null) { response = _inventoryService.Service.Request(request); } if (response != null && response.IsSuccess) { lineItem.IsInventoryAllocated = true; // Store operation keys to Shipment for each line item, to use later for complete request var existedIndex = shipment.OperationKeysMap.ContainsKey(lineItemIndex); var operationKeys = response.Items.Select(c => c.OperationKey); if (!existedIndex) { shipment.AddInventoryOperationKey(lineItemIndex, operationKeys); } else { shipment.InsertOperationKeys(lineItemIndex, operationKeys); } } }
public ActionResult CancelRequest(string code) { // use the "key" ... "WH-location", entry & Qty are irrelevant as the "key" governs what has happend // all are overlooked even if entered List <InventoryRequestItem> requestItems = new List <InventoryRequestItem>(); // holds the "items" InventoryRequestItem requestItem = new InventoryRequestItem(); // calls for some logic requestItem.RequestType = InventoryRequestType.Cancel; // requestItem.OperationKey = TempData["key"] as string; requestItems.Add(requestItem); InventoryRequest inventoryRequest = new InventoryRequest(DateTime.UtcNow, requestItems, null); InventoryResponse inventoryResponse = inventoryService.Service.Request(inventoryRequest); return(RedirectToAction("Index", "Variation")); // Check the "Complete-method" // ...no time-limited reservation (allthough it´s a custom implementation of "the provider") // ......could do a work-around with a timer counting down... and then cancel in code }
public ActionResult SimulatePurchase(InventoryDemoViewModel viewModel) { var request = new InventoryRequest() { RequestDateUtc = DateTime.UtcNow, Items = new[] { new InventoryRequestItem { RequestType = InventoryRequestType.Purchase, CatalogEntryCode = "Long Sleeve Shirt White Small_1", WarehouseCode = viewModel.SelectedWarehouseCode, Quantity = viewModel.PurchaseQuantity, ItemIndex = 0, } } }; InventoryResponse resp = _inventoryService.Request(request); if (resp.IsSuccess) { viewModel.OperationKeys = new List <string>(); foreach (var item in resp.Items) { viewModel.OperationKeys.Add(item.OperationKey); } } else if (resp.Items[0].ResponseType == InventoryResponseType.NotEnough) { viewModel.MessageOutput = "Not enough inventory for the request!"; } ModelFiller(viewModel); return(View("Index", viewModel)); }
public ActionResult RequestInventory(string code) // step through this { string warehouseCode = "Stockholm"; // a bit hard-coded //string warehouseCode = "Nashua"; // a bit hard-coded InventoryRecord inventoryRecord = inventoryService.Service.Get(code, warehouseCode); decimal available = inventoryRecord.PurchaseAvailableQuantity; decimal requested = inventoryRecord.PurchaseRequestedQuantity; decimal backOrderAvailable = inventoryRecord.BackorderAvailableQuantity; decimal backOrderRequested = inventoryRecord.BackorderRequestedQuantity; List <InventoryRequestItem> requestItems = new List <InventoryRequestItem>(); // holds the "items" InventoryRequestItem requestItem = new InventoryRequestItem(); requestItem.CatalogEntryCode = code; requestItem.Quantity = 3M; // ...no time-out --> custom // calls for some logic requestItem.WarehouseCode = warehouseCode; requestItem.RequestType = InventoryRequestType.Purchase; // reserve for now // pseudo-code below //requestItem.OperationKey = requestItem.WarehouseCode + requestItem.CatalogEntryCode + requestItem.Quantity.ToString(); requestItems.Add(requestItem); InventoryRequest inventoryRequest = new InventoryRequest(DateTime.UtcNow, requestItems, null); InventoryResponse inventoryResponse = inventoryService.Service.Request(inventoryRequest); if (inventoryResponse.IsSuccess) { TempData["key"] = inventoryResponse.Items[0].OperationKey; // bad place, just for demo // Storage in [dbo].[Shipment] or "custom" // [OperationKeys] NVARCHAR (MAX) NULL, } else { // could start to adjust Pre/Back-Order-qty InventoryRequestItem backOrderRequestItem = new InventoryRequestItem(); backOrderRequestItem.CatalogEntryCode = code; backOrderRequestItem.Quantity = 3M; backOrderRequestItem.WarehouseCode = warehouseCode; backOrderRequestItem.RequestType = InventoryRequestType.Backorder; // ...if enabled backOrderRequestItem.OperationKey = backOrderRequestItem.RequestType + backOrderRequestItem.WarehouseCode + backOrderRequestItem.CatalogEntryCode + backOrderRequestItem.Quantity.ToString(); List <InventoryRequestItem> backOrderRequestItems = new List <InventoryRequestItem>(); // holds the "items" backOrderRequestItems.Add(backOrderRequestItem); InventoryRequest backOrderRequest = new InventoryRequest(DateTime.UtcNow, backOrderRequestItems, null); InventoryResponse backOrderInventoryResponse = inventoryService.Service.Request(backOrderRequest); // } // ...gets //dbo.InventoryService - table gets the requests and accumulate //inventoryService.Service.Request(requestItem); // request it... // and it increases in reserved until you can´t reserve more --> "!Success" // ...and decreases available return(RedirectToAction("Index", "Variation")); }
public async Task WhenTheInventoryUpdateApiIsCalled() { _response = await _inventoryManagementClient.PutAsync(_request); }
//Injected<IOrderGroupFactory> _ogf; public ActionResult RequestInventory(string code) // step through this { // from Fund, maybe not what we want - heve more in Tran-Scope in CheckOutController //IOrderGroup c = _orderRepository.Create<ICart>(""); // //c.AdjustInventoryOrRemoveLineItems(); //c.UpdateInventoryOrRemoveLineItems() // Get the WH string warehouseCode = "Nashua"; // a bit hard-coded //string warehouseCode = "Stocholm"; // a bit hard-coded here too // somewhat hard-coded... no "Loader" though // could of course get info from the Market--> Country --> City etc. string warehouseCode2 = _warehouseRepository.List() .Where(w => w.ContactInformation.City == "Nashua") .First().Code; // can get several, should have some Geo-LookUp or alike to get the nearest WH IEnumerable <string> www = GetLocalMarketWarehouses(); // Get the actual record in focus InventoryRecord inventoryRecord = _inventoryService.Get(code, warehouseCode); // could have some decisions made by the following props... just havinga look here decimal available = inventoryRecord.PurchaseAvailableQuantity; decimal requested = inventoryRecord.PurchaseRequestedQuantity; decimal backOrderAvailable = inventoryRecord.BackorderAvailableQuantity; decimal backOrderRequested = inventoryRecord.BackorderRequestedQuantity; List <InventoryRequestItem> requestItems = new List <InventoryRequestItem>(); // holds the "items" InventoryRequestItem requestItem = new InventoryRequestItem(); // The one we use now requestItem.CatalogEntryCode = code; requestItem.Quantity = 3M; requestItem.WarehouseCode = warehouseCode; // ...no time-out ootb --> custom coding... like for consert tickets // calls for some logic requestItem.RequestType = InventoryRequestType.Purchase; // reserve for now requestItems.Add(requestItem); InventoryRequest inventoryRequest = new InventoryRequest(DateTime.UtcNow, requestItems, null); InventoryResponse inventoryResponse = _inventoryService.Request(inventoryRequest); // pseudo-code for the "key" below //requestItem.OperationKey = requestItem.WarehouseCode + requestItem.CatalogEntryCode + requestItem.Quantity.ToString(); if (inventoryResponse.IsSuccess) { TempData["key"] = inventoryResponse.Items[0].OperationKey; // bad place, just for demo // Storage is prepared in [dbo].[Shipment] ... or done "custom" // [OperationKeys] NVARCHAR (MAX) NULL, // methods for management sits on the Shipment // Serialized, InMemory and OldSchool } else { // could start to adjust Pre/Back-Order-qty InventoryRequestItem backOrderRequestItem = new InventoryRequestItem(); backOrderRequestItem.CatalogEntryCode = code; backOrderRequestItem.Quantity = 3M; backOrderRequestItem.WarehouseCode = warehouseCode; backOrderRequestItem.RequestType = InventoryRequestType.Backorder; // ...if enabled //Metadata below //backOrderRequestItem.OperationKey = backOrderRequestItem.RequestType + backOrderRequestItem.WarehouseCode + backOrderRequestItem.CatalogEntryCode + backOrderRequestItem.Quantity.ToString(); List <InventoryRequestItem> backOrderRequestItems = new List <InventoryRequestItem>(); // holds the "items" backOrderRequestItems.Add(backOrderRequestItem); InventoryRequest backOrderRequest = new InventoryRequest(DateTime.UtcNow, backOrderRequestItems, null); InventoryResponse backOrderInventoryResponse = _inventoryService.Request(backOrderRequest); } // dbo.InventoryService - table gets the requests and accumulate // inventoryService.Service.Request(requestItem); // and it increases in reserved until you can´t reserve more --> "Not Success" return(RedirectToAction("Index", "Variation")); }
/// <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); }