Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#192 Support for expressions in BPMN gateways #246

Merged
merged 7 commits into from
Jun 1, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Altinn.App.Api/Controllers/InstancesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using Altinn.App.Core.Internal.AppModel;
using Altinn.App.Core.Internal.Process;
using Altinn.App.Core.Models;
using Altinn.App.Core.Models.Process;
using Altinn.App.Core.Models.Validation;
using Altinn.Authorization.ABAC.Xacml.JsonProfile;
using Altinn.Common.PEP.Helpers;
Expand Down
1 change: 1 addition & 0 deletions src/Altinn.App.Api/Controllers/ProcessController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Altinn.App.Core.Internal.Process.Elements;
using Altinn.App.Core.Internal.Process.Elements.AltinnExtensionProperties;
using Altinn.App.Core.Models;
using Altinn.App.Core.Models.Process;
using Altinn.App.Core.Models.Validation;
using Altinn.Platform.Storage.Interface.Models;
using Microsoft.AspNetCore.Authorization;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ private static void AddProcessServices(IServiceCollection services)
services.TryAddTransient<IProcessNavigator, ProcessNavigator>();
services.TryAddSingleton<IProcessReader, ProcessReader>();
services.TryAddTransient<IProcessEventDispatcher, ProcessEventDispatcher>();
services.AddTransient<IProcessExclusiveGateway, ExpressionsExclusiveGateway>();
services.TryAddTransient<ExclusiveGatewayFactory>();
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/Altinn.App.Core/Features/IProcessExclusiveGateway.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Altinn.App.Core.Internal.Process.Elements;
using Altinn.App.Core.Models.Process;
using Altinn.Platform.Storage.Interface.Models;

namespace Altinn.App.Core.Features;
Expand All @@ -18,7 +19,7 @@ public interface IProcessExclusiveGateway
/// </summary>
/// <param name="outgoingFlows">Complete list of defined flows out of gateway</param>
/// <param name="instance">Instance where process is about to move next</param>
/// <param name="action">Action performed by the requester</param>
/// <param name="processGatewayInformation"></param>
tjololo marked this conversation as resolved.
Show resolved Hide resolved
/// <returns></returns>
public Task<List<SequenceFlow>> FilterAsync(List<SequenceFlow> outgoingFlows, Instance instance, string? action);
public Task<List<SequenceFlow>> FilterAsync(List<SequenceFlow> outgoingFlows, Instance instance, ProcessGatewayInformation processGatewayInformation);
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public static bool EvaluateBooleanExpression(LayoutEvaluatorState state, Compone
ExpressionFunction.and => And(args),
ExpressionFunction.or => Or(args),
ExpressionFunction.not => Not(args),
ExpressionFunction.gatewayAction => state.GetGatewayAction(),
_ => throw new ExpressionEvaluatorTypeErrorException($"Function \"{expr.Function}\" not implemented"),
};
return ret;
Expand Down Expand Up @@ -191,6 +192,8 @@ private static (double?, double?) PrepareNumericArgs(object?[] args)
{
bool ab => throw new ExpressionEvaluatorTypeErrorException($"Expected number, got value {(ab ? "true" : "false")}"),
string s => parseNumber(s),
decimal d => (double)d,
int i => (double)i,
object o => o as double?, // assume all relevant numers are representable as double (as in frontend)
_ => null,
};
Expand All @@ -199,6 +202,8 @@ private static (double?, double?) PrepareNumericArgs(object?[] args)
{
bool bb => throw new ExpressionEvaluatorTypeErrorException($"Expected number, got value {(bb ? "true" : "false")}"),
string s => parseNumber(s),
decimal d => (double)d,
int i => (double)i,
object o => o as double?, // assume all relevant numers are representable as double (as in frontend)
_ => null,
};
Expand Down
13 changes: 12 additions & 1 deletion src/Altinn.App.Core/Internal/Expressions/LayoutEvaluatorState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,18 @@ public class LayoutEvaluatorState
private readonly LayoutModel _componentModel;
private readonly FrontEndSettings _frontEndSettings;
private readonly Instance _instanceContext;
private readonly string? _gatewayAction;

/// <summary>
/// Constructor for LayoutEvaluatorState. Usually called via <see cref="LayoutEvaluatorStateInitializer" /> that can be fetched from dependency injection.
/// </summary>
public LayoutEvaluatorState(IDataModelAccessor dataModel, LayoutModel componentModel, FrontEndSettings frontEndSettings, Instance instance)
public LayoutEvaluatorState(IDataModelAccessor dataModel, LayoutModel componentModel, FrontEndSettings frontEndSettings, Instance instance, string? gatewayAction = null)
{
_dataModel = dataModel;
_componentModel = componentModel;
_frontEndSettings = frontEndSettings;
_instanceContext = instance;
_gatewayAction = gatewayAction;
}


Expand Down Expand Up @@ -184,6 +186,15 @@ public string GetInstanceContext(string key)
};
}

/// <summary>
/// Get the gateway action from the instance context
/// </summary>
/// <returns>Returns null if no action defined</returns>
public string? GetGatewayAction()
{
return _gatewayAction;
}

/// <summary>
/// Return a full dataModelBiding from a context aware binding by adding indicies
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ public LayoutEvaluatorStateInitializer(IAppResources appResources, IOptions<Fron
/// <summary>
/// Initialize LayoutEvaluatorState with given Instance, data object and layoutSetId
/// </summary>
public Task<LayoutEvaluatorState> Init(Instance instance, object data, string? layoutSetId)
public Task<LayoutEvaluatorState> Init(Instance instance, object data, string? layoutSetId, string? gatewayAction = null)
{
var layouts = _appResources.GetLayoutModel(layoutSetId);
return Task.FromResult(new LayoutEvaluatorState(new DataModel(data), layouts, _frontEndSettings, instance));
return Task.FromResult(new LayoutEvaluatorState(new DataModel(data), layouts, _frontEndSettings, instance, gatewayAction));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,11 @@ public class AltinnProperties
//[XmlElement(ElementName = "taskType", Namespace = "http://altinn.no", IsNullable = true)]
[XmlElement("taskType", Namespace = "http://altinn.no")]
public string? TaskType { get; set; }

/// <summary>
/// Gets or sets the data type id connected to the task
/// </summary>
[XmlElement("connectedDataTypeId", Namespace = "http://altinn.no", IsNullable = true)]
public string? ConnectedDataTypeId { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ public class ExclusiveGateway: ProcessElement
/// </summary>
[XmlAttribute("default")]
public string? Default { get; set; }

/// <summary>
///
/// </summary>
[XmlElement("extensionElements")]
public ExtensionElements? ExtensionElements { get; set; }

/// <summary>
/// String representation of process element type
Expand Down
6 changes: 6 additions & 0 deletions src/Altinn.App.Core/Internal/Process/Elements/SequenceFlow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,11 @@ public class SequenceFlow
/// </summary>
[XmlAttribute("flowtype", Namespace = "http://altinn.no")]
public string FlowType { get; set; }

/// <summary>
/// Gets or sets the condition expression of a sequence flow
/// </summary>
[XmlElement("conditionExpression")]
public string? ConditionExpression { get; set; }
}
}
168 changes: 168 additions & 0 deletions src/Altinn.App.Core/Internal/Process/ExpressionsExclusiveGateway.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
using System.Text;
using System.Text.Json;
using Altinn.App.Core.Features;
using Altinn.App.Core.Interface;
using Altinn.App.Core.Internal.App;
using Altinn.App.Core.Internal.AppModel;
using Altinn.App.Core.Internal.Expressions;
using Altinn.App.Core.Internal.Process.Elements;
using Altinn.App.Core.Models;
using Altinn.App.Core.Models.Expressions;
using Altinn.App.Core.Models.Process;
using Altinn.Platform.Storage.Interface.Models;

namespace Altinn.App.Core.Internal.Process
{
/// <summary>
/// Class implementing <see cref="IProcessExclusiveGateway" /> for evaluating expressions on flows connected to a gateway
/// </summary>
public class ExpressionsExclusiveGateway : IProcessExclusiveGateway
{
private readonly LayoutEvaluatorStateInitializer _layoutStateInit;
private readonly IAppResources _resources;
private readonly IAppMetadata _appMetadata;
private readonly IData _dataClient;
private readonly IAppModel _appModel;

/// <summary>
/// Constructor for <see cref="ExpressionsExclusiveGateway" />
/// </summary>
/// <param name="layoutEvaluatorStateInitializer"></param>
tjololo marked this conversation as resolved.
Show resolved Hide resolved
/// <param name="resources"></param>
/// <param name="appModel"></param>
/// <param name="appMetadata"></param>
/// <param name="dataClient"></param>
public ExpressionsExclusiveGateway(
LayoutEvaluatorStateInitializer layoutEvaluatorStateInitializer,
IAppResources resources,
IAppModel appModel,
IAppMetadata appMetadata,
IData dataClient)
{
_layoutStateInit = layoutEvaluatorStateInitializer;
_resources = resources;
_appMetadata = appMetadata;
_dataClient = dataClient;
_appModel = appModel;
}

/// <inheritdoc />
public string GatewayId { get; } = "AltinnExpressionsExclusiveGateway";

/// <inheritdoc />
public async Task<List<SequenceFlow>> FilterAsync(List<SequenceFlow> outgoingFlows, Instance instance, ProcessGatewayInformation processGatewayInformation)
{
var state = await GetLayoutEvaluatorState(instance, processGatewayInformation.Action, processGatewayInformation.DataTypeId);

return outgoingFlows.Where(outgoingFlow => EvaluateSequenceFlow(state, outgoingFlow)).ToList();
}

private async Task<LayoutEvaluatorState> GetLayoutEvaluatorState(Instance instance, string? action, string? dataTypeId)
{
var layoutSet = GetLayoutSet(instance);
var (checkedDataTypeId, dataType) = await GetDataType(instance, layoutSet, dataTypeId);
object data = new object();
if (checkedDataTypeId != null && dataType != null)
{
InstanceIdentifier instanceIdentifier = new InstanceIdentifier(instance);
var dataGuid = GetDataId(instance, checkedDataTypeId);
Type dataElementType = dataType;
if (dataGuid != null)
{
data = await _dataClient.GetFormData(instanceIdentifier.InstanceGuid, dataElementType, instance.Org, instance.AppId.Split("/")[1], int.Parse(instance.InstanceOwner.PartyId), dataGuid.Value);
}
}

var state = await _layoutStateInit.Init(instance, data, layoutSetId: layoutSet?.Id, gatewayAction: action);
return state;
}

private bool EvaluateSequenceFlow(LayoutEvaluatorState state, SequenceFlow sequenceFlow)
{
if (sequenceFlow.ConditionExpression != null)
{
var expression = GetExpressionFromCondition(sequenceFlow.ConditionExpression);
foreach (var componentContext in state.GetComponentContexts())
{
var result = ExpressionEvaluator.EvaluateExpression(state, expression, componentContext);
if (result is bool boolResult && boolResult)
{
return true;
}
}
}
else
{
return true;
}

return false;
}

private static Expression GetExpressionFromCondition(string condition)
{
JsonSerializerOptions options = new()
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
PropertyNameCaseInsensitive = true,
};
Utf8JsonReader reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(condition));
reader.Read();
var expressionFromCondition = ExpressionConverter.ReadNotNull(ref reader, options);
return expressionFromCondition;
}

private LayoutSet? GetLayoutSet(Instance instance)
{
string taskId = instance.Process.CurrentTask.ElementId;
JsonSerializerOptions options = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };


string layoutSetsString = _resources.GetLayoutSets();
LayoutSet? layoutSet = null;
if (!string.IsNullOrEmpty(layoutSetsString))
{
LayoutSets? layoutSets = JsonSerializer.Deserialize<LayoutSets>(layoutSetsString, options)!;
layoutSet = layoutSets?.Sets?.FirstOrDefault(t => t.Tasks.Contains(taskId));
}

return layoutSet;
}

private async Task<(string? DataTypeId, Type? DataTypeClassType)> GetDataType(Instance instance, LayoutSet? layoutSet, string? dataTypeId)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This logic seems to belong elsewhere, but we're perhaps missing the natural place to place it. Unless we use similar methods in other parts of the code we should make a note of it and figure out where it should be until next time.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Couldn't find a natural home, I will add a TODO comment stating that we should find a home for it

{
DataType? dataType;
if (dataTypeId != null)
{
dataType = (await _appMetadata.GetApplicationMetadata()).DataTypes.FirstOrDefault(d => d.Id == dataTypeId && d.AppLogic != null);
}
else if (layoutSet != null)
{
dataType = (await _appMetadata.GetApplicationMetadata()).DataTypes.FirstOrDefault(d => d.Id == layoutSet.DataType && d.AppLogic != null);
}
else
{
dataType = (await _appMetadata.GetApplicationMetadata()).DataTypes.FirstOrDefault(d => d.TaskId == instance.Process.CurrentTask.ElementId && d.AppLogic != null);
}

if (dataType != null)
{
return (dataType.Id, _appModel.GetModelType(dataType.AppLogic.ClassRef));
}

return (null, null);
}

private static Guid? GetDataId(Instance instance, string dataType)
{
string? dataId = instance.Data.FirstOrDefault(d => d.DataType == dataType)?.Id;
if (dataId != null)
{
return new Guid(dataId);
}

return null;
}
}
}
2 changes: 1 addition & 1 deletion src/Altinn.App.Core/Internal/Process/IProcessEngine.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Altinn.App.Core.Models;
using Altinn.App.Core.Models.Process;
using Altinn.Platform.Storage.Interface.Models;

namespace Altinn.App.Core.Internal.Process
Expand Down
2 changes: 1 addition & 1 deletion src/Altinn.App.Core/Internal/Process/ProcessEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using Altinn.App.Core.Interface;
using Altinn.App.Core.Internal.Process.Elements;
using Altinn.App.Core.Internal.Process.Elements.Base;
using Altinn.App.Core.Models;
using Altinn.App.Core.Models.Process;
using Altinn.Platform.Profile.Models;
using Altinn.Platform.Storage.Interface.Enums;
using Altinn.Platform.Storage.Interface.Models;
Expand Down
Loading