Repository navigation
business process flows
A Business Process Flow takes the user through a multi-part task, one Stage at a time. The user can finish only when every Stage has passed its rules.
The sample Process:
New sales order ← Process
├── 1. Order Received ← Stage
│ └── 1. Record Order ← Step
└── 2. Payment Processing
├── 1. Apply Discounts
├── 2. Confirm Amount
├── 3. Record Payment Details
└── 4. Authorise Payment
| Part | Interface | Purpose |
|---|---|---|
| Process | IProcess |
Holds the Stages, tracks the current Stage, and creates the domain objects when the user finishes. It is the Aggregate Root: Stages and Steps exist only within it. |
| Stage | IStage |
One part of the Process, with its own data and rules. |
| Step | IStep |
Optional. Splits a Stage into smaller parts, each with its own data and rules. |
Stages are ordered by SequenceOrder. Steps are ordered by SequenceOrder within their Stage.
Use Steps only when a Stage has too many fields to show comfortably at once. Otherwise, put the properties on the Stage.

- The user opens the Process at its
CurrentStageand fills in the fields. - When the user moves on, the Process calls
CompleteAsyncon the current Stage. The Stage checks its own rules, then completes each of its Steps in order. - If every rule passes, the Stage and its Steps become
Completed. If any rule fails, the part that failed becomesInProgress, the user stays on that Stage, and all the failing messages are shown. - When every Stage is
Completed,FinishProcessAsyncuses the data to create the domain objects.
Two consequences:
-
State changes only when rules are checked.
CurrentStatehas aprivate set, so no outside code can mark work as done. -
Completion is never automatic. Your code must call
CompleteAsync. In this sample, the Process does.
Implement IProcess. The framework does not control how the user moves between Stages. You write that logic, and decide whether the user may skip ahead, go back or leave a Stage unfinished. In this sample, the user cannot move past an incomplete Stage.
AdvanceToNextStageAsync completes the current Stage, then moves to the first Stage not yet completed. This may be an earlier Stage.
[UiExplorer(preferredSize: UiExplorerSize.FullScreen)] //👈 Show full-screen
public class SalesOrderProcess : IProcess
{
...
public async Task<Assertion> AdvanceToNextStageAsync(CancellationToken cancellationToken = default)
{
var completion = await CurrentStage.CompleteAsync(cancellationToken); //👈 Completes the Stage and its Steps
if (completion.HasFailed)
return completion;
var next = Stages
.OrderBy(s => s.SequenceOrder)
.FirstOrDefault(s => s.CurrentState != StageState.Completed);
if (next != null)
_CurrentStage = next;
return Assertion.Pass;
}
}MoveToStageAsync moves the user to any Stage. It first completes every earlier Stage, in order. If one fails, the user is moved to that Stage instead.
public async Task<Assertion> MoveToStageAsync(IStage stage, CancellationToken cancellationToken = default)
{
if (!Stages.Contains(stage))
return Assertion.Fail(new ArgumentException("Stage does not belong to this process.", nameof(stage)));
var preceding = Stages
.OrderBy(s => s.SequenceOrder)
.TakeWhile(s => s != stage);
var completion = await CompleteInOrderAsync(preceding, cancellationToken); //👈 Earlier Stages must pass their rules
if (completion.HasFailed)
return completion;
_CurrentStage = stage;
return Assertion.Pass;
}
private async Task<Assertion> CompleteInOrderAsync(IEnumerable<IStage> stages, CancellationToken cancellationToken)
{
foreach (var stage in stages.Where(s => s.CurrentState != StageState.Completed).ToList())
{
var completion = await stage.CompleteAsync(cancellationToken);
if (completion.HasFailed)
{
_CurrentStage = stage; //👈 Move the user to the failing Stage
return completion;
}
}
return Assertion.Pass;
}
⚠️ If a Stage's rules pass on empty data, skipping past it completes it, even though the user never opened it. If a Stage must be filled in, give it a rule that fails on empty input.
FinishProcessAsync does four things:
- It completes any remaining Stages.
- It checks every Stage and Step again, because data may have been edited since completion.
- It checks the Process's own rules, which compare data across Stages.
- If all of that passes, it creates the domain objects.
The Process only collects the data. It is not the permanent record.
public async Task<Assertion> FinishProcessAsync(CancellationToken cancellationToken = default)
{
var completion = await CompleteInOrderAsync(Stages.OrderBy(s => s.SequenceOrder), cancellationToken);
if (completion.HasFailed)
return completion;
var result = new[]
{
await ((IProcess)this).ValidateAllAsync(cancellationToken), //👈 Check all Stages and Steps again
Rules().ToAssertion($"Process '{Name}'"), //👈 Rules that compare several Stages
}
.Consolidate();
if (result.HasFailed)
return result;
// Create your Aggregates and Domain Events here
return Assertion.Pass;
}Implement IStage. A Stage holds its data and the rules that data must satisfy. EvaluateAsync checks the Stage's rules, then its Steps in SequenceOrder.
public class OrderReceivedStage : IStage
{
// Id, Audit, SequenceOrder, Name, Description and Steps: declared as in ApplyDiscountsStep below
...
public StageState CurrentState { get; private set; } //👈 Set only by EvaluateAsync
public string ContactDetails { get; set; } = string.Empty;
public string BusinessType { get; set; } = string.Empty;
private IEnumerable<(bool IsValid, string Error)> Rules() => //👈 Each rule: condition, error message
[
(!string.IsNullOrWhiteSpace(ContactDetails), "Contact details are required"),
(!string.IsNullOrWhiteSpace(BusinessType), "Business type is required"),
];
public Task<Assertion> ValidateAsync(CancellationToken cancellationToken = default)
=> this.EvaluateAsync(Rules(), StageState.Validated, s => CurrentState = s, cancellationToken);
public Task<Assertion> CompleteAsync(CancellationToken cancellationToken = default)
=> this.EvaluateAsync(Rules(), StageState.Completed, s => CurrentState = s, cancellationToken);
}This Stage has only two properties, so it has no Steps. Its Steps collection is empty.
In the sample, Payment Processing has four Steps: discounts, amount, payment details and authorisation. Each is a separate task with its own rules.
A Step is written like a Stage, but uses Evaluate instead of EvaluateAsync, because it has no Steps of its own to check.
public class ApplyDiscountsStep : IStep
{
public Guid Id { get; init; }
public IAudit Audit { get; init; } = new Audit();
public int SequenceOrder { get; init; }
public string Name { get; init; } = string.Empty;
public string Description { get; init; } = string.Empty;
public StepState CurrentState { get; private set; }
public string DiscountCode { get; set; } = string.Empty;
public decimal DiscountAmount { get; set; }
/// <summary>Why the discount was given (required if no code is used).</summary>
[UI(preferredControl: UiControlType.TextArea)]
public string Reason { get; set; } = string.Empty;
/// <summary>Manager who approved the discount.</summary>
public string ApprovedBy { get; set; } = string.Empty;
private IEnumerable<(bool IsValid, string Error)> Rules() =>
[
(DiscountAmount >= 0, "Discount cannot be negative"),
(DiscountAmount == 0 || !string.IsNullOrWhiteSpace(DiscountCode) || !string.IsNullOrWhiteSpace(Reason), "A discount code or reason is required"),
(DiscountAmount == 0 || !string.IsNullOrWhiteSpace(ApprovedBy), "Discounts require approval"),
];
public Task<Assertion> ValidateAsync(CancellationToken cancellationToken = default)
=> Task.FromResult(this.Evaluate(Rules(), StepState.Validated, s => CurrentState = s));
public Task<Assertion> CompleteAsync(CancellationToken cancellationToken = default)
=> Task.FromResult(this.Evaluate(Rules(), StepState.Completed, s => CurrentState = s));
}To group fields on screen without separate rules or completion, use Sections instead of Steps:
[Display(GroupName = "Card")] //👈
public string CardholderName { get; set; } = string.Empty;💡 Every Stage and Step repeats the same properties and two methods. You can move them into your own base classes.
Each rule is a pair: a condition that must be true, and the message shown when it is not. All failing messages are shown together.

Put each rule on the smallest part that has access to every property it uses:
| The rule uses | Put it on | Example |
|---|---|---|
| One Step's properties | that Step | "Discounts require approval" |
| The Stage's properties, or several of its Steps | that Stage | "Authorised amount must match the confirmed amount" |
| Properties from several Stages | the Process | "Expected amount must equal the subtotal less discounts" |
A Step has no reference to the other Steps in its Stage, so a rule comparing two Steps goes on their Stage:
private IEnumerable<(bool IsValid, string Error)> Rules()
{
var confirm = Steps.OfType<ConfirmAmountStep>().Single();
var authorise = Steps.OfType<AuthorisePaymentStep>().Single();
yield return (authorise.Amount == confirm.ActualAmount, "Authorised amount must match the confirmed amount"); //👈
}Process rules are checked only in FinishProcessAsync, so the user sees those errors only on finishing.
| Action | Rules pass | Rules fail |
|---|---|---|
| Validate (check without completing) | → Validated; a Completed item stays Completed
|
→ InProgress
|
| Complete | → Completed
|
→ InProgress
|
If data is edited after completion, the item stays Completed until its rules are next checked. If they then fail, it returns to InProgress. This is why FinishProcessAsync checks everything again.
Build the Process and its Stages in an IFactory<T>:
public class SalesOrderProcessFactory : IFactory<SalesOrderProcess>
{
public SalesOrderProcess Create()
{
var stages = new List<IStage>
{
new OrderReceivedStage
{
Id = Guid.NewGuid(),
SequenceOrder = 1, //👈 Sets the Stage order
Name = "Order Received",
Description = "Captures information about the Order",
},
...
};
return new SalesOrderProcess
{
Id = Guid.NewGuid(),
Stages = stages,
CurrentStage = stages.OrderBy(s => s.SequenceOrder).First()
};
}
}When you run the sample, the user works through each Stage and sees errors as they occur:

Copyright © 2022-2026 Envivo Software
-
Objects
-
Configuring your Model
-
Testing your model
-
Other features