[EventSubscriber(ObjectType::Table, Database::<Table Name>, 'OnBeforeInsertEvent', '', <SkipOnMissingLicense>, <SkipOnMissingPermission>)]
local procedure OnBeforeInsert(var Rec: Record "YourHeaderTable"; var xRec: Record "YourHeaderTable"; RunTrigger: Boolean)
var
JsonObject: JsonObject;
LineItemsArray: JsonArray;
LineItem: JsonObject;
TotalQuantity: Integer;
SumQty: Integer;
begin
// Parse the JSON body from the API request
JsonObject := JsonObject.Parse(Rec.RequestBody);
// Extract TotalQuantity from the header
TotalQuantity := JsonObject.GetValue('TotalQuantity');
// Extract LineItems array
LineItemsArray := JsonObject.GetArray('LineItems');
SumQty := 0;
// Loop through LineItems and sum quantities
foreach LineItem in LineItemsArray do begin
SumQty += LineItem.GetValue('Qty');
end;
// Validate that the sum of quantities matches the TotalQuantity
if SumQty <> TotalQuantity then
Error('The sum of line quantities (%1) must equal the TotalQuantity (%2).', SumQty, TotalQuantity);
end;