@optifye/dashboard-core 1.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/README.md +592 -154
  2. package/dist/index.js +19753 -4399
  3. package/dist/index.mjs +19593 -4238
  4. package/global.css +133 -0
  5. package/package.json +8 -9
package/README.md CHANGED
@@ -1,228 +1,656 @@
1
1
  # @optifye/dashboard-core
2
2
 
3
- A reusable React component library and utility toolkit for building dashboard functionalities, tailored for Optifye applications.
3
+ # @optifye/dashboard-core
4
+
5
+ A comprehensive React component library and core utilities package for building enterprise-grade operational dashboards with real-time metrics, visualizations, and interactive views.
6
+
7
+ ## Overview
8
+
9
+ 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.
10
+
11
+ This package has been designed with a focus on:
12
+
13
+ - **Component Reusability**: All UI components from atomic elements to complete page views
14
+ - **Data Abstraction**: Hooks and services for clean data fetching and management
15
+ - **Configurability**: Extensive prop-based configuration for all components
16
+ - **Type Safety**: Comprehensive TypeScript types throughout
17
+ - **Performance**: Optimized rendering and data fetching strategies
18
+ - **Enterprise Readiness**: Authentication, real-time data, and role-based access controls
19
+
20
+ ## Package Structure
21
+
22
+ ### Core Architecture
23
+
24
+ The package is organized into the following key directories:
25
+
26
+ ```
27
+ @optifye/dashboard-core/
28
+ ├── src/
29
+ │ ├── components/ # UI Components from atomic to composite
30
+ │ ├── lib/ # Core logic, utilities, hooks, services
31
+ │ ├── views/ # Complete page-level view components
32
+ │ └── index.ts # Main export file
33
+ ```
34
+
35
+ ### Component Architecture
36
+
37
+ Components follow a hierarchical organization:
38
+
39
+ ```
40
+ components/
41
+ ├── auth/ # Authentication components
42
+ ├── charts/ # Data visualization components
43
+ ├── common/ # Shared components across domains
44
+ ├── dashboard/ # Domain-specific dashboard components
45
+ │ ├── grid/ # Workspace grid components
46
+ │ ├── kpis/ # KPI visualization components
47
+ │ ├── line/ # Production line components
48
+ │ ├── video/ # Video streaming components
49
+ │ └── workspace/ # Workspace detail components
50
+ ├── data/ # Data display and transformation components
51
+ ├── layouts/ # Layout components and structure
52
+ ├── navigation/ # Navigation components and menus
53
+ ├── ui/ # Fundamental UI components (buttons, cards, etc.)
54
+ └── views/ # View-specific components
55
+ ```
56
+
57
+ ### Core Library Structure
58
+
59
+ The core logic follows a clean separation of concerns:
60
+
61
+ ```
62
+ lib/
63
+ ├── constants/ # Application constants and configuration values
64
+ ├── contexts/ # React context providers and consumers
65
+ ├── hooks/ # Custom React hooks for data and UI
66
+ ├── internal/ # Internal utilities (not exported)
67
+ ├── services/ # Data services and API clients
68
+ │ └── factories/ # Service factory functions
69
+ ├── supabase/ # Supabase client configuration
70
+ ├── types/ # TypeScript type definitions
71
+ └── utils/ # Utility functions by domain
72
+ └── dev/ # Development utilities
73
+ ```
74
+
75
+ ## Key Features
76
+
77
+ ### 1. UI Component System
78
+
79
+ The package provides a complete UI component system for building operational dashboards:
80
+
81
+ #### Foundational UI Components
82
+
83
+ - **Button**: Versatile button component with multiple variants (primary, secondary, outline, ghost)
84
+ - **Card**: Card components with header, body, and footer sections
85
+ - **Select**: Form select components with dropdown options
86
+ - **LoadingSpinner, LoadingOverlay, LoadingPage**: Loading indicators at various levels
87
+ - **DateDisplay, TimeDisplay**: Timezone-aware date and time components
88
+ - **Skeleton**: Loading skeleton placeholders
89
+ - **EmptyStateMessage**: Consistent empty state messaging
90
+
91
+ #### Data Visualization
92
+
93
+ - **KPICard**: Key Performance Indicator display cards
94
+ - **MetricCard**: General metric display cards
95
+ - **LineChart, BarChart**: Chart components for data visualization
96
+ - **HourlyOutputChart**: Specialized chart for hourly production data
97
+ - **WorkspaceHistoryCalendar**: Calendar visualization for workspace metrics history
98
+ - **OutputProgressChart**: Progress visualization for production output
99
+
100
+ #### Video & Real-Time Components
101
+
102
+ - **LiveView**: Real-time HLS video streaming component
103
+ - **BottlenecksContent**: Video clip management for bottleneck analysis
104
+
105
+ #### Navigation & Layout
106
+
107
+ - **MainLayout**: Main application layout with sidebar
108
+ - **DashboardLayout**: Full dashboard layout with header and sidebar
109
+ - **SideNavBar**: Navigation sidebar with configurable items
110
+ - **PageHeader**: Page header with breadcrumbs and user profile
111
+
112
+ ### 2. Data Services
113
+
114
+ The package includes ready-to-use data services for common dashboard operations:
115
+
116
+ - **dashboardService**: Core dashboard data operations
117
+ - **workspaceService**: Workspace management and configuration
118
+ - **actionService**: Action tracking and management
119
+ - **whatsAppService**: WhatsApp integration for notifications
120
+ - **realtimeService**: Real-time data streaming and subscriptions
121
+ - **qualityService**: Quality metrics and analysis
122
+ - **mixpanelService**: Event tracking and analytics
123
+
124
+ ### 3. Custom Hooks
4
125
 
5
- This package provides a set of configurable services, hooks, context providers, and utility functions to interact with a Supabase backend and manage dashboard-specific logic.
126
+ Specialized hooks for data fetching and UI interactions:
6
127
 
7
- ## Features
128
+ - **useDashboardMetrics**: Dashboard-level metrics and KPIs
129
+ - **useMetrics**: General metrics management
130
+ - **useRealtimeLineMetrics**: Real-time line metrics with subscriptions
131
+ - **useLineDetailedMetrics**: Detailed metrics for production lines
132
+ - **useWorkspaceDetailedMetrics**: Detailed metrics for workspaces
133
+ - **useLineWorkspaceMetrics**: Combined line and workspace metrics
134
+ - **useHistoricWorkspaceMetrics**: Historical data for workspaces
135
+ - **useLeaderboardMetrics**: Leaderboard and ranking metrics
136
+ - **useFactoryOverviewMetrics**: Factory-level overview metrics
137
+ - **useTargets**: Production targets management
138
+ - **useWorkspaceOperators**: Operator assignment and management
139
+ - **useShifts**: Shift schedule management
140
+ - **useDateFormatter**: Date formatting utilities
141
+ - **useFormatNumber**: Number formatting utilities
142
+ - **useNavigation**: Navigation helpers
8
143
 
9
- - **Configurable**: Highly configurable via a central `DashboardConfig` object.
10
- - **React Hooks**: A rich set of hooks for accessing data, managing state, and handling metrics.
11
- - **Services**: Modular services for interacting with backend data (e.g., dashboard metrics, line info, user actions).
12
- - **Context Providers**: For managing global state like authentication, configuration, and component overrides.
13
- - **Type-Safe**: Written in TypeScript for improved developer experience and safety.
144
+ ### 4. Complete Views
14
145
 
146
+ Full page-level view components that can be directly used in applications:
147
+
148
+ - **HomeView**: Main dashboard overview
149
+ - **FactoryView**: Factory-level overview with multiple lines
150
+ - **KPIDetailView**: Detailed KPI view for a specific line
151
+ - **WorkspaceDetailView**: Detailed view for a specific workspace
152
+ - **TargetsView**: Production targets management view
153
+ - **ShiftsView**: Shift scheduling and management view
15
154
 
16
155
  ## Installation
17
156
 
18
157
  ```bash
19
158
  npm install @optifye/dashboard-core
20
- # or
21
- yarn add @optifye/dashboard-core
22
159
  ```
23
160
 
24
- ## Quick Start & Usage
161
+ ### Peer Dependencies
162
+
163
+ This package requires the following peer dependencies to be installed in your project:
164
+
165
+ ```bash
166
+ npm install react@^18 react-dom@^18 next@^13 tailwindcss@^3 @supabase/supabase-js@^2 date-fns@^4 date-fns-tz@^3
167
+ ```
168
+
169
+ Or if using Yarn:
170
+
171
+ ```bash
172
+ yarn add react@^18 react-dom@^18 next@^13 tailwindcss@^3 @supabase/supabase-js@^2 date-fns@^4 date-fns-tz@^3
173
+ ```
174
+
175
+ ### CSS Setup
25
176
 
26
- The primary way to integrate `@optifye/dashboard-core` into your application is by using the `DashboardProvider` at the root of your component tree (or a relevant section).
177
+ 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`:
27
178
 
28
179
  ```tsx
29
- // Example: pages/_app.tsx in a Next.js application
30
-
31
- import type { AppProps } from 'next/app';
32
- import {
33
- DashboardProvider,
34
- DashboardConfig,
35
- AuthProvider,
36
- DashboardOverridesProvider
37
- } from '@optifye/dashboard-core';
180
+ // pages/_app.tsx or app/layout.tsx
181
+ import '@optifye/dashboard-core/global.css';
182
+ ```
38
183
 
39
- // 1. Define your application-specific dashboard configuration
40
- const appConfig: Partial<DashboardConfig> = {
41
- supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL!,
42
- supabaseKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
184
+ This CSS file includes:
185
+ - Tailwind CSS base styles
186
+ - Custom component styles
187
+ - React Day Picker styles (for calendar components)
188
+ - Range slider styling
189
+
190
+ **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.
191
+
192
+ ## Integration Guide
193
+
194
+ ### Basic Setup
195
+
196
+ 1. Install the package:
197
+
198
+ ```bash
199
+ npm install @optifye/dashboard-core
200
+ ```
201
+
202
+ 2. Wrap your application with the required providers:
203
+
204
+ ```tsx
205
+ import { SupabaseProvider, DashboardProvider } from '@optifye/dashboard-core';
206
+ import { createClient } from '@supabase/supabase-js';
207
+
208
+ // Initialize Supabase client
209
+ const supabaseClient = createClient(
210
+ process.env.NEXT_PUBLIC_SUPABASE_URL!,
211
+ process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
212
+ );
213
+
214
+ // Dashboard configuration
215
+ const dashboardConfig = {
43
216
  entityConfig: {
44
- companyId: process.env.NEXT_PUBLIC_COMPANY_ID!,
45
- // ... other entity-specific IDs like factoryId, defaultLineId etc.
217
+ lineId: 'your-line-id',
218
+ factoryViewId: 'factory',
219
+ companyId: 'your-company-id'
46
220
  },
47
- // ... other configurations like theme, analytics, dateTimeConfig etc.
221
+ supabaseKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
222
+ apiUrl: process.env.NEXT_PUBLIC_API_URL!,
223
+ timezone: 'Asia/Kolkata',
224
+ // ... other configuration options
48
225
  };
49
226
 
50
- function MyApp({ Component, pageProps }: AppProps) {
227
+ function MyApp({ Component, pageProps }) {
51
228
  return (
52
- <DashboardProvider config={appConfig}>
53
- <AuthProvider> { /* For authentication */ }
54
- <DashboardOverridesProvider overrides={{ /* your component overrides */ }}>
229
+ <SupabaseProvider client={supabaseClient}>
230
+ <DashboardProvider config={dashboardConfig}>
55
231
  <Component {...pageProps} />
56
- </DashboardOverridesProvider>
57
- </AuthProvider>
58
232
  </DashboardProvider>
233
+ </SupabaseProvider>
59
234
  );
60
235
  }
61
236
 
62
237
  export default MyApp;
63
238
  ```
64
239
 
65
- ### Configuration (`DashboardConfig`)
240
+ ### Using Individual Components
66
241
 
67
- The `DashboardConfig` object is crucial for tailoring the package to your specific application instance. It allows you to define:
242
+ ```tsx
243
+ import {
244
+ KPICard,
245
+ Button,
246
+ Card,
247
+ DateDisplay,
248
+ useLineKPIs
249
+ } from '@optifye/dashboard-core';
68
250
 
69
- - Supabase credentials (`supabaseUrl`, `supabaseKey` - **required**)
70
- - Entity identifiers (`entityConfig` - e.g., `companyId`, `factoryId`, line IDs - **often required for services/hooks**)
71
- - API endpoints (`apiBaseUrl`, `endpoints`)
72
- - Theme overrides (`theme`)
73
- - Date/time preferences (`dateTimeConfig`)
74
- - Database table names and schema (`databaseConfig`)
75
- - And more...
251
+ function MyDashboardComponent() {
252
+ const { kpis, isLoading, error } = useLineKPIs('line-id');
76
253
 
77
- Refer to the `DashboardConfig` interface definition within the package (exported from `lib/types/dashboardConfig`) for all available options and their types. For a detailed setup guide, see the [Application Configuration Setup Guide](../../migration_outputs/14_app_configuration_setup.md).
254
+ if (isLoading) return <LoadingSpinner />;
255
+ if (error) return <div>Error loading KPIs</div>;
78
256
 
79
- ## Core Modules
257
+ return (
258
+ <Card>
259
+ <Card.Header>
260
+ <Card.Title>Line Performance</Card.Title>
261
+ <DateDisplay date={new Date()} />
262
+ </Card.Header>
263
+ <Card.Content>
264
+ <div className="grid grid-cols-3 gap-4">
265
+ <KPICard
266
+ title="Efficiency"
267
+ value={kpis.efficiency}
268
+ changeValue={kpis.efficiencyChange}
269
+ variant="percentage"
270
+ />
271
+ <KPICard
272
+ title="Output"
273
+ value={kpis.output}
274
+ changeValue={kpis.outputChange}
275
+ variant="number"
276
+ />
277
+ <KPICard
278
+ title="PPH"
279
+ value={kpis.pph}
280
+ changeValue={kpis.pphChange}
281
+ variant="number"
282
+ />
283
+ </div>
284
+ </Card.Content>
285
+ <Card.Footer>
286
+ <Button>View Details</Button>
287
+ </Card.Footer>
288
+ </Card>
289
+ );
290
+ }
291
+ ```
80
292
 
81
- This package is organized into several core modules:
293
+ ### Using Complete Views
82
294
 
83
- - **`lib/types`**: Contains all TypeScript interface and type definitions.
84
- - **`lib/constants`**: Provides default configurations and other constant values.
85
- - **`lib/contexts`**: Includes React Context providers and hooks for global state.
86
- - **`lib/hooks`**: Custom React hooks for fetching and managing data.
87
- - **`lib/services`**: Service factories for data interaction.
88
- - **`lib/utils`**: Utility functions for common tasks.
89
- - **`lib/supabaseClient`**: Supabase client utilities.
295
+ ```tsx
296
+ import { FactoryView } from '@optifye/dashboard-core';
297
+ import { withAuth } from '@optifye/dashboard-core';
90
298
 
91
- ## Utility Hooks
299
+ // Factory view with authentication protection
300
+ function FactoryPage() {
301
+ return (
302
+ <FactoryView
303
+ lineIds={['line-1-id', 'line-2-id']}
304
+ productIdMap={{
305
+ 'line-1-id': 'product-1-id',
306
+ 'line-2-id': 'product-2-id'
307
+ }}
308
+ showEfficiency={true}
309
+ showOutput={true}
310
+ showUnderperforming={true}
311
+ />
312
+ );
313
+ }
92
314
 
93
- - **`useNavigation`**: Abstracted navigation API.
94
- - **`useDateFormatter`**: Configured date/time formatting.
95
- - **`useWorkspaceNavigation`**: Utilities for workspace navigation parameters.
96
- - **`useFormatNumber`**: Configured number formatting.
315
+ export default withAuth(FactoryPage);
316
+ ```
97
317
 
98
- ## UI Components
318
+ ## Authentication and Security
99
319
 
100
- `@optifye/dashboard-core` provides a suite of reusable UI components.
320
+ The package includes a comprehensive authentication system:
101
321
 
102
- ### Common Components
322
+ - **withAuth**: Higher-order component for route protection
323
+ - **useAuth**: Hook for accessing authentication state and user data
324
+ - **AuthContext**: Context provider for authentication state
325
+ - **Authentication-Ready Views**: All view components have authentication built-in
103
326
 
104
- - **`MetricCard`**: Displays a key metric, value, unit, and trend.
105
- - **Location**: `packages/dashboard-core/src/components/common/MetricCard.tsx`
106
- - **`DateTimeDisplay`**: Shows current date/time, formatted via `DateTimeConfig`.
107
- - **Location**: `packages/dashboard-core/src/components/common/DateTimeDisplay.tsx`
108
- - **`EmptyStateMessage`**: For displaying messages when content is unavailable.
109
- - **Location**: `packages/dashboard-core/src/components/common/EmptyStateMessage.tsx`
110
- - **`WhatsAppShareButton`**: Opens a WhatsApp share link.
111
- - **Location**: `packages/dashboard-core/src/components/common/WhatsAppShareButton.tsx`
112
- - **`BaseHistoryCalendar`**: Foundational calendar using `react-day-picker`.
113
- - **Location**: `packages/dashboard-core/src/components/common/BaseHistoryCalendar.tsx`
327
+ ## Performance Optimizations
114
328
 
115
- ### Dashboard Components
329
+ The package includes several performance optimizations:
116
330
 
117
- #### Line Components
331
+ - **Component Memoization**: React.memo with custom comparison functions
332
+ - **Data Caching**: SWR-based data caching and revalidation
333
+ - **Lazy Loading**: Dynamic imports for heavy components
334
+ - **Tree Shaking**: Proper module exports for better tree shaking
335
+ - **Render Optimizations**: Proper useMemo and useCallback hooks
118
336
 
119
- - **`LinePdfExportButton`**: Captures a DOM element and exports as PDF.
120
- - **Location**: `packages/dashboard-core/src/components/dashboard/line/LinePdfExportButton.tsx`
121
- - **`LineHistoryCalendar`**: Displays monthly history for a line using `BaseHistoryCalendar`.
122
- - **Location**: `packages/dashboard-core/src/components/dashboard/line/LineHistoryCalendar.tsx`
123
- - **`LineMonthlyHistory`**: Monthly historical overview for a line, using `LineHistoryCalendar`.
124
- - **Location**: `packages/dashboard-core/src/components/dashboard/line/LineMonthlyHistory.tsx`
337
+ ## AWS Integration for Video
125
338
 
126
- #### Workspace Components
339
+ The package includes AWS S3 integration for video clips:
127
340
 
128
- - **`WorkspacePdfExportButton`**: Similar to `LinePdfExportButton` for workspace data.
129
- - **Location**: `packages/dashboard-core/src/components/dashboard/workspace/WorkspacePdfExportButton.tsx`
130
- - **`WorkspaceCard`**: Presentational card for workspace information and metrics.
131
- - **Location**: `packages/dashboard-core/src/components/dashboard/workspace/WorkspaceCard.tsx`
132
- - **`LiveView`**: Displays HLS video streams for workspace cameras.
133
- - **Location**: `packages/dashboard-core/src/components/dashboard/workspace/LiveView.tsx`
134
- - **`OperatorsDisplay`**: Displays a list/row of operator avatars/names.
135
- - **Location**: `packages/dashboard-core/src/components/dashboard/workspace/OperatorsDisplay.tsx`
136
- - **`WorkspaceHistoryCalendar`**: Displays monthly history for a workspace, using `BaseHistoryCalendar`.
137
- - **Location**: `packages/dashboard-core/src/components/dashboard/workspace/WorkspaceHistoryCalendar.tsx`
341
+ - **Direct S3 Integration**: No API endpoints required
342
+ - **Signed URL Generation**: Secure access to video content
343
+ - **Configurable Integration**: Custom fetch functions and credentials
344
+ - **Fallback Mode**: Simulated mode when credentials are not available
138
345
 
139
- #### Grid Components
346
+ ## Configuration Reference
140
347
 
141
- - **`WorkspaceGrid`**: Layout for arranging `WorkspaceCard` components.
142
- - **Location**: `packages/dashboard-core/src/components/dashboard/grid/WorkspaceGrid.tsx`
348
+ ### DashboardConfig
143
349
 
144
- ### Chart Components
350
+ ```typescript
351
+ interface DashboardConfig {
352
+ // Entity configuration
353
+ entityConfig: {
354
+ lineId: string;
355
+ factoryViewId: string;
356
+ companyId: string;
357
+ // Optional additional line IDs
358
+ lineIds?: Record<string, string>;
359
+ };
360
+
361
+ // API configuration
362
+ supabaseKey: string;
363
+ apiUrl: string;
364
+
365
+ // Time configuration
366
+ timezone: string;
367
+
368
+ // Feature flags
369
+ features?: {
370
+ enableRealtime?: boolean;
371
+ enableVideoStreaming?: boolean;
372
+ enableWhatsAppShare?: boolean;
373
+ enablePdfExport?: boolean;
374
+ };
375
+
376
+ // Theme configuration
377
+ theme?: {
378
+ primaryColor?: string;
379
+ secondaryColor?: string;
380
+ accentColor?: string;
381
+ errorColor?: string;
382
+ warningColor?: string;
383
+ successColor?: string;
384
+ };
385
+
386
+ // Other configuration options
387
+ options?: {
388
+ refreshInterval?: number;
389
+ dateFormat?: string;
390
+ timeFormat?: string;
391
+ };
392
+ }
393
+ ```
145
394
 
146
- - **`BarChart`**: Generic wrapper for Recharts `BarChart`.
147
- - **Location**: `packages/dashboard-core/src/components/charts/BarChart.tsx`
148
- - **`LineChart`**: Flexible wrapper for Recharts `LineChart`.
149
- - **Location**: `packages/dashboard-core/src/components/charts/LineChart.tsx`
395
+ ## Working with Supabase
150
396
 
151
- ### KPI Components
397
+ The package is designed to work with Supabase for data storage and real-time capabilities:
152
398
 
153
- - **`KPICard`**: Displays KPI metrics with trends, secondary metrics, status indicators.
154
- - **Location**: `packages/dashboard-core/src/components/dashboard/kpis/KPICard.tsx`
155
- - **`KPIGrid`**: Layout for KPI cards (row or grid).
156
- - **Location**: `packages/dashboard-core/src/components/dashboard/kpis/KPIGrid.tsx`
157
- - **`KPIHeader`**: Header for KPI sections with title, subtitle, actions.
158
- - **Location**: `packages/dashboard-core/src/components/dashboard/kpis/KPIHeader.tsx`
159
- - **`KPISection`**: Displays a collection of KPIs using `KPICard`s and `KPIGrid`.
160
- - **Location**: `packages/dashboard-core/src/components/dashboard/kpis/KPISection.tsx`
399
+ 1. The `SupabaseProvider` component must be configured with a Supabase client.
400
+ 2. All data services will use this client for data operations.
401
+ 3. Real-time subscriptions use Supabase's real-time capabilities.
161
402
 
162
- ### Navigation Components
403
+ ### Supabase Schema
163
404
 
164
- - **`SideNavBar`**: Configurable side navigation bar.
165
- - **Location**: `packages/dashboard-core/src/components/navigation/SideNavBar.tsx`
405
+ The package expects the following Supabase tables and structure:
166
406
 
167
- ### Layout Components
407
+ - **metrics_current**: Current metrics for lines and workspaces
408
+ - **metrics_hourly**: Hourly aggregated metrics
409
+ - **metrics_daily**: Daily aggregated metrics
410
+ - **line_operating_hours**: Shift configuration for lines
411
+ - **workspaces**: Workspace definitions and configuration
412
+ - **workspace_actions**: Action configurations for workspaces
413
+ - **workspace_operators**: Operator assignments to workspaces
168
414
 
169
- - **`PageHeader`**: Responsive header for dashboard pages.
170
- - **Location**: `packages/dashboard-core/src/components/layouts/PageHeader.tsx`
171
- - **`DashboardLayout`**: Main layout component for dashboard pages.
172
- - **Location**: `packages/dashboard-core/src/components/layouts/DashboardLayout.tsx`
415
+ ## Integration Examples
173
416
 
417
+ ### Next.js Integration
174
418
 
175
- ### Leaderboard Components
419
+ For Next.js applications, a common pattern is to use the dynamic catch-all routing to render the appropriate view:
176
420
 
177
- Location: `src/components/dashboard/leaderboard/`
421
+ ```tsx
422
+ // pages/[[...dashboard]].tsx
423
+ import { useRouter } from 'next/router';
424
+ import dynamic from 'next/dynamic';
425
+
426
+ // Dynamic imports with loading fallbacks
427
+ const HomeView = dynamic(() => import('@optifye/dashboard-core/views/HomeView'), {
428
+ loading: () => <div className="flex h-screen w-full items-center justify-center">Loading...</div>,
429
+ ssr: false
430
+ });
431
+
432
+ const FactoryView = dynamic(() => import('@optifye/dashboard-core/views/FactoryView'), {
433
+ loading: () => <div className="flex h-screen w-full items-center justify-center">Loading...</div>,
434
+ ssr: false
435
+ });
436
+
437
+ // ... other view imports
438
+
439
+ export default function DashboardPage() {
440
+ const router = useRouter();
441
+ const { dashboard } = router.query;
442
+
443
+ // Determine which view to render based on the route
444
+ const renderView = () => {
445
+ if (!dashboard || dashboard.length === 0) {
446
+ return <HomeView />;
447
+ }
448
+
449
+ const [main, id] = dashboard as string[];
450
+
451
+ switch (main) {
452
+ case 'factory-view':
453
+ return <FactoryView />;
454
+ case 'kpis':
455
+ return <KPIDetailView lineId={id} />;
456
+ case 'workspace':
457
+ return <WorkspaceDetailView workspaceId={id} />;
458
+ case 'targets':
459
+ return <TargetsView />;
460
+ case 'shifts':
461
+ return <ShiftsView />;
462
+ default:
463
+ return <div>Page not found</div>;
464
+ }
465
+ };
466
+
467
+ return (
468
+ <MainLayout>
469
+ {renderView()}
470
+ </MainLayout>
471
+ );
472
+ }
473
+ ```
178
474
 
179
- * **`LeaderboardTable`**: A flexible and sortable table component designed to display leaderboard rankings. It supports custom column definitions, row click handlers, loading/error/empty states, and styling for highlighting top/bottom entries.
180
- * **Key Props**: `data: LeaderboardRowData[]`, `columns?: ColumnDefinitionUnion[]`, `title?: string`, `onRowClick?: (row: LeaderboardRowData) => void`.
181
- * **Usage**: Ideal for presenting ranked lists based on performance metrics.
475
+ ### React SPA Integration
182
476
 
183
- ## Usage
477
+ For React SPA applications, you can use React Router:
184
478
 
185
- To use the `@optifye/dashboard-core` service factory in your application:
479
+ ```tsx
480
+ import { BrowserRouter, Routes, Route } from 'react-router-dom';
481
+ import {
482
+ HomeView,
483
+ FactoryView,
484
+ KPIDetailView,
485
+ WorkspaceDetailView,
486
+ TargetsView,
487
+ ShiftsView
488
+ } from '@optifye/dashboard-core';
186
489
 
187
- 1. **Ensure you have a Supabase client instance initialized in your application.**
490
+ export default function App() {
491
+ return (
492
+ <BrowserRouter>
493
+ <Routes>
494
+ <Route path="/" element={<HomeView />} />
495
+ <Route path="/factory-view" element={<FactoryView />} />
496
+ <Route path="/kpis/:lineId" element={<KPIDetailView />} />
497
+ <Route path="/workspace/:id" element={<WorkspaceDetailView />} />
498
+ <Route path="/targets" element={<TargetsView />} />
499
+ <Route path="/shifts" element={<ShiftsView />} />
500
+ </Routes>
501
+ </BrowserRouter>
502
+ );
503
+ }
504
+ ```
505
+
506
+ ## Available Services
188
507
 
189
- 2. **Prepare a configuration object.** The service factory `createDashboardService` expects a configuration object that can include:
190
- * `entityConfig`: Specifies `companyId`, `factoryId`, `defaultLineId`, `secondaryLineId`, `lineNames`, and `factoryViewId`.
191
- * `supabaseUrl`, `supabaseKey`: Required by certain internal parts of the service (e.g., Edge Function calls) even if a client is passed.
192
- * `apiBaseUrl`: Base URL for API calls, used by features like `getUnderperformingWorkspaces` if its endpoint is relative.
193
- * `endpoints`: Configuration for specific service endpoints, e.g., `worstPerformingWorkspaces`.
194
- * Other configurations like `databaseConfig`, `shiftConfig`, `dateTimeConfig` can be provided to override package defaults.
508
+ ### dashboardService
195
509
 
196
- 3. **Create the service instance:**
510
+ The core service for dashboard data operations.
197
511
 
198
512
  ```typescript
199
- import { createDashboardService } from '@optifye/dashboard-core';
200
- import type { DashboardConfig } from '@optifye/dashboard-core';
201
- import { supabase } from '../path/to/your/supabaseClient'; // Your app's Supabase client
513
+ // Key Methods
514
+ dashboardService.getUnderperformingWorkspaces(lineId: string): Promise<WorkspaceMetrics[]>
515
+ dashboardService.getLineInfo(lineId: string): Promise<LineInfo>
516
+ dashboardService.getLineMetrics(lineId: string): Promise<LineMetrics>
517
+ dashboardService.getWorkspacesForLine(lineId: string): Promise<Workspace[]>
518
+ dashboardService.getHistoricalMetrics(params: HistoricalMetricsParams): Promise<HistoricalMetrics>
519
+ ```
202
520
 
203
- // Example application-specific configuration
204
- const appDashboardConfig: Partial<DashboardConfig> = {
205
- entityConfig: {
206
- companyId: 'YOUR_COMPANY_UUID',
207
- defaultLineId: 'YOUR_DEFAULT_LINE_UUID',
208
- // ... other entity properties
209
- },
210
- supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL,
211
- supabaseKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
212
- apiBaseUrl: process.env.NEXT_PUBLIC_API_URL,
213
- endpoints: {
214
- worstPerformingWorkspaces: '/functions/v1/worst-performing-workspaces' // Or your specific endpoint path
215
- }
216
- };
521
+ ### workspaceService
522
+
523
+ Service for workspace management and configuration.
524
+
525
+ ```typescript
526
+ // Key Methods
527
+ workspaceService.getWorkspace(workspaceId: string): Promise<Workspace>
528
+ workspaceService.getWorkspaceMetrics(workspaceId: string): Promise<WorkspaceDetailedMetrics>
529
+ workspaceService.updateWorkspaceAction(params: WorkspaceActionUpdate): Promise<void>
530
+ workspaceService.bulkUpdateWorkspaceActions(params: BulkWorkspaceActionUpdate): Promise<void>
531
+ workspaceService.getLineWorkspaceThresholds(lineId: string): Promise<LineThreshold[]>
532
+ ```
533
+
534
+ ### actionService
535
+
536
+ Service for action tracking and management.
537
+
538
+ ```typescript
539
+ // Key Methods
540
+ actionService.getActionForWorkspace(workspaceId: string): Promise<Action>
541
+ actionService.updateAction(params: ActionUpdate): Promise<void>
542
+ actionService.addAction(params: ActionCreate): Promise<Action>
543
+ actionService.deleteAction(actionId: string): Promise<void>
544
+ ```
545
+
546
+ ### whatsAppService
217
547
 
218
- export const dashboardService = createDashboardService(appDashboardConfig, supabase);
548
+ WhatsApp integration for notifications.
549
+
550
+ ```typescript
551
+ // Key Methods
552
+ whatsAppService.shareWorkspaceMetrics(params: ShareWorkspaceParams): Promise<string>
553
+ whatsAppService.shareLineMetrics(params: ShareLineParams): Promise<string>
554
+ whatsAppService.shareFactoryMetrics(params: ShareFactoryParams): Promise<string>
219
555
  ```
220
556
 
221
- Now you can use `dashboardService.getLineInfo()`, `dashboardService.getWorkspacesData()`, etc., throughout your application.
557
+ ### realtimeService
558
+
559
+ Real-time data streaming and subscriptions.
560
+
561
+ ```typescript
562
+ // Key Methods
563
+ realtimeService.subscribeToLineMetrics(lineId: string, callback: Callback): Subscription
564
+ realtimeService.subscribeToWorkspaceMetrics(workspaceId: string, callback: Callback): Subscription
565
+ realtimeService.unsubscribe(subscription: Subscription): void
566
+ ```
222
567
 
223
- ## Development
568
+ ## Extension and Customization
224
569
 
225
- (Information about local development, building, and contributing to this package would go here.)
570
+ The package supports several extension mechanisms:
571
+
572
+ ### DashboardOverrides
573
+
574
+ The `DashboardOverridesContext` allows overriding specific components:
575
+
576
+ ```tsx
577
+ import { DashboardOverridesProvider } from '@optifye/dashboard-core';
578
+
579
+ // Custom components for overrides
580
+ const CustomKPICard = (props) => <div>Custom KPI Card: {props.title}</div>;
581
+ const CustomWorkspaceCard = (props) => <div>Custom Workspace: {props.name}</div>;
582
+
583
+ function MyApp({ Component, pageProps }) {
584
+ const overrides = {
585
+ components: {
586
+ KPICard: CustomKPICard,
587
+ WorkspaceCard: CustomWorkspaceCard
588
+ },
589
+ hooks: {
590
+ // Hook overrides
591
+ },
592
+ views: {
593
+ // View overrides
594
+ }
595
+ };
596
+
597
+ return (
598
+ <DashboardOverridesProvider overrides={overrides}>
599
+ <Component {...pageProps} />
600
+ </DashboardOverridesProvider>
601
+ );
602
+ }
603
+ ```
604
+
605
+ ### View Customization
606
+
607
+ All view components accept extensive prop-based customization:
608
+
609
+ ```tsx
610
+ <FactoryView
611
+ lineIds={['line1', 'line2']}
612
+ showEfficiency={true}
613
+ showOutput={true}
614
+ showPPH={true}
615
+ refreshInterval={30000}
616
+ onLineSelect={(lineId) => console.log(`Selected line: ${lineId}`)}
617
+ customHeader={<MyCustomHeader />}
618
+ customFooter={<MyCustomFooter />}
619
+ />
620
+ ```
621
+
622
+ ## Troubleshooting
623
+
624
+ ### Common Issues
625
+
626
+ 1. **React Version Compatibility**
627
+
628
+ If you encounter React type compatibility issues between the package and your application, use type casting:
629
+
630
+ ```tsx
631
+ import ComponentOriginal from '@optifye/dashboard-core/components/path/Component';
632
+ const Component = ComponentOriginal as any;
633
+ ```
634
+
635
+ 2. **Supabase Client Not Initialized**
636
+
637
+ Error: "Supabase client not initialized in @optifye/dashboard-core. Use SupabaseProvider."
638
+
639
+ Solution: Ensure your application is wrapped with `SupabaseProvider` and a valid Supabase client is provided.
640
+
641
+ 3. **Missing Dashboard Configuration**
642
+
643
+ Error: "Dashboard configuration not found. Use DashboardProvider."
644
+
645
+ Solution: Ensure your application is wrapped with `DashboardProvider` and valid configuration is provided.
646
+
647
+ ## Contributing
648
+
649
+ This package is continuously evolving. For contributions, please follow the established code patterns and ensure all tests pass.
650
+
651
+ ## License
652
+
653
+ Proprietary - All rights reserved. This package is for internal use only.
226
654
 
227
655
  ## Publishing to npm
228
656
 
@@ -230,10 +658,20 @@ This package is published to npm as `@optifye/dashboard-core` and follows semant
230
658
 
231
659
  ### How to trigger a new release
232
660
 
233
- 1. Create a changeset for your changes: `pnpm changeset`
661
+ 1. Create a changeset for your changes: `pnpm changeset` or `npx changeset`
234
662
  2. Choose the appropriate version bump (patch, minor, major)
235
- 3. Create a PR with "RELEASE" in the title
236
- 4. When merged, the GitHub Actions workflow will automatically publish the package to npm
663
+ 3. Commit the changeset file and push your branch
664
+ 4. Run `npx changeset version` to update package.json and CHANGELOG.md
665
+ 5. Commit the version changes
666
+ 6. Create a PR with **"RELEASE"** (all caps) in the title
667
+ 7. When merged, the GitHub Actions workflow will automatically publish the package to npm
668
+
669
+ **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.
670
+
671
+ ### Example Release PR Title
672
+ ```
673
+ RELEASE v2.0.1: Fix Next.js CSS import error
674
+ ```
237
675
 
238
676
  ### Package Repository
239
677