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.

Cloud Functions Reference

Source: functions/src/index.ts
Complete reference for all Firebase Cloud Functions exported from the GrantMaster backend. Functions are organized by domain. All onCall functions use Firebase callable transport and return unwrapped .data payloads.

API Gateway

api

  • Type: onRequest
  • Auth: Varies by endpoint
  • Description: Unified API gateway handling tRPC, REST, and MCP protocol requests. See tRPC Procedures for the full router tree.
  • Returns: Varies by endpoint

Organization Setup

startOrganizationSetup

  • Type: onCall
  • Auth: Public (reCAPTCHA protected)
  • Description: Self-serve organization provisioning. Creates a new organization with Potential tier, seeds default roles and config, and generates an admin invitation. Enforces rate limits per IP (6/hour), email (3/day), and domain (20/day). Rejects disposable email domains and applies stricter reCAPTCHA thresholds for free email providers.
  • Parameters: { organizationName: string; adminName: string; adminEmail: string; recaptchaToken?: string }
  • Returns: { success: boolean; organizationId: string; invitationId: string; setupUrl: string }

Authentication

createEmployeeOnOAuthSignIn

  • Type: onCall
  • Auth: Required (no App Check)
  • Description: Creates an employee record and organization after OAuth sign-in. If a pending invitation exists, joins that organization; otherwise creates a new one with Potential tier. Sends a welcome email via Postmark.
  • Parameters: { displayName?: string; photoURL?: string }
  • Returns: { success: boolean; employeeId: string; organizationId: string; isNewOrganization: boolean }

createPeopleOnOAuthSignIn

  • Type: onCall
  • Auth: Required (no App Check)
  • Description: Alias for createEmployeeOnOAuthSignIn. Both names are exported for backward compatibility during the employees-to-people migration.

revokeUserAuth

  • Type: onCall
  • Auth: Required + Admin
  • Description: Revokes Firebase Auth refresh tokens for a user, forcing immediate logout. Used when deactivating a user account.
  • Parameters: { userId: string; organizationId: string; reason?: string }
  • Returns: { success: boolean }

revokeUserAuthHTTP

  • Type: onRequest (HTTP endpoint)
  • Auth: Bearer token (Admin)
  • Description: HTTP variant of revokeUserAuth for service-to-service calls.

MFA / Security

verifyRecaptcha

  • Type: onCall
  • Auth: Public (no auth required)
  • Description: Verifies a reCAPTCHA v3 token with Google. Bypasses verification in emulator and staging environments.
  • Parameters: { token: string }
  • Returns: { success: boolean; score?: number; action?: string; error?: string }

validateMFARecoveryCode

  • Type: onCall
  • Auth: Public (intentionally — user is authenticating)
  • Description: Validates and consumes an MFA recovery code. Logs security events on failed attempts.
  • Parameters: { userId: string; recoveryCode: string }
  • Returns: { success: boolean }

generateMFARecoveryCodes

  • Type: onCall
  • Auth: Required
  • Description: Generates a new set of MFA recovery codes for the authenticated user.
  • Returns: { codes: string[] }

getMFARecoveryCodeCount

  • Type: onCall
  • Auth: Required
  • Description: Returns the number of remaining (unused) recovery codes for the authenticated user.
  • Returns: { count: number }

Document Exports

generateDocx

  • Type: onCall
  • Auth: Required + App Check
  • Description: Generates a Word (.docx) document from report data. Builds sections for executive summary, time entries, and expenses. Uploads the result to Firebase Storage and returns a 1-hour signed download URL.
  • Parameters: { reportData: { project; journals; expenses; totalHours; totalExpenses; totalSpent; dateRange }; template: any; config: { title; reportType; dateRange } }
  • Returns: { downloadUrl: string; filename: string; size: number }

generateXlsx

  • Type: onCall
  • Auth: Required + App Check
  • Description: Generates an Excel (.xlsx) spreadsheet with Summary, Journals, and Expenses worksheets. Uploads to Firebase Storage and returns a 1-hour signed download URL.
  • Parameters: { reportData: { project; journals; expenses; totalHours; totalExpenses; totalSpent; dateRange } }
  • Returns: { downloadUrl: string; filename: string; size: number }

Admin Utilities

clearBlobLogos

  • Type: onCall
  • Auth: Admin-only
  • Description: Cleans up orphaned blob logo references in Firestore.
  • Returns: { success: boolean }

populateRolePermissions

  • Type: onCall
  • Auth: Admin-only
  • Description: Seeds or updates the role-permission matrix in Firestore.
  • Returns: { success: boolean }

sentrySmokeTest

  • Type: onCall
  • Auth: Required (org membership verified)
  • Description: Fires a test Sentry message and exception to verify error monitoring is working. Disabled in production — only available in staging and local environments.
  • Parameters: { organizationId: string }
  • Returns: { success: true; messageEventId?: string; exceptionEventId?: string; environment: 'local' | 'staging' | 'production' }

Activity Feed

submitActivityFeed

  • Type: onCall
  • Auth: Required
  • Description: Creates a new activity feed entry for an organization.
  • Parameters: { organizationId: string; type: string; data: object }
  • Returns: { success: boolean }

getActivityFeed

  • Type: onCall
  • Auth: Required
  • Description: Retrieves paginated activity feed entries for an organization.
  • Parameters: { organizationId: string; limit?: number; startAfter?: string }
  • Returns: { entries: ActivityFeedEntry[]; hasMore: boolean }

deleteActivityFeed

  • Type: onCall
  • Auth: Admin-only
  • Description: Deletes an activity feed entry.
  • Parameters: { organizationId: string; entryId: string }
  • Returns: { success: boolean }

AI / Genkit

generateJournalEntries

  • Type: onCall
  • Auth: Required
  • Description: Uses Gemini AI to generate journal entries from a monthly journal summary. Produces structured journal entries distributed across projects. Validates that the employee belongs to the authenticated user.
  • Parameters: { input: JournalInput; projects: Project[]; employee: Employee; organization?: Organization }
  • Returns: { success: boolean; entries: GeneratedJournalEntry[] }

generateTimesheetEntries

  • Type: onCall
  • Auth: Required
  • Description: Alias for generateJournalEntries. Maintained for backward compatibility during the timesheets-to-journals rename.

kickoffJournalGenerationJob

  • Type: onCall
  • Auth: Required
  • Description: Creates a journal generation job document in Firestore, which triggers the background processJournalGenerationJob pipeline. Provides a job ID for polling status.
  • Returns: { jobId: string }

processJournalGenerationJob

  • Type: onDocumentWritten (Firestore trigger)
  • Auth: N/A (triggered automatically)
  • Description: Background processor for journal generation jobs. Runs a multi-stage pipeline (validate, load context, retrieve documents, draft entries, self-review, finalize) and writes the resulting artifact back to the job document.
  • Trigger: journalGenerationJobs/{jobId}

RAG (Document Intelligence)

onDocumentUpload

  • Type: onObjectFinalized (Storage trigger)
  • Auth: N/A (triggered automatically)
  • Description: Automatically processes uploaded documents. Extracts text, chunks content, generates embeddings via Gemini, and stores vectors in Firestore for semantic search.
  • Trigger: Files created in organizations/{orgId}/documents/ storage path.

queryRAG

  • Type: onCall
  • Auth: Required
  • Description: Performs semantic search across processed document chunks using vector similarity.
  • Parameters: { query: string; projectId: string; organizationId: string; limit?: number; category?: 'budget' | 'compliance' | 'reporting' | 'general'; minSimilarity?: number }
  • Returns: { success: boolean; results: DocumentChunkResult[]; query: string; error?: string }

processDocumentManual

  • Type: onCall
  • Auth: Required
  • Description: Manually triggers document processing (chunking + embedding). Useful for reprocessing or handling edge cases.
  • Parameters: { documentId: string; organizationId: string }
  • Returns: { success: boolean; documentId: string; chunkCount?: number; error?: string }

Stripe / Billing

createCheckoutSession

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Creates a Stripe Checkout session for subscription purchase. Determines price IDs from the requested tier and billing interval.
  • Parameters: { organizationId: string; tier: string; interval: 'month' | 'year'; successUrl: string; cancelUrl: string; seatCount?: number }
  • Returns: { sessionId: string; url: string }

createPortalSession

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Creates a Stripe Customer Portal session for self-service billing management.
  • Parameters: { organizationId: string; returnUrl: string }
  • Returns: { url: string }

getPaymentMethods

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Lists all payment methods attached to the organization’s Stripe customer. Marks the default payment method.
  • Parameters: { organizationId: string }
  • Returns: { paymentMethods: PaymentMethod[] }

getInvoices

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Retrieves paginated invoice history from Stripe for the organization.
  • Parameters: { organizationId: string; limit?: number; startingAfter?: string }
  • Returns: { invoices: Invoice[]; hasMore: boolean }

getSubscriptionDetails

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Retrieves detailed subscription information from Stripe including current period, tier, and billing details.
  • Parameters: { organizationId: string }
  • Returns: { subscription: SubscriptionDetails | null }

stripeWebhook

  • Type: onRequest (HTTP endpoint)
  • Auth: Public (verified via Stripe signature)
  • Description: Handles Stripe webhook events with idempotent processing and state machine validation. Processes 11 event types including checkout completion, subscription updates, invoice events, and payment failures.
  • Handled Events: checkout.session.completed, customer.subscription.created, customer.subscription.updated, customer.subscription.deleted, invoice.paid, invoice.payment_failed, invoice.payment_action_required, invoice.finalized, payment_intent.succeeded, payment_intent.payment_failed, customer.updated
  • Returns: { received: true }

Stripe / Payment Methods

createSetupIntent

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Creates a Stripe SetupIntent for securely adding a payment method via Stripe Elements. The client uses the returned clientSecret with the Payment Element.
  • Parameters: { organizationId: string }
  • Returns: { clientSecret: string }

attachPaymentMethod

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Attaches a payment method to the organization’s Stripe customer.
  • Parameters: { organizationId: string; paymentMethodId: string }
  • Returns: { success: boolean; paymentMethod: PaymentMethod }

detachPaymentMethod

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Detaches (removes) a payment method from the organization’s Stripe customer.
  • Parameters: { organizationId: string; paymentMethodId: string }
  • Returns: { success: boolean }

setDefaultPaymentMethod

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Sets the default payment method for both the customer and active subscription. Updates Stripe and Firestore.
  • Parameters: { organizationId: string; paymentMethodId: string }
  • Returns: { success: boolean }

Stripe / Subscription Operations

updateSubscription

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Upgrades or downgrades the subscription tier. Handles proration and updates Firestore records.
  • Parameters: { organizationId: string; newTier: string; interval?: 'month' | 'year' }
  • Returns: { success: boolean; subscription: SubscriptionDetails }

cancelSubscription

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Cancels the subscription at the end of the current billing period.
  • Parameters: { organizationId: string; reason?: string; feedback?: string }
  • Returns: { success: boolean; cancelAt: string }

reactivateSubscription

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Reactivates a subscription that was scheduled for cancellation.
  • Parameters: { organizationId: string }
  • Returns: { success: boolean }

Stripe / Payment Settings

getPaymentSettings

  • Type: onCall
  • Auth: Required + App Check (any org member)
  • Description: Retrieves payment settings for the organization (billing email, auto-recharge, invoice preferences).
  • Parameters: { organizationId: string }
  • Returns: { settings: PaymentSettings }

updatePaymentSettings

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Updates payment settings for the organization.
  • Parameters: { organizationId: string; settings: Partial<PaymentSettings> }
  • Returns: { success: boolean }

Stripe / Subscription Management (Seats)

updateSubscriptionSeats

  • Type: onCall
  • Auth: Required + App Check + Admin/Super Admin
  • Description: Updates the seat quantity on the subscription. Handles proration and Stripe quantity changes.
  • Parameters: { organizationId: string; newSeatCount: number }
  • Returns: { success: boolean; newQuantity: number; prorationAmount?: number }

getSeatsUsage

  • Type: onCall
  • Auth: Required + App Check
  • Description: Returns current seat usage vs. allocation for the organization.
  • Parameters: { organizationId: string }
  • Returns: { used: number; total: number; available: number }

syncSubscriptionUsage

  • Type: onCall
  • Auth: Required + App Check
  • Description: Synchronizes local seat counts with the Stripe subscription quantity.
  • Parameters: { organizationId: string }
  • Returns: { success: boolean; synced: boolean }

checkSeatAvailability

  • Type: onCall
  • Auth: Required + App Check
  • Description: Checks whether additional seats are available for new user invitations.
  • Parameters: { organizationId: string; requestedSeats?: number }
  • Returns: { available: boolean; remainingSeats: number }

calculateSeatChangeCost

  • Type: onCall
  • Auth: Required + App Check
  • Description: Previews the cost of adding or removing seats, including proration.
  • Parameters: { organizationId: string; newSeatCount: number }
  • Returns: { currentSeats: number; newSeats: number; proratedAmount: number; nextInvoiceAmount: number }

refreshSeatCounts

  • Type: onCall
  • Auth: Required + App Check
  • Description: Recounts active employees and updates the organization’s seat usage in Firestore.
  • Parameters: { organizationId: string }
  • Returns: { success: boolean; seatCount: number }

Postmark / Email Admin

getEmailActivity

  • Type: onCall
  • Auth: Required + Super Admin
  • Description: Retrieves recent email activity from Postmark (sends, opens, bounces).
  • Parameters: { count?: number; offset?: number }
  • Returns: { totalCount: number; messages: PostmarkMessage[] }

getEmailStats

  • Type: onCall
  • Auth: Required + Super Admin
  • Description: Retrieves email delivery statistics from Postmark (sent, bounced, opened, etc.).
  • Parameters: { fromDate?: string; toDate?: string; tag?: string }
  • Returns: { stats: PostmarkStats }

getBounces

  • Type: onCall
  • Auth: Required + Super Admin
  • Description: Retrieves bounced email list from Postmark.
  • Parameters: { count?: number; offset?: number; type?: string; inactive?: boolean; emailFilter?: string }
  • Returns: { totalCount: number; bounces: PostmarkBounce[] }

activateBounce

  • Type: onCall
  • Auth: Required + Super Admin
  • Description: Reactivates a bounced email address in Postmark, allowing future sends.
  • Parameters: { bounceId: number }
  • Returns: { message: string; bounce: PostmarkBounce }

searchEmailByRecipient

  • Type: onCall
  • Auth: Required
  • Description: Searches Postmark email activity by recipient address.
  • Parameters: { recipient: string; count?: number; offset?: number }
  • Returns: { totalCount: number; messages: PostmarkMessage[] }

sendTestEmail

  • Type: onCall
  • Auth: Required + Super Admin
  • Description: Sends a test email via Postmark to verify configuration.
  • Parameters: { to: string; subject?: string; body?: string }
  • Returns: { success: boolean; messageId: string }

Email Invitations

sendAdminInvitation

  • Type: onCall
  • Auth: Required + Super Admin
  • Description: Creates an invitation record and sends an invitation email to a new user. Creates the invitation document in Firestore which triggers onInvitationCreated.
  • Parameters: { email: string; organizationId: string; role?: string; organizationRole?: string; message?: string }
  • Returns: { success: boolean; invitationId: string }

onInvitationCreated

  • Type: onDocumentCreated (Firestore trigger)
  • Auth: N/A (triggered automatically)
  • Description: Sends an invitation email via Postmark when a new invitation document is created in Firestore.
  • Trigger: invitations/{invitationId}

resendInvitation

  • Type: onCall
  • Auth: Required + Admin or original inviter
  • Description: Resends a pending invitation email and updates the invitation timestamp.
  • Parameters: { invitationId: string; organizationId: string }
  • Returns: { success: boolean }

Notification Emails

onNotificationCreated

  • Type: onDocumentCreated (Firestore trigger)
  • Auth: N/A (triggered automatically)
  • Description: Sends an email when a new notification document is created. Respects user preferences: checks email enabled/disabled, frequency setting (immediate vs. digest), quiet hours, and per-category opt-outs. Uses Postmark templates for known notification types (journal approved/rejected, expense approved/rejected, budget alerts, deadline reminders) and falls back to a generic HTML template for other types.
  • Trigger: notifications/{notificationId}

sendDailyDigests

  • Type: onSchedule
  • Schedule: Daily at 08:00 UTC
  • Auth: N/A (scheduled)
  • Description: Sends daily notification digest emails to users who have frequency set to “daily”. Collects up to 50 unread, un-emailed notifications per user, groups them by category (journals, expenses, projects, budget, security, system), and sends a single digest email via Postmark.

sendWeeklyDigests

  • Type: onSchedule
  • Schedule: Mondays at 08:00 UTC
  • Auth: N/A (scheduled)
  • Description: Sends weekly notification digest emails to users who have frequency set to “weekly”. Same grouping as daily digests but covers the past 7 days with a limit of 100 notifications per user.

Scheduled Deadline Reminders

checkDeadlineReminders

  • Type: onSchedule
  • Schedule: Daily at 08:00 UTC
  • Auth: N/A (scheduled)
  • Description: Scans all organizations for active milestones/deadlines and sends reminder notifications at 7 days, 1 day, same day, and marks overdue items. Creates notification documents in Firestore (which in turn trigger onNotificationCreated).

triggerDeadlineReminders

  • Type: onCall
  • Auth: Required + Super Admin
  • Description: Manually triggers the deadline reminder check for a single organization or all organizations.
  • Parameters: { organizationId?: string }
  • Returns: { success: boolean; stats: { totalOrganizations; totalDeadlines; totalReminders; errors } }

Scheduled Invitation Reminders

sendScheduledInvitationReminders

  • Type: onSchedule
  • Schedule: Daily at 10:00 UTC
  • Auth: N/A (scheduled)
  • Description: Finds pending invitations that are 7+ days old without a response, sends reminder emails via Postmark, and updates invitation records. Includes 100ms rate limiting between emails.

triggerInvitationReminders

  • Type: onCall
  • Auth: Required + Admin
  • Description: Manually triggers invitation reminders for an organization.
  • Returns: { success: boolean; result: ReminderProcessingResult }

getInvitationReminderMetrics

  • Type: onCall
  • Auth: Required + Admin
  • Description: Retrieves metrics on invitation reminder performance over a configurable window.
  • Parameters: { days?: number }
  • Returns: Reminder metrics summary

Referral Credits

onEmployeeCreated

  • Type: onDocumentCreated (Firestore trigger)
  • Auth: N/A (triggered automatically)
  • Description: Awards Mission Credits (EUR 100) to the referrer when a new employee signs up using a referral code and their organization reaches the Growth tier.
  • Trigger: employees/{employeeId}

manuallyAwardReferralCredit

  • Type: onCall
  • Auth: Required + Super Admin
  • Description: Manually awards a referral credit to an organization. Used for manual corrections or special promotions.
  • Parameters: { organizationId: string; referrerOrganizationId: string; amount?: number; reason?: string }
  • Returns: { success: boolean; transactionId: string }

Feedback

submitFeedback

  • Type: onCall
  • Auth: Public (works with or without auth)
  • Description: Submits user feedback. Sends an email via Postmark to support@grantmaster.ai and stores the feedback in Firestore.
  • Parameters: { type: 'bug' | 'feature' | 'general'; subject: string; message: string; email?: string; metadata?: object }
  • Returns: { success: boolean }

Waitlist

joinWaitlist

  • Type: onCall
  • Auth: Public (no auth required)
  • Description: Adds an email to the waitlist. Sends an early-registration welcome email via Postmark on first sign-up. Idempotent — returns alreadyJoined: true for repeat submissions.
  • Parameters: { email: string; name?: string }
  • Returns: { success: true; alreadyJoined: boolean; emailSent: boolean }

framerWaitlistWebhook

  • Type: onRequest (HTTP endpoint)
  • Auth: Framer webhook signature (HMAC-SHA256)
  • Description: Receives Framer form submission webhooks. Verifies the Framer-Signature header using the shared secret, extracts email and name from the payload, and processes a waitlist sign-up.
  • Returns: 201 on new sign-up, 200 if already joined

Usage Monitoring

checkUsageAlerts

  • Type: onSchedule
  • Schedule: Every 1 hour
  • Auth: N/A (scheduled)
  • Description: Checks all organizations’ usage aggregates (API calls, AI generations, storage) against tier limits. Sends alerts at 80%, 90%, 95%, and 100% thresholds. Alerts are deduplicated per period.

resetMonthlyCounters

  • Type: onSchedule
  • Schedule: 1st of each month at 00:00 UTC (0 0 1 * *)
  • Auth: N/A (scheduled)
  • Description: Resets monthly usage aggregate counters for all organizations (API calls, AI generations, storage, report generations, data exports).

checkOrganizationAlerts

  • Type: onCall
  • Auth: Required
  • Description: Manually triggers the usage alert check for a single organization.
  • Parameters: { organizationId: string }
  • Returns: { success: boolean; message: string }

Durable Eventing

The durable eventing system implements the Transactional Outbox pattern for reliable cross-domain event processing. Events written to the eventOutbox collection are dispatched to Cloud Tasks, processed by registered consumer handlers, and moved to the dead-letter queue after exhausting retries.

onEventOutboxCreated

  • Type: onDocumentCreated (Firestore trigger)
  • Auth: N/A (triggered automatically)
  • Description: Listens for new documents in the eventOutbox collection. Enqueues a Cloud Task for processing and marks the event as DISPATCHED.
  • Trigger: eventOutbox/{eventId}

processDurableSystemEvent

  • Type: onTaskDispatched (Cloud Tasks worker)
  • Auth: N/A (task queue)
  • Description: Processes a durable event by fanning out to registered consumer handlers. Each consumer runs with idempotency guarantees via the eventConsumptions collection. After all consumers succeed, the event is marked PROCESSED. After 5 failed attempts, the event moves to the eventDlq collection.
  • Retry Config: Max 5 attempts, 10-300 second backoff with 5 doublings, max 20 concurrent dispatches at 5/second.
  • Registered Consumers:
    • core-system-events-ledger — persists all events to systemEvents collection (wildcard)
    • approval-projection-v1 — updates durableApprovalSummaries for approval/rejection events
    • credit-projection-v1 — updates durableCreditSummaries for credit consumed/purchased/exhausted events
    • module-projection-v1 — tracks module lifecycle state in durableModuleStates
    • intelligence-audit-v1 — writes intelligence consent and compliance violation events to durableIntelligenceAudit

replayDurableEvents

  • Type: onCall
  • Auth: Required + Admin/Super Admin
  • Description: Replays failed events from the dead-letter queue. Supports filtering by event IDs, event type, date range, and optionally includes outbox failures. Re-enqueues matching events for processing.
  • Parameters: { eventIds?: string[]; eventType?: string; startDate?: string; endDate?: string; maxEvents?: number; includeOutboxFailures?: boolean }
  • Returns: { replayedCount: number; replayedEventIds: string[]; skipped: string[] }

cleanupDurableEventRetention

  • Type: onSchedule
  • Schedule: Daily at 03:00 UTC
  • Auth: N/A (scheduled)
  • Description: Deletes old durable eventing records: successful eventConsumptions older than 30 days, PROCESSED outbox records older than 30 days, and DLQ records older than 90 days. Uses batched deletes of 500 documents.

Intelligence Platform

The cross-organization intelligence platform collects anonymized usage data from opted-in organizations, computes benchmarks, detects sector trends, and generates AI-powered predictions. All data processing enforces privacy constraints: raw data never leaves function memory, and minimum cohort sizes are required.

collectIntelligenceData

  • Type: onSchedule
  • Schedule: Daily at 02:00 UTC
  • Auth: N/A (scheduled)
  • Description: Core intelligence pipeline. Queries opted-in organizations, collects raw data via Admin SDK, anonymizes into metric snapshots, aggregates into benchmarks, and refreshes per-org caches.

triggerIntelligencePipeline

  • Type: onCall
  • Auth: Required + Admin
  • Description: Manually triggers the intelligence data collection pipeline for a specific organization.
  • Parameters: { organizationId: string }
  • Returns: { success: boolean }

onConsentChange

  • Type: onDocumentWritten (Firestore trigger)
  • Auth: N/A (triggered automatically)
  • Description: Handles changes to intelligence data consent settings. Enables or disables data collection based on organization preferences.
  • Trigger: intelligenceConsent/{organizationId}

generatePrediction

  • Type: onCall
  • Auth: Required (Ultimate tier subscription)
  • Region: europe-west1
  • Description: AI-powered prediction engine using Gemini via Genkit. Generates predictions for grant success probability and budget risk with factor analysis and confidence scores. Requires opt-in to intelligence platform.
  • Parameters: { type: 'grant_success' | 'budget_risk'; organizationId: string; ... (type-specific params) }
  • Returns: { type; score; confidence; riskLevel; factors: PredictionFactor[]; recommendations: string[] }

triggerFunderProfileRefresh

  • Type: onCall
  • Auth: Required + Super Admin
  • Region: europe-west1
  • Description: Manually refreshes funder/grantor intelligence profiles. Aggregates decision times, win rates, amounts, compliance categories, and reporting frequency patterns from opted-in organizations.
  • Returns: { success: boolean; profilesRefreshed: number }

detectSectorTrends

  • Type: onSchedule
  • Schedule: Daily at 04:00 UTC
  • Auth: N/A (scheduled)
  • Description: Compares current and previous month metric snapshots to detect sector-level trends. Also computes template effectiveness scores. Persists trend records and template effectiveness data.

getTrends

  • Type: onCall
  • Auth: Required (intelligence consent required)
  • Description: Retrieves sector trends and top-performing templates filtered by the organization’s sectors.
  • Parameters: { organizationId: string; limit?: number; includeTemplates?: boolean }
  • Returns: { trends: SectorTrend[]; templates?: TemplateEffectiveness[] }

generateHealthReport

  • Type: onCall
  • Auth: Required + Super Admin
  • Description: Generates a comprehensive health report for the intelligence platform covering opt-in rates, pipeline status, cohort sizes, data freshness, and trend statistics.
  • Returns: IntelligenceHealthReport (overall status, opt-in metrics, pipeline health, cohort coverage, freshness scores)

dailyHealthCheck

  • Type: onSchedule
  • Schedule: Daily (configured in function options)
  • Auth: N/A (scheduled)
  • Description: Automated daily health check for the intelligence platform. Runs the same diagnostics as generateHealthReport and persists the report for monitoring.

getQuickStatus

  • Type: onCall
  • Auth: Required
  • Description: Returns a lightweight status summary of the intelligence platform (overall health, opt-in count, pipeline status).
  • Returns: Quick status summary object

Search Indexing (Firestore to Typesense)

All search index triggers fire on document writes (create/update/delete) and sync data to Typesense for full-text search. If Typesense is not configured, triggers silently skip indexing.

onProjectWrite

  • Type: onDocumentWritten (Firestore trigger)
  • Description: Syncs project documents to Typesense search index.
  • Trigger: projects/{projectId}

onEmployeeWrite

  • Type: onDocumentWritten (Firestore trigger)
  • Description: Syncs employee documents to Typesense search index.
  • Trigger: people/{employeeId}

onExpenseWrite

  • Type: onDocumentWritten (Firestore trigger)
  • Description: Syncs expense documents to Typesense search index.
  • Trigger: expenses/{expenseId}

onJournalWrite

  • Type: onDocumentWritten (Firestore trigger)
  • Description: Syncs journal documents to Typesense search index.
  • Trigger: timesheets/{journalId}

onTimesheetWrite

  • Type: onDocumentWritten (Firestore trigger)
  • Description: Alias trigger for journal indexing using the legacy timesheets collection path.
  • Trigger: timesheets/{timesheetId}

onDocumentWrite

  • Type: onDocumentWritten (Firestore trigger)
  • Description: Syncs document metadata to Typesense search index.
  • Trigger: documents/{documentId}

onContactWrite

  • Type: onDocumentWritten (Firestore trigger)
  • Description: Syncs contact documents to Typesense search index.
  • Trigger: contacts/{contactId}

onComplianceRuleWrite

  • Type: onDocumentWritten (Firestore trigger)
  • Description: Syncs compliance rule documents to Typesense search index.
  • Trigger: compliance/{complianceRuleId}

reindexCollection

  • Type: onCall
  • Auth: Required + Admin
  • Description: Manually triggers a full reindex of a specified Firestore collection into Typesense.
  • Parameters: { collection: string; organizationId: string }
  • Returns: { success: boolean; indexed: number }

searchTypesenseSecure

  • Type: onCall
  • Auth: Required
  • Description: Server-side search proxy. Executes multi-collection Typesense queries with tenant isolation (filters by organizationId), role-based collection access, weighted query fields, typo tolerance tuning, and highlight extraction.
  • Parameters: { query: string; organizationId: string; collections?: SearchCollectionName[]; filters?: { status?; projectIds?; userIds? }; limit?: number }
  • Returns: { hits: SearchCallableHit[]; totalFound: number }

reportSearchTelemetry

  • Type: onCall
  • Auth: Required
  • Description: Records search telemetry metrics (success counts, errors, Fuse fallback counts) and no-result queries. Enforces tenant isolation.
  • Parameters: { organizationId: string; metricName: 'typesense_success' | 'secure_callable_error' | 'fuse_fallback_count'; query?: string; source?: string }
  • Returns: { success: boolean }

nightlyTuneSearchFromNoResults

  • Type: onSchedule
  • Schedule: Daily at 02:00 Europe/Amsterdam
  • Auth: N/A (scheduled)
  • Description: Analyzes the top no-result queries from the past 7 days, derives synonym groups, upserts them into all Typesense collections, and adjusts typo tolerance configuration. Persists a tuning report.

nightlyReconcileSearchIndex

  • Type: onSchedule
  • Schedule: Daily at 02:30 Europe/Amsterdam
  • Auth: N/A (scheduled)
  • Description: Compares document counts between Firestore collections and their Typesense counterparts. Persists a reconciliation report with drift analysis. Used to detect index drift requiring manual reindexing.

Stakeholder Portal

validatePortalToken

  • Type: onCall
  • Auth: Public (rate-limited by IP, 10 req/window)
  • Description: Validates a stakeholder portal access token, checks IP restrictions if configured, creates an audit session, and returns filtered project data based on the token’s visibility settings plus organization branding.
  • Parameters: { tokenId: string }
  • Returns: { valid: boolean; session?: PortalSession; project?: FilteredProjectData; branding?: OrgBranding }

postPortalComment

  • Type: onCall
  • Auth: Public (token-based)
  • Description: Posts a comment from a stakeholder in the portal interface.
  • Parameters: { token: string; reportId: string; comment: string }
  • Returns: { success: boolean; commentId: string }

acknowledgePortalReport

  • Type: onCall
  • Auth: Public (token-based)
  • Description: Records stakeholder acknowledgment of a shared report.
  • Parameters: { token: string; reportId: string }
  • Returns: { success: boolean }

updatePortalSession

  • Type: onCall
  • Auth: Public (token-based)
  • Description: Updates the portal session with activity tracking data.
  • Parameters: { token: string; activity: object }
  • Returns: { success: boolean }

endPortalSession

  • Type: onCall
  • Auth: Public (token-based)
  • Description: Ends a stakeholder portal session and records session summary.
  • Parameters: { token: string }
  • Returns: { success: boolean }

getPortalUploadUrl

  • Type: onCall
  • Auth: Public (token-based, rate-limited 5 req/window)
  • Description: Generates a signed upload URL for portal document submissions. Returns a 15-minute signed URL restricted to allowed MIME types (PDF, DOCX, XLSX, DOC, XLS, JPEG, PNG) with a max file size limit. Requires allowReportSubmission visibility on the token.
  • Parameters: { tokenId: string; sessionId?: string; fileName: string; mimeType: string; fileSize: number }
  • Returns: { uploadUrl: string; submissionId: string; storagePath: string }

submitPortalReport

  • Type: onCall
  • Auth: Public (token-based, rate-limited 5 req/window)
  • Description: Creates a submission record in Firestore after files have been uploaded via signed URLs. Creates a notification for project managers. Requires allowReportSubmission visibility on the token.
  • Parameters: { tokenId: string; sessionId?: string; submissionId: string; title: string; description?: string; attachments: Attachment[]; linkedReportId?: string }
  • Returns: { success: boolean; submissionId: string }

Monitoring & Evaluation (M&E)

onMEDataPointWrite

  • Type: onDocumentWritten (Firestore trigger)
  • Auth: N/A (triggered automatically)
  • Description: Processes M&E data point changes, recomputes indicator summary statistics, and triggers workflow evaluations.
  • Trigger: M&E data point documents

syncKoboForm

  • Type: onCall
  • Auth: Required
  • Description: Manually triggers a one-time sync of submissions from a KoboToolbox form into M&E data points.
  • Parameters: { organizationId: string; formId: string; indicatorId: string }
  • Returns: { success: boolean; synced: number }

syncKoboFormScheduled

  • Type: onSchedule
  • Schedule: Every 6 hours
  • Auth: N/A (scheduled)
  • Description: Scheduled function that periodically syncs all configured KoboToolbox forms for organizations with active integrations.

testKoboConnection

  • Type: onCall
  • Auth: Required
  • Description: Tests connectivity to a KoboToolbox instance with the provided credentials.
  • Parameters: { organizationId: string; apiUrl: string; apiToken: string }
  • Returns: { success: boolean; formCount?: number; error?: string }

generateDonorExport

  • Type: onCall
  • Auth: Required
  • Description: Generates a donor-ready export of M&E data (PDF or Excel) with formatted indicators, charts, and narrative.
  • Parameters: { organizationId: string; projectId: string; format: 'pdf' | 'xlsx'; indicatorIds?: string[]; dateRange?: { start: string; end: string } }
  • Returns: { success: boolean; downloadUrl: string }

meAIAnalysis

  • Type: onCall
  • Auth: Required
  • Description: Uses AI to analyze M&E data trends and generate narrative insights for reporting.
  • Parameters: { organizationId: string; projectId: string; indicatorIds: string[]; analysisType: string }
  • Returns: { success: boolean; analysis: string; recommendations?: string[] }

evaluateWorkflowOnDataPoint

  • Type: onDocumentWritten (Firestore trigger)
  • Auth: N/A (triggered automatically)
  • Description: Evaluates M&E threshold workflow rules when a data point is created or updated. Executes matching actions (notifications, status changes).
  • Trigger: M&E data point documents

evaluateEventWorkflowRules

  • Type: onCall
  • Auth: Required
  • Description: Evaluates all event-based workflow rules for a given trigger event in the M&E system.
  • Parameters: { organizationId: string; eventType: string; eventData: object }
  • Returns: { success: boolean; rulesEvaluated: number; actionsExecuted: number }

Backup & Restore

createTenantExport

  • Type: onCall
  • Auth: Required + Admin (tenant-scoped)
  • Description: Creates a backup export job for an organization. Generates a backup artifact with checksum and storage path. Writes audit events.
  • Parameters: { organizationId: string; scope?: 'tenant_full' | 'collection_subset' | 'platform_snapshot'; format?: 'json' | 'csv' | 'parquet' }
  • Returns: { backupJobId: string }

getTenantBackupJobs

  • Type: onCall
  • Auth: Required + Admin (tenant-scoped)
  • Description: Lists paginated backup jobs for an organization with their associated artifacts.
  • Parameters: { organizationId: string; cursor?: string; limit?: number }
  • Returns: { jobs: BackupJob[]; cursor: string | null }

createRestoreRequest

  • Type: onCall
  • Auth: Required + Admin (tenant-scoped)
  • Description: Creates a restore request linked to a backup artifact. The request must be approved by a SuperAdmin before execution.
  • Parameters: { organizationId: string; sourceArtifactId: string; reason: string; targetMode?: 'sandbox' | 'promote' }
  • Returns: { restoreRequestId: string }

getRestoreRequests

  • Type: onCall
  • Auth: Required + Admin (SuperAdmin sees all tenants)
  • Description: Lists restore requests, filtered by organization and/or status.
  • Parameters: { organizationId?: string; status?: string; limit?: number }
  • Returns: { requests: RestoreRequest[] }

approveRestoreRequest

  • Type: onCall
  • Auth: Required + Super Admin + Step-up Auth (MFA required, 15-min auth window)
  • Description: Approves or denies a restore request. Requires recent re-authentication and MFA second factor.
  • Parameters: { restoreRequestId: string; decision: 'approve' | 'deny'; notes?: string }
  • Returns: { success: boolean }

executeRestore

  • Type: onCall
  • Auth: Required + Super Admin + Step-up Auth (MFA required, 15-min auth window)
  • Description: Executes an approved restore request. Creates a restore job, stages data in a sandbox namespace, and records audit events.
  • Parameters: { restoreRequestId: string }
  • Returns: { restoreJobId: string }

getRestoreStatus

  • Type: onCall
  • Auth: Required + Admin (tenant-scoped)
  • Description: Returns the current status of a restore job.
  • Parameters: { restoreJobId: string }
  • Returns: { restoreJob: RestoreJob }

updateBackupPolicy

  • Type: onCall
  • Auth: Required + Super Admin
  • Description: Updates the backup policy (retention days, legal hold, schedule, immutability window) at the global or per-tenant level.
  • Parameters: { organizationId?: string; retentionDays: number; legalHold: boolean; schedule: string; immutabilityDays?: number }
  • Returns: { policyId: string }

updateBackupPolicyHttp

  • Type: onRequest (HTTP endpoint)
  • Auth: Bearer token (Super Admin)
  • Description: HTTP variant of updateBackupPolicy for service-to-service or CI/CD calls.

runPlatformResilienceBackup

  • Type: onSchedule
  • Schedule: Daily at 02:00 UTC
  • Auth: N/A (scheduled)
  • Description: Automated daily platform-level backup. Creates a backup job and artifact with a 90-day expiry for platform disaster recovery.

Audit Export

processAuditExport

  • Type: onCall
  • Auth: Required + Admin/Auditor (tenant-scoped) or Super Admin
  • Description: Processes an audit data export job. Reads the export job configuration from Firestore, fetches the requested data (audit logs, journals, expenses), formats it as CSV, JSON, or PDF, uploads to Cloud Storage, and updates the job document with a 1-hour signed download URL. Supports date range filtering, user/action/resource type filters, and severity filters.
  • Parameters: { jobId: string; organizationId: string }
  • Returns: { success: boolean; downloadUrl: string; totalRecords: number; fileSize: number }

Integration OAuth

Server-side token exchange and refresh for third-party OAuth integrations. Raw tokens are stored in Firestore and never returned to the client.

exchangeGoogleCalendarCode

  • Type: onCall
  • Auth: Required + org membership
  • Description: Exchanges a Google OAuth authorization code for access and refresh tokens. Stores tokens in the organization’s integrationConfigs/googleCalendar Firestore document. Requires GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET environment variables.
  • Parameters: { organizationId: string; code: string; redirectUri: string }
  • Returns: { success: boolean }

refreshGoogleCalendarToken

  • Type: onCall
  • Auth: Required + org membership
  • Description: Refreshes an expired Google Calendar access token using the stored refresh token. Updates the token in Firestore.
  • Parameters: { organizationId: string }
  • Returns: { success: boolean }

refreshHubSpotToken

  • Type: onCall
  • Auth: Required + org membership
  • Description: Refreshes an expired HubSpot access token using the stored refresh token. Requires HUBSPOT_CLIENT_ID and HUBSPOT_CLIENT_SECRET environment variables. Stores updated tokens in the organization’s integrationConfigs/hubspot Firestore document.
  • Parameters: { organizationId: string }
  • Returns: { success: boolean }

Partnership Health Scores

computePartnerHealthScores

  • Type: onSchedule
  • Schedule: Daily at 03:00 UTC
  • Auth: N/A (scheduled)
  • Description: Computes health scores for each active partner per organization. Scores are based on three dimensions: activity score (interaction frequency, agreement freshness), milestone score (deliverable completion rate, expiry proximity), and mutual benefit score (financial value relative to effort). Results are stored in the partnerHealthScores collection keyed by {organizationId}_{partnerId}.

Function Type Reference

TypeDescription
onCallFirebase Callable Function (invoked via SDK, includes auth context)
onRequestRaw HTTP endpoint (Express-compatible request/response)
onDocumentCreatedFirestore trigger on new document creation
onDocumentWrittenFirestore trigger on create, update, or delete
onObjectFinalizedCloud Storage trigger when a file upload completes
onScheduleCloud Scheduler trigger (cron-based)
onTaskDispatchedCloud Tasks worker (dispatched from task queue)

Auth Level Reference

LevelDescription
PublicNo authentication required
RequiredFirebase Auth token must be present
Required + App CheckAuth token + Firebase App Check verification
Admin/Super AdminAuth + employee must have Admin or Super Admin systemRole
Super AdminAuth + employee must have Super Admin systemRole
Super Admin + Step-upAuth + Super Admin + recent re-auth within 15 min + MFA second factor
Token-basedPortal access token validated instead of Firebase Auth

Function Count Summary

DomainCount
API Gateway1
Organization Setup1
Authentication3
MFA / Security4
Document Exports2
Admin Utilities3
Activity Feed3
AI / Genkit4
RAG (Document Intelligence)3
Stripe / Billing18
Postmark / Email Admin6
Email Invitations3
Notification Emails3
Scheduled Deadline Reminders2
Scheduled Invitation Reminders3
Referral Credits2
Feedback1
Waitlist2
Usage Monitoring3
Durable Eventing4
Intelligence Platform9
Search Indexing13
Stakeholder Portal7
M&E7
Backup & Restore9
Audit Export1
Integration OAuth3
Partnership Health Scores1
Total~121