Skip to main content

Documentation Index

Fetch the complete documentation index at: https://grantmaster.dev/llms.txt

Use this file to discover all available pages before exploring further.

State Machines & Lifecycles

GrantMaster manages several complex business lifecycles using structured state machines. This document details the transitions, triggers, and side-effects for each.

1. Grant Pipeline Lifecycle

Moves an opportunity from discovery to final outcome.

Transition Details

FromToTriggerSide-Effects
AnyPROSPECTaddToPipeline()Create GrantPipelineEntry, emit PIPELINE_ENTRY_CREATED.
PROSPECTIN_PREPARATIONupdateStage()Initialize GrantApplication workspace, create default tasks.
SUBMITTEDWONconvertToActiveGrant()Create ActiveGrant, freeze budget, notify finance team.
AnyDEADarchivePipeline()Log rejectionReason, notify team.

2. Expense Approval Lifecycle

Source: ExpenseStatus in the expense schema/workflow contracts.

Transition Details

StateBehavior
DRAFTEditable by the creator. Not visible in department budgets.
PENDINGImmutable by creator. Blocks relevant budget line items as “committed”.
APPROVEDFinal state for grant allocation. Emits EXPENSE_APPROVED trigger for Novu.
REJECTEDReturned to creator with comments. Can be edited and resubmitted.

3. Reporting Lifecycle (Post-Award)

Managed for each ActiveGrant.

Automated Triggers

  • 30 Days Before: Send internal reminder to Project Lead.
  • 7 Days Before: Escalation notification to Director if status is not SUBMITTED.
  • Day After: Mark as OVERDUE and trigger high-priority system alert.

4. Monthly Journal Lifecycle

Source: JournalSubmissionStatus in src/schemas/journals.schema.ts
Managed for monthly journal submissions via useJournalSubmissions hook.

States

StateBehavior
DRAFTEditable by the employee. May be auto-generated from journal data.
SUBMITTEDLocked for employee edits. Awaiting manager review.
APPROVEDFinal state. Feeds into compliance reporting.
REJECTEDReturned with feedback. Employee can edit and resubmit.
REGENERATION_NEEDEDAI-generated content flagged for regeneration. Returns to DRAFT.

5. Active Grant Lifecycle

Source: ActiveGrantStatus in the grants contract module.
Tracks the lifecycle of a won grant from activation through completion or early termination.

States

StateBehavior
ACTIVEGrant is live. Budget tracking, reporting, and compliance are active.
COMPLETEDAll deliverables and reports submitted. Grant is closed normally.
SUSPENDEDTemporarily paused. Expenditures blocked until resolved.
TERMINATEDEarly closure. Triggers close-out reporting and remaining fund return.

6. Subscription Lifecycle

Source: functions/src/stripe/stateMachine.ts
Stripe-driven subscription state machine. Transitions are validated and audit-logged. Invalid transitions are stored in the subscription_transition_logs collection.

States

StateCategoryBehavior
trialingActiveFull access to tier features. No charges yet.
activeActiveSubscription is current and paid.
past_duePayment problemPayment failed, retrying via Stripe dunning. Features remain accessible.
unpaidPayment problemAll retry attempts exhausted. Features may be restricted.
incompletePayment problemInitial payment not yet confirmed.
pausedPausedManually paused. No charges; features may be limited.
canceledTerminalSubscription ended. Organization downgraded to Starter (free) tier.
incomplete_expiredTerminalInitial payment window expired. Organization on Starter tier.

Helper Functions (functions/src/stripe/stateMachine.ts)

FunctionDescription
isValidTransition(from, to)Check if a state transition is allowed
validateAndLogTransition(orgId, from, to)Validate and audit-log the transition
isTerminalStatus(status)true for canceled and incomplete_expired
isActiveStatus(status)true for active and trialing
isPaymentProblemStatus(status)true for past_due, unpaid, incomplete
getTierForStatus(status)Returns 'Starter' for terminal/unpaid states


7. Document Lifecycle

Source: DocumentStatus in the documents contract module.
Documents pass through a RAG-indexing pipeline after upload, and can optionally enter an approval workflow before being shared externally.

States

StateBehavior
UPLOADINGFile is in transit to Firebase Storage.
PROCESSINGDocument Brain is chunking and embedding the file for RAG.
INDEXEDAvailable for AI search. Editable metadata, downloadable.
FAILEDProcessing error. Admin can retry or delete.
PENDING_APPROVALAwaiting manager sign-off before external distribution.
APPROVEDCleared for sharing. Share link can be generated.
REJECTEDReturned to INDEXED state; rejection reason visible to uploader.
SHAREDExternal link is live and accessible.
ARCHIVEDSoft-deleted. Hidden from search; restorable by admin within 30 days.

Side-Effects

TransitionSide-Effects
PROCESSING → INDEXEDEmit DOCUMENT_INDEXED; notify uploader
PROCESSING → FAILEDEmit DOCUMENT_PROCESSING_FAILED; create compliance alert if required doc
PENDING_APPROVAL → APPROVEDEmit DOCUMENT_APPROVED; generate share link
PENDING_APPROVAL → REJECTEDNotify uploader with rejection reason

8. Project Phase Lifecycle

Source: ProjectPhase and ProjectStatus enums in src/schemas/projects.schema.ts
Projects have two overlapping state dimensions: phase (where the project is in its lifecycle) and status (operational health). Phase advances sequentially; status can change at any phase.

Phase Progression

Status Overlay

Phase / Status Matrix

PhaseAllowed StatusesNotes
initiationplanningInitial state on project creation
planningplanning, activeBudget and team assigned
executionactive, on_holdMilestone tracking live
monitoringactive, on_holdReporting and evaluation active
closureactive, completedFinal reports being prepared
AnyarchivedTerminal; all write operations blocked

Side-Effects

TransitionSide-Effects
Phase initiation → planningCreate default budget categories; emit PROJECT_CREATED
Phase planning → executionEmit PROJECT_STARTED; activate budget tracking
Status active → on_holdEmit PROJECT_ON_HOLD; notify project manager and finance
Phase monitoring → closureEmit PROJECT_CLOSURE_INITIATED; trigger grant report reminders
Status * → completedEmit PROJECT_COMPLETED; archive active milestones; notify linked grant managers
Status * → archivedEmit PROJECT_ARCHIVED; freeze all writes on linked budgets and tasks

9. User Invitation Lifecycle

Source: InvitationStatus in the shared auth contracts and invitationService.ts in src/shared/auth/

States

StateBehavior
PENDINGInvitation email sent; signed JWT stored in invitations collection.
ACCEPTEDUser account created in Firebase Auth; employees document created; invitation document deleted.
EXPIREDToken TTL elapsed. Admin can issue a new invitation; original record remains for audit.
REVOKEDAdmin manually cancelled before acceptance.

Side-Effects

TransitionSide-Effects
[*] → PENDINGSend Postmark user-invitation email; emit USER_INVITED; write audit log
PENDING → ACCEPTEDCreate employees document with role from invitation; emit USER_ONBOARDED; trigger role-based onboarding tour
PENDING → EXPIREDEmit INVITATION_EXPIRED (scheduled check); update invitation status
PENDING → REVOKEDEmit INVITATION_REVOKED; write audit log

10. Extension / Module Installation Lifecycle

Source: extension contracts and ExtensionActivationService.ts in src/shared/platform/

States

StateBehavior
INSTALLINGactivate() hook running. ModuleRegistry entry created. Extension not yet visible to users.
ACTIVEExtension fully operational. Widgets registered; commands available in ⌘K palette.
ERRORActivation or runtime failure. Widgets and commands unregistered. Admin sees error details.
DEACTIVATEDManually disabled. Widgets and commands removed; Firestore data preserved.

Activation Steps (in order)

  1. isCompatible(manifest.coreApiVersion) — version check; rejects if false
  2. Quota check — does the org’s tier allow this module?
  3. Call extension.activate() — registers EventBus subscriptions, widgets, commands
  4. Write ModuleInstallation document with status: 'active'
  5. Emit MODULE_INSTALLED on EventBus

Deactivation Steps (in order)

  1. Call extension.deactivate() — cleans up commands and widgets
  2. Call bus.unsubscribeAll() — removes all EventBus listeners
  3. Update ModuleInstallation.status to 'deactivated'
  4. Emit MODULE_DEACTIVATED on EventBus

11. Compliance Violation Lifecycle

Source: compliance schema/contracts.

States

StateBehavior
OPENAlert created; visible in compliance dashboard and auditor 5-dimension view.
ACKNOWLEDGEDTeam member has seen it. SLA clock starts.
IN_PROGRESSActive remediation work underway. Linked to a task or workflow.
ESCALATEDSLA threshold breached; escalated to Director or Admin.
RESOLVEDUnderlying rule condition no longer met; resolution notes recorded.

SLA Defaults by Severity

SeverityAcknowledge byResolve by
low5 business days30 days
medium2 business days14 days
high1 business day7 days
critical4 hours24 hours

Side-Effects

TransitionSide-Effects
[*] → OPENEmit COMPLIANCE_VIOLATION_DETECTED; send notification to compliance lead
OPEN → ESCALATEDEmit COMPLIANCE_ESCALATED; notify Director / Admin
IN_PROGRESS → RESOLVEDEmit COMPLIANCE_VIOLATION_RESOLVED; write audit log with resolution notes

Maintenance

Update this document when:
  • Adding a new stage to the owning schema or feature contract enum.
  • Changing the lead time for automated reminders.
  • Introducing a new workflow (e.g., Partner Onboarding).
  • Adding or changing SLA defaults for compliance alerts.