CROP
ProjectsAdmin Panel

Health Analytics API Integration

Backend Health Analytics microservice is ready for integration with the admin dashboard.

Health Analytics API Integration

Backend Health Analytics microservice is ready for integration with the admin dashboard.

API Overview

Base URL: https://api.crop.com/api/health

The Health Analytics API provides real-time system health monitoring with vendor-level data quality metrics and digital maturation pipeline tracking.

Endpoints

1. Get System Overview

GET /api/health/overview

Returns high-level system health summary with total counts and service status.

Response:

{
  overall: {
    status: "healthy" | "degraded" | "critical";
    score: number; // 0-100
    message: string;
  };
  totals: {
    totalParts: number;
    catalogReadyParts: number;
    searchableParts: number;
    vendorCount: number;
  };
  services: {
    mongodb: { ok: boolean; latency?: number };
    elasticsearch: { ok: boolean; latency?: number };
    searchService: { ok: boolean; latency?: number };
  };
  lastUpdated: string; // ISO 8601
}

2. List All Vendors

GET /api/health/vendors

Returns health metrics for all vendors/manufacturers.

Response:

{
  vendors: VendorHealth[];
  lastUpdated: string;
}

3. Get Single Vendor

GET /api/health/vendors/:vendorCode

Returns detailed health metrics for a specific vendor.

Path Parameters:

  • vendorCode - Vendor code (e.g., "bosch", "continental")

Response:

VendorHealth // See TypeScript types below

4. Get MongoDB Collections Stats

GET /api/health/collections

Returns statistics for all MongoDB collections (both admin and manufacturer collections).

Response:

{
  adminCollections: CollectionStats[];
  manufacturerCollections: CollectionStats[];
  lastUpdated: string;
}

interface CollectionStats {
  name: string;
  count: number;
  size: number;
  avgObjSize: number;
  storageSize: number;
  indexes: number;
}

TypeScript Types

All TypeScript types are available in the existing lib/types/health.ts file:

import type {
  VendorHealth,
  SystemHealth,
  CollectionStats,
  QualityScore,
  StageDefinition
} from "@/lib/types/health";

Key Types

VendorHealth:

  • vendorCode, vendorName - Vendor identification
  • stages - 8-stage digital maturation pipeline counts
  • quality - Quality distribution (excellent/good/fair/poor)
  • pricing, media, fitment - Coverage metrics
  • healthScore - Overall vendor health (0-100)
  • integrity - Data integrity flags

SystemHealth:

  • overall - System-wide status and score
  • vendors - Array of all vendor health metrics
  • totals - Aggregate counts
  • services - Dependency health checks

Authentication

All API requests must include a valid Clerk JWT token with the "api" template.

Setup

  1. Configure Clerk JWT template in Dashboard:

    • Template name: api
    • Claims: Default claims are sufficient
  2. Get token in your component:

import { useAuth } from "@clerk/nextjs";

const { getToken } = useAuth();
const token = await getToken({ template: "api" });
  1. Include token in API requests:
const response = await fetch("https://api.crop.com/api/health/overview", {
  headers: {
    "Authorization": `Bearer ${token}`,
    "Content-Type": "application/json"
  }
});

Integration Example

Create API Client

Create lib/health-analytics-api.ts:

import type { SystemHealth, VendorHealth, CollectionStats } from "@/lib/types/health";

const BASE_URL = process.env.NEXT_PUBLIC_HEALTH_API_URL || "https://api.crop.com/api/health";

export class HealthAnalyticsAPI {
  constructor(private getToken: () => Promise<string | null>) {}

  private async request<T>(endpoint: string): Promise<T> {
    const token = await this.getToken();
    if (!token) throw new Error("No authentication token available");

    const response = await fetch(`${BASE_URL}${endpoint}`, {
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json"
      },
      cache: "no-store"
    });

    if (!response.ok) {
      throw new Error(`API request failed: ${response.statusText}`);
    }

    return response.json();
  }

  async getOverview() {
    return this.request<SystemHealth>("/overview");
  }

  async getVendors() {
    return this.request<{ vendors: VendorHealth[]; lastUpdated: string }>("/vendors");
  }

  async getVendor(vendorCode: string) {
    return this.request<VendorHealth>(`/vendors/${vendorCode}`);
  }

  async getCollections() {
    return this.request<{
      adminCollections: CollectionStats[];
      manufacturerCollections: CollectionStats[];
      lastUpdated: string;
    }>("/collections");
  }
}

Use in Component

"use client";

import { useAuth } from "@clerk/nextjs";
import { useEffect, useState } from "react";
import { HealthAnalyticsAPI } from "@/lib/health-analytics-api";
import type { SystemHealth } from "@/lib/types/health";

export function HealthDashboard() {
  const { getToken } = useAuth();
  const [health, setHealth] = useState<SystemHealth | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const api = new HealthAnalyticsAPI(() => getToken({ template: "api" }));

    api.getOverview()
      .then(setHealth)
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [getToken]);

  if (loading) return <div>Loading...</div>;
  if (!health) return <div>Failed to load health data</div>;

  return (
    <div>
      <h1>System Health: {health.overall.status}</h1>
      <p>Score: {health.overall.score}/100</p>
      {/* Render health metrics */}
    </div>
  );
}

Environment Variables

Add to .env.local:

# Health Analytics API
NEXT_PUBLIC_HEALTH_API_URL=https://api.crop.com/api/health

# Clerk (if not already configured)
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_...
CLERK_SECRET_KEY=sk_...
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up

Data Refresh Strategy

The Health Analytics API provides near-real-time data. Recommended refresh strategies:

  1. Overview Dashboard: Refresh every 30 seconds
  2. Vendor Details: Refresh every 60 seconds
  3. Collections Stats: Refresh every 5 minutes (less volatile)

Example with auto-refresh:

useEffect(() => {
  const api = new HealthAnalyticsAPI(() => getToken({ template: "api" }));

  const fetchData = () => {
    api.getOverview().then(setHealth).catch(console.error);
  };

  fetchData(); // Initial fetch
  const interval = setInterval(fetchData, 30000); // Every 30s

  return () => clearInterval(interval);
}, [getToken]);

Error Handling

The API returns standard HTTP status codes:

  • 200 - Success
  • 401 - Unauthorized (invalid/missing token)
  • 404 - Resource not found (e.g., invalid vendor code)
  • 500 - Internal server error

Always implement proper error handling:

try {
  const data = await api.getOverview();
  setHealth(data);
} catch (error) {
  if (error instanceof Error) {
    if (error.message.includes("401")) {
      // Token expired or invalid - trigger re-authentication
      await signOut();
    } else {
      // Show user-friendly error message
      setError("Failed to load health data. Please try again.");
    }
  }
}

Migration from Mock Data

Current Source Tab uses mock data. To migrate:

  1. Create HealthAnalyticsAPI client (see above)
  2. Replace mock data in app/(dashboard)/dashboard/health/_components/source-tab.tsx
  3. Add loading and error states
  4. Implement auto-refresh
  5. Remove mock data and alerts about backend requirements

Next Steps

  1. Clerk Configuration

    • Set up JWT template in Clerk Dashboard
    • Configure domains (admin.crop.com)
    • Test token generation
  2. API Integration

    • Create Health Analytics API client
    • Update Source Tab component
    • Add loading states and error handling
    • Implement auto-refresh
  3. Testing

    • Test authentication flow
    • Verify API responses match TypeScript types
    • Test error scenarios (network failure, auth errors)
    • Performance testing with auto-refresh
  4. Production Deployment

    • Update environment variables
    • Configure CORS if needed
    • Monitor API performance
    • Set up error tracking (Sentry, etc.)

Support

  • Backend API documentation: services/health-analytics/README.md
  • TypeScript types: lib/types/health.ts
  • Clerk integration: docs/CLERK_FRONTEND_INTEGRATION.md

For questions or issues, contact the backend team.

On this page