Skip to Content
Admin APIAdmin 3 tRPC Routes

Admin 3 tRPC Routes

This document provides a comprehensive breakdown of every tRPC route in the esteem-therapeutics/admin-3 repository, including their permissions and access control requirements.

Permission System Overview

The Admin 3 application uses a role-based permission system with three types of procedures:

  • publicProcedure: No authentication required
  • protectedProcedure: Requires authentication (any logged-in user)
  • roleProcedure(roles): Requires specific user roles

User Roles

The system supports the following user roles:

  • superadmin - Full system access (bypasses all role checks)
  • admin - Administrative access
  • coordinator - Care coordination access
  • ecm - Extended Care Management access
  • billing - Billing and claims access
  • kristen - Special role for specific user

Router Structure

The main tRPC router aggregates 15 sub-routers:

export const appRouter = createTRPCRouter({ appointment: appointmentRouter, ai: aiRouter, claim: claimRouter, cpt: cptRouter, note: noteRouter, ecm: ecmRouter, hubspot: hubspotRouter, insurances: insurancesRouter, metrics: metricsRouter, patient: patientRouter, provider: providerRouter, slots: slotsRouter, tags: tagsRouter, user: userRouter, audit: auditRouter, videos: videosRouter, });

Route Breakdown by Router

1. Appointment Router (appointment)

Permission Level: protectedProcedure (any authenticated user)

Queries

  • all - Filter and list appointments

    • Input: FilterAppointmentSchema (page, filters, etc.)
    • Returns: Paginated appointment listings with total count
  • one - Get single appointment by ID

    • Input: { id: number }
    • Returns: Single appointment details
  • filters - Get available filter options

    • Input: None
    • Returns: Available status, types, providers, patients for filtering

Mutations

  • create - Create new appointment
  • createMultiple - Create multiple appointments
  • refreshTwillioTokens - Refresh Twilio tokens
  • reminderText - Send reminder text
  • update - Update appointment
  • remove - Remove appointment

2. AI Router (ai)

Permission Level: protectedProcedure (any authenticated user)

Queries

  • mcpStatus - Check MCP service status

    • Input: None
    • Returns: Boolean status
  • ocr - Extract data from insurance card images

    • Input: { patient_id: number | string }
    • Returns: OCR results with extracted member ID, name, DOB

Mutations

  • test - Test AI content generation

    • Input: { content: string, context?: string }
    • Returns: Generated text response
  • withMcp - Generate content with MCP tools

    • Input: { content: string }
    • Returns: Generated text with tool access

3. Audit Router (audit)

Permission Level: roleProcedure(["superadmin"]) (superadmin only)

Queries

  • events - List audit events with filtering

    • Input: Optional filters (page, page_size, auditable_type, patient_id, provider_id, user_id, claim_id, documentation_id, appointment_id, start_date, end_date)
    • Returns: Paginated audit events
  • event - Get single audit event

    • Input: { id: number }
    • Returns: Single audit event details

4. Claim Router (claim)

Permission Levels:

  • Most routes: roleProcedure(["admin", "billing"])
  • getAll: roleProcedure(["admin", "billing", "kristen"])

Queries

  • all - Filter and list claims

    • Input: ClaimRequestFiltersSchema
    • Returns: Paginated claims with total count and amount
  • getAll - Get all claims for date range

    • Input: { start_date: string, end_date: string }
    • Returns: All claims in date range
  • one - Get single claim

    • Input: Claim ID (string)
    • Returns: Single claim details
  • comments - Get claim comments

    • Input: { claim_id: number }
    • Returns: Firestore comments for claim
  • latestComments - Get latest comments across claims

    • Input: { page_size: number, cursor?: string }
    • Returns: Latest comments with pagination
  • children - Get child claims

    • Input: Parent claim ID (number)
    • Returns: Array of child claims

Mutations

  • build - Build claim
  • submit - Submit claims (requires superadmin)
  • destroy - Delete claim
  • destroyComment - Delete claim comment
  • comment - Add claim comment
  • update - Update claim

5. CPT Router (cpt)

Permission Level: roleProcedure(["admin", "billing"])

Queries

  • all - Get all CPT codes
    • Input: None
    • Returns: Array of CPT code rates

Mutations

  • create - Create CPT code

    • Input: { code: string, payer_id: number, amount: number }
    • Returns: Created CPT code
  • update - Update CPT code

    • Input: { id: number, code?: string, payer_id?: number, amount?: number }
    • Returns: Updated CPT code
  • destroy - Delete CPT code

    • Input: CPT code ID (number)
    • Returns: Success confirmation

6. ECM Router (ecm)

Permission Levels:

  • Most routes: protectedProcedure
  • updateContact: roleProcedure(["billing", "admin"])

Queries

  • billing - Get billing contacts with filtering

    • Input: { page?: string, perPage?: number, type: "enrollment" | "outreach" | "no_filter", search?: string }
    • Returns: Paginated HubSpot contacts
  • contact - Get single contact details

    • Input: { id: string }
    • Returns: Contact details with calls
  • prtf - Get PRTF data

    • Input: { page: number, perPage: number }
    • Returns: Formatted PRTF contact data
  • eligibilty - Get eligibility contacts

    • Input: { page?: string, perPage?: number, search?: string, sort_by?: string, sort_dir?: "asc" | "desc" }
    • Returns: Eligibility contact listings
  • recentContacts - Get recently contacted patients

    • Input: { days: number } (default 30)
    • Returns: Contacts contacted within specified days
  • tasks - Get tasks for contacts

    • Input: { contactIds: string[] }
    • Returns: Tasks associated with contacts
  • calls - Get calls for contacts

    • Input: { contactIds: string[] }
    • Returns: Call history for contacts
  • messages - Get messages for contacts

    • Input: { contactIds: string[], messageTypes?: string[] }
    • Returns: Communication messages
  • contactEmails - Get emails for specific contact

    • Input: { contactId: string, limit?: number, sortDirection?: "asc" | "desc" }
    • Returns: Email communications for contact

Mutations

  • updateContact - Update contact eligibility
    • Permission: roleProcedure(["billing", "admin"])
    • Input: { hubspotId: string, cencal_eligibility_august_2025: "Eligible" | "NOT ELIGIBLE" | "none" }
    • Returns: Updated contact

7. HubSpot Router (hubspot)

Permission Level: protectedProcedure (any authenticated user)

Queries

  • contact - Get contact by ID

    • Input: Contact ID (string)
    • Returns: HubSpot contact data
  • contactSearch - Search contacts

    • Input: { properties: string[], limit?: number, filters: HubspotFilter[] }
    • Returns: Filtered contacts with specified properties
  • properties - Get object properties

    • Input: Object type (string)
    • Returns: Available properties for object type
  • associations - Get object associations

    • Input: { to: string, from: string, contactIds: string[] }
    • Returns: Association data
  • findByMemberId - Find contact by member identifiers

    • Input: { cin?: string, auth_no?: string, monthly_auth_no?: string }
    • Returns: Matching contact or null

8. Insurances Router (insurances)

Permission Levels:

  • Queries: protectedProcedure
  • Mutations: roleProcedure("superadmin")

Queries

  • plans - Get insurance plans
    • Input: None
    • Returns: Sorted array of insurance payers

Mutations

  • create - Create/update insurance plan

    • Permission: roleProcedure("superadmin")
    • Input: { id?: number, name: string, payer_name: string, payer_id: string }
    • Returns: Created/updated insurance plan
  • delete - Delete insurance plan

    • Permission: roleProcedure("superadmin")
    • Input: { id: number }
    • Returns: Success confirmation

9. Metrics Router (metrics)

Permission Levels: Varies by query

Queries

  • activeByMonth - Get active patients by month

    • Permission: roleProcedure("superadmin")
    • Input: None
    • Returns: Patient activity data for specific month
  • financials - Get financial appointment data

    • Permission: roleProcedure(["admin"])
    • Input: Optional filters (page, start_date, end_date, status, appointment_type, search, insurance_plan_id, provider_name, page_size)
    • Returns: Financial appointment data with totals
  • rolledOver - Get rolled over eligibility data (deprecated)

    • Permission: roleProcedure("superadmin")
    • Input: None
    • Returns: Eligibility rollover analysis
  • weeklyMetrics - Get weekly metrics

    • Permission: protectedProcedure
    • Input: { start_date: string, end_date: string }
    • Returns: Weekly appointment metrics

10. Note Router (note)

Permission Level: roleProcedure(["admin", "coordinator", "ecm", "billing"])

Queries

  • all - Filter and list session notes

    • Input: FilterDocumentationRequestSchema
    • Returns: Paginated session notes
  • one - Get single session note

    • Input: Note ID (number | string)
    • Returns: Single session note details

Mutations

  • adminSign - Admin sign note

  • addendum - Add note addendum

  • update - Update note


11. Patient Router (patient)

Permission Level: protectedProcedure (any authenticated user)

Queries

  • one - Get single patient record

    • Input: Patient ID (number | string)
    • Returns: Complete patient record
  • all - Filter and list patients

    • Input: FilterPatientRequestSchema
    • Returns: Paginated patient listings
  • documents - Get patient documents

    • Input: { id: number }
    • Returns: Array of patient documents
  • getLatestTreatmentPlan - Get latest treatment plan

    • Input: { id: number }
    • Returns: Latest treatment plan for patient

Mutations

  • comment - Add patient comment
  • destroyDocument - Delete patient document
  • eligibility - Check patient eligibility
  • update - Update patient
  • filter - Filter patients
  • updatePhone - Update patient phone
  • checkPVerify - Check PVerify status
  • doSearch - Perform patient search
  • merge - Merge patient records

12. Provider Router (provider)

Permission Level: protectedProcedure (any authenticated user)

Queries

  • all - Filter and list providers

    • Input: FilterRequestSchema + { hide_testers?: boolean }
    • Returns: Paginated provider listings (sorted alphabetically)
  • one - Get single provider

    • Input: { id?: number }
    • Returns: Single provider record
  • findById - Find provider by ID

    • Input: { id?: number }
    • Returns: Provider or null

Mutations

  • setActive - Set provider active status
  • create - Create provider
  • update - Update provider
  • search - Search providers

13. Slots Router (slots)

Permission Level: protectedProcedure (any authenticated user)

Queries

  • availableSlots - Get all available slots

    • Input: None
    • Returns: Available appointment slots
  • searchAvailableSlots - Search available slots with filters

    • Input: SlotFilterSchema (start_date, end_date, provider_ids)
    • Returns: Filtered available slots (excludes conflicting appointments)
  • providerSlots - Get slots for specific provider

    • Input: { provider_id?: number }
    • Returns: Provider-specific availability
  • books - Get booking information

    • Input: None
    • Returns: Booking data

Mutations

  • Available through mutations import (create-slot, delete-slot, update-slot, create-multiple-slots, delete-multiple-slots, create-booking)

14. Tags Router (tags)

Permission Level: roleProcedure(["admin", "billing"])

Queries

  • all - Get all tags

    • Input: TagFiltersSchema (page, page_size, sort_by, sort_dir)
    • Returns: Paginated tags with total count
  • taggedResources - Get tagged resources

    • Input: TaggedResourcesFiltersSchema (page, tag_ids, page_size)
    • Returns: Resources associated with tags

Mutations

  • create - Create tag
  • destroy - Delete tag
  • update - Update tag

15. User Router (user)

Permission Levels: Varies by operation

Queries

  • all - Filter and list users

    • Permission: protectedProcedure
    • Input: Optional filters (search, page, filters.roles)
    • Returns: Paginated user listings
  • one - Get single user

    • Permission: protectedProcedure
    • Input: { id: string }
    • Returns: Single user details
  • validateToken - Validate password reset token

    • Permission: publicProcedure
    • Input: { token: string }
    • Returns: User associated with valid token

Mutations

  • create - Create user

    • Permission: roleProcedure(["admin", "coordinator"])
  • resetPassword - Reset user password

  • requestPasswordReset - Request password reset

  • archive - Archive user

  • update - Update user

  • updateRoles - Update user roles

    • Permission: roleProcedure(["superadmin"])

16. Videos Router (videos)

Permission Level: protectedProcedure (any authenticated user)

Queries

  • all - Get all videos
    • Input: None
    • Returns: Array of video objects (id, name, url, timestamps)

Security Notes

  1. Superadmin Bypass: Users with superadmin role have access to all routes regardless of specific role requirements.

  2. Restricted Operations:

    • Audit events are restricted to superadmin only
    • User role updates require superadmin
    • Insurance plan mutations require superadmin
    • Claim submission requires superadmin
    • Note admin signing is restricted to specific email addresses
  3. Authentication: Most routes require authentication (protectedProcedure or roleProcedure), with only token validation being public.

  4. Role Hierarchy: The system uses specific role combinations rather than hierarchical roles, requiring explicit role grants for access.

Implementation Details

  • Base URL: Routes are accessed via tRPC client as trpc.{router}.{procedure}.{method}
  • Error Handling: Uses tRPC error codes (UNAUTHORIZED, INTERNAL_SERVER_ERROR, BAD_REQUEST, NOT_FOUND, FORBIDDEN)
  • Validation: Input validation using Zod schemas
  • Context: All protected procedures have access to session, firestore, hubspot, apiFetch, and ai in context