Project 5: Approval Workflow Engine

Build a policy-driven approval orchestrator that routes high-risk quotes using explicit thresholds, state transitions, and SLA escalations.

Quick Reference

Attribute Value
Difficulty Level 3 (Advanced)
Time Estimate 2-3 weeks
Main Programming Language Python (Alternatives: TypeScript, Java, Go)
Coolness Level Level 3
Business Potential 3. Service & Support Model
Prerequisites Projects 3-4, state machine basics, async processing
Key Topics Routing plans, authority matrix, escalations, idempotency

1. Learning Objectives

  1. Model approvals as data-driven routing plans.
  2. Implement deterministic state transitions and action handling.
  3. Attach evidence packets for faster approval decisions.
  4. Monitor workflow health with SLA and queue metrics.

2. All Theory Needed (Per-Concept Breakdown)

Concept A: Approval as Policy Execution

Fundamentals Approvals are execution of commercial policy, not just notifications.

Deep Dive into the concept Separate decisioning (whether and who) from execution (task lifecycle). Persist policy version and evidence with every workflow instance. Ensure actions are idempotent.

How this fit on projects Primary here, reused in P07-crm-sync-integration.md and P10-visual-rule-builder.md.

Definitions & key terms

  • Authority matrix
  • SLA escalation
  • Routing plan

Mental model diagram

Policy Check -> Routing Plan -> Task Graph -> Final Decision

How it works

  1. Evaluate quote against approval triggers.
  2. Build approver plan.
  3. Execute tasks with deadlines.
  4. Apply approve/reject events idempotently.

Minimal concrete example

if margin < 24% => finance approval required
if non-standard clause => legal approval required

Common misconceptions

  • “Parallel approvals mean any approver is enough.” Completion semantics must be explicit.

Check-your-understanding questions

  1. Why persist policy version id?
  2. Why separate SLA from authority escalation?

Check-your-understanding answers

  1. To explain decision logic later.
  2. They solve different risks (delay vs authority limits).

Real-world applications Deal desks, legal review workflows, procurement approvals.

Where you’ll apply it This project and P10-visual-rule-builder.md.

References

  • Workflow patterns website.
  • Salesforce quote automation context.

Key insights Approval speed improves when policy and evidence are explicit.

Summary Stateful, observable approval orchestration protects margin without stalling sales.

Homework/Exercises to practice the concept Design authority matrix for three discount bands.

Solutions to the homework/exercises Bind thresholds to role groups and add expiry dates for exceptions.

3. Project Specification

3.1 What You Will Build

A workflow service that creates approval tasks from quote policy triggers and drives lifecycle transitions.

3.2 Functional Requirements

  1. Generate routing plans from quote context.
  2. Support sequential and parallel steps.
  3. Implement timeout escalation and delegation.
  4. Return full workflow status and history.

3.3 Non-Functional Requirements

  • Performance: create workflow in under 500ms.
  • Reliability: idempotent action processing.
  • Usability: clear pending reasons and due dates.

3.4 Example Usage / Output

$ cpq approval submit --quote Q-2026-0120
workflow=WF-8821 status=pending steps=2

3.5 Data Formats / Schemas / Protocols

  • WorkflowInstance(id, quoteId, policyVersion, status)
  • ApprovalTask(id, role, assignee, dueAt, status)
  • WorkflowEvent(id, taskId, action, actor, timestamp)

3.6 Edge Cases

  • Duplicate approve clicks.
  • Delegate unavailable.
  • Policy updated mid-flow.

3.7 Real World Outcome

3.7.1 How to Run (Copy/Paste)

$ cpq approval submit --quote Q-2026-0120
$ cpq approval status --workflow WF-8821
$ cpq approval action --workflow WF-8821 --task T-22 --action approve

3.7.2 Golden Path Demo (Deterministic)

Low-margin quote triggers manager + finance, both approve, status becomes approved.

3.7.3 If CLI: Exact terminal transcript

$ cpq approval status --workflow WF-8821
status=pending
current_tasks=[manager,finance]
margin_trigger=below_floor

4. Solution Architecture

4.1 High-Level Design

Quote Policy Evaluator -> Routing Planner -> Workflow Executor -> Notification/History

4.2 Key Components

| Component | Responsibility | Key Decisions | |———–|—————-|—————| | Trigger Evaluator | Determine if approval needed | threshold matrix | | Routing Planner | Build step graph | sequential/parallel semantics | | Executor | Handle state transitions | idempotent events |

4.4 Data Structures (No Full Code)

RoutingStep { role, required, slaHours }
WorkflowState { status, currentTaskIds, history }

4.4 Algorithm Overview

  1. Build routing plan from triggers.
  2. Initialize workflow tasks.
  3. Consume actions and update state.
  4. Escalate overdue tasks.

5. Implementation Guide

5.1 Development Environment Setup

$ cpq seed --scenario approvals
$ cpq test --suite workflow

5.2 Project Structure

approval-engine/
  src/
    planner/
    executor/
    escalations/

5.3 The Core Question You’re Answering

“How do we encode policy controls without manual approval chaos?”

5.4 Concepts You Must Understand First

  • State machine transitions
  • Authority and SLA rules
  • Idempotent action handling

5.5 Questions to Guide Your Design

  • What triggers each approval role?
  • How do you resolve stale tasks?

5.6 Thinking Exercise

Design rejection path and quote revision re-entry behavior.

5.7 The Interview Questions They’ll Ask

  1. How do you design a scalable approval workflow?
  2. How do you prevent duplicate approvals?
  3. How do you monitor workflow bottlenecks?

5.8 Hints in Layers

  • Hint 1: persist policy snapshots.
  • Hint 2: model transitions explicitly.
  • Hint 3: treat actions as idempotent events.

5.9 Books That Will Help

| Topic | Book | Chapter | |——-|——|———| | System orchestration | “Fundamentals of Software Architecture” | Ch. 7-10 | | Use case boundaries | “Clean Architecture” | Ch. 20-23 |

5.10 Implementation Phases

  • Phase 1: policy triggers and planner.
  • Phase 2: task executor and transitions.
  • Phase 3: escalation and observability.

5.11 Key Implementation Decisions

| Decision | Options | Recommendation | Rationale | |———-|———|—————-|———–| | Transition model | implicit, explicit FSM | explicit FSM | debugging clarity | | Action processing | best effort, idempotent | idempotent | retry safety |

6. Testing Strategy

6.1 Test Categories

| Category | Purpose | Examples | |———-|———|———-| | Unit | transition guards | approve/reject | | Integration | workflow lifecycle | multi-step approval | | Chaos | retries/timeouts | duplicate events |

6.2 Critical Test Cases

  1. Parallel approval with all-required semantics.
  2. Escalation after SLA breach.
  3. Duplicate approve event replay.

6.3 Test Data

approval_matrix.json, workflow_scenarios.json.

7. Common Pitfalls & Debugging

7.1 Frequent Mistakes

| Pitfall | Symptom | Solution | |———|———|———-| | No policy version snapshot | cannot explain decisions | persist policy id | | Non-idempotent handlers | duplicate transitions | event dedupe keys |

7.2 Debugging Strategies

  • Rebuild timeline from workflow events.
  • Compare task graph to policy plan.

7.3 Performance Traps

Avoid synchronous fan-out notifications in transition path.

8. Extensions & Challenges

8.1 Beginner Extensions

  • Add comment requirements for rejections.
  • Add reminder notifications.

8.2 Intermediate Extensions

  • Delegation windows with role constraints.
  • Approval analytics dashboard.

8.3 Advanced Extensions

  • Policy experimentation with safe canary rollout.
  • Predictive approval-time estimation.

9. Real-World Connections

9.1 Industry Applications

  • Deal desk operations.
  • Enterprise procurement approvals.

9.3 Interview Relevance

Demonstrates controlled stateful orchestration under business policy constraints.

10. Resources

10.1 Essential Reading

  • Workflow patterns references.
  • Architecture tradeoff chapters.

10.2 Video Resources

  • Workflow engine design sessions.

10.3 Tools & Documentation

  • Temporal/Camunda docs.

11. Self-Assessment Checklist

  • I can explain every approval path and trigger.
  • I can replay workflow history from events.
  • I can prove duplicate actions are harmless.

12. Submission / Completion Criteria

Minimum Viable Completion:

  • Workflow submission and action handling work.
  • Status and history APIs exist.

Full Completion:

  • Escalations and delegation implemented.
  • Observability metrics instrumented.

Excellence (Going Above & Beyond):

  • Policy simulation and bottleneck heatmaps.