Codeunit 30195 Shpfy Inventory API
src/Apps/W1/Shopify/App/src/Inventory/Codeunits/ShpfyInventoryAPI.Codeunit.al360 lines, Copyright (c) Microsoft Corporation. MIT
// ------------------------------------------------------------------------------------------------// Copyright (c) Microsoft Corporation. All rights reserved.// Licensed under the MIT License. See License.txt in the project root for license information.// ------------------------------------------------------------------------------------------------namespace Microsoft.Integration.Shopify;using Microsoft.Inventory.Item;/// <summary>/// Codeunit Shpfy Inventory API (ID 30195)./// </summary>codeunit 30195 "Shpfy Inventory API"{ Access = Internal; Permissions = tabledata Item = r, tabledata "Item Unit of Measure" = r; var ShopifyShop: Record "Shpfy Shop"; ShopifyCommunicationMgt: Codeunit "Shpfy Communication Mgt."; InventoryEvents: Codeunit "Shpfy Inventory Events"; JsonHelper: Codeunit "Shpfy Json Helper"; InventoryIds: List of [Guid]; internal procedure GetStock(ShopInventory: Record "Shpfy Shop Inventory") Stock: Decimal var Item: Record Item; ItemUnitofMeasure: Record "Item Unit of Measure"; ShopLocation: Record "Shpfy Shop Location"; ShopifyProduct: Record "Shpfy Product"; ShopifyVariant: Record "Shpfy Variant"; StockCalculation: Interface "Shpfy Stock Calculation"; UOM: Code[10]; SalesUOM: Code[10]; begin SetShop(ShopInventory."Shop Code"); if ShopifyProduct.Get(ShopInventory."Product Id") and ShopifyVariant.Get(ShopInventory."Variant Id") then begin ShopLocation.SetRange("Shop Code", ShopInventory."Shop Code"); ShopLocation.SetRange(Id, ShopInventory."Location Id"); ShopLocation.SetFilter("Stock Calculation", '<>%1', ShopLocation."Stock Calculation"::Disabled); if ShopLocation.FindFirst() and Item.GetBySystemId(ShopifyVariant."Item SystemId") then Item.SetRange("Date Filter", 0D, Today); Item.SetFilter("Location Filter", ShopLocation."Location Filter"); if not IsNullGuid(ShopifyVariant."Item Variant SystemId") then begin ShopifyVariant.CalcFields("Variant Code"); Item.SetFilter("Variant Filter", ShopifyVariant."Variant Code"); end; StockCalculationFactory(StockCalculation, ShopLocation."Stock Calculation"); SalesUOM := Item."Sales Unit of Measure"; if StockCalculation is "Shpfy Extended Stock Calculation" then Stock := (StockCalculation as "Shpfy Extended Stock Calculation").GetStock(Item, ShopLocation) else Stock := StockCalculation.GetStock(Item); case ShopifyVariant."UoM Option Id" of 1: UOM := CopyStr(ShopifyVariant."Option 1 Value", 1, MaxStrLen(UOM)); 2: UOM := CopyStr(ShopifyVariant."Option 2 Value", 1, MaxStrLen(UOM)); 3: UOM := CopyStr(ShopifyVariant."Option 3 Value", 1, MaxStrLen(UOM)); else UOM := SalesUOM; end; if (UOM <> '') and (UOM <> Item."Base Unit of Measure") then if ItemUnitofMeasure.Get(Item."No.", UOM) then Stock := Stock / ItemUnitofMeasure."Qty. per Unit of Measure"; InventoryEvents.OnAfterCalculationStock(Item, ShopifyShop, ShopLocation."Location Filter", Stock); end; end; local procedure GetId(JObject: JsonObject) Result: BigInteger var JValue: JsonValue; Path: List of [Text]; Gid: Text; begin if JsonHelper.GetJsonValue(JObject, JValue, 'id') then begin Gid := JValue.AsText(); Path := Gid.Split('/'); Gid := Path.Get(Path.Count()); if Evaluate(Result, Gid) then; end; end; local procedure GetInventoryLevels(JObject: JsonObject; var JResult: JsonObject): Boolean; var JData: JsonObject; JLocation: JsonObject; begin if JsonHelper.GetJsonObject(JObject, JData, 'data') then if JsonHelper.GetJsonObject(JData, JLocation, 'location') then exit(JsonHelper.GetJsonObject(JLocation, JResult, 'inventoryLevels')); end; internal procedure SetInventoryIds() var ShopInventory: Record "Shpfy Shop Inventory"; begin Clear(InventoryIds); ShopInventory.SetRange("Shop Code", ShopifyShop.Code); ShopInventory.LoadFields(SystemId); if ShopInventory.FindSet() then repeat InventoryIds.Add(ShopInventory.SystemId); until ShopInventory.Next() = 0; end; internal procedure RemoveUnusedInventoryIds() var ShopInventory: Record "Shpfy Shop Inventory"; Id: Guid; begin ShopInventory.LoadFields(SystemId); foreach Id in InventoryIds do if ShopInventory.GetBySystemId(Id) then ShopInventory.Delete(); end; internal procedure ExportStock(var ShopInventory: Record "Shpfy Shop Inventory"; ForceExport: Boolean) var GraphQLQueries: Codeunit "Shpfy GraphQL Queries"; JGraphQL: JsonObject; JQuantities: JsonArray; JQuantity: JsonObject; ExpectedCost: Integer; InputSize: Integer; GraphQLText: Text; begin if ShopInventory.FindSet() then begin GraphQLText := GraphQLQueries.GetQueryWithCost(Enum::"Shpfy GraphQL Type"::Inventory_ModifyInventory, ExpectedCost); JGraphQL.ReadFrom(GraphQLText); JQuantities := JsonHelper.GetJsonArray(JGraphQL, 'variables.input.quantities'); repeat JQuantity := CalcStock(ShopInventory, ForceExport); if JQuantity.Keys.Count = 4 then begin JQuantities.Add(JQuantity); InputSize += 1; if InputSize = 250 then begin ExecuteInventoryGraphQL(JGraphQL, ExpectedCost); Clear(JGraphQL); JGraphQL.ReadFrom(GraphQLText); JQuantities := JsonHelper.GetJsonArray(JGraphQL, 'variables.input.quantities'); InputSize := 0; end; end; until ShopInventory.Next() = 0; if InputSize > 0 then ExecuteInventoryGraphQL(JGraphQL, ExpectedCost); end; end; local procedure ExecuteInventoryGraphQL(JGraphQL: JsonObject; ExpectedCost: Integer) var JResponse: JsonToken; JUserErrors: JsonArray; GraphQLText: Text; IdempotencyKey: Guid; RetryAttempt: Integer; MaxRetries: Integer; HasConcurrencyError: Boolean; ErrorCode: Text; JError: JsonToken; begin MaxRetries := 3; RetryAttempt := 0; repeat HasConcurrencyError := false; IdempotencyKey := CreateGuid(); GraphQLText := Format(JGraphQL); GraphQLText := GraphQLText.Replace('{{IdempotencyKey}}', Format(IdempotencyKey, 0, 4).TrimStart('{').TrimEnd('}')); JResponse := ShopifyCommunicationMgt.ExecuteGraphQL(GraphQLText, ExpectedCost); if JsonHelper.GetJsonArray(JResponse, JUserErrors, 'data.inventorySetQuantities.userErrors') then foreach JError in JUserErrors do begin ErrorCode := JsonHelper.GetValueAsText(JError, 'code'); if ErrorCode in ['IDEMPOTENCY_CONCURRENT_REQUEST', 'CHANGE_FROM_QUANTITY_STALE'] then begin HasConcurrencyError := true; break; end; end; RetryAttempt += 1; until (not HasConcurrencyError) or (RetryAttempt > MaxRetries); if HasConcurrencyError then LogSkippedInventoryUpdate(JGraphQL, ErrorCode); end; local procedure LogSkippedInventoryUpdate(JGraphQL: JsonObject; ErrorCode: Text) var SkippedRecord: Codeunit "Shpfy Skipped Record"; EmptyRecordId: RecordId; JQuantities: JsonArray; SkippedMsg: Label 'Inventory update skipped after retry due to %1 error', Comment = '%1 = Error code'; begin if JsonHelper.GetJsonArray(JGraphQL, JQuantities, 'variables.input.quantities') then if JQuantities.Count > 0 then SkippedRecord.LogSkippedRecord(EmptyRecordId, CopyStr(StrSubstNo(SkippedMsg, ErrorCode), 1, 250), ShopifyShop); end; local procedure CalcStock(var ShopInventory: Record "Shpfy Shop Inventory"; ForceExport: Boolean) JQuantity: JsonObject var Item: Record Item; DelShopInventory: Record "Shpfy Shop Inventory"; ShopLocation: Record "Shpfy Shop Location"; ShopifyVariant: Record "Shpfy Variant"; IStockAvailable: Interface "Shpfy IStock Available"; JNull: JsonValue; InventoryItemIdTxt: Label 'gid://shopify/InventoryItem/%1', Locked = true, Comment = '%1 = The inventory Item Id'; LocationIdTxt: Label 'gid://shopify/Location/%1', Locked = true, Comment = '%1 = The Location Id'; begin ShopifyVariant.SetRange(Id, ShopInventory."Variant Id"); if ShopifyVariant.IsEmpty then begin if DelShopInventory.GetBySystemId(ShopInventory.SystemId) then DelShopInventory.Delete(); exit; end; if ShopifyVariant.Get(ShopInventory."Variant Id") then if Item.GetBySystemId(ShopifyVariant."Item SystemId") then if not (Item.Type in [Item.Type::"Non-Inventory", Item.Type::Service]) then begin ShopInventory.Validate(Stock, Round(GetStock(ShopInventory), 1, '<')); ShopInventory.Modify(); if (ShopInventory.Stock <> ShopInventory."Shopify Stock") or ForceExport then if ShopLocation.Get(ShopInventory."Shop Code", ShopInventory."Location Id") then begin IStockAvailable := ShopLocation."Stock Calculation"; if IStockAvailable.CanHaveStock() then begin JQuantity.Add('inventoryItemId', StrSubstNo(InventoryItemIdTxt, ShopInventory."Inventory Item Id")); JQuantity.Add('locationId', StrSubstNo(LocationIdTxt, ShopLocation.Id)); if ShopInventory.Stock < 0 then JQuantity.Add('quantity', 0) else JQuantity.Add('quantity', ShopInventory.Stock); JNull.SetValueToNull(); JQuantity.Add('changeFromQuantity', JNull); end; end; end; end; local procedure HasNextResults(JObject: JsonObject): Boolean var JPageInfo: JsonObject; JValue: JsonValue; begin if JsonHelper.GetJsonObject(JObject, JPageInfo, 'pageInfo') then if JsonHelper.GetJsonValue(JPageInfo, JValue, 'hasNextPage') then exit(JValue.AsBoolean()); end; internal procedure ImportInventoryLevels(var ShopLocation: Record "Shpfy Shop Location"; var Parameters: Dictionary of [Text, Text]; var GraphQLType: Enum "Shpfy GraphQL Type"; var JInventoryLevels: JsonObject) var ShopInventory: Record "Shpfy Shop Inventory"; ShopVariant: Record "Shpfy Variant"; InventoryItemId: BigInteger; ProductId: BigInteger; VariantId: BigInteger; Stock: Decimal; JArray: JsonArray; JQuantities: JsonArray; JInventoryItem: JsonObject; JNode: JsonObject; JProduct: JsonObject; JVariant: JsonObject; JQuantity: JsonToken; JItem: JsonToken; JValue: JsonValue; Cursor: Text; begin if JsonHelper.GetJsonArray(JInventoryLevels, JArray, 'edges') then begin foreach JItem in JArray do begin if JsonHelper.GetJsonValue(JItem.AsObject(), JValue, 'cursor') then Cursor := JValue.AsText() else Clear(Cursor); if JsonHelper.GetJsonObject(JItem.AsObject(), JNode, 'node') then begin if JsonHelper.GetJsonArray(JNode, JQuantities, 'quantities') then if JQuantities.Get(0, JQuantity) then if JsonHelper.GetJsonValue(JQuantity, JValue, 'quantity') then Stock := JValue.AsInteger() else Stock := 0; InventoryItemId := 0; VariantId := 0; ProductId := 0; if JsonHelper.GetJsonObject(JNode, JInventoryItem, 'item') then begin InventoryItemId := GetId(JInventoryItem); if JsonHelper.GetJsonObject(JInventoryItem, JVariant, 'variant') then begin VariantId := GetId(JVariant); ShopVariant.SetRange(Id, VariantId); if not ShopVariant.IsEmpty then if JsonHelper.GetJsonObject(JVariant, JProduct, 'product') then begin ProductId := GetId(JProduct); if ShopInventory.Get(ShopLocation."Shop Code", ProductId, VariantId, ShopLocation.Id) then begin ShopInventory.Validate("Shopify Stock", Stock); ShopInventory."Inventory Item Id" := InventoryItemId; ShopInventory.Modify(); InventoryIds.Remove(ShopInventory.SystemId); end else begin Clear(ShopInventory); ShopInventory."Shop Code" := ShopLocation."Shop Code"; ShopInventory."Product Id" := ProductId; ShopInventory."Variant Id" := VariantId; ShopInventory."Location Id" := ShopLocation.Id; ShopInventory."Inventory Item Id" := InventoryItemId; ShopInventory.Validate("Shopify Stock", Stock); ShopInventory.Insert(); end; end; end; end; end; end; GraphQLType := GraphQLType::Inventory_GetNextInventoryEntries; if Parameters.ContainsKey('After') then Parameters.Set('After', Cursor) else Parameters.Add('After', Cursor); end; end; internal procedure ImportStock(ShopLocation: Record "Shpfy Shop Location") var Parameters: Dictionary of [Text, Text]; GraphQLType: Enum "Shpfy GraphQL Type"; JInventoryLevels: JsonObject; JResponse: JsonToken; begin Parameters.Add('LocationId', Format(ShopLocation.Id)); GraphQLType := GraphQLType::Inventory_GetInventoryEntries; repeat JResponse := ShopifyCommunicationMgt.ExecuteGraphQL(GraphQLType, Parameters); if GetInventoryLevels(JResponse.AsObject(), JInventoryLevels) then ImportInventoryLevels(ShopLocation, Parameters, GraphQLType, JInventoryLevels); until not HasNextResults(JInventoryLevels); end; internal procedure SetShop(ShopCode: Code[20]) begin if ShopifyShop.Code <> ShopCode then begin ShopifyShop.Get(ShopCode); ShopifyCommunicationMgt.SetShop(ShopifyShop); end; end; local procedure StockCalculationFactory(var StockCalculation: Interface "Shpfy Stock Calculation"; CalculationType: Enum "Shpfy Stock Calculation") begin StockCalculation := CalculationType; end;}