Skip to main content
Version: Latest
Technical ManualLooking for step-by-step instructions? In the User Manual: Approvals

Add an approval type

The Approvals module records approvals for any module. A module registers an approval type (a pay run, a ticket, a time sheet) and asks for approval of one of its records; a policy chosen by type and amount says who decides, in what stages, and how many must approve each; every decision is kept with who made it, when and why. Payroll's pay run approval is built this way, and a ticket, time sheet, expense or purchase order approval is added the same way, without changing Approvals.

Feature IDNameDepends on
CrestApps.OrchardCore.ApprovalsApprovalsnone (uses Staff, Notifications and Workflows when they are on)

Projects: CrestApps.OrchardCore.Approvals.Abstractions (models and contracts: reference it from your module's .Core or .Abstractions), CrestApps.OrchardCore.Approvals.Core (store, rules, providers, resolver, inbox), CrestApps.OrchardCore.Approvals (the module). Approvals records decisions; reminders and escalations stay in Workflows.

How a request moves​

  1. A module calls IApprovalService.RequestAsync with an ApprovalSubmission: the type (SubjectKind), the record's id, an optional amount, currency and access scope, and optionally a policy.
  2. The policy is the one named, or the first enabled policy (by Order) whose Types include the type and whose amount, currency and scope conditions match (IApprovalPolicyResolver). No match is an error that says so.
  3. The request copies the policy's stages, then the type's handler runs RequestingAsync: it fills the title and the subject's page, adds approvers, stores its own data on the request, or refuses.
  4. The current stage's approvers are told (the Approvals to decide notification). A person a rule of the stage names may decide; the type's handler runs DecidingAsync first and may refuse.
  5. When a stage has its approvals, the next one starts (StageApprovedAsync, and its approvers are told). One rejection at any stage rejects the request (RejectedAsync); the last stage's approvals approve it (ApprovedAsync). A withdrawn or replaced request calls CanceledAsync. The closing hooks run in the decision's unit of work.

Two rules are built in, on by default and checked at every stage: the requester can't approve (AllowRequesterToApprove), and a person in the request's SubjectUserIds can't decide it (AllowSubjectToDecide). A person decides one stage of a request at most, unless the policy has AllowSamePersonAcrossStages. Being named by a rule isn't enough: the approver must also pass the type's source access at the Manage level (ISourceAccess for the type and the request's AccessScope, when the type has one) and the handler's CanAccessAsync, so a role rule never lets a clerk of one employer decide another's pay runs.

Decisions are made under a lock per request, on the request as stored (IApprovalRequestManager.FindCommittedAsync, not the copy loaded earlier), and the store checks concurrency: two approvers deciding at once never overwrite each other, and the second is told to reload.

Register a type​

In your module's startup, or in its .Core service registration:

services.AddApprovalType<TicketApprovalTypeHandler>("Ticket", type =>
{
type.DisplayName = LocalizationSource.Create<TicketApprovalTypeHandler>("Ticket");
type.Description = LocalizationSource.Create<TicketApprovalTypeHandler>("A ticket that needs a manager's yes before the work starts.");

// The standard conditions its policies offer: an amount range and currency, and a scope.
type.Conditions = ApprovalConditions.Amount | ApprovalConditions.Scope;
});

The name is stored on requests and policies and never changes. The display name shows on the requests list (with a Type filter), on the request page, on the card of the Add approval policy dialog (with the description), on workflow events, and in the Type column of the Approval requests data set. A type whose feature is off keeps its requests and policies; its requests get a handler that does nothing.

Write the handler​

Derive from ApprovalTypeHandlerBase and override the hooks the type needs:

HookWhenTypical use
RequestingAsync(ApprovalRequestingContext)Before the request is storedFill Request.Title, SubjectUrl, SubjectUserIds, SubjectStaffMemberId; AddApprover(rule) to every stage; Request.Put(...) the type's data; Refuse(reason).
DecidingAsync(ApprovalDecidingContext)Before a decision is recorded, once the person is an approverRefuse(reason) when the record changed since it was asked (compare Request.SubjectVersion).
CanAccessAsync(request, user)When deciding who may decide, after the type's source accessRefuse a named approver the record isn't theirs to act on.
StageApprovedAsync(request)A stage that isn't the last is approvedMove the record to the next step.
ApprovedAsync, RejectedAsync, CanceledAsyncThe request closesMove the record on, in the same unit of work.
GetSubjectUrlAsync, GetSubjectDisplayAsyncThe request pageLink to and describe the record (defaults: SubjectUrl, Title).
public sealed class TicketApprovalTypeHandler : ApprovalTypeHandlerBase
{
private readonly ITicketManager _tickets;

public TicketApprovalTypeHandler(ITicketManager tickets)
{
_tickets = tickets;
}

public override async Task RequestingAsync(ApprovalRequestingContext context, CancellationToken cancellationToken = default)
{
if (await _tickets.FindByIdAsync(context.Request.SubjectId, cancellationToken) is not { } ticket || ticket.IsClosed)
{
context.Refuse("The ticket is closed.");

return;
}

context.Request.Title ??= $"Ticket {ticket.Number}: {ticket.Subject}";
context.Request.SubjectUrl ??= $"~/Admin/tickets/{ticket.ItemId}";
context.Request.SubjectUserIds.Add(ticket.RequesterUserId);
context.Request.Put(new TicketApprovalData { TeamId = ticket.AssigneeTeamId });
}

public override async Task ApprovedAsync(ApprovalRequest request, CancellationToken cancellationToken = default)
=> await _tickets.MarkApprovedAsync(request.SubjectId, cancellationToken);

public override async Task RejectedAsync(ApprovalRequest request, CancellationToken cancellationToken = default)
=> await _tickets.MarkRejectedAsync(request.SubjectId, request.Decisions[^1].Note, cancellationToken);
}

A request is a catalog item: a type keeps its own data on it with Put and reads it with TryGet, in handlers, providers and display drivers.

Name approvers: approver rule providers​

A stage's Approvers are ApproverRules: a provider's name (Kind) and a value. Approvals ships:

Provider (Kind)ValueWho it namesRegistered
PermissionA permission's nameAnyone the authorization service grants itAlways
RoleA role's nameAnyone in the roleAlways
UsersUser ids, comma separated (the user picker)Those usersAlways
ManagernoneThe managers up the chain of SubjectStaffMemberIdWith Staff on
StaffStaff member ids, comma separatedTheir usersWith Staff on

Add your own with IApproverRuleProvider and services.AddApproverRuleProvider<T>(). Deciding asks IsNamedAsync; notices, Waiting for me and the approver count ask GetUserIdsAsync. Set DependsOnRequest when who it names depends on each request.

public sealed class AssigneeTeamApproverRuleProvider : IApproverRuleProvider
{
private readonly ITeamDirectory _teams;

public AssigneeTeamApproverRuleProvider(ITeamDirectory teams)
{
_teams = teams;
}

public string Name => "AssigneeTeam";

public LocalizationSource DisplayName { get; } = LocalizationSource.Create<AssigneeTeamApproverRuleProvider>("The ticket's assignee team");

public bool NeedsValue => false;

public bool DependsOnRequest => true;

public async Task<bool> IsNamedAsync(ApproverRule rule, ApprovalRequest request, ClaimsPrincipal user, CancellationToken cancellationToken = default)
=> (await GetUserIdsAsync(rule, request, cancellationToken)).Contains(user.FindFirstValue(ClaimTypes.NameIdentifier));

public async Task<IReadOnlyList<string>> GetUserIdsAsync(ApproverRule rule, ApprovalRequest request, CancellationToken cancellationToken = default)
=> request.TryGet<TicketApprovalData>(out var data) ? await _teams.GetMemberUserIdsAsync(data.TeamId, cancellationToken) : [];
}

The policy editor lists every provider in each rule row and shows the value editor of the one chosen: the ApproverRuleValue_Edit shape (a text box) with the alternate ApproverRuleValue_Edit__{Kind}. Add Views/ApproverRuleValue.Edit-AssigneeTeam.cshtml for your own; its model's Editor (ApproverRuleValueEditorViewModel, in Approvals.Abstractions) gives the FieldName to post under and the current Value. A rule whose provider's feature is off is kept and names nobody.

Rules stored before providers were open held a number (0 Permission, 1 Role, 2 Manager, 3 Staff); ApproverRuleKindJsonConverter reads it as the name, so old policies and requests load and decide unchanged.

Policies​

An ApprovalPolicy (INamedCatalogManager<ApprovalPolicy>) has a Name modules and workflows ask for, a Title, the one Type it approves (chosen in the Add approval policy dialog and fixed afterwards), Enabled (chosen for requests that name none), Order, the conditions MinimumAmount, MaximumAmount, Currency and AccessScope, Stages (each a Title, Approvers and RequiredApprovals, ten at most), the two built-in rules and DueAfterHours. A policy without Stages is one stage made of its Approvers and RequiredApprovals, as policies saved before stages; GetStages() returns either. A request copies the stages when it is made, so a later change of the policy never changes a request already asked.

Policies saved when a policy served a list of Types load with that list's type as Type when it held one; with several or none they stay general policies that serve any type (Serves(type)), show every standard condition, and keep Types as it was.

Conditions​

A type opts into the standard conditions with ApprovalType.Conditions: Amount shows the amount range and currency, Scope shows a Scope list filled by the handler's GetScopesAsync (Payroll's pay run type lists its employers, matched to ApprovalSubmission.AccessScope). A condition the type doesn't use is cleared when the policy is saved, so it can't keep choosing the policy unseen.

A condition of the type's own goes in a DisplayDriver<ApprovalPolicy> whose CanHandleModel accepts only policies of the type, stored on the policy with Put, and the handler's MatchesAsync checks it: the resolver tries enabled policies by Order, keeps those whose type and standard conditions match, and takes the first MatchesAsync accepts.

public override Task<bool> MatchesAsync(ApprovalPolicy policy, ApprovalSubmission submission, CancellationToken cancellationToken = default)
=> Task.FromResult(!policy.TryGet<TicketPolicyQueue>(out var queue) || string.IsNullOrEmpty(queue.Queue) || queue.Queue == submission.AccessScope);

Time sheet example: a policy TimesheetApproval for the Timesheet type with two stages, Manager (Manager, 1 approval) then Payroll (Role Payroll Clerk, 1 approval); and a policy for expenses over 1,000 USD with Order 10 and three stages, before the general expense policy with Order 50.

Ask for approval​

From code:

var result = await approvalService.RequestAsync(new ApprovalSubmission
{
SubjectKind = "Timesheet",
SubjectId = timesheet.ItemId,
SubjectStaffMemberId = timesheet.StaffMemberId,
SubjectUserIds = [timesheet.UserId],
SubjectVersion = timesheet.Version,
Title = $"Time sheet of {timesheet.PersonName}, week {timesheet.Week}",
Amount = timesheet.Hours,
}, User);

if (!result.Succeeded)
{
// result.Errors says why: no policy matches, the handler refused, ...
}

Name a policy with Policy (id or technical name) to use it whatever its conditions, as Payroll does with PayRunApproval; a named policy that doesn't serve the type is refused. Asking again while a request is pending returns it; asking with another SubjectVersion withdraws it and asks again.

From a workflow: Request Approval takes the approval type, an optional policy, the subject's id, scope, title, page, amount and currency (Liquid), and writes ApprovalRequestId. The Approval Requested, Approval Partly Approved, Approval Stage Approved, Approval Approved, Approval Rejected and Approval Canceled events take an optional Approval type, so a workflow starts only for its type.

Add fields with display drivers​

The request page renders the request with display type DetailAdmin, and the list rows with SummaryAdmin and SummaryAdminGrid; the policy editor is an editor of ApprovalPolicy. Add a DisplayDriver<ApprovalRequest> whose CanHandleModel accepts only your type to show the ticket's details on the request page:

public sealed class TicketApprovalDisplayDriver : DisplayDriver<ApprovalRequest>
{
public override bool CanHandleModel(ApprovalRequest request)
=> request.SubjectKind == "Ticket";

public override IDisplayResult Display(ApprovalRequest request, BuildDisplayContext context)
=> context.DisplayType == "DetailAdmin"
? View("TicketApproval_DetailAdmin", request).Location("Content:5")
: null;
}

A DisplayDriver<ApprovalPolicy> adds fields to the policy editor the same way, stored on the policy with Put; check policy.Type in CanHandleModel so the fields show only on your type's policies. The editor's own shapes are ApprovalPolicyFields_Edit (Content:1), ApprovalPolicyConditions_Edit (Content:2, only for types with conditions) and ApprovalPolicyStages_Edit (Content:10). Each card of the Add approval policy dialog is the ApprovalPolicyType_Link shape with the alternate ApprovalPolicyType_Link__{Name}, so a type can give its card its own look.

Who sees and decides requests​

WhoSeesDecides
A person a rule of the current stage namesWaiting for me, and the request page (still, after deciding it)Yes, with no Approvals permission
The requesterMy requests, and the request pageNo (unless the policy allows); may withdraw it
ViewApprovalRequestsAll requests of the subject types their source access allowsOnly where a rule names them
ManageApprovalRequestsas ViewMay withdraw any request their source access allows at the Manage level

The module that owns a type registers an ISourceAccess for it (see Banking: who sees which disbursements); approvers need it at the Manage level, and the list, export, data set and workflow tasks use it for people who see requests through the permission. Anyone else gets "not found" for a request, not even that it exists. Waiting for me reads the pending requests the person's access allows from the database, a batch at a time (ApprovalInbox.BatchSize), and checks each one's current stage, so its count is exact.

Reference​

IApprovalService:

MethodDoes
RequestAsync(submission, requester)Asks under the named or chosen policy; one request at a time per subject (a lock).
GetEligibilityAsync(request, user)Whether the person may decide the current stage, and why not.
DecideAsync(request, user, kind, note)Approves or rejects; rejecting needs a note. One decision at a time per request, on a fresh read.
CancelAsync(request, reason)Withdraws a pending request.
GetApproverUserIdsAsync(request)The users who may still decide the current stage, for notices.

Other extension points: IApprovalObserver (services.AddApprovalObserver<T>()) after every change (Requested, PartlyApproved, StageApproved, Approved, Rejected, Canceled); IApprovalTypeCatalog to list types and get their handlers.

Notifications. With OrchardCore.Notifications on, the notification center is the approver's inbox: Approval (Approvals to decide) for each stage's approvers, removed when the stage or the request closes, and ApprovalDecided (Approval decisions) for the requester.

Workflows. Events: Approval Requested, Approval Partly Approved (one approver approved and more are needed), Approval Stage Approved (the next stage starts; Stage and ApproverUserNames are the new stage's), Approval Approved, Approval Rejected and Approval Canceled (withdrawn; Note is the reason) (correlation id is the request id; input RequestId, SubjectKind, SubjectId, Title, PolicyId, PolicyTitle, Status, Change, RequesterName, ApproverUserNames, Decider, Note, DueUtc, Stage, Amount, Currency). Tasks: Request Approval, Approve Request and Reject Request (decide as the person the workflow runs for; outcomes Done, NotAllowed, NotFound), Get Approval Request. The Automation: remind approvers recipe adds a disabled reminder workflow (a Timer Event and Notify User Task).

Data. The Approval requests data set (ApprovalRequests) has a row per request with its type, stage, policy, status, amount, approvals, requester, deciders and dates. Recipe and deployment steps ApprovalPolicies (with Types, Enabled, Order, the conditions and Stages) and ApprovalRequests (history only).

PermissionAllows
ManageApprovalPoliciesAdd, edit and delete approval policies.
ViewApprovalRequestsSee all the requests the source access allows. Deciding needs a rule that names you, not this permission.
ManageApprovalRequestsWithdraw anyone's pending request. Implies View.