# @optifye/dashboard-core

# @optifye/dashboard-core

A comprehensive React component library and core utilities package for building enterprise-grade operational dashboards with real-time metrics, visualizations, and interactive views.

## Overview

The **@optifye/dashboard-core** package provides a complete solution for building data-rich, real-time operational dashboards for manufacturing, production lines, and industrial workspaces. It includes a comprehensive set of UI components, data hooks, services, utilities, and fully-composed view components that can be used to build complete dashboard applications with minimal effort.

This package has been designed with a focus on:

- **Component Reusability**: All UI components from atomic elements to complete page views
- **Data Abstraction**: Hooks and services for clean data fetching and management
- **Configurability**: Extensive prop-based configuration for all components
- **Type Safety**: Comprehensive TypeScript types throughout
- **Performance**: Optimized rendering and data fetching strategies
- **Enterprise Readiness**: Authentication, real-time data, and role-based access controls

## Package Structure

### Core Architecture

The package is organized into the following key directories:

```
@optifye/dashboard-core/
├── src/
│   ├── components/     # UI Components from atomic to composite
│   ├── lib/            # Core logic, utilities, hooks, services
│   ├── views/          # Complete page-level view components
│   └── index.ts        # Main export file
```

### Component Architecture

Components follow a hierarchical organization:

```
components/
├── auth/           # Authentication components
├── charts/         # Data visualization components
├── common/         # Shared components across domains
├── dashboard/      # Domain-specific dashboard components
│   ├── grid/       # Workspace grid components
│   ├── kpis/       # KPI visualization components
│   ├── line/       # Production line components
│   ├── video/      # Video streaming components
│   └── workspace/  # Workspace detail components
├── data/           # Data display and transformation components
├── layouts/        # Layout components and structure
├── navigation/     # Navigation components and menus
├── ui/             # Fundamental UI components (buttons, cards, etc.)
└── views/          # View-specific components
```

### Core Library Structure

The core logic follows a clean separation of concerns:

```
lib/
├── constants/      # Application constants and configuration values
├── contexts/       # React context providers and consumers
├── hooks/          # Custom React hooks for data and UI
├── internal/       # Internal utilities (not exported)
├── services/       # Data services and API clients
│   └── factories/  # Service factory functions
├── supabase/       # Supabase client configuration
├── types/          # TypeScript type definitions
└── utils/          # Utility functions by domain
    └── dev/        # Development utilities
```

## Key Features

### 1. UI Component System

The package provides a complete UI component system for building operational dashboards:

#### Foundational UI Components

- **Button**: Versatile button component with multiple variants (primary, secondary, outline, ghost)
- **Card**: Card components with header, body, and footer sections
- **Select**: Form select components with dropdown options
- **LoadingSpinner, LoadingOverlay, LoadingPage**: Loading indicators at various levels
- **DateDisplay, TimeDisplay**: Timezone-aware date and time components
- **Skeleton**: Loading skeleton placeholders
- **EmptyStateMessage**: Consistent empty state messaging

#### Data Visualization

- **KPICard**: Key Performance Indicator display cards
- **MetricCard**: General metric display cards
- **LineChart, BarChart**: Chart components for data visualization
- **HourlyOutputChart**: Specialized chart for hourly production data
- **WorkspaceHistoryCalendar**: Calendar visualization for workspace metrics history
- **OutputProgressChart**: Progress visualization for production output

#### Video & Real-Time Components

- **LiveView**: Real-time HLS video streaming component
- **BottlenecksContent**: Video clip management for bottleneck analysis

#### Navigation & Layout

- **MainLayout**: Main application layout with sidebar
- **DashboardLayout**: Full dashboard layout with header and sidebar
- **SideNavBar**: Navigation sidebar with configurable items
- **PageHeader**: Page header with breadcrumbs and user profile

### 2. Data Services

The package includes ready-to-use data services for common dashboard operations:

- **dashboardService**: Core dashboard data operations
- **workspaceService**: Workspace management and configuration
- **actionService**: Action tracking and management
- **whatsAppService**: WhatsApp integration for notifications
- **realtimeService**: Real-time data streaming and subscriptions
- **qualityService**: Quality metrics and analysis
- **mixpanelService**: Event tracking and analytics

### Sentry Utilities

The exported Sentry helpers are intended for high-signal dashboard failures. `captureSentryException`, `captureHandledFrontendException`, and `captureSentryMessage` sanitize exception payloads, messages, fingerprints, routes, and extras before capture, then apply quota controls. They may drop duplicate or over-budget handled events by design, and no-op when `@sentry/nextjs` is not installed. Use breadcrumbs for optional degraded behavior and direct app-level Sentry configuration for app-specific instrumentation.

### 3. Custom Hooks

Specialized hooks for data fetching and UI interactions:

- **useDashboardMetrics**: Dashboard-level metrics and KPIs
- **useMetrics**: General metrics management
- **useRealtimeLineMetrics**: Real-time line metrics with subscriptions
- **useLineDetailedMetrics**: Detailed metrics for production lines
- **useWorkspaceDetailedMetrics**: Detailed metrics for workspaces
- **useLineWorkspaceMetrics**: Combined line and workspace metrics
- **useHistoricWorkspaceMetrics**: Historical data for workspaces
- **useLeaderboardMetrics**: Leaderboard and ranking metrics
- **useFactoryOverviewMetrics**: Factory-level overview metrics
- **useTargets**: Production targets management
- **useWorkspaceOperators**: Operator assignment and management
- **useShifts**: Shift schedule management
- **useDateFormatter**: Date formatting utilities
- **useFormatNumber**: Number formatting utilities
- **useNavigation**: Navigation helpers

### 4. Complete Views

Full page-level view components that can be directly used in applications:

- **HomeView**: Main dashboard overview
- **FactoryView**: Factory-level overview with multiple lines
- **KPIDetailView**: Detailed KPI view for a specific line
- **WorkspaceDetailView**: Detailed view for a specific workspace
- **TargetsView**: Production targets management view
- **ShiftsView**: Shift scheduling and management view

## Installation

```bash
npm install @optifye/dashboard-core
```

### Peer Dependencies

This package requires the following peer dependencies to be installed in your project:

```bash
npm install react@^18 react-dom@^18 next@^13 tailwindcss@^3 @supabase/supabase-js@^2 date-fns@^4 date-fns-tz@^3
```

Additionally, you'll need to install these UI and utility dependencies:

```bash
npm install lucide-react @heroicons/react @tabler/icons-react @radix-ui/react-select @radix-ui/react-slider @radix-ui/react-slot @radix-ui/react-tabs recharts react-day-picker sonner swr zustand axios hls.js html2canvas jspdf mixpanel-browser tailwindcss-animate @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
```

Or if using Yarn:

```bash
yarn add react@^18 react-dom@^18 next@^13 tailwindcss@^3 @supabase/supabase-js@^2 date-fns@^4 date-fns-tz@^3
yarn add lucide-react @heroicons/react @tabler/icons-react @radix-ui/react-select @radix-ui/react-slider @radix-ui/react-slot @radix-ui/react-tabs recharts react-day-picker sonner swr zustand axios hls.js html2canvas jspdf mixpanel-browser tailwindcss-animate @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
```

### CSS Setup

This package includes global CSS styles that need to be imported in your application. In your Next.js app, import the global CSS file once in your `_app.tsx` or `layout.tsx`:

```tsx
// pages/_app.tsx or app/layout.tsx
import '@optifye/dashboard-core/global.css';
```

This CSS file includes:
- Tailwind CSS base styles
- Custom component styles
- React Day Picker styles (for calendar components)
- Range slider styling

**Note:** You do NOT need to separately import `react-day-picker/dist/style.css` as these styles are already included in the package's global CSS.

## Authentication Components

The package now includes built-in authentication components for a complete Supabase OTP-based authentication flow. See [AUTH_COMPONENTS_GUIDE.md](./AUTH_COMPONENTS_GUIDE.md) for detailed usage.

### Quick Start

1. **Copy the Optifye logo** from `node_modules/@optifye/dashboard-core/src/assets/optifye-logo.png` to your `public` folder.

2. **Create login page**:
```tsx
import { LoginPage } from '@optifye/dashboard-core';

export default function Login() {
  return <LoginPage logoSrc="/optifye-logo.png" />;
}
```

3. **Create auth callback page**:
```tsx
import { AuthCallback } from '@optifye/dashboard-core';

export default function AuthCallbackPage() {
  return <AuthCallback />;
}
```

### Available Auth Components

- **LoginPage**: Full-featured login page with email OTP authentication
- **AuthCallback**: Handles Supabase authentication callbacks
- **DebugAuth**: Debug page for troubleshooting Supabase configuration
- **withAuth**: HOC for protecting routes (already documented)

### Rate Limiting

The package includes built-in rate limiting utilities:

```tsx
import { checkRateLimit } from '@optifye/dashboard-core';

// In your API route
const { allowed, retryAfter } = checkRateLimit(email, {
  windowMs: 60000,  // 1 minute
  maxRequests: 3    // 3 attempts
});
```

## Mobile Responsiveness

All dashboard components are designed to be fully responsive and mobile-friendly:

### Responsive Features

- **Adaptive Grid Layouts**: Workspace video grids automatically adjust to show 2x2 layout on mobile screens
- **Responsive Text Sizes**: Text sizes scale appropriately across different screen sizes
- **Touch-Optimized Controls**: Buttons and interactive elements are sized for touch interaction
- **Flexible KPI Cards**: KPI cards stack vertically on mobile screens for better readability
- **Mobile-First Navigation**: Compact headers and navigation elements on smaller screens

### Breakpoint System

The dashboard uses Tailwind CSS breakpoints:
- Mobile: < 640px (default)
- Small (sm): ≥ 640px
- Medium (md): ≥ 768px
- Large (lg): ≥ 1024px
- Extra Large (xl): ≥ 1280px

### Usage Example for Mobile View

```tsx
// The dashboard automatically adapts to mobile screens
<HomeView 
  defaultLineId={defaultLineId}
  factoryViewId={factoryViewId}
  // ... other props
/>
```

Components handle responsive behavior internally, no additional configuration needed.

## Troubleshooting

### Next.js Module Resolution Error

If you encounter an error like:
```
Error: Cannot find module 'next/router' imported from node_modules/@optifye/dashboard-core/dist/index.mjs
```

This package is designed to be used within a Next.js application with proper bundler configuration. Make sure:
1. You're importing this package within a Next.js application
2. Your Next.js configuration is set up correctly
3. You're not trying to import this package in a pure Node.js ESM environment

If you're using this package in a custom setup, ensure your bundler is configured to handle Next.js module resolution.

## Integration Guide

### Basic Setup

1. Install the package:

```bash
npm install @optifye/dashboard-core
```

2. Wrap your application with the required providers:

```tsx
import { SupabaseProvider, DashboardProvider } from '@optifye/dashboard-core';
import { createClient } from '@supabase/supabase-js';

// Initialize Supabase client
const supabaseClient = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);

// Dashboard configuration
const dashboardConfig = {
  entityConfig: {
    lineId: 'your-line-id',
    factoryViewId: 'factory',
    companyId: 'your-company-id'
  },
  supabaseKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
  apiUrl: process.env.NEXT_PUBLIC_API_URL!,
  timezone: 'Asia/Kolkata',
  // ... other configuration options
};

function MyApp({ Component, pageProps }) {
  return (
    <SupabaseProvider client={supabaseClient}>
      <DashboardProvider config={dashboardConfig}>
          <Component {...pageProps} />
    </DashboardProvider>
    </SupabaseProvider>
  );
}

export default MyApp;
```

### Using Individual Components

```tsx
import { 
  KPICard, 
  Button, 
  Card, 
  DateDisplay,
  useLineKPIs
} from '@optifye/dashboard-core';

function MyDashboardComponent() {
  const { kpis, isLoading, error } = useLineKPIs('line-id');

  if (isLoading) return <LoadingSpinner />;
  if (error) return <div>Error loading KPIs</div>;

  return (
    <Card>
      <Card.Header>
        <Card.Title>Line Performance</Card.Title>
        <DateDisplay date={new Date()} />
      </Card.Header>
      <Card.Content>
        <div className="grid grid-cols-3 gap-4">
          <KPICard 
            title="Efficiency" 
            value={kpis.efficiency} 
            changeValue={kpis.efficiencyChange} 
            variant="percentage"
          />
          <KPICard 
            title="Output" 
            value={kpis.output} 
            changeValue={kpis.outputChange} 
            variant="number"
          />
          <KPICard 
            title="PPH" 
            value={kpis.pph} 
            changeValue={kpis.pphChange} 
            variant="number"
          />
        </div>
      </Card.Content>
      <Card.Footer>
        <Button>View Details</Button>
      </Card.Footer>
    </Card>
  );
}
```

### Using Complete Views

```tsx
import { FactoryView } from '@optifye/dashboard-core';
import { withAuth } from '@optifye/dashboard-core';

// Factory view with authentication protection
function FactoryPage() {
  return (
    <FactoryView 
      lineIds={['line-1-id', 'line-2-id']}
      productIdMap={{
        'line-1-id': 'product-1-id',
        'line-2-id': 'product-2-id'
      }}
      showEfficiency={true}
      showOutput={true}
      showUnderperforming={true}
    />
  );
}

export default withAuth(FactoryPage);
```

## Authentication and Security

The package includes a comprehensive authentication system:

- **withAuth**: Higher-order component for route protection
- **useAuth**: Hook for accessing authentication state and user data
- **AuthContext**: Context provider for authentication state
- **Authentication-Ready Views**: All view components have authentication built-in

## Performance Optimizations

The package includes several performance optimizations:

- **Component Memoization**: React.memo with custom comparison functions
- **Data Caching**: SWR-based data caching and revalidation
- **Lazy Loading**: Dynamic imports for heavy components
- **Tree Shaking**: Proper module exports for better tree shaking
- **Render Optimizations**: Proper useMemo and useCallback hooks

## AWS Integration for Video

The package includes AWS S3 integration for video clips:

- **Direct S3 Integration**: No API endpoints required
- **Signed URL Generation**: Secure access to video content
- **Configurable Integration**: Custom fetch functions and credentials
- **Fallback Mode**: Simulated mode when credentials are not available

## Configuration Reference

### DashboardConfig

```typescript
interface DashboardConfig {
  // Entity configuration
  entityConfig: {
    lineId: string;
    factoryViewId: string;
    companyId: string;
    // Optional additional line IDs
    lineIds?: Record<string, string>;
  };
  
  // API configuration
  supabaseKey: string;
  apiUrl: string;
  
  // Time configuration
  timezone: string;
  
  // Feature flags
  features?: {
    enableRealtime?: boolean;
    enableVideoStreaming?: boolean;
    enableWhatsAppShare?: boolean;
    enablePdfExport?: boolean;
  };
  
  // Theme configuration
  theme?: {
    primaryColor?: string;
    secondaryColor?: string;
    accentColor?: string;
    errorColor?: string;
    warningColor?: string;
    successColor?: string;
  };
  
  // Other configuration options
  options?: {
    refreshInterval?: number;
    dateFormat?: string;
    timeFormat?: string;
  };
}
```

## Working with Supabase

The package is designed to work with Supabase for data storage and real-time capabilities:

1. The `SupabaseProvider` component must be configured with a Supabase client.
2. All data services will use this client for data operations.
3. Real-time subscriptions use Supabase's real-time capabilities.

### Supabase Schema

The package expects the following Supabase tables and structure:

- **metrics_current**: Current metrics for lines and workspaces
- **metrics_hourly**: Hourly aggregated metrics
- **metrics_daily**: Daily aggregated metrics
- **line_operating_hours**: Shift configuration for lines
- **workspaces**: Workspace definitions and configuration
- **workspace_actions**: Action configurations for workspaces
- **workspace_operators**: Operator assignments to workspaces

## Integration Examples

### Next.js Integration

For Next.js applications, a common pattern is to use the dynamic catch-all routing to render the appropriate view:

```tsx
// pages/[[...dashboard]].tsx
import { useRouter } from 'next/router';
import dynamic from 'next/dynamic';

// Dynamic imports with loading fallbacks
const HomeView = dynamic(() => import('@optifye/dashboard-core/views/HomeView'), {
  loading: () => <div className="flex h-screen w-full items-center justify-center">Loading...</div>,
  ssr: false
});

const FactoryView = dynamic(() => import('@optifye/dashboard-core/views/FactoryView'), {
  loading: () => <div className="flex h-screen w-full items-center justify-center">Loading...</div>,
  ssr: false
});

// ... other view imports

export default function DashboardPage() {
  const router = useRouter();
  const { dashboard } = router.query;
  
  // Determine which view to render based on the route
  const renderView = () => {
    if (!dashboard || dashboard.length === 0) {
      return <HomeView />;
    }
    
    const [main, id] = dashboard as string[];
    
    switch (main) {
      case 'factory-view':
        return <FactoryView />;
      case 'kpis':
        return <KPIDetailView lineId={id} />;
      case 'workspace':
        return <WorkspaceDetailView workspaceId={id} />;
      case 'targets':
        return <TargetsView />;
      case 'shifts':
        return <ShiftsView />;
      default:
        return <div>Page not found</div>;
    }
  };
  
  return (
    <MainLayout>
      {renderView()}
    </MainLayout>
  );
}
```

### React SPA Integration

For React SPA applications, you can use React Router:

```tsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { 
  HomeView, 
  FactoryView, 
  KPIDetailView,
  WorkspaceDetailView,
  TargetsView,
  ShiftsView
} from '@optifye/dashboard-core';

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<HomeView />} />
        <Route path="/factory-view" element={<FactoryView />} />
        <Route path="/kpis/:lineId" element={<KPIDetailView />} />
        <Route path="/workspace/:id" element={<WorkspaceDetailView />} />
        <Route path="/targets" element={<TargetsView />} />
        <Route path="/shifts" element={<ShiftsView />} />
      </Routes>
    </BrowserRouter>
  );
}
```

## Available Services

### dashboardService

The core service for dashboard data operations.

```typescript
// Key Methods
dashboardService.getUnderperformingWorkspaces(lineId: string): Promise<WorkspaceMetrics[]>
dashboardService.getLineInfo(lineId: string): Promise<LineInfo>
dashboardService.getLineMetrics(lineId: string): Promise<LineMetrics>
dashboardService.getWorkspacesForLine(lineId: string): Promise<Workspace[]>
dashboardService.getHistoricalMetrics(params: HistoricalMetricsParams): Promise<HistoricalMetrics>
```

### workspaceService

Service for workspace management and configuration.

```typescript
// Key Methods
workspaceService.getWorkspace(workspaceId: string): Promise<Workspace>
workspaceService.getWorkspaceMetrics(workspaceId: string): Promise<WorkspaceDetailedMetrics>
workspaceService.updateWorkspaceAction(params: WorkspaceActionUpdate): Promise<void>
workspaceService.bulkUpdateWorkspaceActions(params: BulkWorkspaceActionUpdate): Promise<void>
workspaceService.getLineWorkspaceThresholds(lineId: string): Promise<LineThreshold[]>
```

### actionService

Service for action tracking and management.

```typescript
// Key Methods
actionService.getActionForWorkspace(workspaceId: string): Promise<Action>
actionService.updateAction(params: ActionUpdate): Promise<void>
actionService.addAction(params: ActionCreate): Promise<Action>
actionService.deleteAction(actionId: string): Promise<void>
```

### whatsAppService

WhatsApp integration for notifications.

```typescript
// Key Methods
whatsAppService.shareWorkspaceMetrics(params: ShareWorkspaceParams): Promise<string>
whatsAppService.shareLineMetrics(params: ShareLineParams): Promise<string>
whatsAppService.shareFactoryMetrics(params: ShareFactoryParams): Promise<string>
```

### realtimeService

Real-time data streaming and subscriptions.

```typescript
// Key Methods
realtimeService.subscribeToLineMetrics(lineId: string, callback: Callback): Subscription
realtimeService.subscribeToWorkspaceMetrics(workspaceId: string, callback: Callback): Subscription
realtimeService.unsubscribe(subscription: Subscription): void
```

## Extension and Customization

The package supports several extension mechanisms:

### DashboardOverrides

The `DashboardOverridesContext` allows overriding specific components:

```tsx
import { DashboardOverridesProvider } from '@optifye/dashboard-core';

// Custom components for overrides
const CustomKPICard = (props) => <div>Custom KPI Card: {props.title}</div>;
const CustomWorkspaceCard = (props) => <div>Custom Workspace: {props.name}</div>;

function MyApp({ Component, pageProps }) {
  const overrides = {
    components: {
      KPICard: CustomKPICard,
      WorkspaceCard: CustomWorkspaceCard
    },
    hooks: {
      // Hook overrides
    },
    views: {
      // View overrides
    }
  };

  return (
    <DashboardOverridesProvider overrides={overrides}>
      <Component {...pageProps} />
    </DashboardOverridesProvider>
  );
}
```

### View Customization

All view components accept extensive prop-based customization:

```tsx
<FactoryView
  lineIds={['line1', 'line2']}
  showEfficiency={true}
  showOutput={true}
  showPPH={true}
  refreshInterval={30000}
  onLineSelect={(lineId) => console.log(`Selected line: ${lineId}`)}
  customHeader={<MyCustomHeader />}
  customFooter={<MyCustomFooter />}
/>
```

## Troubleshooting

### Common Issues

1. **React Version Compatibility**

If you encounter React type compatibility issues between the package and your application, use type casting:

```tsx
import ComponentOriginal from '@optifye/dashboard-core/components/path/Component';
const Component = ComponentOriginal as any;
```

2. **Supabase Client Not Initialized**

Error: "Supabase client not initialized in @optifye/dashboard-core. Use SupabaseProvider."

Solution: Ensure your application is wrapped with `SupabaseProvider` and a valid Supabase client is provided.

3. **Missing Dashboard Configuration**

Error: "Dashboard configuration not found. Use DashboardProvider."

Solution: Ensure your application is wrapped with `DashboardProvider` and valid configuration is provided.

## Contributing

This package is continuously evolving. For contributions, please follow the established code patterns and ensure all tests pass.

## License

Proprietary - All rights reserved. This package is for internal use only.

## Publishing to npm

This package is published to npm as `@optifye/dashboard-core` and follows semantic versioning. New releases are automatically published when a PR with "RELEASE" in the title is merged to the main branch.

### How to trigger a new release

1. Create a changeset for your changes: `pnpm changeset` or `npx changeset`
2. Choose the appropriate version bump (patch, minor, major)
3. Commit the changeset file and push your branch
4. Run `npx changeset version` to update package.json and CHANGELOG.md
5. Commit the version changes
6. Create a PR with **"RELEASE"** (all caps) in the title
7. When merged, the GitHub Actions workflow will automatically publish the package to npm

**Important:** The release workflow is triggered by PR merges, not direct pushes to main. The PR title MUST contain "RELEASE" for the workflow to run.

### Example Release PR Title
```
RELEASE v2.0.1: Fix Next.js CSS import error
```

### Package Repository

The package repository field has been properly formatted for npm publishing standards.

## License

(License information, e.g., MIT, would go here.)

---

*Last updated for v4.0.0 - Published to npm*
