Workflows

Workflow engine for managing renovation project execution. Template-based system: workflow templates define phases and tasks; the factory instantiates them as workflow packages (one per won quote / engagement); a state machine governs transitions; product-pair rules enable automation.

Pivot: the V3 engine is being superseded by Workflow v4. The engine first moved from quote-owned phases to the workflow_packages instance family (contractor-engagement rebuild, spec 2026-05-09-contractor-engagement-rebuild-design.md; handover redesign 2026-05-29). Workflow v4 is now landing in three parts under umbrella I#1933: PR-1 data layer merged PR#1942; siblings are I#1934 (Admin Kanban UI) and I#1935 (Wochenplan).

Source Files

LayerPath
Schemabackend/src/db/schema.ts
Routesbackend/src/routes/workflow/ (packages, tasks, phases, workflow-templates, deals, quotes, contractor-engagement, time-bookings, task-types, checklist-templates, analytics, …)
Package Servicebackend/src/services/workflow-package-service.ts + backend/src/services/workflow-package/
Phase / Task Servicesbackend/src/services/phase-service.ts, task-service.ts
State Machinebackend/src/services/workflow-state-machine.ts
Config / Template Servicesbackend/src/services/workflow-config-service.ts, workflow-template-service.ts
v4 Primitivesfrontend/src/lib/workflow/kanban-scoring.ts, effective-deadline.ts
Pagefrontend/src/pages/internal/WorkflowPage.tsx
Componentsfrontend/src/components/workflow/
Storefrontend/src/store/workflow.ts (Zustand)

Database Tables

Template side (config)

TablePurpose
workflowTemplatesReusable definitions — code, bilingual name (LocalizedText), engagementType, product matching arrays (matchingProductsRequired/Optional)
workflowTemplatePhasesPhases — ordering, wait phases, dependencies, optional phases, averageDurationDays (copied to packages at creation)
workflowTemplatePhaseTasksTasks — task type, workspace modules/layout, billing trigger config, documentObtainingId link to Document Obtaining
workflowTemplateVersionsVersion history (changeset jsonb per template version)
workflowChecklistTemplatesReusable checklist definitions (sections jsonb)
workflowTaskTypesTask type catalog (auto-start, approval, customer visibility, revenue share)
workflowRulesProduct-pair automation rules — type (trigger/parallel/blocks/exclusive/conditional), sourceProduct/targetProduct keys, definition jsonb

Instance side (per engagement)

TablePurpose
workflowPackagesThe running instance — projectId (nullable for manual external-contractor packages), sourceQuoteId, templateId+templateVersion, status, engagementType, order deadline, customerScore snapshot
workflowPackagePhases / workflowPackagePhaseTasksInstantiated phases/tasks — status, assignees, per-phase deadline + averageDurationDays, cancellation tracking
workflowPackageItems / workflowPackageSkillAssignments / workflowPackageAbSnapshots / workflowPackagePhaseHistoryLine-item mirror, skills, comparison snapshots, phase audit
workflowPackageDependenciesCross-package dependencies
scopeChangeLogQuote-change journaling — fromVersion/toVersion, triggerQuoteId/previousQuoteId, typed ScopeDiff with work-done warnings (see Quotes)
engagementTasks / engagementTaskDependencies / engagementTaskTemplatesContractor-engagement task layer
customTimelineItemsOperator-added timeline entries
workflowTransitionLogAudit trail of state transitions
taskTimeBookingsTime tracking entries per task

Architecture

State Machine

workflow-state-machine.ts governs phase and task transitions:

  • Phases progress with dependency/blocking rules (blockedBy, canStartWith, wait phases)
  • Transitions are validated against the current state before execution; guarded transitions require a reason
  • Every transition is logged in workflowTransitionLog (entityType: quote, phase, task, task_billing; triggeredBy: user or cascade)

Transition Log Attribution

workflowTransitionLog.actorId references contacts.id (Human FK Rule — durable identity, not users.id) since PR#1931. FK is NO ACTION so log rows survive.

Template Versioning

Templates are versioned via workflowTemplateVersions (changeset snapshots). Packages pin templateVersion at creation; phases track syncedFromVersion when template updates are synced in.

Workflow v4 Time Management (PR-1, merged)

  • Kanban scoring — 5-axis weighted sort (LIFO 0.35 / deadline 0.25 / priority 0.15 / revenue 0.10 / customer score 0.15), weights tunable + URL-shareable (kanban-scoring.ts)
  • Effective deadline — 3-level resolver: task > phase > package (effective-deadline.ts); exactly one order deadline per package
  • Duration stamping — factory copies averageDurationDays from template phases; first transition to in_progress stamps startedAt and derives task dueDate
  • Customer score — admin-configurable HubSpot property mapping onto projects.customerScore, snapshotted (frozen) onto the package at handover

Key Features

  • Phase/task hierarchy — templates define phases; phases contain tasks; tasks have checklists and workspace modules
  • Quote handover — won quotes spawn packages via the factory (sourceQuoteId); quote changes re-point packages and journal to scopeChangeLog
  • Billing triggers — task completion can trigger invoicing (partial/final, see Invoices billing module)
  • Time booking — staff log time against tasks via taskTimeBookings
  • Template management — admins create and version templates in Admin Dashboard
  • Document integration — tasks auto-create Document Obtaining collections via documentObtainingId / document set templates

Frontend State

The workflow UI uses a Zustand store at frontend/src/store/workflow.ts plus React Query (lib/queries/workflowQueries.ts) for:

  • Current package and active phase/task
  • Task status updates and optimistic mutations
  • Kanban board with weighted sorting (SortWeightsControl)

Relationships

WorkflowTemplate 1──* TemplatePhases 1──* TemplateTasks
WorkflowTemplate 1──* TemplateVersions
WorkflowTemplate 1──* WorkflowPackages (templateId + pinned version)
Quote 1──* WorkflowPackages (sourceQuoteId)
WorkflowPackage *──1 Project / Building
WorkflowPackage 1──* PackagePhases 1──* PackageTasks
WorkflowPackage 1──* ScopeChangeLog
Task *──1 WorkflowTaskType
Task 1──* TaskTimeBookings
TransitionLog *──1 Contact (actorId)

Projects | Quotes | Contacts | Users | Appointments | Document Obtaining | Departments | Admin Dashboard | Service Layer Pattern | Database Architecture