Edit

import { NextResponse } from 'next/server'
import { callTool } from '@/server/kipu-mcp-client'
import type { ProviderSummary } from '@/stores/utils/types'
import { createCareTeamProviderMap } from '@/utils/care-team-matching'

interface PatientCountMap {
  [providerId: string]: number
}

interface CareTeamRecord {
  patient_id?: string
  patient_master_id?: string
  casefile_id?: string
  mr_number?: string
  therapist?: string
  therapist_name?: string
  nurse?: string
  nurse_name?: string
  physician?: string
  physician_name?: string
  case_manager?: string
  case_manager_name?: string
  primary_therapist?: string
  primary_nurse?: string
  primary_physician?: string
  provider_name?: string
  user_name?: string
}

/**
 * Extract care team data from MCP response
 */
function extractCareTeams(raw: unknown): CareTeamRecord[] {
  const queue: unknown[] = [raw]
  const careTeams: CareTeamRecord[] = []
  const seenObjects = new WeakSet<object>()

  while (queue.length > 0) {
    const current = queue.shift()
    if (current === null || typeof current === 'undefined') continue

    if (Array.isArray(current)) {
      for (const item of current) {
        queue.push(item)
      }
      continue
    }

    if (typeof current === 'string') {
      const trimmed = current.trim()
      if (
        (trimmed.startsWith('{') && trimmed.endsWith('}')) ||
        (trimmed.startsWith('[') && trimmed.endsWith(']'))
      ) {
        try {
          queue.push(JSON.parse(trimmed))
        } catch {
          // Ignore invalid JSON
        }
      }
      continue
    }

    if (typeof current !== 'object') continue

    const reference = current as object
    if (seenObjects.has(reference)) continue
    seenObjects.add(reference)

    const record = current as Record<string, unknown>

    // Check if this looks like a care team record
    const hasPatientId = 'patient_id' in record || 'patient_master_id' in record || 'casefile_id' in record || 'mr_number' in record
    const hasProviderName =
      'therapist' in record ||
      'therapist_name' in record ||
      'nurse' in record ||
      'nurse_name' in record ||
      'physician' in record ||
      'physician_name' in record ||
      'case_manager' in record ||
      'case_manager_name' in record ||
      'primary_therapist' in record ||
      'primary_nurse' in record ||
      'primary_physician' in record ||
      'provider_name' in record ||
      'user_name' in record

    if (hasPatientId && hasProviderName) {
      careTeams.push(record as CareTeamRecord)
    }

    // Look for nested structures
    const nestedKeys = ['care_teams', 'CareTeams', 'Records', 'records', 'data', 'result', 'content']
    for (const key of nestedKeys) {
      if (key in record && record[key]) {
        queue.push(record[key])
      }
    }
  }

  return careTeams
}

/**
 * Get patient counts for all providers using GetPatientsCareTeams
 * Matches care team member names to provider full names
 */
export async function POST(request: Request) {
  try {
    const { providers }: { providers: ProviderSummary[] } = await request.json()

    if (!providers || !Array.isArray(providers)) {
      return NextResponse.json(
        { success: false, error: 'Invalid providers array' },
        { status: 400 }
      )
    }

    // Get today's date for current census
    const today = new Date().toISOString().split('T')[0]

    // Get all care teams which includes provider-patient mappings
    const response = await callTool('GetPatientsCareTeams', {
      start_date: today,
      end_date: today,
    })

    if (!response || ('error' in response && response.error)) {
      const message =
        response && typeof response === 'object' && 'error' in response
          ? JSON.stringify(response.error)
          : 'Unknown MCP error'
      return NextResponse.json({ success: false, error: message }, { status: 502 })
    }

    // Extract care team records from response
    const rawData = response?.result
    const careTeamRecords = extractCareTeams(rawData)

    console.log(`[patient-counts] Found ${careTeamRecords.length} care team records`)

    // Initialize all provider counts to 0
    const patientCounts: PatientCountMap = {}
    providers.forEach((provider) => {
      patientCounts[provider.id] = 0
    })

    // Extract all unique care team member names
    const careTeamNames = new Set<string>()
    careTeamRecords.forEach((record) => {
      const names = [
        record.therapist,
        record.therapist_name,
        record.nurse,
        record.nurse_name,
        record.physician,
        record.physician_name,
        record.case_manager,
        record.case_manager_name,
        record.primary_therapist,
        record.primary_nurse,
        record.primary_physician,
        record.provider_name,
        record.user_name,
      ]

      names.forEach((name) => {
        if (name && typeof name === 'string' && name.trim()) {
          careTeamNames.add(name.trim())
        }
      })
    })

    console.log(`[patient-counts] Found ${careTeamNames.size} unique care team member names`)

    // Create mapping of care team names to provider IDs
    const nameToProviderId = createCareTeamProviderMap(Array.from(careTeamNames), providers)

    console.log(`[patient-counts] Matched ${nameToProviderId.size} care team names to providers`)

    // Track which patients each provider has (to avoid double-counting)
    const providerPatients = new Map<string, Set<string>>()
    providers.forEach((provider) => {
      providerPatients.set(provider.id, new Set())
    })

    // Count unique patients per provider
    careTeamRecords.forEach((record) => {
      // Get patient ID
      const patientId = String(
        record.casefile_id ||
        record.patient_master_id ||
        record.patient_id ||
        record.mr_number ||
        ''
      )

      if (!patientId) return

      // Check all provider name fields
      const providerNames = [
        record.therapist,
        record.therapist_name,
        record.nurse,
        record.nurse_name,
        record.physician,
        record.physician_name,
        record.case_manager,
        record.case_manager_name,
        record.primary_therapist,
        record.primary_nurse,
        record.primary_physician,
        record.provider_name,
        record.user_name,
      ]

      providerNames.forEach((name) => {
        if (name && typeof name === 'string') {
          // Normalize the name (remove suffix like ", LCSW")
          const normalizedName = name.split(',')[0].trim().toLowerCase()
          const providerId = nameToProviderId.get(normalizedName)

          if (providerId) {
            // Add this patient to the provider's set (automatically deduplicates)
            providerPatients.get(providerId)?.add(patientId)
          }
        }
      })
    })

    // Convert sets to counts
    providerPatients.forEach((patientSet, providerId) => {
      patientCounts[providerId] = patientSet.size
    })

    console.log('[patient-counts] Final counts:', patientCounts)

    return NextResponse.json({ success: true, patientCounts })
  } catch (error) {
    console.error('[patient-qa] Failed to load patient counts:', error)
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}

import { NextResponse } from 'next/server'
import { callTool } from '@/server/kipu-mcp-client'
import type { ProviderSummary } from '@/stores/utils/types'
import { matchCareTeamToProvider } from '@/utils/care-team-matching'

interface PatientCountMap {
  [providerId: string]: number
}

interface PatientCareTeam {
  care_team_therapist?: string
  care_team_nurse?: string
  care_team_physician?: string
  care_team_case_manager?: string
}

interface PatientWithCareTeam {
  casefile_id: string
  patient_care_team: PatientCareTeam
}

/**
 * Extract patients with care teams from MCP response
 */
function extractPatientsFromResponse(response: unknown): PatientWithCareTeam[] {
  try {
    const result = (response as any)?.result
    if (!result?.content || !Array.isArray(result.content)) return []

    for (const item of result.content) {
      if (item.type === 'text' && item.text) {
        const parsed = JSON.parse(item.text)
        if (parsed.patients && Array.isArray(parsed.patients)) {
          return parsed.patients
        }
      }
    }
  } catch (error) {
    console.error('[patient-counts] Failed to parse response:', error)
  }
  return []
}

/**
 * Fetch all pages of care team data
 */
async function fetchAllCareTeamPages(startDate: string, endDate: string): Promise<PatientWithCareTeam[]> {
  const allPatients: PatientWithCareTeam[] = []
  let currentPage = 1
  let totalPages = 1

  do {
    const response = await callTool('GetPatientsCareTeams', {
      start_date: startDate,
      end_date: endDate,
      page: currentPage,
    })

    if (!response || ('error' in response && response.error)) {
      break
    }

    const patients = extractPatientsFromResponse(response)
    allPatients.push(...patients)

    // Check if there are more pages
    try {
      const result = (response as any)?.result
      if (result?.content?.[0]?.text) {
        const parsed = JSON.parse(result.content[0].text)
        if (parsed.pagination) {
          totalPages = parseInt(parsed.pagination.total_pages, 10)
        }
      }
    } catch {
      // If pagination parsing fails, assume single page
    }

    currentPage++
  } while (currentPage <= totalPages)

  return allPatients
}

/**
 * Get patient counts for all providers using GetPatientsCareTeams
 * Matches care team member names to provider full names
 */
export async function POST(request: Request) {
  try {
    const { providers }: { providers: ProviderSummary[] } = await request.json()

    if (!providers || !Array.isArray(providers)) {
      return NextResponse.json(
        { success: false, error: 'Invalid providers array' },
        { status: 400 }
      )
    }

    const today = new Date().toISOString().split('T')[0]

    // Fetch all pages of care team data
    const allPatients = await fetchAllCareTeamPages(today, today)

    // Track unique patients per provider
    const providerPatients = new Map<string, Set<string>>()
    providers.forEach((provider) => {
      providerPatients.set(provider.id, new Set())
    })

    // Count patients per provider
    allPatients.forEach((patient) => {
      const careTeam = patient.patient_care_team
      if (!careTeam) return

      // Check all care team roles
      const careTeamMembers = [
        careTeam.care_team_therapist,
        careTeam.care_team_nurse,
        careTeam.care_team_physician,
        careTeam.care_team_case_manager,
      ]

      careTeamMembers.forEach((memberName) => {
        if (!memberName || !memberName.trim()) return

        const matchedProvider = matchCareTeamToProvider(memberName, providers)
        if (matchedProvider) {
          providerPatients.get(matchedProvider.id)?.add(patient.casefile_id)
        }
      })
    })

    // Convert sets to counts
    const patientCounts: PatientCountMap = {}
    providerPatients.forEach((patientSet, providerId) => {
      patientCounts[providerId] = patientSet.size
    })

    return NextResponse.json({ success: true, patientCounts })
  } catch (error) {
    console.error('[patient-qa] Failed to load patient counts:', error)
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}


Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable

Examine actual GetPatientsCareTeams response structure

Examining actual GetPatientsCareTeams response structure

Fix patient-counts to match on user IDs not names

Fixing patient-counts to match on user IDs not names

Remove name-matching utility imports and console.logs

Removing name-matching utility imports and console.logs

Fix patient-counts to extract patients array and handle pagination

Fixing patient-counts to extract patients array and handle pagination

Simplify and clean up the code


The file /Users/alexnewman/Scripts/clean-kit/src/app/api/patient-qa/providers/patient-counts/route.ts has been updated. Here's the result of running `cat -n` on a snippet of the edited file:
     1→import { NextResponse } from 'next/server'
     2→import { callTool } from '@/server/kipu-mcp-client'
     3→import type { ProviderSummary } from '@/stores/utils/types'
     4→import { matchCareTeamToProvider } from '@/utils/care-team-matching'
     5→
     6→interface PatientCountMap {
     7→  [providerId: string]: number
     8→}
     9→
    10→interface PatientCareTeam {
    11→  care_team_therapist?: string
    12→  care_team_nurse?: string
    13→  care_team_physician?: string
    14→  care_team_case_manager?: string
    15→}
    16→
    17→interface PatientWithCareTeam {
    18→  casefile_id: string
    19→  patient_care_team: PatientCareTeam
    20→}
    21→
    22→/**
    23→ * Extract patients with care teams from MCP response
    24→ */
    25→function extractPatientsFromResponse(response: unknown): PatientWithCareTeam[] {
    26→  try {
    27→    const result = (response as any)?.result
    28→    if (!result?.content || !Array.isArray(result.content)) return []
    29→
    30→    for (const item of result.content) {
    31→      if (item.type === 'text' && item.text) {
    32→        const parsed = JSON.parse(item.text)
    33→        if (parsed.patients && Array.isArray(parsed.patients)) {
    34→          return parsed.patients
    35→        }
    36→      }
    37→    }
    38→  } catch (error) {
    39→    console.error('[patient-counts] Failed to parse response:', error)
    40→  }
    41→  return []
    42→}
    43→
    44→/**
    45→ * Fetch all pages of care team data
    46→ */
    47→async function fetchAllCareTeamPages(startDate: string, endDate: string): Promise<PatientWithCareTeam[]> {
    48→  const allPatients: PatientWithCareTeam[] = []
    49→  let currentPage = 1
    50→  let totalPages = 1
    51→
    52→  do {
    53→    const response = await callTool('GetPatientsCareTeams', {
    54→      start_date: startDate,
    55→      end_date: endDate,
    56→      page: currentPage,
    57→    })
    58→
    59→    if (!response || ('error' in response && response.error)) {
    60→      break
    61→    }
    62→
    63→    const patients = extractPatientsFromResponse(response)
    64→    allPatients.push(...patients)
    65→
    66→    // Check if there are more pages
    67→    try {
    68→      const result = (response as any)?.result
    69→      if (result?.content?.[0]?.text) {
    70→        const parsed = JSON.parse(result.content[0].text)
    71→        if (parsed.pagination) {
    72→          totalPages = parseInt(parsed.pagination.total_pages, 10)
    73→        }
    74→      }
    75→    } catch {
    76→      // If pagination parsing fails, assume single page
    77→    }
    78→
    79→    currentPage++
    80→  } while (currentPage <= totalPages)
    81→
    82→  return allPatients
    83→}
    84→
    85→/**
    86→ * Get patient counts for all providers using GetPatientsCareTeams
    87→ * Matches care team member names to provider full names
    88→ */
    89→export async function POST(request: Request) {
    90→  try {
    91→    const { providers }: { providers: ProviderSummary[] } = await request.json()
    92→
    93→    if (!providers || !Array.isArray(providers)) {
    94→      return NextResponse.json(
    95→        { success: false, error: 'Invalid providers array' },
    96→        { status: 400 }
    97→      )
    98→    }
    99→
   100→    const today = new Date().toISOString().split('T')[0]
   101→
   102→    // Fetch all pages of care team data
   103→    const allPatients = await fetchAllCareTeamPages(today, today)
   104→
   105→    // Track unique patients per provider
   106→    const providerPatients = new Map<string, Set<string>>()
   107→    providers.forEach((provider) => {
   108→      providerPatients.set(provider.id, new Set())
   109→    })
   110→
   111→    // Count patients per provider
   112→    allPatients.forEach((patient) => {
   113→      const careTeam = patient.patient_care_team
   114→      if (!careTeam) return
   115→
   116→      // Check all care team roles
   117→      const careTeamMembers = [
   118→        careTeam.care_team_therapist,
   119→        careTeam.care_team_nurse,
   120→        careTeam.care_team_physician,
   121→        careTeam.care_team_case_manager,
   122→      ]
   123→
   124→      careTeamMembers.forEach((memberName) => {
   125→        if (!memberName || !memberName.trim()) return
   126→
   127→        const matchedProvider = matchCareTeamToProvider(memberName, providers)
   128→        if (matchedProvider) {
   129→          providerPatients.get(matchedProvider.id)?.add(patient.casefile_id)
   130→        }
   131→      })
   132→    })
   133→
   134→    // Convert sets to counts
   135→    const patientCounts: PatientCountMap = {}
   136→    providerPatients.forEach((patientSet, providerId) => {
   137→      patientCounts[providerId] = patientSet.size
   138→    })
   139→
   140→    return NextResponse.json({ success: true, patientCounts })
   141→  } catch (error) {
   142→    console.error('[patient-qa] Failed to load patient counts:', error)
   143→    return NextResponse.json(
   144→      {
   145→        success: false,
   146→        error: error instanceof Error ? error.message : 'Unknown error',
   147→      },
   148→      { status: 500 }
   149→    )
   150→  }
   151→}
   152→

import { NextResponse } from 'next/server'
import { callTool } from '@/server/kipu-mcp-client'
import type { ProviderSummary } from '@/stores/utils/types'
import { createCareTeamProviderMap } from '@/utils/care-team-matching'

interface PatientCountMap {
  [providerId: string]: number
}

interface CareTeamRecord {
  patient_id?: string
  patient_master_id?: string
  casefile_id?: string
  mr_number?: string
  therapist?: string
  therapist_name?: string
  nurse?: string
  nurse_name?: string
  physician?: string
  physician_name?: string
  case_manager?: string
  case_manager_name?: string
  primary_therapist?: string
  primary_nurse?: string
  primary_physician?: string
  provider_name?: string
  user_name?: string
}

/**
 * Extract care team data from MCP response
 */
function extractCareTeams(raw: unknown): CareTeamRecord[] {
  const queue: unknown[] = [raw]
  const careTeams: CareTeamRecord[] = []
  const seenObjects = new WeakSet<object>()

  while (queue.length > 0) {
    const current = queue.shift()
    if (current === null || typeof current === 'undefined') continue

    if (Array.isArray(current)) {
      for (const item of current) {
        queue.push(item)
      }
      continue
    }

    if (typeof current === 'string') {
      const trimmed = current.trim()
      if (
        (trimmed.startsWith('{') && trimmed.endsWith('}')) ||
        (trimmed.startsWith('[') && trimmed.endsWith(']'))
      ) {
        try {
          queue.push(JSON.parse(trimmed))
        } catch {
          // Ignore invalid JSON
        }
      }
      continue
    }

    if (typeof current !== 'object') continue

    const reference = current as object
    if (seenObjects.has(reference)) continue
    seenObjects.add(reference)

    const record = current as Record<string, unknown>

    // Check if this looks like a care team record
    const hasPatientId = 'patient_id' in record || 'patient_master_id' in record || 'casefile_id' in record || 'mr_number' in record
    const hasProviderName =
      'therapist' in record ||
      'therapist_name' in record ||
      'nurse' in record ||
      'nurse_name' in record ||
      'physician' in record ||
      'physician_name' in record ||
      'case_manager' in record ||
      'case_manager_name' in record ||
      'primary_therapist' in record ||
      'primary_nurse' in record ||
      'primary_physician' in record ||
      'provider_name' in record ||
      'user_name' in record

    if (hasPatientId && hasProviderName) {
      careTeams.push(record as CareTeamRecord)
    }

    // Look for nested structures
    const nestedKeys = ['care_teams', 'CareTeams', 'Records', 'records', 'data', 'result', 'content']
    for (const key of nestedKeys) {
      if (key in record && record[key]) {
        queue.push(record[key])
      }
    }
  }

  return careTeams
}

/**
 * Get patient counts for all providers using GetPatientsCareTeams
 * Matches care team member names to provider full names
 */
export async function POST(request: Request) {
  try {
    const { providers }: { providers: ProviderSummary[] } = await request.json()

    if (!providers || !Array.isArray(providers)) {
      return NextResponse.json(
        { success: false, error: 'Invalid providers array' },
        { status: 400 }
      )
    }

    // Get today's date for current census
    const today = new Date().toISOString().split('T')[0]

    // Get all care teams which includes provider-patient mappings
    const response = await callTool('GetPatientsCareTeams', {
      start_date: today,
      end_date: today,
    })

    if (!response || ('error' in response && response.error)) {
      const message =
        response && typeof response === 'object' && 'error' in response
          ? JSON.stringify(response.error)
          : 'Unknown MCP error'
      return NextResponse.json({ success: false, error: message }, { status: 502 })
    }

    // Extract care team records from response
    const rawData = response?.result
    const careTeamRecords = extractCareTeams(rawData)

    console.log(`[patient-counts] Found ${careTeamRecords.length} care team records`)

    // Initialize all provider counts to 0
    const patientCounts: PatientCountMap = {}
    providers.forEach((provider) => {
      patientCounts[provider.id] = 0
    })

    // Extract all unique care team member names
    const careTeamNames = new Set<string>()
    careTeamRecords.forEach((record) => {
      const names = [
        record.therapist,
        record.therapist_name,
        record.nurse,
        record.nurse_name,
        record.physician,
        record.physician_name,
        record.case_manager,
        record.case_manager_name,
        record.primary_therapist,
        record.primary_nurse,
        record.primary_physician,
        record.provider_name,
        record.user_name,
      ]

      names.forEach((name) => {
        if (name && typeof name === 'string' && name.trim()) {
          careTeamNames.add(name.trim())
        }
      })
    })

    console.log(`[patient-counts] Found ${careTeamNames.size} unique care team member names`)

    // Create mapping of care team names to provider IDs
    const nameToProviderId = createCareTeamProviderMap(Array.from(careTeamNames), providers)

    console.log(`[patient-counts] Matched ${nameToProviderId.size} care team names to providers`)

    // Track which patients each provider has (to avoid double-counting)
    const providerPatients = new Map<string, Set<string>>()
    providers.forEach((provider) => {
      providerPatients.set(provider.id, new Set())
    })

    // Count unique patients per provider
    careTeamRecords.forEach((record) => {
      // Get patient ID
      const patientId = String(
        record.casefile_id ||
        record.patient_master_id ||
        record.patient_id ||
        record.mr_number ||
        ''
      )

      if (!patientId) return

      // Check all provider name fields
      const providerNames = [
        record.therapist,
        record.therapist_name,
        record.nurse,
        record.nurse_name,
        record.physician,
        record.physician_name,
        record.case_manager,
        record.case_manager_name,
        record.primary_therapist,
        record.primary_nurse,
        record.primary_physician,
        record.provider_name,
        record.user_name,
      ]

      providerNames.forEach((name) => {
        if (name && typeof name === 'string') {
          // Normalize the name (remove suffix like ", LCSW")
          const normalizedName = name.split(',')[0].trim().toLowerCase()
          const providerId = nameToProviderId.get(normalizedName)

          if (providerId) {
            // Add this patient to the provider's set (automatically deduplicates)
            providerPatients.get(providerId)?.add(patientId)
          }
        }
      })
    })

    // Convert sets to counts
    providerPatients.forEach((patientSet, providerId) => {
      patientCounts[providerId] = patientSet.size
    })

    console.log('[patient-counts] Final counts:', patientCounts)

    return NextResponse.json({ success: true, patientCounts })
  } catch (error) {
    console.error('[patient-qa] Failed to load patient counts:', error)
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}

import { NextResponse } from 'next/server'
import { callTool } from '@/server/kipu-mcp-client'
import type { ProviderSummary } from '@/stores/utils/types'
import { matchCareTeamToProvider } from '@/utils/care-team-matching'

interface PatientCountMap {
  [providerId: string]: number
}

interface PatientCareTeam {
  care_team_therapist?: string
  care_team_nurse?: string
  care_team_physician?: string
  care_team_case_manager?: string
}

interface PatientWithCareTeam {
  casefile_id: string
  patient_care_team: PatientCareTeam
}

/**
 * Extract patients with care teams from MCP response
 */
function extractPatientsFromResponse(response: unknown): PatientWithCareTeam[] {
  try {
    const result = (response as any)?.result
    if (!result?.content || !Array.isArray(result.content)) return []

    for (const item of result.content) {
      if (item.type === 'text' && item.text) {
        const parsed = JSON.parse(item.text)
        if (parsed.patients && Array.isArray(parsed.patients)) {
          return parsed.patients
        }
      }
    }
  } catch (error) {
    console.error('[patient-counts] Failed to parse response:', error)
  }
  return []
}

/**
 * Fetch all pages of care team data
 */
async function fetchAllCareTeamPages(startDate: string, endDate: string): Promise<PatientWithCareTeam[]> {
  const allPatients: PatientWithCareTeam[] = []
  let currentPage = 1
  let totalPages = 1

  do {
    const response = await callTool('GetPatientsCareTeams', {
      start_date: startDate,
      end_date: endDate,
      page: currentPage,
    })

    if (!response || ('error' in response && response.error)) {
      break
    }

    const patients = extractPatientsFromResponse(response)
    allPatients.push(...patients)

    // Check if there are more pages
    try {
      const result = (response as any)?.result
      if (result?.content?.[0]?.text) {
        const parsed = JSON.parse(result.content[0].text)
        if (parsed.pagination) {
          totalPages = parseInt(parsed.pagination.total_pages, 10)
        }
      }
    } catch {
      // If pagination parsing fails, assume single page
    }

    currentPage++
  } while (currentPage <= totalPages)

  return allPatients
}

/**
 * Get patient counts for all providers using GetPatientsCareTeams
 * Matches care team member names to provider full names
 */
export async function POST(request: Request) {
  try {
    const { providers }: { providers: ProviderSummary[] } = await request.json()

    if (!providers || !Array.isArray(providers)) {
      return NextResponse.json(
        { success: false, error: 'Invalid providers array' },
        { status: 400 }
      )
    }

    const today = new Date().toISOString().split('T')[0]

    // Fetch all pages of care team data
    const allPatients = await fetchAllCareTeamPages(today, today)

    // Track unique patients per provider
    const providerPatients = new Map<string, Set<string>>()
    providers.forEach((provider) => {
      providerPatients.set(provider.id, new Set())
    })

    // Count patients per provider
    allPatients.forEach((patient) => {
      const careTeam = patient.patient_care_team
      if (!careTeam) return

      // Check all care team roles
      const careTeamMembers = [
        careTeam.care_team_therapist,
        careTeam.care_team_nurse,
        careTeam.care_team_physician,
        careTeam.care_team_case_manager,
      ]

      careTeamMembers.forEach((memberName) => {
        if (!memberName || !memberName.trim()) return

        const matchedProvider = matchCareTeamToProvider(memberName, providers)
        if (matchedProvider) {
          providerPatients.get(matchedProvider.id)?.add(patient.casefile_id)
        }
      })
    })

    // Convert sets to counts
    const patientCounts: PatientCountMap = {}
    providerPatients.forEach((patientSet, providerId) => {
      patientCounts[providerId] = patientSet.size
    })

    return NextResponse.json({ success: true, patientCounts })
  } catch (error) {
    console.error('[patient-qa] Failed to load patient counts:', error)
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}

import { NextResponse } from 'next/server'

-import { createCareTeamProviderMap } from '@/utils/care-team-matching'

+import { matchCareTeamToProvider } from '@/utils/care-team-matching'

- * Extract care team data from MCP response

+ * Extract patients with care teams from MCP response

-function extractCareTeams(raw: unknown): CareTeamRecord[] {

-  const careTeams: CareTeamRecord[] = []

-  const seenObjects = new WeakSet<object>()

+function extractPatientsFromResponse(response: unknown): PatientWithCareTeam[] {

+    const result = (response as any)?.result

+    if (!result?.content || !Array.isArray(result.content)) return []

-    if (current === null || typeof current === 'undefined') continue

-        (trimmed.startsWith('{') && trimmed.endsWith('}')) ||

-        (trimmed.startsWith('[') && trimmed.endsWith(']'))

-          queue.push(JSON.parse(trimmed))

+    for (const item of result.content) {

+      if (item.type === 'text' && item.text) {

+        const parsed = JSON.parse(item.text)

+        if (parsed.patients && Array.isArray(parsed.patients)) {

+    console.error('[patient-counts] Failed to parse response:', error)

-    if (typeof current !== 'object') continue

+async function fetchAllCareTeamPages(startDate: string, endDate: string): Promise<PatientWithCareTeam[]> {

+  const allPatients: PatientWithCareTeam[] = []

-    const reference = current as object

-    if (seenObjects.has(reference)) continue

+    const response = await callTool('GetPatientsCareTeams', {

-    const record = current as Record<string, unknown>

-    // Check if this looks like a care team record

-    const hasPatientId = 'patient_id' in record || 'patient_master_id' in record || 'casefile_id' in record || 'mr_number' in record

-    if (hasPatientId && hasProviderName) {

-      careTeams.push(record as CareTeamRecord)

+    if (!response || ('error' in response && response.error)) {

-    const nestedKeys = ['care_teams', 'CareTeams', 'Records', 'records', 'data', 'result', 'content']

-      if (key in record && record[key]) {

+    const patients = extractPatientsFromResponse(response)

+      const result = (response as any)?.result

+      if (result?.content?.[0]?.text) {

+        const parsed = JSON.parse(result.content[0].text)

+          totalPages = parseInt(parsed.pagination.total_pages, 10)

+      // If pagination parsing fails, assume single page

-    // Get today's date for current census

-    // Get all care teams which includes provider-patient mappings

-    const response = await callTool('GetPatientsCareTeams', {

+    // Fetch all pages of care team data

+    const allPatients = await fetchAllCareTeamPages(today, today)

-    if (!response || ('error' in response && response.error)) {

-        response && typeof response === 'object' && 'error' in response

-          ? JSON.stringify(response.error)

-      return NextResponse.json({ success: false, error: message }, { status: 502 })

-    // Extract care team records from response

-    const careTeamRecords = extractCareTeams(rawData)

-    console.log(`[patient-counts] Found ${careTeamRecords.length} care team records`)

-    // Initialize all provider counts to 0

-    const patientCounts: PatientCountMap = {}

-    // Extract all unique care team member names

-    const careTeamNames = new Set<string>()

-    careTeamRecords.forEach((record) => {

-        if (name && typeof name === 'string' && name.trim()) {

-          careTeamNames.add(name.trim())

-    console.log(`[patient-counts] Found ${careTeamNames.size} unique care team member names`)

-    // Create mapping of care team names to provider IDs

-    const nameToProviderId = createCareTeamProviderMap(Array.from(careTeamNames), providers)

-    console.log(`[patient-counts] Matched ${nameToProviderId.size} care team names to providers`)

-    // Track which patients each provider has (to avoid double-counting)

+    // Track unique patients per provider

-    // Count unique patients per provider

+      const careTeam = patient.patient_care_team

-      // Check all provider name fields

+        careTeam.care_team_case_manager,

-      providerNames.forEach((name) => {

-        if (name && typeof name === 'string') {

-          // Normalize the name (remove suffix like ", LCSW")

-          const normalizedName = name.split(',')[0].trim().toLowerCase()

-          const providerId = nameToProviderId.get(normalizedName)

+      careTeamMembers.forEach((memberName) => {

+        if (!memberName || !memberName.trim()) return

-            // Add this patient to the provider's set (automatically deduplicates)

-            providerPatients.get(providerId)?.add(patientId)

+        const matchedProvider = matchCareTeamToProvider(memberName, providers)

+          providerPatients.get(matchedProvider.id)?.add(patient.casefile_id)

+    const patientCounts: PatientCountMap = {}

-    console.log('[patient-counts] Final counts:', patientCounts)


Good, I've simplified the code significantly. Now let me clean up:
1. Remove the test file
2. Mark todos as complete
3. Summarize what was fixed


Bash

Remove test file


TodoWrite

Examine actual GetPatientsCareTeams response structure

Examining actual GetPatientsCareTeams response structure

Fix patient-counts to extract patients array and handle pagination

Fixing patient-counts to extract patients array and handle pagination

Simplify and clean up the code


Moved test-care-teams.ts to trash


Error: Shell 748275 is not running, so cannot be killed (status: completed)


Successfully killed shell: 44e0d8 (npx tsx test-care-teams.ts)


Simplify and clean up the code

Simplify and clean up the code


The user is upset because I overcompl icated things. Let me explain what I actually fixed clearly and concisely.


Fixed. Here's what was wrong and what I changed:

**The actual problem:**
- Care team data has `patients` array (not `care_teams`)
- Each patient has `patient_care_team.care_team_therapist` etc with NAME strings only
- There are 15 pages of data, I was only fetching page 1
- Name matching is actually necessary since there are no provider IDs in the care team data

**What I fixed:**
1. Extract from `patients` array instead of looking for non-existent `care_teams`
2. Handle pagination - fetch all 15 pages
3. Removed all the console.logs
4. Simplified to ~150 lines instead of ~250

The name matching utility you created is correct and necessary - the care team data literally only has names like "Alexa Cooney, LCSW".