@optifye/dashboard-core 6.12.22 → 6.12.25

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.
package/dist/index.mjs CHANGED
@@ -10,7 +10,7 @@ import { EventEmitter } from 'events';
10
10
  import { createClient, REALTIME_SUBSCRIBE_STATES } from '@supabase/supabase-js';
11
11
  import Hls, { Events, ErrorTypes } from 'hls.js';
12
12
  import useSWR from 'swr';
13
- import { Camera, AlertTriangle, ChevronDown, ChevronUp, Check, Map as Map$1, Video, ShieldCheck, Star, Award, Filter, X, Coffee, Plus, ArrowUp, ArrowDown, ArrowRight, ArrowLeft, Clock, Calendar, Save, AlertCircle, Loader2, Minus, ChevronLeft, ChevronRight, TrendingUp, Sparkles, Pause, Play, XCircle, HelpCircle, Activity, Wrench, UserX, Package, RefreshCw, Palette, CheckCircle2, TrendingDown, FolderOpen, Folder, ArrowDownWideNarrow, Tag, Sliders, Layers, Search, Edit2, CheckCircle, User, Users, Shield, Building2, Mail, Lock, Info, Share2, Trophy, Target, Download, Copy, Sun, Moon, MousePointer, UserPlus, UserCog, Trash2, Eye, MoreVertical, BarChart3, Pencil, UserCheck, LogOut, Film, MessageSquare, Menu, Send, Settings, LifeBuoy, EyeOff, Zap, Flame, Crown, Medal } from 'lucide-react';
13
+ import { Camera, AlertTriangle, ChevronDown, ChevronUp, Check, ShieldCheck, Star, Award, Filter, X, Coffee, Plus, ArrowUp, ArrowDown, ArrowRight, CheckCircle2, ArrowLeft, Clock, Calendar, Save, AlertCircle, Loader2, Minus, ChevronLeft, ChevronRight, TrendingUp, Sparkles, Pause, Play, XCircle, HelpCircle, Activity, Wrench, UserX, Package, RefreshCw, Palette, TrendingDown, FolderOpen, Folder, ArrowDownWideNarrow, Tag, Sliders, Layers, Search, Edit2, CheckCircle, User, Users, Shield, Building2, Mail, Lock, Info, Share2, Trophy, Target, Download, Video, Copy, Sun, Moon, MousePointer, UserPlus, UserCog, Trash2, Eye, MoreVertical, BarChart3, Pencil, UserCheck, LogOut, Film, MessageSquare, Menu, Send, Settings, LifeBuoy, EyeOff, Zap, Flame, Crown, Medal } from 'lucide-react';
14
14
  import { memo, noop, warning, invariant, progress, secondsToMilliseconds, millisecondsToSeconds } from 'motion-utils';
15
15
  import { BarChart as BarChart$1, CartesianGrid, XAxis, YAxis, ReferenceLine, Tooltip, Legend, Bar, LabelList, ResponsiveContainer, LineChart as LineChart$1, Line, Customized, Cell, PieChart, Pie, ComposedChart, Area, ScatterChart, Scatter } from 'recharts';
16
16
  import { Slot } from '@radix-ui/react-slot';
@@ -9904,7 +9904,8 @@ var LinesService = class {
9904
9904
  line.video_grid_metric_mode,
9905
9905
  line.assembly ?? false
9906
9906
  ),
9907
- recentFlowWindowMinutes: line.recent_flow_window_minutes ?? 7
9907
+ recentFlowWindowMinutes: line.recent_flow_window_minutes ?? 7,
9908
+ factoryAreaId: line.factory_area_id ?? null
9908
9909
  }));
9909
9910
  } catch (error) {
9910
9911
  console.error("Error fetching lines:", error);
@@ -9963,7 +9964,8 @@ var LinesService = class {
9963
9964
  line.video_grid_metric_mode,
9964
9965
  line.assembly ?? false
9965
9966
  ),
9966
- recentFlowWindowMinutes: line.recent_flow_window_minutes ?? 7
9967
+ recentFlowWindowMinutes: line.recent_flow_window_minutes ?? 7,
9968
+ factoryAreaId: line.factory_area_id ?? null
9967
9969
  }));
9968
9970
  } catch (error) {
9969
9971
  console.error("Error fetching all lines:", error);
@@ -10030,7 +10032,8 @@ var LinesService = class {
10030
10032
  data.video_grid_metric_mode,
10031
10033
  data.assembly ?? false
10032
10034
  ),
10033
- recentFlowWindowMinutes: data.recent_flow_window_minutes ?? 7
10035
+ recentFlowWindowMinutes: data.recent_flow_window_minutes ?? 7,
10036
+ factoryAreaId: data.factory_area_id ?? null
10034
10037
  };
10035
10038
  } catch (error) {
10036
10039
  console.error("Error fetching line:", error);
@@ -11644,6 +11647,9 @@ var lineLeaderboardService = {
11644
11647
  if (typeof params.limit === "number") {
11645
11648
  searchParams.set("limit", params.limit.toString());
11646
11649
  }
11650
+ if (params.includeBelowThreshold) {
11651
+ searchParams.set("include_below_threshold", "true");
11652
+ }
11647
11653
  const data = await fetchBackendJson(
11648
11654
  supabase,
11649
11655
  `/api/dashboard/line-leaderboard-daily?${searchParams.toString()}`
@@ -14580,6 +14586,32 @@ function getEfficiencyTextColorClasses(efficiency, legend = DEFAULT_EFFICIENCY_L
14580
14586
  }
14581
14587
  }
14582
14588
 
14589
+ // src/lib/utils/qaGreenStreakParams.ts
14590
+ var QA_GREEN_STREAK_QUERY_PARAM_NAMES = [
14591
+ "qa_green_streak_started_at",
14592
+ "qa_green_streak_elapsed_seconds",
14593
+ "qa_green_streak_status"
14594
+ ];
14595
+ var isTruthyEnv = (value) => ["1", "true", "yes", "on"].includes(String(value || "").trim().toLowerCase());
14596
+ var isQaGreenStreakForwardingEnabled = () => isTruthyEnv(process.env.NEXT_PUBLIC_DASHBOARD_QA_GREEN_STREAK_OVERRIDE_ENABLED);
14597
+ var appendQaGreenStreakSearchParams = (targetParams) => {
14598
+ if (!isQaGreenStreakForwardingEnabled() || typeof window === "undefined") {
14599
+ return;
14600
+ }
14601
+ const sourceParams = new URLSearchParams(window.location.search);
14602
+ QA_GREEN_STREAK_QUERY_PARAM_NAMES.forEach((paramName) => {
14603
+ const value = sourceParams.get(paramName);
14604
+ if (value !== null) {
14605
+ targetParams.set(paramName, value);
14606
+ }
14607
+ });
14608
+ };
14609
+ var getQaGreenStreakQueryString = () => {
14610
+ const params = new URLSearchParams();
14611
+ appendQaGreenStreakSearchParams(params);
14612
+ return params.toString();
14613
+ };
14614
+
14583
14615
  // src/lib/utils/monitorWorkspaceMetrics.ts
14584
14616
  var sortWorkspaceMetrics = (left, right) => {
14585
14617
  if (left.line_id !== right.line_id) {
@@ -14668,11 +14700,22 @@ var transformMonitorWorkspaceMetrics = ({
14668
14700
  actionType: item.action_type,
14669
14701
  actionName: item.action_name
14670
14702
  }),
14703
+ factory_area_id: item.factory_area_id ?? null,
14704
+ factory_area_key: item.factory_area_key ?? null,
14705
+ factory_area_name: item.factory_area_name ?? null,
14706
+ factory_area_enabled: item.factory_area_enabled ?? null,
14707
+ leaderboard_metric_kind: item.leaderboard_metric_kind ?? void 0,
14708
+ leaderboard_value: item.leaderboard_value ?? null,
14709
+ avg_recent_flow: item.avg_recent_flow ?? null,
14671
14710
  recent_flow_percent: item.recent_flow_percent ?? null,
14672
14711
  recent_flow_window_minutes: item.recent_flow_window_minutes ?? null,
14673
14712
  recent_flow_effective_end_at: item.recent_flow_effective_end_at ?? null,
14674
14713
  recent_flow_computed_at: item.recent_flow_computed_at ?? null,
14675
14714
  recent_flow_forced_zero_after_shift: item.recent_flow_forced_zero_after_shift ?? null,
14715
+ video_grid_green_streak_active: item.video_grid_green_streak_active ?? null,
14716
+ video_grid_green_streak_minutes: item.video_grid_green_streak_minutes ?? null,
14717
+ video_grid_green_streak_anchor_at: item.video_grid_green_streak_anchor_at ?? null,
14718
+ video_grid_green_streak_started_at: item.video_grid_green_streak_started_at ?? null,
14676
14719
  scheduled_break_active: item.scheduled_break_active ?? false,
14677
14720
  incoming_wip_current: item.incoming_wip_current ?? null,
14678
14721
  incoming_wip_effective_at: item.incoming_wip_effective_at ?? null,
@@ -14692,12 +14735,12 @@ var logDebug = (...args) => {
14692
14735
  if (!DEBUG_DASHBOARD_LOGS) return;
14693
14736
  console.log(...args);
14694
14737
  };
14695
- var buildMetricsScopeKey = (lineId, lineIds) => {
14738
+ var buildMetricsScopeKey = (lineId, lineIds, blueComparisonLineIds) => {
14696
14739
  const normalizedLineIds = Array.from(new Set((lineIds || []).filter(Boolean))).sort();
14697
- if (normalizedLineIds.length > 0) {
14698
- return `${lineId}|${normalizedLineIds.join(",")}`;
14699
- }
14700
- return lineId;
14740
+ const normalizedBlueComparisonLineIds = Array.from(new Set((blueComparisonLineIds || []).filter(Boolean))).sort();
14741
+ const lineKey = normalizedLineIds.length > 0 ? normalizedLineIds.join(",") : lineId;
14742
+ const comparisonKey = normalizedBlueComparisonLineIds.length > 0 ? normalizedBlueComparisonLineIds.join(",") : lineKey;
14743
+ return `${lineId}|${lineKey}|blue:${comparisonKey}`;
14701
14744
  };
14702
14745
  var parseEfficiencyLegend = (legend) => {
14703
14746
  if (!legend) return null;
@@ -14719,6 +14762,7 @@ var useDashboardMetrics = ({
14719
14762
  onLineMetricsUpdate,
14720
14763
  lineId,
14721
14764
  lineIds,
14765
+ blueComparisonLineIds,
14722
14766
  userAccessibleLineIds,
14723
14767
  enabled = true
14724
14768
  }) => {
@@ -14741,6 +14785,10 @@ var useDashboardMetrics = ({
14741
14785
  const sourceLineIds = lineIds !== void 0 ? lineIds : userAccessibleLineIds !== void 0 ? userAccessibleLineIds : configuredLineIds;
14742
14786
  return Array.from(new Set((sourceLineIds || []).filter(Boolean)));
14743
14787
  }, [lineIds, userAccessibleLineIds, configuredLineIds]);
14788
+ const normalizedBlueComparisonLineIds = useMemo(
14789
+ () => Array.from(new Set((blueComparisonLineIds || []).filter(Boolean))),
14790
+ [blueComparisonLineIds]
14791
+ );
14744
14792
  const { shiftConfig: staticShiftConfig } = useDashboardConfig();
14745
14793
  const {
14746
14794
  shiftConfigMap: multiLineShiftConfigMap,
@@ -14778,7 +14826,7 @@ var useDashboardMetrics = ({
14778
14826
  const supabase = useSupabase();
14779
14827
  const [metrics2, setMetrics] = useState({ workspaceMetrics: [], lineMetrics: [] });
14780
14828
  const [metricsLineId, setMetricsLineId] = useState(lineId ?? null);
14781
- const [metricsScopeKey, setMetricsScopeKey] = useState(() => buildMetricsScopeKey(lineId, lineIds));
14829
+ const [metricsScopeKey, setMetricsScopeKey] = useState(() => buildMetricsScopeKey(lineId, lineIds, blueComparisonLineIds));
14782
14830
  const [isLoading, setIsLoading] = useState(true);
14783
14831
  const [error, setError] = useState(null);
14784
14832
  const lineIdRef = useRef(lineId);
@@ -14820,8 +14868,12 @@ var useDashboardMetrics = ({
14820
14868
  [entityConfig.companyId]
14821
14869
  );
14822
14870
  const requestedScopeKey = useMemo(
14823
- () => buildMetricsScopeKey(lineId, isFactoryView ? targetFactoryLineIds : void 0),
14824
- [isFactoryView, lineId, targetFactoryLineIds]
14871
+ () => buildMetricsScopeKey(
14872
+ lineId,
14873
+ isFactoryView ? targetFactoryLineIds : void 0,
14874
+ normalizedBlueComparisonLineIds.length ? normalizedBlueComparisonLineIds : void 0
14875
+ ),
14876
+ [isFactoryView, lineId, targetFactoryLineIds, normalizedBlueComparisonLineIds]
14825
14877
  );
14826
14878
  useEffect(() => {
14827
14879
  lineIdRef.current = lineId;
@@ -14851,12 +14903,15 @@ var useDashboardMetrics = ({
14851
14903
  const isFactory = currentLineIdToUse === factoryViewId;
14852
14904
  const targetLineIds = isFactory ? targetFactoryLineIds : [currentLineIdToUse];
14853
14905
  const targetLineIdsKey = targetLineIds.slice().sort().join(",");
14906
+ const effectiveBlueComparisonLineIds = normalizedBlueComparisonLineIds.length ? normalizedBlueComparisonLineIds : targetLineIds;
14907
+ const blueComparisonLineIdsKey = effectiveBlueComparisonLineIds.slice().sort().join(",");
14854
14908
  const usesShiftGroups = isFactory && shiftGroups.length > 0;
14855
14909
  const singleShiftDetails = usesShiftGroups ? null : shiftConfig ? getCurrentShift(defaultTimezone, shiftConfig) : shiftGroups.length === 1 ? { date: shiftGroups[0].date, shiftId: shiftGroups[0].shiftId } : getCurrentShift(defaultTimezone, staticShiftConfig);
14856
- const fetchKey = usesShiftGroups ? `factory|${companyId || "unknown"}|${shiftGroupsKey}` : isFactory ? `factory|${companyId || "unknown"}|${singleShiftDetails?.date}|${singleShiftDetails?.shiftId}|${targetLineIdsKey}` : `${currentLineIdToUse}|${companyId || "unknown"}|${singleShiftDetails?.date}|${singleShiftDetails?.shiftId}`;
14910
+ const fetchKey = usesShiftGroups ? `factory|${companyId || "unknown"}|${shiftGroupsKey}|blue:${blueComparisonLineIdsKey}` : isFactory ? `factory|${companyId || "unknown"}|${singleShiftDetails?.date}|${singleShiftDetails?.shiftId}|${targetLineIdsKey}|blue:${blueComparisonLineIdsKey}` : `${currentLineIdToUse}|${companyId || "unknown"}|${singleShiftDetails?.date}|${singleShiftDetails?.shiftId}|blue:${blueComparisonLineIdsKey}`;
14857
14911
  const responseScopeKey = buildMetricsScopeKey(
14858
14912
  currentLineIdToUse,
14859
- isFactory ? targetLineIds : void 0
14913
+ isFactory ? targetLineIds : void 0,
14914
+ normalizedBlueComparisonLineIds.length ? normalizedBlueComparisonLineIds : void 0
14860
14915
  );
14861
14916
  logDebug("[useDashboardMetrics] Fetch key details:", {
14862
14917
  isFactory,
@@ -14886,6 +14941,7 @@ var useDashboardMetrics = ({
14886
14941
  logDebug("[useDashboardMetrics] Skipping fetch: no target line IDs after scope filtering");
14887
14942
  setMetrics({
14888
14943
  workspaceMetrics: [],
14944
+ blueComparisonWorkspaceMetrics: [],
14889
14945
  lineMetrics: [],
14890
14946
  metadata: void 0,
14891
14947
  efficiencyLegend: DEFAULT_EFFICIENCY_LEGEND
@@ -14896,14 +14952,18 @@ var useDashboardMetrics = ({
14896
14952
  return;
14897
14953
  }
14898
14954
  let allWorkspaceMetrics = [];
14955
+ let allBlueComparisonWorkspaceMetrics = [];
14899
14956
  let allLineMetrics = [];
14900
14957
  let hasFlowBuffers = false;
14901
14958
  let idleTimeVlmByLine = {};
14902
14959
  let efficiencyLegend;
14903
14960
  const forceParam = force ? "&force_refresh=true" : "";
14961
+ const qaGreenStreakParamString = getQaGreenStreakQueryString();
14962
+ const qaGreenStreakParams = qaGreenStreakParamString ? `&${qaGreenStreakParamString}` : "";
14904
14963
  const buildMetricsEndpoint = (params) => {
14905
14964
  const lineIdsParam = isFactory ? `line_ids=${params.groupLineIds.join(",")}` : `line_id=${params.groupLineIds[0]}`;
14906
- return `/api/dashboard/metrics?${lineIdsParam}&date=${params.date}&shift_id=${params.shiftId}&company_id=${companyId}${forceParam}`;
14965
+ const blueComparisonParam = effectiveBlueComparisonLineIds.length ? `&blue_comparison_line_ids=${effectiveBlueComparisonLineIds.join(",")}` : "";
14966
+ return `/api/dashboard/metrics?${lineIdsParam}${blueComparisonParam}&date=${params.date}&shift_id=${params.shiftId}&company_id=${companyId}${forceParam}${qaGreenStreakParams}`;
14907
14967
  };
14908
14968
  if (usesShiftGroups) {
14909
14969
  logDebug("[useDashboardMetrics] Factory view shift groups fetch:", {
@@ -14953,10 +15013,16 @@ var useDashboardMetrics = ({
14953
15013
  if (result.workspace_metrics) {
14954
15014
  allWorkspaceMetrics.push(...result.workspace_metrics);
14955
15015
  }
15016
+ if (result.blue_comparison_workspace_metrics) {
15017
+ allBlueComparisonWorkspaceMetrics.push(...result.blue_comparison_workspace_metrics);
15018
+ }
14956
15019
  if (result.line_metrics) {
14957
15020
  allLineMetrics.push(...result.line_metrics);
14958
15021
  }
14959
15022
  });
15023
+ if (allBlueComparisonWorkspaceMetrics.length === 0) {
15024
+ allBlueComparisonWorkspaceMetrics = allWorkspaceMetrics;
15025
+ }
14960
15026
  logDebug(`[useDashboardMetrics] \u{1F4CA} Merged metrics from ${results.length} shift groups:`, {
14961
15027
  workspaceCount: allWorkspaceMetrics.length,
14962
15028
  lineMetricsCount: allLineMetrics.length
@@ -14994,6 +15060,7 @@ var useDashboardMetrics = ({
14994
15060
  lineCount: backendData.line_metrics?.length || 0
14995
15061
  });
14996
15062
  allWorkspaceMetrics = backendData.workspace_metrics || [];
15063
+ allBlueComparisonWorkspaceMetrics = backendData.blue_comparison_workspace_metrics || allWorkspaceMetrics;
14997
15064
  allLineMetrics = backendData.line_metrics || [];
14998
15065
  hasFlowBuffers = Boolean(backendData?.metadata?.has_flow_buffers);
14999
15066
  if (backendData?.metadata?.idle_time_vlm_by_line && typeof backendData.metadata.idle_time_vlm_by_line === "object") {
@@ -15012,8 +15079,19 @@ var useDashboardMetrics = ({
15012
15079
  shouldOverrideShiftType: (metricLineId) => isFactoryView ? Boolean(multiLineShiftConfigMap.get(metricLineId)) : Boolean(shiftConfig),
15013
15080
  fallbackShiftConfig: staticShiftConfig
15014
15081
  });
15082
+ const transformedBlueComparisonWorkspaceData = allBlueComparisonWorkspaceMetrics === allWorkspaceMetrics ? transformedWorkspaceData : transformMonitorWorkspaceMetrics({
15083
+ rows: allBlueComparisonWorkspaceMetrics,
15084
+ companyId: companyId || "",
15085
+ workspaceConfig: effectiveWorkspaceConfig,
15086
+ appTimezone: detailTimezone,
15087
+ lineMetrics: allLineMetrics,
15088
+ resolveShiftConfig: (metricLineId) => isFactoryView ? multiLineShiftConfigMap.get(metricLineId) || staticShiftConfig : shiftConfig || staticShiftConfig,
15089
+ shouldOverrideShiftType: (metricLineId) => isFactoryView ? Boolean(multiLineShiftConfigMap.get(metricLineId)) : Boolean(shiftConfig),
15090
+ fallbackShiftConfig: staticShiftConfig
15091
+ });
15015
15092
  const newMetricsState = {
15016
15093
  workspaceMetrics: transformedWorkspaceData,
15094
+ blueComparisonWorkspaceMetrics: transformedBlueComparisonWorkspaceData.length ? transformedBlueComparisonWorkspaceData : transformedWorkspaceData,
15017
15095
  lineMetrics: allLineMetrics || [],
15018
15096
  metadata: { hasFlowBuffers, idleTimeVlmByLine },
15019
15097
  efficiencyLegend: efficiencyLegend ?? DEFAULT_EFFICIENCY_LEGEND
@@ -15084,6 +15162,7 @@ var useDashboardMetrics = ({
15084
15162
  shiftGroupsKey,
15085
15163
  configuredLineIds,
15086
15164
  targetFactoryLineIds,
15165
+ normalizedBlueComparisonLineIds,
15087
15166
  isFactoryView,
15088
15167
  multiLineShiftConfigMap,
15089
15168
  staticShiftConfig,
@@ -15524,9 +15603,10 @@ var useDashboardMetrics = ({
15524
15603
  const isCurrentScopeResolved = metricsScopeKey === requestedScopeKey;
15525
15604
  const hasLastGoodMetrics = metrics2.workspaceMetrics.length > 0 || metrics2.lineMetrics.length > 0;
15526
15605
  const canReuseLastGoodMetrics = hasLastGoodMetrics && !isCurrentScopeResolved && (isLoading || !!error);
15527
- const safeMetrics = isCurrentScopeResolved || canReuseLastGoodMetrics ? metrics2 : { workspaceMetrics: [], lineMetrics: [], metadata: void 0, efficiencyLegend: DEFAULT_EFFICIENCY_LEGEND };
15606
+ const safeMetrics = isCurrentScopeResolved || canReuseLastGoodMetrics ? metrics2 : { workspaceMetrics: [], blueComparisonWorkspaceMetrics: [], lineMetrics: [], metadata: void 0, efficiencyLegend: DEFAULT_EFFICIENCY_LEGEND };
15528
15607
  return {
15529
15608
  workspaceMetrics: safeMetrics?.workspaceMetrics || [],
15609
+ blueComparisonWorkspaceMetrics: safeMetrics?.blueComparisonWorkspaceMetrics || safeMetrics?.workspaceMetrics || [],
15530
15610
  lineMetrics: safeMetrics?.lineMetrics || [],
15531
15611
  efficiencyLegend: safeMetrics?.efficiencyLegend || DEFAULT_EFFICIENCY_LEGEND,
15532
15612
  metadata: safeMetrics?.metadata,
@@ -22144,6 +22224,77 @@ var buildKpiLineHierarchy = (lines) => {
22144
22224
  };
22145
22225
  };
22146
22226
 
22227
+ // src/lib/utils/leaderboardGrouping.ts
22228
+ var isFiniteNumber2 = (value) => typeof value === "number" && Number.isFinite(value);
22229
+ var getEnabledFactoryArea = (line) => {
22230
+ if (!line.factory_area_id) return null;
22231
+ if (line.factory_area_enabled !== true) return null;
22232
+ const areaName = line.factory_area_name?.trim();
22233
+ if (!areaName) return null;
22234
+ return { id: line.factory_area_id, name: areaName };
22235
+ };
22236
+ var getLineEfficiency = (lineId, efficiencyByLineId, isLoading) => {
22237
+ if (efficiencyByLineId.has(lineId)) {
22238
+ const value = efficiencyByLineId.get(lineId);
22239
+ return isFiniteNumber2(value) ? value : null;
22240
+ }
22241
+ if (isLoading) return null;
22242
+ return 0;
22243
+ };
22244
+ var buildLineLeaderboardRows = ({
22245
+ lines,
22246
+ efficiencyByLineId,
22247
+ fallbackEfficiencyByLineId,
22248
+ isLoading
22249
+ }) => {
22250
+ const rows = [];
22251
+ const areaGroups = /* @__PURE__ */ new Map();
22252
+ lines.forEach((line) => {
22253
+ const area = getEnabledFactoryArea(line);
22254
+ if (!area) {
22255
+ const efficiency = getLineEfficiency(line.id, efficiencyByLineId, isLoading);
22256
+ rows.push({
22257
+ rowType: "line",
22258
+ id: line.id,
22259
+ displayName: line.line_name,
22260
+ line,
22261
+ lines: [line],
22262
+ efficiency,
22263
+ sortValue: isFiniteNumber2(efficiency) ? efficiency : -1
22264
+ });
22265
+ return;
22266
+ }
22267
+ const group = areaGroups.get(area.id);
22268
+ if (group) {
22269
+ group.lines.push(line);
22270
+ return;
22271
+ }
22272
+ areaGroups.set(area.id, {
22273
+ areaId: area.id,
22274
+ areaName: area.name,
22275
+ lines: [line]
22276
+ });
22277
+ });
22278
+ areaGroups.forEach((group) => {
22279
+ const validEfficiencies = group.lines.map((line) => efficiencyByLineId.get(line.id)).filter(isFiniteNumber2);
22280
+ const fallbackEfficiencies = validEfficiencies.length === 0 ? group.lines.map((line) => fallbackEfficiencyByLineId?.get(line.id)).filter(isFiniteNumber2) : [];
22281
+ const efficiencyValues = validEfficiencies.length > 0 ? validEfficiencies : fallbackEfficiencies;
22282
+ const shouldRenderZeroFallback = efficiencyValues.length === 0 && !!fallbackEfficiencyByLineId && !isLoading;
22283
+ if (efficiencyValues.length === 0 && !shouldRenderZeroFallback) return;
22284
+ const efficiency = shouldRenderZeroFallback ? 0 : efficiencyValues.reduce((sum, value) => sum + value, 0) / efficiencyValues.length;
22285
+ rows.push({
22286
+ rowType: "area",
22287
+ id: `area:${group.areaId}`,
22288
+ displayName: group.areaName,
22289
+ areaId: group.areaId,
22290
+ lines: group.lines,
22291
+ efficiency,
22292
+ sortValue: efficiency
22293
+ });
22294
+ });
22295
+ return rows.sort((left, right) => right.sortValue - left.sortValue).map((row, index) => ({ ...row, rank: index + 1 }));
22296
+ };
22297
+
22147
22298
  // src/lib/utils/awards.ts
22148
22299
  var toNumber2 = (value) => {
22149
22300
  if (typeof value === "number" && Number.isFinite(value)) return value;
@@ -37430,7 +37581,58 @@ HourlyOutputChart.displayName = "HourlyOutputChart";
37430
37581
  // src/components/dashboard/grid/videoGridMetricUtils.ts
37431
37582
  var VIDEO_GRID_LEGEND_LABEL = "Real-Time efficiency";
37432
37583
  var MAP_GRID_LEGEND_LABEL = "Efficiency";
37433
- var isFiniteNumber2 = (value) => typeof value === "number" && Number.isFinite(value);
37584
+ var GREEN_STREAK_FRESHNESS_GRACE_MS = 2 * 60 * 1e3;
37585
+ var CONFIRMED_MINUTE_DURATION_MS = 60 * 1e3;
37586
+ var RECENT_FLOW_COMPUTED_FRESHNESS_MS = 120 * 1e3;
37587
+ var isFiniteNumber3 = (value) => typeof value === "number" && Number.isFinite(value);
37588
+ var padTwoDigits = (value) => String(value).padStart(2, "0");
37589
+ var parseTimestampMs = (value) => {
37590
+ if (!value) {
37591
+ return Number.NaN;
37592
+ }
37593
+ const timestampMs = Date.parse(value);
37594
+ return Number.isFinite(timestampMs) ? timestampMs : Number.NaN;
37595
+ };
37596
+ var isAllGreenStreakFresh = (workspace, anchorAtMs, nowMs2) => {
37597
+ const computedAt = workspace.recent_flow_computed_at;
37598
+ if (typeof computedAt === "string" && computedAt.trim()) {
37599
+ const computedAtMs = parseTimestampMs(computedAt);
37600
+ return Number.isFinite(computedAtMs) && nowMs2 - computedAtMs <= RECENT_FLOW_COMPUTED_FRESHNESS_MS;
37601
+ }
37602
+ return Number.isFinite(anchorAtMs) && nowMs2 <= anchorAtMs + CONFIRMED_MINUTE_DURATION_MS + GREEN_STREAK_FRESHNESS_GRACE_MS;
37603
+ };
37604
+ var formatAllGreenStreakDuration = (elapsedSeconds) => {
37605
+ const safeElapsedSeconds = Math.max(0, Math.floor(elapsedSeconds));
37606
+ const hours = Math.floor(safeElapsedSeconds / 3600);
37607
+ const minutes = Math.floor(safeElapsedSeconds % 3600 / 60);
37608
+ const seconds = safeElapsedSeconds % 60;
37609
+ if (hours > 0) {
37610
+ return `${hours}h ${padTwoDigits(minutes)}m ${padTwoDigits(seconds)}s`;
37611
+ }
37612
+ if (minutes > 0) {
37613
+ return `${minutes}m ${padTwoDigits(seconds)}s`;
37614
+ }
37615
+ return `${seconds}s`;
37616
+ };
37617
+ var getAllGreenStreakMilestone = (elapsedSeconds) => {
37618
+ const safeElapsedSeconds = Math.max(0, Math.floor(elapsedSeconds));
37619
+ const thirtyMinutesSeconds = 30 * 60;
37620
+ const oneHourSeconds = 60 * 60;
37621
+ if (safeElapsedSeconds < thirtyMinutesSeconds) {
37622
+ return null;
37623
+ }
37624
+ if (safeElapsedSeconds < oneHourSeconds) {
37625
+ return {
37626
+ milestoneSeconds: thirtyMinutesSeconds,
37627
+ headline: "30 min"
37628
+ };
37629
+ }
37630
+ const hours = Math.floor(safeElapsedSeconds / oneHourSeconds);
37631
+ return {
37632
+ milestoneSeconds: hours * oneHourSeconds,
37633
+ headline: `${hours * 60} min`
37634
+ };
37635
+ };
37434
37636
  var isVideoGridRecentFlowEnabled = (workspace) => isRecentFlowVideoGridMetricMode(
37435
37637
  workspace.video_grid_metric_mode,
37436
37638
  workspace.assembly_enabled === true
@@ -37439,11 +37641,11 @@ var isVideoGridWipGated = (workspace) => isWipGatedVideoGridMetricMode(
37439
37641
  workspace.video_grid_metric_mode,
37440
37642
  workspace.assembly_enabled === true
37441
37643
  );
37442
- var hasVideoGridRecentFlow = (workspace) => isVideoGridRecentFlowEnabled(workspace) && isFiniteNumber2(workspace.recent_flow_percent);
37644
+ var hasVideoGridRecentFlow = (workspace) => isVideoGridRecentFlowEnabled(workspace) && isFiniteNumber3(workspace.recent_flow_percent);
37443
37645
  var isVideoGridRecentFlowUnavailable = (workspace) => isVideoGridRecentFlowEnabled(workspace) && !hasVideoGridRecentFlow(workspace);
37444
37646
  var getRawVideoGridMetricValue = (workspace) => {
37445
37647
  const recentFlowPercent = workspace.recent_flow_percent;
37446
- if (hasVideoGridRecentFlow(workspace) && isFiniteNumber2(recentFlowPercent)) {
37648
+ if (hasVideoGridRecentFlow(workspace) && isFiniteNumber3(recentFlowPercent)) {
37447
37649
  return recentFlowPercent;
37448
37650
  }
37449
37651
  if (isVideoGridRecentFlowUnavailable(workspace)) {
@@ -37452,9 +37654,63 @@ var getRawVideoGridMetricValue = (workspace) => {
37452
37654
  return workspace.efficiency;
37453
37655
  };
37454
37656
  var hasIncomingWipMapping = (workspace) => Boolean(workspace.incoming_wip_buffer_name);
37657
+ var getVideoGridWorkspaceKey = (workspace) => workspace.workspace_uuid || `${workspace.line_id || "unknown"}:${workspace.workspace_name || "unknown"}`;
37658
+ var getVideoGridBlueComparisonGroupKey = (workspace) => {
37659
+ const factoryAreaId = typeof workspace.factory_area_id === "string" ? workspace.factory_area_id.trim() : "";
37660
+ if (factoryAreaId && workspace.factory_area_enabled === true) {
37661
+ return `area:${factoryAreaId}`;
37662
+ }
37663
+ const lineId = typeof workspace.line_id === "string" ? workspace.line_id.trim() : "";
37664
+ return lineId ? `line:${lineId}` : null;
37665
+ };
37666
+ var isVideoGridBlueCandidate = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) => hasVideoGridRecentFlow(workspace) && isFiniteNumber3(workspace.recent_flow_percent) && workspace.recent_flow_percent >= legend.green_min;
37667
+ var selectVideoGridBlueWinnerIds = (workspaces, legend = DEFAULT_EFFICIENCY_LEGEND) => {
37668
+ const candidatesByGroup = /* @__PURE__ */ new Map();
37669
+ for (const workspace of workspaces) {
37670
+ if (!isVideoGridBlueCandidate(workspace, legend)) {
37671
+ continue;
37672
+ }
37673
+ const groupKey = getVideoGridBlueComparisonGroupKey(workspace);
37674
+ if (!groupKey) {
37675
+ continue;
37676
+ }
37677
+ const candidates = candidatesByGroup.get(groupKey) || [];
37678
+ candidates.push(workspace);
37679
+ candidatesByGroup.set(groupKey, candidates);
37680
+ }
37681
+ const winners = /* @__PURE__ */ new Set();
37682
+ for (const candidates of candidatesByGroup.values()) {
37683
+ candidates.sort((left, right) => {
37684
+ const leftCurrent = left.recent_flow_percent;
37685
+ const rightCurrent = right.recent_flow_percent;
37686
+ if (rightCurrent !== leftCurrent) {
37687
+ return rightCurrent - leftCurrent;
37688
+ }
37689
+ const leftAverage = isFiniteNumber3(left.avg_recent_flow) ? left.avg_recent_flow : Number.NEGATIVE_INFINITY;
37690
+ const rightAverage = isFiniteNumber3(right.avg_recent_flow) ? right.avg_recent_flow : Number.NEGATIVE_INFINITY;
37691
+ if (rightAverage !== leftAverage) {
37692
+ return rightAverage - leftAverage;
37693
+ }
37694
+ const lineCompare = (left.line_id || "").localeCompare(right.line_id || "");
37695
+ if (lineCompare !== 0) {
37696
+ return lineCompare;
37697
+ }
37698
+ const nameCompare = (left.workspace_name || "").localeCompare(right.workspace_name || "");
37699
+ if (nameCompare !== 0) {
37700
+ return nameCompare;
37701
+ }
37702
+ return getVideoGridWorkspaceKey(left).localeCompare(getVideoGridWorkspaceKey(right));
37703
+ });
37704
+ const winner = candidates[0];
37705
+ if (winner) {
37706
+ winners.add(getVideoGridWorkspaceKey(winner));
37707
+ }
37708
+ }
37709
+ return winners;
37710
+ };
37455
37711
  var getVideoGridBaseColorState = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) => {
37456
37712
  const metricValue = getRawVideoGridMetricValue(workspace);
37457
- if (!isFiniteNumber2(metricValue)) {
37713
+ if (!isFiniteNumber3(metricValue)) {
37458
37714
  return "neutral";
37459
37715
  }
37460
37716
  return getEfficiencyColor(metricValue, legend);
@@ -37475,7 +37731,7 @@ var isLowWipGreenOverride = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) => {
37475
37731
  if (!hasIncomingWipMapping(workspace)) {
37476
37732
  return false;
37477
37733
  }
37478
- return isFiniteNumber2(workspace.incoming_wip_current) && workspace.incoming_wip_current <= 1;
37734
+ return isFiniteNumber3(workspace.incoming_wip_current) && workspace.incoming_wip_current <= 1;
37479
37735
  };
37480
37736
  var isHighEfficiencyRedFlowOverride = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) => {
37481
37737
  if (workspace.scheduled_break_active === true) {
@@ -37493,7 +37749,7 @@ var isHighEfficiencyRedFlowOverride = (workspace, legend = DEFAULT_EFFICIENCY_LE
37493
37749
  if (getVideoGridBaseColorState(workspace, legend) !== "red") {
37494
37750
  return false;
37495
37751
  }
37496
- return isFiniteNumber2(workspace.efficiency) && workspace.efficiency > 100;
37752
+ return isFiniteNumber3(workspace.efficiency) && workspace.efficiency > 100;
37497
37753
  };
37498
37754
  var getVideoGridMetricValue = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) => isHighEfficiencyRedFlowOverride(workspace, legend) ? workspace.efficiency : getRawVideoGridMetricValue(workspace);
37499
37755
  var toMinuteBucket = (minuteBucket) => Number.isFinite(minuteBucket) ? Math.floor(minuteBucket) : Math.floor(Date.now() / 6e4);
@@ -37522,7 +37778,10 @@ var getSyntheticLowWipDisplayValue = (workspace, minuteBucket) => {
37522
37778
  return 100 + offset;
37523
37779
  };
37524
37780
  var getVideoGridDisplayValue = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND, minuteBucket) => isLowWipGreenOverride(workspace, legend) ? getSyntheticLowWipDisplayValue(workspace, minuteBucket) : getVideoGridMetricValue(workspace, legend);
37525
- var getVideoGridColorState = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) => {
37781
+ var getVideoGridColorState = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND, blueWinnerIds) => {
37782
+ if (blueWinnerIds?.has(getVideoGridWorkspaceKey(workspace)) && isVideoGridBlueCandidate(workspace, legend)) {
37783
+ return "blue";
37784
+ }
37526
37785
  const baseColor = getVideoGridBaseColorState(workspace, legend);
37527
37786
  if (!hasVideoGridRecentFlow(workspace)) {
37528
37787
  return baseColor;
@@ -37542,11 +37801,54 @@ var getVideoGridColorState = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) =>
37542
37801
  if (!hasIncomingWipMapping(workspace)) {
37543
37802
  return baseColor;
37544
37803
  }
37545
- if (!isFiniteNumber2(workspace.incoming_wip_current)) {
37804
+ if (!isFiniteNumber3(workspace.incoming_wip_current)) {
37546
37805
  return "neutral";
37547
37806
  }
37548
37807
  return baseColor;
37549
37808
  };
37809
+ var hasAllVideoGridWorkspacesGreen = (workspaces, legend = DEFAULT_EFFICIENCY_LEGEND) => {
37810
+ const visibleWorkspaces = workspaces.filter((workspace) => Boolean(workspace.workspace_uuid || workspace.workspace_name));
37811
+ return visibleWorkspaces.length > 0 && visibleWorkspaces.every((workspace) => getVideoGridColorState(workspace, legend) === "green");
37812
+ };
37813
+ var getAllVideoGridGreenStreakDisplay = (workspaces, legend = DEFAULT_EFFICIENCY_LEGEND, nowMs2 = Date.now()) => {
37814
+ const visibleWorkspaces = workspaces.filter((workspace) => Boolean(workspace.workspace_uuid || workspace.workspace_name));
37815
+ if (visibleWorkspaces.length === 0 || !hasAllVideoGridWorkspacesGreen(visibleWorkspaces, legend)) {
37816
+ return null;
37817
+ }
37818
+ const activeStreaks = visibleWorkspaces.map((workspace) => {
37819
+ const startedAt = workspace.video_grid_green_streak_started_at;
37820
+ const anchorAt = workspace.video_grid_green_streak_anchor_at;
37821
+ const streakMinutes = workspace.video_grid_green_streak_minutes;
37822
+ const startedAtMs = parseTimestampMs(startedAt);
37823
+ const anchorAtMs = parseTimestampMs(anchorAt);
37824
+ const isFresh = isAllGreenStreakFresh(workspace, anchorAtMs, nowMs2);
37825
+ const tickOriginAtMs = anchorAtMs + CONFIRMED_MINUTE_DURATION_MS;
37826
+ if (workspace.video_grid_green_streak_active === true && isFiniteNumber3(streakMinutes) && streakMinutes > 0 && startedAt && anchorAt && Number.isFinite(startedAtMs) && isFresh) {
37827
+ return {
37828
+ startedAt,
37829
+ startedAtMs,
37830
+ anchorAt,
37831
+ streakMinutes,
37832
+ tickOriginAtMs
37833
+ };
37834
+ }
37835
+ return null;
37836
+ });
37837
+ if (activeStreaks.some((streak) => streak === null)) {
37838
+ return null;
37839
+ }
37840
+ const strictestStartedAt = activeStreaks.reduce((latest, current) => current.streakMinutes < latest.streakMinutes || current.streakMinutes === latest.streakMinutes && current.startedAtMs > latest.startedAtMs ? current : latest);
37841
+ const confirmedSeconds = Math.max(0, Math.floor(strictestStartedAt.streakMinutes * 60));
37842
+ return {
37843
+ label: "All green",
37844
+ elapsedSeconds: confirmedSeconds,
37845
+ confirmedSeconds,
37846
+ durationText: formatAllGreenStreakDuration(confirmedSeconds),
37847
+ startedAt: strictestStartedAt.startedAt,
37848
+ anchorAt: strictestStartedAt.anchorAt,
37849
+ tickOriginAtMs: strictestStartedAt.tickOriginAtMs
37850
+ };
37851
+ };
37550
37852
  var getVideoGridLegendLabel = (workspaces) => {
37551
37853
  const visibleWorkspaces = workspaces;
37552
37854
  if (visibleWorkspaces.length === 0) {
@@ -37577,6 +37879,7 @@ var VideoCard = React144__default.memo(({
37577
37879
  compact = false,
37578
37880
  displayMinuteBucket,
37579
37881
  displayName,
37882
+ isBlueBest = false,
37580
37883
  lastSeenLabel,
37581
37884
  hasRecentHealthSignal: hasRecentHealthSignal2 = false,
37582
37885
  onMouseEnter,
@@ -37598,7 +37901,11 @@ var VideoCard = React144__default.memo(({
37598
37901
  const workspaceDisplayName = displayName || workspace.displayName || workspace.workspace_name;
37599
37902
  const videoGridMetricValue = getVideoGridMetricValue(workspace, effectiveLegend);
37600
37903
  const videoGridDisplayValue = getVideoGridDisplayValue(workspace, effectiveLegend, displayMinuteBucket);
37601
- const videoGridColorState = getVideoGridColorState(workspace, effectiveLegend);
37904
+ const videoGridColorState = getVideoGridColorState(
37905
+ workspace,
37906
+ effectiveLegend,
37907
+ isBlueBest ? /* @__PURE__ */ new Set([getVideoGridWorkspaceKey(workspace)]) : void 0
37908
+ );
37602
37909
  const isRecentFlowCard = isVideoGridRecentFlowEnabled(workspace);
37603
37910
  const isHighEfficiencyOverride = isHighEfficiencyRedFlowOverride(workspace, effectiveLegend);
37604
37911
  const hasDisplayMetric = typeof videoGridDisplayValue === "number" && Number.isFinite(videoGridDisplayValue);
@@ -37606,9 +37913,9 @@ var VideoCard = React144__default.memo(({
37606
37913
  const shouldRenderMetricBadge = hasDisplayMetric;
37607
37914
  const badgeTitle = isHighEfficiencyOverride ? `Efficiency ${Math.round(videoGridDisplayValue ?? 0)}%` : hasVideoGridRecentFlow(workspace) ? `Flow ${Math.round(videoGridDisplayValue ?? 0)}%` : isRecentFlowCard ? "Flow unavailable" : `Efficiency ${Math.round(videoGridDisplayValue ?? 0)}%`;
37608
37915
  const badgeLabel = `${Math.round(videoGridDisplayValue ?? 0)}%`;
37609
- const efficiencyOverlayClass = videoGridColorState === "green" ? "bg-[#00D654]/25" : videoGridColorState === "yellow" ? "bg-[#FFD700]/30" : videoGridColorState === "red" ? "bg-[#FF2D0A]/30" : "bg-transparent";
37610
- const efficiencyBarClass = videoGridColorState === "green" ? "bg-[#00AB45]" : videoGridColorState === "yellow" ? "bg-[#FFB020]" : videoGridColorState === "red" ? "bg-[#E34329]" : "bg-gray-500/70";
37611
- const efficiencyStatus = videoGridColorState === "green" ? "High" : videoGridColorState === "yellow" ? "Medium" : videoGridColorState === "red" ? "Low" : "Neutral";
37916
+ const efficiencyOverlayClass = videoGridColorState === "green" ? "bg-[#00D654]/25" : videoGridColorState === "blue" ? "bg-[#0EA5E9]/30" : videoGridColorState === "yellow" ? "bg-[#FFD700]/30" : videoGridColorState === "red" ? "bg-[#FF2D0A]/30" : "bg-transparent";
37917
+ const efficiencyBarClass = videoGridColorState === "green" ? "bg-[#00AB45]" : videoGridColorState === "blue" ? "bg-[#0EA5E9]" : videoGridColorState === "yellow" ? "bg-[#FFB020]" : videoGridColorState === "red" ? "bg-[#E34329]" : "bg-gray-500/70";
37918
+ const efficiencyStatus = videoGridColorState === "green" ? "High" : videoGridColorState === "blue" ? "Best" : videoGridColorState === "yellow" ? "Medium" : videoGridColorState === "red" ? "Low" : "Neutral";
37612
37919
  const trendInfo = workspace.trend !== void 0 ? getTrendArrowAndColor(workspace.trend) : null;
37613
37920
  const handleClick = useCallback(() => {
37614
37921
  trackCoreEvent("Workspace Card Clicked", {
@@ -37729,6 +38036,9 @@ var VideoCard = React144__default.memo(({
37729
38036
  if (prevProps.displayName !== nextProps.displayName) {
37730
38037
  return false;
37731
38038
  }
38039
+ if (prevProps.isBlueBest !== nextProps.isBlueBest) {
38040
+ return false;
38041
+ }
37732
38042
  if (prevProps.lastSeenLabel !== nextProps.lastSeenLabel) {
37733
38043
  return false;
37734
38044
  }
@@ -37770,6 +38080,7 @@ var hasRecentHealthSignal = (lastHeartbeat) => {
37770
38080
  };
37771
38081
  var VideoGridView = React144__default.memo(({
37772
38082
  workspaces,
38083
+ blueComparisonWorkspaces,
37773
38084
  selectedLine,
37774
38085
  className = "",
37775
38086
  legend,
@@ -37898,6 +38209,7 @@ var VideoGridView = React144__default.memo(({
37898
38209
  return a.workspace_name.localeCompare(b.workspace_name);
37899
38210
  });
37900
38211
  }, [filteredWorkspaces]);
38212
+ const blueWinnerIds = useMemo(() => selectVideoGridBlueWinnerIds(blueComparisonWorkspaces || sortedWorkspaces, effectiveLegend), [blueComparisonWorkspaces, sortedWorkspaces, effectiveLegend]);
37901
38213
  const streamsResolvedForWorkspaceSet = resolvedStreamWorkspaceKey === workspaceIdsKey;
37902
38214
  const resolveWorkspaceDisplayName = useCallback((workspace) => {
37903
38215
  return workspace.displayName || displayNames[`${workspace.line_id}_${workspace.workspace_name}`] || workspace.workspace_name;
@@ -38106,11 +38418,13 @@ var VideoGridView = React144__default.memo(({
38106
38418
  isR2Stream,
38107
38419
  shouldPlay,
38108
38420
  lastSeenLabel,
38109
- hasRecentHealthSignal: hasRecentHealthSignal(workspaceHealth?.lastHeartbeat)
38421
+ hasRecentHealthSignal: hasRecentHealthSignal(workspaceHealth?.lastHeartbeat),
38422
+ isBlueBest: blueWinnerIds.has(getVideoGridWorkspaceKey(workspace))
38110
38423
  };
38111
38424
  });
38112
38425
  }, [
38113
38426
  sortedWorkspaces,
38427
+ blueWinnerIds,
38114
38428
  visibleWorkspaces,
38115
38429
  getWorkspaceCropping,
38116
38430
  videoStreamsByWorkspaceId,
@@ -38157,6 +38471,7 @@ var VideoGridView = React144__default.memo(({
38157
38471
  useRAF: effectiveUseRAF,
38158
38472
  displayMinuteBucket,
38159
38473
  compact: !selectedLine,
38474
+ isBlueBest: card.isBlueBest,
38160
38475
  onMouseEnter: onWorkspaceHover ? () => onWorkspaceHover(card.workspaceId) : void 0,
38161
38476
  onMouseLeave: onWorkspaceHoverEnd ? () => onWorkspaceHoverEnd(card.workspaceId) : void 0
38162
38477
  }
@@ -54714,6 +55029,10 @@ var Legend5 = ({
54714
55029
  ":"
54715
55030
  ] }),
54716
55031
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 sm:gap-4", children: [
55032
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
55033
+ /* @__PURE__ */ jsx("div", { className: "w-2 h-2 sm:w-2.5 sm:h-2.5 rounded-full bg-[#0EA5E9]" }),
55034
+ /* @__PURE__ */ jsx("span", { children: "Best" })
55035
+ ] }),
54717
55036
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
54718
55037
  /* @__PURE__ */ jsx("div", { className: "w-2 h-2 sm:w-2.5 sm:h-2.5 rounded-full bg-[#00AB45]" }),
54719
55038
  /* @__PURE__ */ jsx("span", { children: formatPercentRange(effectiveLegend.green_min, effectiveLegend.green_max) })
@@ -54832,6 +55151,7 @@ var WorkspaceGridItem = React144__default.memo(({
54832
55151
  WorkspaceGridItem.displayName = "WorkspaceGridItem";
54833
55152
  var WorkspaceGrid = React144__default.memo(({
54834
55153
  workspaces,
55154
+ blueComparisonWorkspaces,
54835
55155
  isPdfMode = false,
54836
55156
  customWorkspacePositions,
54837
55157
  lineNames = {},
@@ -54848,13 +55168,8 @@ var WorkspaceGrid = React144__default.memo(({
54848
55168
  onWorkspaceHoverEnd,
54849
55169
  toolbarRightContent
54850
55170
  }) => {
54851
- const dashboardConfig = useDashboardConfig();
54852
- const mapViewEnabled = dashboardConfig?.mapViewConfig?.enabled ?? false;
55171
+ const mapViewEnabled = false;
54853
55172
  const [viewMode, setViewMode] = useState(() => {
54854
- if (typeof window !== "undefined" && mapViewEnabled) {
54855
- const saved = localStorage.getItem("home-view-mode");
54856
- return saved === "map" || saved === "video" ? saved : "video";
54857
- }
54858
55173
  return "video";
54859
55174
  });
54860
55175
  useEffect(() => {
@@ -54863,7 +55178,7 @@ var WorkspaceGrid = React144__default.memo(({
54863
55178
  total_workspaces: workspaces.length
54864
55179
  });
54865
55180
  }, [workspaces.length]);
54866
- const handleViewModeToggle = useCallback(() => {
55181
+ useCallback(() => {
54867
55182
  const newMode = viewMode === "video" ? "map" : "video";
54868
55183
  setViewMode(newMode);
54869
55184
  if (typeof window !== "undefined") {
@@ -54877,8 +55192,8 @@ var WorkspaceGrid = React144__default.memo(({
54877
55192
  }, [viewMode]);
54878
55193
  const { VideoGridView: VideoGridViewComponent, MapGridView: MapGridViewComponent } = useRegistry();
54879
55194
  const legendMetricLabel = useMemo(
54880
- () => viewMode === "video" ? getVideoGridLegendLabel(workspaces) : MAP_GRID_LEGEND_LABEL,
54881
- [viewMode, workspaces]
55195
+ () => getVideoGridLegendLabel(workspaces),
55196
+ [workspaces]
54882
55197
  );
54883
55198
  return /* @__PURE__ */ jsxs("div", { className: `flex flex-col w-full h-full overflow-hidden bg-slate-50/50 ${className}`, children: [
54884
55199
  /* @__PURE__ */ jsxs(
@@ -54890,21 +55205,7 @@ var WorkspaceGrid = React144__default.memo(({
54890
55205
  /* @__PURE__ */ jsx("div", { className: "hidden sm:block", children: /* @__PURE__ */ jsx("div", { className: "inline-flex bg-white/95 rounded-lg shadow-sm px-4 py-2 border border-slate-200/60 backdrop-blur-sm", children: /* @__PURE__ */ jsx(Legend5, { legend, metricLabel: legendMetricLabel }) }) }),
54891
55206
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-3 shrink-0", children: [
54892
55207
  toolbarRightContent,
54893
- mapViewEnabled && /* @__PURE__ */ jsx(
54894
- "button",
54895
- {
54896
- onClick: handleViewModeToggle,
54897
- className: "flex items-center gap-2 px-3 py-1.5 bg-white border border-slate-200 rounded-md shadow-sm hover:bg-slate-50 transition-colors duration-200 text-slate-700",
54898
- title: viewMode === "video" ? "Switch to Map View" : "Switch to Video View",
54899
- children: viewMode === "video" ? /* @__PURE__ */ jsxs(Fragment, { children: [
54900
- /* @__PURE__ */ jsx(Map$1, { className: "w-4 h-4 text-slate-500" }),
54901
- /* @__PURE__ */ jsx("span", { className: "hidden sm:inline text-sm font-medium", children: "Map View" })
54902
- ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
54903
- /* @__PURE__ */ jsx(Video, { className: "w-4 h-4 text-slate-500" }),
54904
- /* @__PURE__ */ jsx("span", { className: "hidden sm:inline text-sm font-medium", children: "Video View" })
54905
- ] })
54906
- }
54907
- )
55208
+ mapViewEnabled
54908
55209
  ] })
54909
55210
  ]
54910
55211
  }
@@ -54922,6 +55223,7 @@ var WorkspaceGrid = React144__default.memo(({
54922
55223
  VideoGridViewComponent,
54923
55224
  {
54924
55225
  workspaces,
55226
+ blueComparisonWorkspaces,
54925
55227
  lineNames,
54926
55228
  lineOrder,
54927
55229
  videoSources,
@@ -57218,12 +57520,25 @@ var SideNavBar = memo$1(({
57218
57520
  console.log("\u{1F50D} [SideNavBar] ticketsConfig:", dashboardConfig?.ticketsConfig);
57219
57521
  console.log("\u{1F50D} [SideNavBar] ticketsEnabled:", ticketsEnabled);
57220
57522
  const pathname = propPathname || router.pathname;
57523
+ const rawCurrentTabQuery = currentQuery?.tab ?? router.query?.tab;
57524
+ const currentTabQuery = Array.isArray(rawCurrentTabQuery) ? rawCurrentTabQuery[0] : rawCurrentTabQuery;
57525
+ const isKpisLeaderboardRoute = pathname === "/kpis" && currentTabQuery === "leaderboard";
57526
+ const isPathActive = useCallback((path) => {
57527
+ if (path === "/") return pathname === "/";
57528
+ if (path === "/leaderboard") {
57529
+ return pathname === "/leaderboard" || pathname.startsWith("/leaderboard/");
57530
+ }
57531
+ if (path === "/kpis") {
57532
+ return pathname === "/kpis" || pathname.startsWith("/kpis/");
57533
+ }
57534
+ return pathname === path || pathname.startsWith(path + "/");
57535
+ }, [pathname]);
57221
57536
  const getButtonClasses = useCallback((path) => {
57222
- const isActive = pathname === path || pathname.startsWith(path + "/");
57537
+ const isActive = isPathActive(path);
57223
57538
  return `w-full flex flex-col items-center justify-center py-4 sm:py-3 px-2 sm:px-1 rounded-lg relative group min-h-[44px] sm:min-h-0
57224
57539
  ${isActive ? "bg-blue-50/80 text-blue-600 font-medium" : "hover:bg-gray-50 text-gray-500 hover:text-gray-700 font-medium active:bg-gray-100"}
57225
57540
  transition-all duration-200 ease-out focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2`;
57226
- }, [pathname]);
57541
+ }, [isPathActive]);
57227
57542
  const buildDashboardSurfaceTrackingEvent = useCallback((source, destinationPath, dashboardSurface) => ({
57228
57543
  name: ROOT_DASHBOARD_EVENT_NAMES[dashboardSurface],
57229
57544
  properties: {
@@ -57256,17 +57571,24 @@ var SideNavBar = memo$1(({
57256
57571
  onMobileMenuClose?.();
57257
57572
  }, [navigate, onMobileMenuClose, buildDashboardSurfaceTrackingEvent]);
57258
57573
  const handleKPIsClick = useCallback(() => {
57259
- navigate(`/kpis`, {
57260
- trackingEvent: {
57261
- name: "KPI Page Clicked",
57262
- properties: {
57263
- source: "side_nav",
57264
- page_type: "overview"
57265
- }
57574
+ const trackingEvent = {
57575
+ name: "KPI Page Clicked",
57576
+ properties: {
57577
+ source: "side_nav",
57578
+ page_type: "overview"
57266
57579
  }
57580
+ };
57581
+ if (isKpisLeaderboardRoute) {
57582
+ trackCoreEvent(trackingEvent.name, trackingEvent.properties);
57583
+ void router.replace("/kpis", void 0, { shallow: false });
57584
+ onMobileMenuClose?.();
57585
+ return;
57586
+ }
57587
+ navigate(`/kpis`, {
57588
+ trackingEvent
57267
57589
  });
57268
57590
  onMobileMenuClose?.();
57269
- }, [navigate, onMobileMenuClose]);
57591
+ }, [isKpisLeaderboardRoute, navigate, onMobileMenuClose, router]);
57270
57592
  const handleImprovementClick = useCallback(() => {
57271
57593
  navigate("/improvement-center", {
57272
57594
  trackingEvent: {
@@ -57536,14 +57858,14 @@ var SideNavBar = memo$1(({
57536
57858
  });
57537
57859
  onMobileMenuClose?.();
57538
57860
  }, [navigate, onMobileMenuClose, buildDashboardSurfaceTrackingEvent, rootDashboardSurface]);
57539
- const homeButtonClasses = useMemo(() => getButtonClasses("/"), [getButtonClasses, pathname]);
57540
- const liveButtonClasses = useMemo(() => getButtonClasses("/live-monitor"), [getButtonClasses, pathname]);
57541
- const leaderboardButtonClasses = useMemo(() => getButtonClasses("/leaderboard"), [getButtonClasses, pathname]);
57542
- const kpisButtonClasses = useMemo(() => getButtonClasses("/kpis"), [getButtonClasses, pathname]);
57543
- const improvementButtonClasses = useMemo(() => getButtonClasses("/improvement-center"), [getButtonClasses, pathname]);
57544
- useMemo(() => getButtonClasses("/supervisor-management"), [getButtonClasses, pathname]);
57545
- const skusButtonClasses = useMemo(() => getButtonClasses("/skus"), [getButtonClasses, pathname]);
57546
- const healthButtonClasses = useMemo(() => getButtonClasses("/health"), [getButtonClasses, pathname]);
57861
+ const homeButtonClasses = useMemo(() => getButtonClasses("/"), [getButtonClasses]);
57862
+ const liveButtonClasses = useMemo(() => getButtonClasses("/live-monitor"), [getButtonClasses]);
57863
+ const leaderboardButtonClasses = useMemo(() => getButtonClasses("/leaderboard"), [getButtonClasses]);
57864
+ const kpisButtonClasses = useMemo(() => getButtonClasses("/kpis"), [getButtonClasses]);
57865
+ const improvementButtonClasses = useMemo(() => getButtonClasses("/improvement-center"), [getButtonClasses]);
57866
+ useMemo(() => getButtonClasses("/supervisor-management"), [getButtonClasses]);
57867
+ const skusButtonClasses = useMemo(() => getButtonClasses("/skus"), [getButtonClasses]);
57868
+ const healthButtonClasses = useMemo(() => getButtonClasses("/health"), [getButtonClasses]);
57547
57869
  const settingsButtonClasses = useMemo(() => {
57548
57870
  const isAnyItemActive = settingsItems.some((item) => item.isActive);
57549
57871
  const isActive = isSettingsOpen || isAnyItemActive;
@@ -57577,7 +57899,7 @@ var SideNavBar = memo$1(({
57577
57899
  "aria-label": "Home",
57578
57900
  tabIndex: 0,
57579
57901
  role: "tab",
57580
- "aria-selected": pathname === "/" || pathname.startsWith("//"),
57902
+ "aria-selected": isPathActive("/"),
57581
57903
  children: [
57582
57904
  /* @__PURE__ */ jsx(HomeIcon, { className: "w-5 h-5 mb-1" }),
57583
57905
  /* @__PURE__ */ jsx("span", { className: "text-xs sm:text-[10px] font-medium leading-tight", children: "Home" })
@@ -57592,7 +57914,7 @@ var SideNavBar = memo$1(({
57592
57914
  "aria-label": "Monitor",
57593
57915
  tabIndex: 0,
57594
57916
  role: "tab",
57595
- "aria-selected": pathname === "/live-monitor" || pathname.startsWith("/live-monitor/"),
57917
+ "aria-selected": isPathActive("/live-monitor"),
57596
57918
  children: [
57597
57919
  /* @__PURE__ */ jsx(VideoCameraIcon, { className: "w-5 h-5 mb-1" }),
57598
57920
  /* @__PURE__ */ jsx("span", { className: "text-xs sm:text-[10px] font-medium leading-tight", children: "Monitor" })
@@ -57609,7 +57931,7 @@ var SideNavBar = memo$1(({
57609
57931
  "aria-label": "Leaderboard",
57610
57932
  tabIndex: 0,
57611
57933
  role: "tab",
57612
- "aria-selected": pathname === "/leaderboard" || pathname.startsWith("/leaderboard/"),
57934
+ "aria-selected": isPathActive("/leaderboard"),
57613
57935
  children: [
57614
57936
  /* @__PURE__ */ jsx(TrophyIcon, { className: "w-5 h-5 mb-1" }),
57615
57937
  /* @__PURE__ */ jsx("span", { className: "text-xs sm:text-[10px] font-medium leading-tight", children: "Leaders" })
@@ -57624,7 +57946,7 @@ var SideNavBar = memo$1(({
57624
57946
  "aria-label": "Lines",
57625
57947
  tabIndex: 0,
57626
57948
  role: "tab",
57627
- "aria-selected": pathname === "/kpis" || pathname.startsWith("/kpis/"),
57949
+ "aria-selected": isPathActive("/kpis"),
57628
57950
  children: [
57629
57951
  /* @__PURE__ */ jsx(ChartBarIcon, { className: "w-5 h-5 mb-1" }),
57630
57952
  /* @__PURE__ */ jsx("span", { className: "text-xs sm:text-[10px] font-medium leading-tight", children: "Lines" })
@@ -57639,7 +57961,7 @@ var SideNavBar = memo$1(({
57639
57961
  "aria-label": "Improvement Center",
57640
57962
  tabIndex: 0,
57641
57963
  role: "tab",
57642
- "aria-selected": pathname === "/improvement-center" || pathname.startsWith("/improvement-center/"),
57964
+ "aria-selected": isPathActive("/improvement-center"),
57643
57965
  children: [
57644
57966
  /* @__PURE__ */ jsx(LightBulbIcon, { className: "w-5 h-5 mb-1" }),
57645
57967
  /* @__PURE__ */ jsx("span", { className: "text-xs sm:text-[10px] font-medium leading-tight text-center", children: "Improve" })
@@ -57655,7 +57977,7 @@ var SideNavBar = memo$1(({
57655
57977
  "aria-label": "SKU Management",
57656
57978
  tabIndex: 0,
57657
57979
  role: "tab",
57658
- "aria-selected": pathname === "/skus" || pathname.startsWith("/skus/"),
57980
+ "aria-selected": isPathActive("/skus"),
57659
57981
  children: [
57660
57982
  /* @__PURE__ */ jsx(CubeIcon, { className: "w-5 h-5 mb-1" }),
57661
57983
  /* @__PURE__ */ jsx("span", { className: "text-xs sm:text-[10px] font-medium leading-tight", children: "SKUs" })
@@ -57670,7 +57992,7 @@ var SideNavBar = memo$1(({
57670
57992
  "aria-label": "System Health",
57671
57993
  tabIndex: 0,
57672
57994
  role: "tab",
57673
- "aria-selected": pathname === "/health" || pathname.startsWith("/health/"),
57995
+ "aria-selected": isPathActive("/health"),
57674
57996
  children: [
57675
57997
  /* @__PURE__ */ jsx(HeartIcon, { className: "w-5 h-5 mb-1" }),
57676
57998
  /* @__PURE__ */ jsx("span", { className: "text-xs sm:text-[10px] font-medium leading-tight", children: "Health" })
@@ -57700,17 +58022,12 @@ var SideNavBar = memo$1(({
57700
58022
  ) })
57701
58023
  ] });
57702
58024
  const MobileNavigationContent = () => {
57703
- const isActive = (path) => {
57704
- if (path === "/" && pathname === "/") return true;
57705
- if (path !== "/" && pathname.startsWith(path)) return true;
57706
- return false;
57707
- };
57708
58025
  const getMobileButtonClass = (path) => {
57709
- const active = isActive(path);
58026
+ const active = isPathActive(path);
57710
58027
  return `w-full flex items-center gap-3 px-5 py-3.5 rounded-lg transition-colors active:scale-[0.98] ${active ? "bg-blue-50 text-blue-700" : "text-gray-700 hover:bg-gray-100 active:bg-gray-200"}`;
57711
58028
  };
57712
58029
  const getIconClass = (path) => {
57713
- const active = isActive(path);
58030
+ const active = isPathActive(path);
57714
58031
  return `w-7 h-7 ${active ? "text-blue-600" : "text-gray-600"}`;
57715
58032
  };
57716
58033
  const handleMobileNavClick = (handler) => {
@@ -63644,6 +63961,8 @@ var HelpView = ({
63644
63961
  };
63645
63962
  var AuthenticatedHelpView = withAuth(HelpView);
63646
63963
  var HelpView_default = HelpView;
63964
+ var REALTIME_REFRESH_DEBOUNCE_MS2 = 1500;
63965
+ var REALTIME_REFRESH_MIN_INTERVAL_MS2 = 5e3;
63647
63966
  var transformActiveBreaks = (activeBreaksByLine) => {
63648
63967
  if (!activeBreaksByLine) return [];
63649
63968
  return Object.values(activeBreaksByLine).flat().map((item) => ({
@@ -63667,6 +63986,7 @@ var createEmptyState = () => ({
63667
63986
  scopeKey: null,
63668
63987
  lines: [],
63669
63988
  workspaceMetrics: [],
63989
+ blueComparisonWorkspaceMetrics: [],
63670
63990
  lineMetrics: [],
63671
63991
  kpiTrend: null,
63672
63992
  activeBreaks: [],
@@ -63681,8 +64001,20 @@ var normalizeMetadata = (metadata) => ({
63681
64001
  cacheStatus: metadata?.cache_status,
63682
64002
  warnings: metadata?.warnings ?? []
63683
64003
  });
64004
+ var createResolvedScopeLookup = (resolvedScope, workspaces, blueComparisonWorkspaces) => {
64005
+ const lookup = /* @__PURE__ */ new Set();
64006
+ const addEntry = (lineId, date, shiftId) => {
64007
+ if (!lineId || !date || shiftId === void 0 || shiftId === null) return;
64008
+ lookup.add(`${lineId}|${date}|${shiftId}`);
64009
+ };
64010
+ resolvedScope.forEach((entry) => addEntry(entry.line_id, entry.date, entry.shift_id));
64011
+ workspaces.forEach((workspace) => addEntry(workspace.line_id, workspace.date, workspace.shift_id));
64012
+ blueComparisonWorkspaces.forEach((workspace) => addEntry(workspace.line_id, workspace.date, workspace.shift_id));
64013
+ return lookup;
64014
+ };
63684
64015
  var useLiveMonitorBootstrap = ({
63685
64016
  lineIds,
64017
+ blueComparisonLineIds,
63686
64018
  companyId,
63687
64019
  enabled = true,
63688
64020
  appTimezone,
@@ -63697,33 +64029,56 @@ var useLiveMonitorBootstrap = ({
63697
64029
  const effectiveWorkspaceConfig = workspaceConfig || DEFAULT_WORKSPACE_CONFIG;
63698
64030
  const effectiveTimezone = appTimezone || "Asia/Kolkata";
63699
64031
  const rawLineIdsKey = (lineIds || []).filter(Boolean).join(",");
64032
+ const rawBlueComparisonLineIdsKey = (blueComparisonLineIds || lineIds || []).filter(Boolean).join(",");
63700
64033
  const normalizedLineIds = useMemo(
63701
64034
  () => Array.from(new Set(rawLineIdsKey ? rawLineIdsKey.split(",") : [])),
63702
64035
  [rawLineIdsKey]
63703
64036
  );
64037
+ const normalizedBlueComparisonLineIds = useMemo(
64038
+ () => Array.from(new Set(rawBlueComparisonLineIdsKey ? rawBlueComparisonLineIdsKey.split(",") : [])),
64039
+ [rawBlueComparisonLineIdsKey]
64040
+ );
64041
+ const realtimeLineIds = useMemo(
64042
+ () => Array.from(new Set([...normalizedLineIds, ...normalizedBlueComparisonLineIds].filter(Boolean))).sort(),
64043
+ [normalizedLineIds, normalizedBlueComparisonLineIds]
64044
+ );
63704
64045
  const requestKey = useMemo(
63705
- () => normalizedLineIds.slice().sort().join(","),
63706
- [normalizedLineIds]
64046
+ () => `${normalizedLineIds.slice().sort().join(",")}|blue:${normalizedBlueComparisonLineIds.slice().sort().join(",")}`,
64047
+ [normalizedLineIds, normalizedBlueComparisonLineIds]
64048
+ );
64049
+ const realtimeLineIdsKey = useMemo(() => realtimeLineIds.join(","), [realtimeLineIds]);
64050
+ const companySpecificMetricsTable = useMemo(
64051
+ () => getCompanyMetricsTableName(resolvedCompanyId, "performance_metrics"),
64052
+ [resolvedCompanyId]
63707
64053
  );
63708
64054
  const [state, setState] = useState(() => createEmptyState());
63709
64055
  const [rawState, setRawState] = useState(null);
63710
64056
  const [isLoading, setIsLoading] = useState(false);
63711
64057
  const [error, setError] = useState(null);
63712
64058
  const activeRequestIdRef = useRef(0);
64059
+ const isFetchingRef = useRef(false);
64060
+ const pendingRealtimeRefreshRef = useRef(false);
64061
+ const realtimeRefreshTimerRef = useRef(null);
64062
+ const lastRealtimeRefreshStartedAtRef = useRef(0);
63713
64063
  const fetchBootstrap = useCallback(async (force = false) => {
63714
64064
  if (!enabled || !supabase || !resolvedCompanyId || normalizedLineIds.length === 0) {
63715
64065
  return;
63716
64066
  }
63717
64067
  const requestId = ++activeRequestIdRef.current;
64068
+ isFetchingRef.current = true;
63718
64069
  setIsLoading(true);
63719
64070
  setError(null);
63720
64071
  try {
63721
64072
  const searchParams = new URLSearchParams();
63722
64073
  searchParams.set("company_id", resolvedCompanyId);
63723
64074
  searchParams.set("line_ids", normalizedLineIds.join(","));
64075
+ if (normalizedBlueComparisonLineIds.length) {
64076
+ searchParams.set("blue_comparison_line_ids", normalizedBlueComparisonLineIds.join(","));
64077
+ }
63724
64078
  if (force) {
63725
64079
  searchParams.set("force_refresh", "true");
63726
64080
  }
64081
+ appendQaGreenStreakSearchParams(searchParams);
63727
64082
  const response = await fetchBackendJson(
63728
64083
  supabase,
63729
64084
  `/api/dashboard/monitor-bootstrap?${searchParams.toString()}`,
@@ -63752,6 +64107,7 @@ var useLiveMonitorBootstrap = ({
63752
64107
  extras: {
63753
64108
  company_id: resolvedCompanyId,
63754
64109
  line_ids: normalizedLineIds,
64110
+ blue_comparison_line_ids: normalizedBlueComparisonLineIds,
63755
64111
  force_refresh: force,
63756
64112
  pathname: typeof window !== "undefined" ? window.location.pathname : "unknown"
63757
64113
  }
@@ -63760,6 +64116,7 @@ var useLiveMonitorBootstrap = ({
63760
64116
  } finally {
63761
64117
  if (requestId === activeRequestIdRef.current) {
63762
64118
  setIsLoading(false);
64119
+ isFetchingRef.current = false;
63763
64120
  }
63764
64121
  }
63765
64122
  }, [
@@ -63767,8 +64124,55 @@ var useLiveMonitorBootstrap = ({
63767
64124
  supabase,
63768
64125
  resolvedCompanyId,
63769
64126
  normalizedLineIds,
64127
+ normalizedBlueComparisonLineIds,
63770
64128
  requestKey
63771
64129
  ]);
64130
+ const fetchBootstrapRef = useRef(fetchBootstrap);
64131
+ useEffect(() => {
64132
+ fetchBootstrapRef.current = fetchBootstrap;
64133
+ }, [fetchBootstrap]);
64134
+ const clearRealtimeRefreshTimer = useCallback(() => {
64135
+ if (realtimeRefreshTimerRef.current !== null) {
64136
+ window.clearTimeout(realtimeRefreshTimerRef.current);
64137
+ realtimeRefreshTimerRef.current = null;
64138
+ }
64139
+ }, []);
64140
+ const scheduleRealtimeRefresh = useCallback(() => {
64141
+ if (!enabled || !supabase || realtimeRefreshTimerRef.current !== null) {
64142
+ return;
64143
+ }
64144
+ const elapsedSinceLastRealtimeRefresh = Date.now() - lastRealtimeRefreshStartedAtRef.current;
64145
+ const minIntervalRemaining = Math.max(0, REALTIME_REFRESH_MIN_INTERVAL_MS2 - elapsedSinceLastRealtimeRefresh);
64146
+ const nextDelay = Math.max(REALTIME_REFRESH_DEBOUNCE_MS2, minIntervalRemaining);
64147
+ realtimeRefreshTimerRef.current = window.setTimeout(() => {
64148
+ realtimeRefreshTimerRef.current = null;
64149
+ if (!pendingRealtimeRefreshRef.current) {
64150
+ return;
64151
+ }
64152
+ if (isFetchingRef.current) {
64153
+ scheduleRealtimeRefresh();
64154
+ return;
64155
+ }
64156
+ pendingRealtimeRefreshRef.current = false;
64157
+ lastRealtimeRefreshStartedAtRef.current = Date.now();
64158
+ void fetchBootstrapRef.current(true);
64159
+ }, nextDelay);
64160
+ }, [enabled, supabase]);
64161
+ const queueRealtimeRefresh = useCallback(() => {
64162
+ if (!enabled || !supabase) {
64163
+ pendingRealtimeRefreshRef.current = false;
64164
+ clearRealtimeRefreshTimer();
64165
+ return;
64166
+ }
64167
+ pendingRealtimeRefreshRef.current = true;
64168
+ scheduleRealtimeRefresh();
64169
+ }, [clearRealtimeRefreshTimer, enabled, scheduleRealtimeRefresh, supabase]);
64170
+ useEffect(() => {
64171
+ return () => {
64172
+ pendingRealtimeRefreshRef.current = false;
64173
+ clearRealtimeRefreshTimer();
64174
+ };
64175
+ }, [clearRealtimeRefreshTimer]);
63772
64176
  useEffect(() => {
63773
64177
  if (!enabled || !rawState || !resolvedCompanyId) {
63774
64178
  return;
@@ -63785,6 +64189,16 @@ var useLiveMonitorBootstrap = ({
63785
64189
  fallbackShiftConfig
63786
64190
  });
63787
64191
  const activeBreaks = transformActiveBreaks(rawState.response.active_breaks_by_line);
64192
+ const blueComparisonWorkspaceMetrics = rawState.response.blue_comparison_workspace_metrics ? transformMonitorWorkspaceMetrics({
64193
+ rows: rawState.response.blue_comparison_workspace_metrics,
64194
+ companyId: resolvedCompanyId,
64195
+ workspaceConfig: effectiveWorkspaceConfig,
64196
+ appTimezone: effectiveTimezone,
64197
+ lineMetrics: rawState.response.line_metrics || [],
64198
+ resolveShiftConfig: (lineId) => lineShiftConfigs?.get(lineId) || fallbackShiftConfig,
64199
+ shouldOverrideShiftType: (lineId) => Boolean(lineShiftConfigs?.get(lineId)),
64200
+ fallbackShiftConfig
64201
+ }) : workspaceMetrics;
63788
64202
  const metadata = normalizeMetadata(rawState.response.metadata);
63789
64203
  const workspaceIds = workspaceMetrics.map((metric) => metric.workspace_uuid).filter((workspaceId) => Boolean(workspaceId));
63790
64204
  const videoStreamsByWorkspaceId = rawState.response.video_streams_by_workspace_id || {};
@@ -63802,6 +64216,7 @@ var useLiveMonitorBootstrap = ({
63802
64216
  scopeKey: rawState.response.scope_key || null,
63803
64217
  lines: rawState.response.lines || [],
63804
64218
  workspaceMetrics,
64219
+ blueComparisonWorkspaceMetrics: blueComparisonWorkspaceMetrics.length ? blueComparisonWorkspaceMetrics : workspaceMetrics,
63805
64220
  lineMetrics: rawState.response.line_metrics || [],
63806
64221
  kpiTrend: rawState.response.kpi_trend || null,
63807
64222
  activeBreaks,
@@ -63836,6 +64251,83 @@ var useLiveMonitorBootstrap = ({
63836
64251
  }
63837
64252
  void fetchBootstrap(false);
63838
64253
  }, [enabled, resolvedCompanyId, normalizedLineIds, supabase, fetchBootstrap]);
64254
+ const realtimeScopeKey = useMemo(() => Array.from(createResolvedScopeLookup(
64255
+ state.resolvedScope,
64256
+ state.workspaceMetrics,
64257
+ state.blueComparisonWorkspaceMetrics
64258
+ )).sort().join("||"), [state.resolvedScope, state.workspaceMetrics, state.blueComparisonWorkspaceMetrics]);
64259
+ useEffect(() => {
64260
+ if (!enabled || !resolvedCompanyId || !realtimeLineIdsKey || !supabase) {
64261
+ return void 0;
64262
+ }
64263
+ const scopeLookup = new Set(realtimeScopeKey ? realtimeScopeKey.split("||") : []);
64264
+ if (scopeLookup.size === 0) {
64265
+ return void 0;
64266
+ }
64267
+ const realtimeLineIdsForFilter = realtimeLineIdsKey.split(",").filter(Boolean);
64268
+ if (realtimeLineIdsForFilter.length === 0) {
64269
+ return void 0;
64270
+ }
64271
+ const lineIdFilter = `line_id=in.(${realtimeLineIdsForFilter.join(",")})`;
64272
+ const channels = [];
64273
+ const shouldRefreshForPayload = (payload) => {
64274
+ const payloadData = payload.new || payload.old;
64275
+ return scopeLookup.has(`${payloadData?.line_id}|${payloadData?.date}|${payloadData?.shift_id}`);
64276
+ };
64277
+ const createSubscription = (table, channelNameBase) => {
64278
+ const channelName = `${channelNameBase}-${state.scopeKey || requestKey}`.replace(/[^a-zA-Z0-9_-]/g, "");
64279
+ const channel = supabase.channel(channelName).on(
64280
+ "postgres_changes",
64281
+ { event: "*", schema: "public", table, filter: lineIdFilter },
64282
+ (payload) => {
64283
+ if (shouldRefreshForPayload(payload)) {
64284
+ queueRealtimeRefresh();
64285
+ }
64286
+ }
64287
+ ).subscribe();
64288
+ channels.push(channel);
64289
+ };
64290
+ createSubscription(companySpecificMetricsTable, "monitor-bootstrap-ws");
64291
+ createSubscription("line_metrics", "monitor-bootstrap-lm");
64292
+ createSubscription("wip_buffer_metrics", "monitor-bootstrap-wip-metrics");
64293
+ createSubscription("wip_buffer_alerts", "monitor-bootstrap-wip-alerts");
64294
+ return () => {
64295
+ channels.forEach((channel) => {
64296
+ supabase.removeChannel(channel);
64297
+ });
64298
+ };
64299
+ }, [
64300
+ enabled,
64301
+ resolvedCompanyId,
64302
+ realtimeLineIdsKey,
64303
+ supabase,
64304
+ realtimeScopeKey,
64305
+ state.scopeKey,
64306
+ requestKey,
64307
+ companySpecificMetricsTable,
64308
+ queueRealtimeRefresh
64309
+ ]);
64310
+ useEffect(() => {
64311
+ if (!enabled || !resolvedCompanyId || normalizedLineIds.length === 0 || !supabase) {
64312
+ return void 0;
64313
+ }
64314
+ const forceRefreshOnResume = () => {
64315
+ void fetchBootstrapRef.current(true);
64316
+ };
64317
+ const handleVisibilityChange = () => {
64318
+ if (document.visibilityState === "visible") {
64319
+ forceRefreshOnResume();
64320
+ }
64321
+ };
64322
+ document.addEventListener("visibilitychange", handleVisibilityChange);
64323
+ window.addEventListener("focus", forceRefreshOnResume);
64324
+ window.addEventListener("online", forceRefreshOnResume);
64325
+ return () => {
64326
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
64327
+ window.removeEventListener("focus", forceRefreshOnResume);
64328
+ window.removeEventListener("online", forceRefreshOnResume);
64329
+ };
64330
+ }, [enabled, normalizedLineIds.length, resolvedCompanyId, supabase]);
63839
64331
  useEffect(() => {
63840
64332
  if (!enabled || !resolvedCompanyId || normalizedLineIds.length === 0 || !supabase) {
63841
64333
  return void 0;
@@ -63869,6 +64361,7 @@ var useLiveMonitorBootstrap = ({
63869
64361
  scopeKey: state.scopeKey,
63870
64362
  lines: state.lines,
63871
64363
  workspaceMetrics: state.workspaceMetrics,
64364
+ blueComparisonWorkspaceMetrics: state.blueComparisonWorkspaceMetrics,
63872
64365
  lineMetrics: state.lineMetrics,
63873
64366
  kpiTrend: state.kpiTrend,
63874
64367
  activeBreaks: state.activeBreaks,
@@ -64139,6 +64632,22 @@ var logDebug3 = (...args) => {
64139
64632
  };
64140
64633
  var EMPTY_LINE_IDS = [];
64141
64634
  var EMPTY_WORKSPACES = [];
64635
+ var ALL_GREEN_CELEBRATION_DURATION_MS = 6e3;
64636
+ var ALL_GREEN_MILESTONE_DURATION_MS = 6e3;
64637
+ var ALL_GREEN_STREAK_LOCAL_SECOND_CAP = 59;
64638
+ var formatAllGreenCelebrationTimer = (elapsedSeconds) => {
64639
+ const safeElapsedSeconds = Math.max(1, Math.floor(elapsedSeconds));
64640
+ const minutes = Math.floor(safeElapsedSeconds / 60);
64641
+ const seconds = safeElapsedSeconds % 60;
64642
+ return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}s`;
64643
+ };
64644
+ var getAllGreenBackendVisibleSeconds = (confirmedSeconds, tickOriginAtMs, nowMs2) => {
64645
+ const localSecondOffset = Math.min(
64646
+ ALL_GREEN_STREAK_LOCAL_SECOND_CAP,
64647
+ Math.max(0, Math.floor((nowMs2 - tickOriginAtMs) / 1e3))
64648
+ );
64649
+ return confirmedSeconds + localSecondOffset;
64650
+ };
64142
64651
  var LoadingPageCmp = LoadingPage_default;
64143
64652
  var LoadingOverlayCmp = LoadingOverlay_default;
64144
64653
  function HomeView({
@@ -64280,6 +64789,31 @@ function HomeView({
64280
64789
  () => new Set(selectedLineIds),
64281
64790
  [selectedLineIds]
64282
64791
  );
64792
+ const blueComparisonLineIds = useMemo(() => {
64793
+ const selectedFactoryAreaIds = /* @__PURE__ */ new Set();
64794
+ for (const line of dbLines) {
64795
+ if (!selectedLineIdSet.has(line.id)) {
64796
+ continue;
64797
+ }
64798
+ const factoryAreaId = typeof line.factory_area_id === "string" ? line.factory_area_id.trim() : "";
64799
+ if (factoryAreaId) {
64800
+ selectedFactoryAreaIds.add(factoryAreaId);
64801
+ }
64802
+ }
64803
+ if (selectedFactoryAreaIds.size === 0) {
64804
+ return selectedLineIds;
64805
+ }
64806
+ const dbLinesById = new Map(dbLines.map((line) => [line.id, line]));
64807
+ const selectedIds = new Set(selectedLineIds);
64808
+ return visibleLineIds.filter((lineId) => {
64809
+ if (selectedIds.has(lineId)) {
64810
+ return true;
64811
+ }
64812
+ const line = dbLinesById.get(lineId);
64813
+ const factoryAreaId = typeof line?.factory_area_id === "string" ? line.factory_area_id.trim() : "";
64814
+ return factoryAreaId ? selectedFactoryAreaIds.has(factoryAreaId) : false;
64815
+ });
64816
+ }, [dbLines, selectedLineIdSet, selectedLineIds, visibleLineIds]);
64283
64817
  const metricsScopeLineId = isMultiLineSelection ? factoryViewId : primarySelectedLineId;
64284
64818
  const userCompanyId = useMemo(() => {
64285
64819
  return user?.properties?.company_id || user?.company_id || entityConfig.companyId;
@@ -64320,6 +64854,7 @@ function HomeView({
64320
64854
  }, []);
64321
64855
  const {
64322
64856
  workspaceMetrics: legacyWorkspaceMetrics,
64857
+ blueComparisonWorkspaceMetrics: legacyMetricsBlueComparisonWorkspaceMetrics,
64323
64858
  lineMetrics: legacyLineMetrics,
64324
64859
  efficiencyLegend: legacyEfficiencyLegend,
64325
64860
  metadata: legacyMetricsMetadata,
@@ -64330,6 +64865,7 @@ function HomeView({
64330
64865
  } = useDashboardMetrics({
64331
64866
  lineId: metricsScopeLineId,
64332
64867
  lineIds: selectedLineIds,
64868
+ blueComparisonLineIds,
64333
64869
  onLineMetricsUpdate: handleLineMetricsUpdate,
64334
64870
  userAccessibleLineIds: visibleLineIds,
64335
64871
  enabled: shouldEnableMetricsFetch && !isBootstrapMonitorMode
@@ -64384,6 +64920,7 @@ function HomeView({
64384
64920
  const { trend: legacyKpiTrend } = useKpiTrends(legacyTrendOptions);
64385
64921
  const bootstrapMonitor = useLiveMonitorBootstrap({
64386
64922
  lineIds: selectedLineIds,
64923
+ blueComparisonLineIds,
64387
64924
  companyId: userCompanyId,
64388
64925
  enabled: shouldEnableMetricsFetch && !isLegacyMonitorMode,
64389
64926
  appTimezone: timezone,
@@ -64392,6 +64929,7 @@ function HomeView({
64392
64929
  lineShiftConfigs
64393
64930
  });
64394
64931
  const currentWorkspaceMetrics = isBootstrapMonitorMode ? bootstrapMonitor.workspaceMetrics : legacyWorkspaceMetrics;
64932
+ const currentBlueComparisonWorkspaceMetrics = isBootstrapMonitorMode ? bootstrapMonitor.blueComparisonWorkspaceMetrics : legacyMetricsBlueComparisonWorkspaceMetrics;
64395
64933
  const currentLineMetrics = isBootstrapMonitorMode ? bootstrapMonitor.lineMetrics : legacyLineMetrics;
64396
64934
  const currentEfficiencyLegend = isBootstrapMonitorMode ? bootstrapMonitor.efficiencyLegend : legacyEfficiencyLegend;
64397
64935
  const currentMetricsMetadata = isBootstrapMonitorMode ? bootstrapMonitor.metadata : legacyMetricsMetadata;
@@ -64529,6 +65067,212 @@ function HomeView({
64529
65067
  setBreakNotificationsDismissed(false);
64530
65068
  }
64531
65069
  }, [currentActiveBreaks.length]);
65070
+ const effectiveEfficiencyLegend = currentEfficiencyLegend || DEFAULT_EFFICIENCY_LEGEND;
65071
+ useMemo(
65072
+ () => workspaceMetricsWithBreakState.filter((workspace) => Boolean(workspace.workspace_uuid || workspace.workspace_name)).length,
65073
+ [workspaceMetricsWithBreakState]
65074
+ );
65075
+ const allGreenCelebrationSignature = useMemo(() => {
65076
+ const workspaceSignature = workspaceMetricsWithBreakState.map((workspace) => workspace.workspace_uuid || `${workspace.line_id}:${workspace.workspace_name}`).filter(Boolean).sort().join(",");
65077
+ return `${selectedLineIds.join(",")}::${workspaceSignature}`;
65078
+ }, [selectedLineIds, workspaceMetricsWithBreakState]);
65079
+ const allGreenTransitionRef = useRef({ signature: null, previousValidStreakIdentity: null });
65080
+ const allGreenCelebrationTimerRef = useRef(null);
65081
+ const allGreenMilestoneTimerRef = useRef(null);
65082
+ const allGreenMilestoneTrackingRef = useRef({ identity: null, lastMilestoneSeconds: null });
65083
+ const allGreenStreakTimerBaselineRef = useRef(null);
65084
+ const [showAllGreenCelebration, setShowAllGreenCelebration] = useState(false);
65085
+ const [greenStreakMilestoneBanner, setGreenStreakMilestoneBanner] = useState(null);
65086
+ const [allGreenStreakNowMs, setAllGreenStreakNowMs] = useState(() => Date.now());
65087
+ const currentAllGreenStreakNowMs = Math.max(allGreenStreakNowMs, Date.now());
65088
+ const allGreenStreakDisplay = useMemo(
65089
+ () => getAllVideoGridGreenStreakDisplay(
65090
+ workspaceMetricsWithBreakState,
65091
+ effectiveEfficiencyLegend,
65092
+ currentAllGreenStreakNowMs
65093
+ ),
65094
+ [currentAllGreenStreakNowMs, effectiveEfficiencyLegend, workspaceMetricsWithBreakState]
65095
+ );
65096
+ const allGreenMilestoneIdentity = useMemo(() => allGreenStreakDisplay ? `${allGreenCelebrationSignature}::${allGreenStreakDisplay.startedAt}` : null, [allGreenCelebrationSignature, allGreenStreakDisplay]);
65097
+ const visibleAllGreenStreakDisplay = useMemo(() => {
65098
+ if (!allGreenStreakDisplay || !allGreenMilestoneIdentity) {
65099
+ allGreenStreakTimerBaselineRef.current = null;
65100
+ return null;
65101
+ }
65102
+ const confirmedSeconds = allGreenStreakDisplay.confirmedSeconds;
65103
+ const backendVisibleSeconds = getAllGreenBackendVisibleSeconds(
65104
+ confirmedSeconds,
65105
+ allGreenStreakDisplay.tickOriginAtMs,
65106
+ currentAllGreenStreakNowMs
65107
+ );
65108
+ const backendMaxVisibleSeconds = confirmedSeconds + ALL_GREEN_STREAK_LOCAL_SECOND_CAP;
65109
+ const currentBaseline = allGreenStreakTimerBaselineRef.current;
65110
+ if (!currentBaseline || currentBaseline.identity !== allGreenMilestoneIdentity) {
65111
+ allGreenStreakTimerBaselineRef.current = {
65112
+ identity: allGreenMilestoneIdentity,
65113
+ baseSeconds: backendVisibleSeconds,
65114
+ baseReceivedAtMs: currentAllGreenStreakNowMs,
65115
+ maxVisibleSeconds: backendMaxVisibleSeconds
65116
+ };
65117
+ } else {
65118
+ currentBaseline.maxVisibleSeconds = Math.max(
65119
+ currentBaseline.maxVisibleSeconds,
65120
+ backendMaxVisibleSeconds
65121
+ );
65122
+ const visibleSeconds = Math.min(
65123
+ currentBaseline.maxVisibleSeconds,
65124
+ currentBaseline.baseSeconds + Math.max(0, Math.floor((currentAllGreenStreakNowMs - currentBaseline.baseReceivedAtMs) / 1e3))
65125
+ );
65126
+ if (backendVisibleSeconds > visibleSeconds) {
65127
+ allGreenStreakTimerBaselineRef.current = {
65128
+ identity: allGreenMilestoneIdentity,
65129
+ baseSeconds: backendVisibleSeconds,
65130
+ baseReceivedAtMs: currentAllGreenStreakNowMs,
65131
+ maxVisibleSeconds: currentBaseline.maxVisibleSeconds
65132
+ };
65133
+ }
65134
+ }
65135
+ const baseline = allGreenStreakTimerBaselineRef.current;
65136
+ const elapsedSeconds = baseline ? Math.min(
65137
+ baseline.maxVisibleSeconds,
65138
+ baseline.baseSeconds + Math.max(0, Math.floor((currentAllGreenStreakNowMs - baseline.baseReceivedAtMs) / 1e3))
65139
+ ) : backendVisibleSeconds;
65140
+ return {
65141
+ ...allGreenStreakDisplay,
65142
+ elapsedSeconds,
65143
+ durationText: formatAllGreenStreakDuration(elapsedSeconds)
65144
+ };
65145
+ }, [allGreenMilestoneIdentity, allGreenStreakDisplay, currentAllGreenStreakNowMs]);
65146
+ const allGreenCelebrationTimerText = useMemo(() => {
65147
+ if (!showAllGreenCelebration || !visibleAllGreenStreakDisplay) {
65148
+ return null;
65149
+ }
65150
+ return formatAllGreenCelebrationTimer(visibleAllGreenStreakDisplay.elapsedSeconds);
65151
+ }, [showAllGreenCelebration, visibleAllGreenStreakDisplay]);
65152
+ useEffect(() => {
65153
+ const hasPossibleStreakTimer = showAllGreenCelebration || Boolean(allGreenStreakDisplay) || workspaceMetricsWithBreakState.some((workspace) => workspace.video_grid_green_streak_active === true);
65154
+ if (!hasPossibleStreakTimer) {
65155
+ return void 0;
65156
+ }
65157
+ const timerId = setInterval(() => {
65158
+ setAllGreenStreakNowMs(Date.now());
65159
+ }, 1e3);
65160
+ return () => {
65161
+ clearInterval(timerId);
65162
+ };
65163
+ }, [allGreenStreakDisplay, showAllGreenCelebration, workspaceMetricsWithBreakState]);
65164
+ const dismissAllGreenCelebration = useCallback(() => {
65165
+ if (allGreenCelebrationTimerRef.current) {
65166
+ clearTimeout(allGreenCelebrationTimerRef.current);
65167
+ allGreenCelebrationTimerRef.current = null;
65168
+ }
65169
+ setShowAllGreenCelebration(false);
65170
+ }, []);
65171
+ const triggerAllGreenCelebration = useCallback(() => {
65172
+ setShowAllGreenCelebration(true);
65173
+ if (allGreenCelebrationTimerRef.current) {
65174
+ clearTimeout(allGreenCelebrationTimerRef.current);
65175
+ }
65176
+ allGreenCelebrationTimerRef.current = setTimeout(() => {
65177
+ setShowAllGreenCelebration(false);
65178
+ allGreenCelebrationTimerRef.current = null;
65179
+ }, ALL_GREEN_CELEBRATION_DURATION_MS);
65180
+ }, []);
65181
+ const dismissGreenStreakMilestoneBanner = useCallback(() => {
65182
+ if (allGreenMilestoneTimerRef.current) {
65183
+ clearTimeout(allGreenMilestoneTimerRef.current);
65184
+ allGreenMilestoneTimerRef.current = null;
65185
+ }
65186
+ setGreenStreakMilestoneBanner(null);
65187
+ }, []);
65188
+ const triggerGreenStreakMilestoneBanner = useCallback((milestone) => {
65189
+ setGreenStreakMilestoneBanner(milestone);
65190
+ if (allGreenMilestoneTimerRef.current) {
65191
+ clearTimeout(allGreenMilestoneTimerRef.current);
65192
+ }
65193
+ allGreenMilestoneTimerRef.current = setTimeout(() => {
65194
+ setGreenStreakMilestoneBanner(null);
65195
+ allGreenMilestoneTimerRef.current = null;
65196
+ }, ALL_GREEN_MILESTONE_DURATION_MS);
65197
+ }, []);
65198
+ useEffect(() => {
65199
+ return () => {
65200
+ if (allGreenCelebrationTimerRef.current) {
65201
+ clearTimeout(allGreenCelebrationTimerRef.current);
65202
+ }
65203
+ if (allGreenMilestoneTimerRef.current) {
65204
+ clearTimeout(allGreenMilestoneTimerRef.current);
65205
+ }
65206
+ };
65207
+ }, []);
65208
+ useEffect(() => {
65209
+ const milestoneTracking = allGreenMilestoneTrackingRef.current;
65210
+ if (currentMetricsLoading) {
65211
+ return;
65212
+ }
65213
+ if (!visibleAllGreenStreakDisplay || !allGreenMilestoneIdentity) {
65214
+ milestoneTracking.identity = null;
65215
+ milestoneTracking.lastMilestoneSeconds = null;
65216
+ dismissGreenStreakMilestoneBanner();
65217
+ return;
65218
+ }
65219
+ const currentMilestone = getAllGreenStreakMilestone(visibleAllGreenStreakDisplay.elapsedSeconds);
65220
+ const currentMilestoneSeconds = currentMilestone?.milestoneSeconds ?? null;
65221
+ if (milestoneTracking.identity !== allGreenMilestoneIdentity) {
65222
+ milestoneTracking.identity = allGreenMilestoneIdentity;
65223
+ milestoneTracking.lastMilestoneSeconds = currentMilestoneSeconds;
65224
+ dismissGreenStreakMilestoneBanner();
65225
+ return;
65226
+ }
65227
+ if (!currentMilestone) {
65228
+ milestoneTracking.lastMilestoneSeconds = null;
65229
+ return;
65230
+ }
65231
+ if ((milestoneTracking.lastMilestoneSeconds ?? 0) < currentMilestone.milestoneSeconds) {
65232
+ milestoneTracking.lastMilestoneSeconds = currentMilestone.milestoneSeconds;
65233
+ triggerGreenStreakMilestoneBanner(currentMilestone);
65234
+ }
65235
+ }, [
65236
+ allGreenMilestoneIdentity,
65237
+ currentMetricsLoading,
65238
+ dismissGreenStreakMilestoneBanner,
65239
+ triggerGreenStreakMilestoneBanner,
65240
+ visibleAllGreenStreakDisplay
65241
+ ]);
65242
+ useEffect(() => {
65243
+ if (currentMetricsLoading) {
65244
+ return;
65245
+ }
65246
+ const currentValidStreakIdentity = visibleAllGreenStreakDisplay && allGreenMilestoneIdentity ? allGreenMilestoneIdentity : null;
65247
+ const transitionState = allGreenTransitionRef.current;
65248
+ if (transitionState.signature !== allGreenCelebrationSignature) {
65249
+ transitionState.signature = allGreenCelebrationSignature;
65250
+ transitionState.previousValidStreakIdentity = currentValidStreakIdentity;
65251
+ dismissAllGreenCelebration();
65252
+ return;
65253
+ }
65254
+ if (!currentValidStreakIdentity) {
65255
+ transitionState.previousValidStreakIdentity = null;
65256
+ dismissAllGreenCelebration();
65257
+ return;
65258
+ }
65259
+ if (transitionState.previousValidStreakIdentity === null) {
65260
+ transitionState.previousValidStreakIdentity = currentValidStreakIdentity;
65261
+ triggerAllGreenCelebration();
65262
+ return;
65263
+ }
65264
+ if (transitionState.previousValidStreakIdentity !== currentValidStreakIdentity) {
65265
+ transitionState.previousValidStreakIdentity = currentValidStreakIdentity;
65266
+ dismissAllGreenCelebration();
65267
+ }
65268
+ }, [
65269
+ allGreenCelebrationSignature,
65270
+ allGreenMilestoneIdentity,
65271
+ currentMetricsLoading,
65272
+ dismissAllGreenCelebration,
65273
+ triggerAllGreenCelebration,
65274
+ visibleAllGreenStreakDisplay
65275
+ ]);
64532
65276
  const {
64533
65277
  streamsByWorkspaceId: legacyVideoStreamsByWorkspaceId,
64534
65278
  isLoading: legacyVideoStreamsLoading
@@ -65095,6 +65839,28 @@ function HomeView({
65095
65839
  updateSelectedLineIds,
65096
65840
  isAllLinesSelection
65097
65841
  ]);
65842
+ const gridToolbarControls = useMemo(() => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-2", children: [
65843
+ /* @__PURE__ */ jsx(AnimatePresence, { children: visibleAllGreenStreakDisplay ? /* @__PURE__ */ jsxs(
65844
+ motion.div,
65845
+ {
65846
+ initial: { opacity: 0, y: -4 },
65847
+ animate: { opacity: 1, y: 0 },
65848
+ exit: { opacity: 0, y: -4 },
65849
+ transition: { duration: 0.18, ease: "easeOut" },
65850
+ className: "inline-flex items-center gap-1.5 rounded-md border border-[#00AB45]/20 bg-[#00AB45]/10 px-3 py-1.5 text-sm font-semibold text-[#00AB45] shadow-sm",
65851
+ "aria-label": "All green streak",
65852
+ children: [
65853
+ /* @__PURE__ */ jsx(CheckCircle2, { className: "h-4 w-4" }),
65854
+ /* @__PURE__ */ jsx("span", { children: `${visibleAllGreenStreakDisplay.label} \xB7 ${visibleAllGreenStreakDisplay.durationText}` })
65855
+ ]
65856
+ },
65857
+ visibleAllGreenStreakDisplay.startedAt
65858
+ ) : null }),
65859
+ lineSelectorComponent
65860
+ ] }), [
65861
+ lineSelectorComponent,
65862
+ visibleAllGreenStreakDisplay
65863
+ ]);
65098
65864
  const useSmoothLoading = (isLoading, minDuration = 400) => {
65099
65865
  const [showLoading, setShowLoading] = useState(isLoading);
65100
65866
  const loadingStartRef2 = useRef(null);
@@ -65267,17 +66033,18 @@ function HomeView({
65267
66033
  className: "h-full",
65268
66034
  children: React144__default.createElement(WorkspaceGrid, {
65269
66035
  workspaces: workspaceMetricsWithBreakState,
66036
+ blueComparisonWorkspaces: currentBlueComparisonWorkspaceMetrics || workspaceMetricsWithBreakState,
65270
66037
  lineNames: mergedLineNames,
65271
66038
  lineOrder: selectedLineIds,
65272
66039
  factoryView: factoryViewId,
65273
- legend: currentEfficiencyLegend,
66040
+ legend: effectiveEfficiencyLegend,
65274
66041
  videoSources,
65275
66042
  videoStreamsByWorkspaceId: currentVideoStreamsByWorkspaceId,
65276
66043
  videoStreamsLoading: currentVideoStreamsLoading,
65277
66044
  displayNames: metricsDisplayNames,
65278
66045
  hasFlowBuffers,
65279
66046
  className: "h-full",
65280
- toolbarRightContent: lineSelectorComponent,
66047
+ toolbarRightContent: gridToolbarControls,
65281
66048
  onWorkspaceHover: handleWorkspaceHover,
65282
66049
  onWorkspaceHoverEnd: handleWorkspaceHoverEnd
65283
66050
  })
@@ -65300,17 +66067,18 @@ function HomeView({
65300
66067
  children: React144__default.createElement(WorkspaceGrid, {
65301
66068
  workspaces: [],
65302
66069
  // Show empty grid while loading
66070
+ blueComparisonWorkspaces: [],
65303
66071
  lineNames: mergedLineNames,
65304
66072
  lineOrder: selectedLineIds,
65305
66073
  factoryView: factoryViewId,
65306
- legend: currentEfficiencyLegend,
66074
+ legend: effectiveEfficiencyLegend,
65307
66075
  videoSources,
65308
66076
  videoStreamsByWorkspaceId: currentVideoStreamsByWorkspaceId,
65309
66077
  videoStreamsLoading: currentVideoStreamsLoading,
65310
66078
  displayNames: metricsDisplayNames,
65311
66079
  hasFlowBuffers,
65312
66080
  className: "h-full",
65313
- toolbarRightContent: lineSelectorComponent,
66081
+ toolbarRightContent: gridToolbarControls,
65314
66082
  onWorkspaceHover: handleWorkspaceHover,
65315
66083
  onWorkspaceHoverEnd: handleWorkspaceHoverEnd
65316
66084
  })
@@ -65343,6 +66111,149 @@ function HomeView({
65343
66111
  contentVariant: "plain"
65344
66112
  }
65345
66113
  ),
66114
+ /* @__PURE__ */ jsx(AnimatePresence, { children: showAllGreenCelebration ? /* @__PURE__ */ jsxs(React144__default.Fragment, { children: [
66115
+ /* @__PURE__ */ jsx(
66116
+ motion.div,
66117
+ {
66118
+ initial: { opacity: 0 },
66119
+ animate: { opacity: 1 },
66120
+ exit: { opacity: 0 },
66121
+ transition: { duration: 0.4 },
66122
+ className: "pointer-events-none fixed inset-0 z-[9998] bg-slate-900/40 backdrop-blur-sm",
66123
+ "aria-hidden": "true"
66124
+ },
66125
+ "all-green-backdrop"
66126
+ ),
66127
+ /* @__PURE__ */ jsxs(
66128
+ motion.div,
66129
+ {
66130
+ initial: { opacity: 0 },
66131
+ animate: { opacity: 1 },
66132
+ exit: { opacity: 0, y: -50, scale: 0.9, filter: "blur(10px)" },
66133
+ transition: { duration: 0.4 },
66134
+ className: "pointer-events-none fixed inset-0 z-[10000] flex flex-col items-center justify-center px-4",
66135
+ role: "status",
66136
+ "aria-live": "polite",
66137
+ "aria-label": "All green celebration",
66138
+ children: [
66139
+ /* @__PURE__ */ jsxs(
66140
+ motion.div,
66141
+ {
66142
+ initial: { opacity: 0, y: 8, filter: "blur(6px)" },
66143
+ animate: { opacity: 1, y: 0, filter: "blur(0px)" },
66144
+ transition: { duration: 0.28, ease: [0.16, 1, 0.3, 1] },
66145
+ className: "flex flex-wrap items-center justify-center gap-x-4 sm:gap-x-8",
66146
+ children: [
66147
+ /* @__PURE__ */ jsx(
66148
+ "span",
66149
+ {
66150
+ className: "text-[100px] font-black uppercase leading-none tracking-tight text-white drop-shadow-2xl sm:text-[140px]",
66151
+ style: { textShadow: "0 18px 36px rgba(0,0,0,0.34)" },
66152
+ children: "ALL"
66153
+ }
66154
+ ),
66155
+ /* @__PURE__ */ jsx(
66156
+ "span",
66157
+ {
66158
+ className: "text-[100px] font-black uppercase leading-none tracking-tight text-[#00AB45] drop-shadow-2xl sm:text-[140px]",
66159
+ style: { filter: "drop-shadow(0 18px 36px rgba(0,171,69,0.28))" },
66160
+ children: "GREEN"
66161
+ }
66162
+ )
66163
+ ]
66164
+ }
66165
+ ),
66166
+ /* @__PURE__ */ jsx(
66167
+ motion.div,
66168
+ {
66169
+ initial: { opacity: 0, scaleX: 0 },
66170
+ animate: { opacity: 1, scaleX: 1 },
66171
+ transition: { delay: 0.18, duration: 0.45, ease: [0.16, 1, 0.3, 1] },
66172
+ className: "mt-4 h-1 w-44 origin-left rounded-full bg-[#00AB45] shadow-[0_0_16px_rgba(0,171,69,0.44)] sm:w-64"
66173
+ }
66174
+ ),
66175
+ allGreenCelebrationTimerText && /* @__PURE__ */ jsxs(
66176
+ motion.div,
66177
+ {
66178
+ initial: { opacity: 0, y: 4 },
66179
+ animate: { opacity: 1, y: 0 },
66180
+ transition: { delay: 0.28, duration: 0.18, ease: "easeOut" },
66181
+ className: "mt-3 flex items-center justify-center gap-2 text-2xl font-semibold tracking-tight text-white drop-shadow-[0_4px_18px_rgba(0,0,0,0.45)] sm:mt-4 sm:text-3xl",
66182
+ children: [
66183
+ /* @__PURE__ */ jsx("span", { className: "h-2.5 w-2.5 rounded-full bg-[#00AB45] shadow-[0_0_10px_rgba(0,171,69,0.72)]" }),
66184
+ /* @__PURE__ */ jsx("span", { children: allGreenCelebrationTimerText })
66185
+ ]
66186
+ }
66187
+ )
66188
+ ]
66189
+ },
66190
+ "all-green-center-toast"
66191
+ )
66192
+ ] }, "all-green-celebration") : null }),
66193
+ /* @__PURE__ */ jsx(AnimatePresence, { children: greenStreakMilestoneBanner ? /* @__PURE__ */ jsxs(React144__default.Fragment, { children: [
66194
+ /* @__PURE__ */ jsx(
66195
+ motion.div,
66196
+ {
66197
+ initial: { opacity: 0 },
66198
+ animate: { opacity: 1 },
66199
+ exit: { opacity: 0 },
66200
+ transition: { duration: 0.4 },
66201
+ className: "pointer-events-none fixed inset-0 z-[9998] bg-slate-900/40 backdrop-blur-sm",
66202
+ "aria-hidden": "true"
66203
+ },
66204
+ `green-streak-backdrop-${greenStreakMilestoneBanner.milestoneSeconds}`
66205
+ ),
66206
+ /* @__PURE__ */ jsx(
66207
+ motion.div,
66208
+ {
66209
+ initial: { opacity: 0 },
66210
+ animate: { opacity: 1 },
66211
+ exit: { opacity: 0, y: -50, scale: 0.9, filter: "blur(10px)" },
66212
+ transition: { duration: 0.4 },
66213
+ className: "pointer-events-none fixed inset-0 z-[10000] flex flex-col items-center justify-center px-4",
66214
+ role: "status",
66215
+ "aria-live": "polite",
66216
+ "aria-label": `Green streak milestone: ${greenStreakMilestoneBanner.headline}`,
66217
+ children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center gap-y-4", children: [
66218
+ /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center", children: /* @__PURE__ */ jsx(
66219
+ motion.div,
66220
+ {
66221
+ initial: { opacity: 0, y: 8, filter: "blur(6px)" },
66222
+ animate: { opacity: 1, y: 0, filter: "blur(0px)" },
66223
+ transition: { delay: 0.08, duration: 0.28, ease: [0.16, 1, 0.3, 1] },
66224
+ className: "text-[80px] font-black uppercase leading-none tracking-tight text-white drop-shadow-2xl sm:text-[120px]",
66225
+ style: { textShadow: "0 18px 36px rgba(0,0,0,0.34)" },
66226
+ children: greenStreakMilestoneBanner.headline
66227
+ }
66228
+ ) }),
66229
+ /* @__PURE__ */ jsx(
66230
+ motion.div,
66231
+ {
66232
+ initial: { opacity: 0, scaleX: 0 },
66233
+ animate: { opacity: 1, scaleX: 1 },
66234
+ transition: { delay: 0.22, duration: 0.45, ease: [0.16, 1, 0.3, 1] },
66235
+ className: "h-1 w-40 origin-left rounded-full bg-[#00AB45] shadow-[0_0_16px_rgba(0,171,69,0.44)] sm:w-56"
66236
+ }
66237
+ ),
66238
+ /* @__PURE__ */ jsxs(
66239
+ motion.div,
66240
+ {
66241
+ initial: { opacity: 0, y: 8, filter: "blur(6px)" },
66242
+ animate: { opacity: 1, y: 0, filter: "blur(0px)" },
66243
+ transition: { delay: 0.28, duration: 0.28, ease: [0.16, 1, 0.3, 1] },
66244
+ className: "flex flex-wrap items-center justify-center gap-x-4 text-[60px] font-black uppercase leading-none tracking-tight text-[#00AB45] drop-shadow-2xl sm:gap-x-8 sm:text-[90px]",
66245
+ style: { filter: "drop-shadow(0 18px 36px rgba(0,171,69,0.28))" },
66246
+ children: [
66247
+ /* @__PURE__ */ jsx("span", { children: "ALL" }),
66248
+ /* @__PURE__ */ jsx("span", { children: "GREEN" })
66249
+ ]
66250
+ }
66251
+ )
66252
+ ] })
66253
+ },
66254
+ `green-streak-milestone-${greenStreakMilestoneBanner.milestoneSeconds}`
66255
+ )
66256
+ ] }, `green-streak-milestone-wrapper-${greenStreakMilestoneBanner.milestoneSeconds}`) : null }),
65346
66257
  diagnosisModalOpen && bottleneckModalData?.clipId && /* @__PURE__ */ jsx(
65347
66258
  DiagnosisVideoModal,
65348
66259
  {
@@ -68737,6 +69648,7 @@ var LinesLeaderboard = ({
68737
69648
  timeRange,
68738
69649
  setTimeRange,
68739
69650
  todayEfficiencyByLineId,
69651
+ dailyFallbackEfficiencyByLineId,
68740
69652
  monthlyEfficiencyByLineId,
68741
69653
  supervisorsByLineId,
68742
69654
  supervisorNamesByLineId,
@@ -68772,8 +69684,12 @@ var LinesLeaderboard = ({
68772
69684
  });
68773
69685
  setTimeRange(newRange);
68774
69686
  }, [timeRange, lines.length, monthlyEfficiencyByLineId, setTimeRange]);
69687
+ const canClickLeaderboardRow = React144__default.useCallback(
69688
+ (item) => item.rowType === "line" && !!item.line && canClickLine(item.line.id),
69689
+ [canClickLine]
69690
+ );
68775
69691
  const handleLeaderboardLineClick = React144__default.useCallback((item, clickSource) => {
68776
- if (!canClickLine(item.line.id)) return;
69692
+ if (!canClickLeaderboardRow(item) || !item.line) return;
68777
69693
  trackCoreEvent("Leaderboard Line Clicked", {
68778
69694
  line_id: item.line.id,
68779
69695
  line_name: item.line.line_name,
@@ -68785,33 +69701,46 @@ var LinesLeaderboard = ({
68785
69701
  supervisor_name: item.supervisorName || "Unassigned"
68786
69702
  });
68787
69703
  onLineClick(item.line);
68788
- }, [canClickLine, onLineClick, timeRange]);
69704
+ }, [canClickLeaderboardRow, onLineClick, timeRange]);
68789
69705
  const viewLoadedTrackedRef = React144__default.useRef(null);
68790
69706
  const leaderboardData = React144__default.useMemo(() => {
68791
69707
  const loading = timeRange === "today" ? isLoadingToday : isLoadingMonthly;
68792
69708
  const efficiencyMap = timeRange === "today" ? todayEfficiencyByLineId : monthlyEfficiencyByLineId;
68793
- return lines.map((line) => {
68794
- const supervisors = supervisorsByLineId?.get(line.id) || [];
69709
+ const fallbackEfficiencyMap = timeRange === "today" ? dailyFallbackEfficiencyByLineId : void 0;
69710
+ return buildLineLeaderboardRows({
69711
+ lines,
69712
+ efficiencyByLineId: efficiencyMap,
69713
+ fallbackEfficiencyByLineId: fallbackEfficiencyMap,
69714
+ isLoading: loading
69715
+ }).map((row, index) => {
69716
+ const supervisorByUserId = /* @__PURE__ */ new Map();
69717
+ const fallbackSupervisorNames = [];
69718
+ row.lines.forEach((line) => {
69719
+ (supervisorsByLineId?.get(line.id) || []).forEach((supervisor) => {
69720
+ supervisorByUserId.set(supervisor.userId, supervisor);
69721
+ });
69722
+ const fallbackName = supervisorNamesByLineId.get(line.id);
69723
+ if (fallbackName && !fallbackSupervisorNames.includes(fallbackName)) {
69724
+ fallbackSupervisorNames.push(fallbackName);
69725
+ }
69726
+ });
69727
+ const supervisors = Array.from(supervisorByUserId.values());
68795
69728
  const primarySupervisor = supervisors[0];
68796
- const supervisorName = supervisorNamesByLineId.get(line.id) || primarySupervisor?.displayName || "Unassigned";
69729
+ const supervisorName = supervisors.length > 1 ? `${supervisors.length} supervisors` : primarySupervisor?.displayName || fallbackSupervisorNames[0] || "Unassigned";
68797
69730
  const supervisorImage = primarySupervisor?.profilePhotoUrl || null;
68798
- const hasEfficiency = efficiencyMap.has(line.id);
68799
- const efficiency = hasEfficiency ? efficiencyMap.get(line.id) ?? 0 : loading ? null : timeRange === "monthly" ? 0 : null;
68800
- const sortValue = typeof efficiency === "number" ? efficiency : -1;
68801
69731
  return {
68802
- id: line.id,
68803
- line,
69732
+ ...row,
69733
+ rank: row.rank ?? index + 1,
68804
69734
  supervisorName,
68805
69735
  supervisorImage,
68806
- supervisors,
68807
- efficiency,
68808
- sortValue
69736
+ supervisors
68809
69737
  };
68810
- }).sort((a, b) => b.sortValue - a.sortValue).map((item, index) => ({ ...item, rank: index + 1 }));
69738
+ });
68811
69739
  }, [
68812
69740
  lines,
68813
69741
  timeRange,
68814
69742
  todayEfficiencyByLineId,
69743
+ dailyFallbackEfficiencyByLineId,
68815
69744
  monthlyEfficiencyByLineId,
68816
69745
  supervisorsByLineId,
68817
69746
  supervisorNamesByLineId,
@@ -68828,11 +69757,11 @@ var LinesLeaderboard = ({
68828
69757
  trackCoreEvent("Leaderboard View Loaded", {
68829
69758
  time_range: timeRange,
68830
69759
  lines_count: leaderboardData.length,
68831
- top_line_id: topLine?.line.id,
68832
- top_line_name: topLine?.line.line_name,
69760
+ top_line_id: topLine?.rowType === "line" ? topLine.line?.id : topLine?.areaId,
69761
+ top_line_name: topLine?.displayName,
68833
69762
  top_efficiency: topLine?.efficiency,
68834
- bottom_line_id: bottomLine?.line.id,
68835
- bottom_line_name: bottomLine?.line.line_name,
69763
+ bottom_line_id: bottomLine?.rowType === "line" ? bottomLine.line?.id : bottomLine?.areaId,
69764
+ bottom_line_name: bottomLine?.displayName,
68836
69765
  bottom_efficiency: bottomLine?.efficiency,
68837
69766
  efficiency_spread: topLine && bottomLine && topLine.efficiency !== null && bottomLine.efficiency !== null ? (topLine.efficiency - bottomLine.efficiency).toFixed(1) : null,
68838
69767
  from_page: "kpis_overview"
@@ -68939,7 +69868,7 @@ var LinesLeaderboard = ({
68939
69868
  const isFirst = item.rank === 1;
68940
69869
  const isSecond = item.rank === 2;
68941
69870
  item.rank === 3;
68942
- const isClickable = canClickLine(item.line.id);
69871
+ const isClickable = canClickLeaderboardRow(item);
68943
69872
  return /* @__PURE__ */ jsxs(
68944
69873
  "div",
68945
69874
  {
@@ -68982,7 +69911,11 @@ var LinesLeaderboard = ({
68982
69911
  className: `flex flex-col items-center w-32 md:w-40 lg:w-48 xl:w-60 px-2 md:px-3 xl:px-4 pb-3 md:pb-4 pt-8 md:pt-10 rounded-2xl border bg-gradient-to-b shadow-2xl backdrop-blur-sm ${getRankColor(item.rank)} ${isFirst ? "h-44 md:h-52 lg:h-60 xl:h-64" : isSecond ? "h-36 md:h-44 lg:h-52 xl:h-56" : "h-28 md:h-36 lg:h-44 xl:h-48"}`,
68983
69912
  children: /* @__PURE__ */ jsxs("div", { className: "flex-1 flex flex-col items-center justify-center w-full", children: [
68984
69913
  /* @__PURE__ */ jsx("h3", { className: `font-bold text-gray-900 text-center line-clamp-1 mb-1 ${isFirst ? "text-xs md:text-sm lg:text-base xl:text-lg" : "text-[10px] md:text-xs lg:text-sm xl:text-base"}`, children: item.supervisorName }),
68985
- /* @__PURE__ */ jsx("p", { className: `text-gray-600 text-center line-clamp-1 font-medium opacity-80 bg-white/50 px-2 md:px-3 py-0.5 rounded-full ${isFirst ? "text-[9px] md:text-[10px] lg:text-xs xl:text-sm mb-2 md:mb-3" : "text-[8px] md:text-[9px] lg:text-[10px] xl:text-xs mb-1 md:mb-2"}`, children: item.line.line_name }),
69914
+ /* @__PURE__ */ jsx("p", { className: `text-gray-600 text-center line-clamp-1 font-medium opacity-80 bg-white/50 px-2 md:px-3 py-0.5 rounded-full ${isFirst ? "text-[9px] md:text-[10px] lg:text-xs xl:text-sm mb-2 md:mb-3" : "text-[8px] md:text-[9px] lg:text-[10px] xl:text-xs mb-1 md:mb-2"}`, children: item.displayName }),
69915
+ item.rowType === "area" && /* @__PURE__ */ jsxs("span", { className: "mb-1 text-[8px] md:text-[9px] lg:text-[10px] xl:text-xs font-semibold uppercase text-gray-500", children: [
69916
+ item.lines.length,
69917
+ " lines"
69918
+ ] }),
68986
69919
  /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center mt-auto", children: [
68987
69920
  /* @__PURE__ */ jsx("span", { className: `font-bold uppercase tracking-widest mb-0.5 ${isFirst ? "text-yellow-700/70 text-[8px] md:text-[9px] lg:text-[10px] xl:text-xs" : isSecond ? "text-gray-600/70 text-[7px] md:text-[8px] lg:text-[9px] xl:text-[10px]" : "text-orange-700/70 text-[7px] md:text-[8px] lg:text-[9px] xl:text-[10px]"}`, children: viewType === "machine" ? "Utilization" : "Efficiency" }),
68988
69921
  /* @__PURE__ */ jsx("span", { className: `font-black tracking-tight leading-none ${isFirst ? "text-lg md:text-xl lg:text-2xl xl:text-3xl text-transparent bg-clip-text bg-gradient-to-br from-yellow-600 to-yellow-800 drop-shadow-sm" : isSecond ? "text-base md:text-lg lg:text-xl xl:text-2xl text-transparent bg-clip-text bg-gradient-to-br from-gray-600 to-gray-800 drop-shadow-sm" : "text-sm md:text-base lg:text-lg xl:text-xl text-transparent bg-clip-text bg-gradient-to-br from-orange-600 to-orange-800 drop-shadow-sm"}`, children: formatEfficiency(item.efficiency) })
@@ -69005,7 +69938,7 @@ var LinesLeaderboard = ({
69005
69938
  ] }) }),
69006
69939
  /* @__PURE__ */ jsx("tbody", { className: "divide-y divide-gray-100", children: leaderboardData.map((item) => {
69007
69940
  const isTopThree = item.rank <= 3;
69008
- const isClickable = canClickLine(item.line.id);
69941
+ const isClickable = canClickLeaderboardRow(item);
69009
69942
  return /* @__PURE__ */ jsxs(
69010
69943
  "tr",
69011
69944
  {
@@ -69037,7 +69970,13 @@ var LinesLeaderboard = ({
69037
69970
  ] }) : /* @__PURE__ */ jsx("div", { className: "w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center text-gray-500 overflow-hidden border border-gray-200 flex-shrink-0", children: item.supervisorImage ? /* @__PURE__ */ jsx("img", { src: item.supervisorImage, alt: item.supervisorName, className: "w-full h-full object-cover" }) : /* @__PURE__ */ jsx("span", { className: "text-xs font-bold", children: getInitials(item.supervisorName) }) }),
69038
69971
  /* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-gray-900", children: item.supervisorName })
69039
69972
  ] }) }),
69040
- /* @__PURE__ */ jsx("td", { className: "px-4 py-3 whitespace-nowrap text-sm text-gray-500", children: item.line.line_name }),
69973
+ /* @__PURE__ */ jsx("td", { className: "px-4 py-3 whitespace-nowrap text-sm text-gray-500", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
69974
+ /* @__PURE__ */ jsx("span", { className: "font-medium text-gray-700", children: item.displayName }),
69975
+ item.rowType === "area" && /* @__PURE__ */ jsxs("span", { className: "text-xs text-gray-400", children: [
69976
+ item.lines.length,
69977
+ " lines"
69978
+ ] })
69979
+ ] }) }),
69041
69980
  /* @__PURE__ */ jsx("td", { className: "px-4 py-3 whitespace-nowrap text-right", children: /* @__PURE__ */ jsx("div", { className: "flex flex-col items-end", children: /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold text-gray-900", children: formatEfficiency(item.efficiency) }) }) })
69042
69981
  ]
69043
69982
  },
@@ -69315,17 +70254,6 @@ var KPIsOverviewView = ({
69315
70254
  const filterRef = useRef(null);
69316
70255
  const filterButtonRef = useRef(null);
69317
70256
  const [error, setError] = useState(null);
69318
- const [topPerformer, setTopPerformer] = useState({
69319
- name: "Top Performer",
69320
- role: "Sup.",
69321
- unit: "Line",
69322
- periodLabel: (/* @__PURE__ */ new Date()).toLocaleDateString("en-US", { month: "long", year: "numeric" }),
69323
- efficiency: null,
69324
- imageUrl: null,
69325
- initials: "TP"
69326
- });
69327
- const [topPerformerLoading, setTopPerformerLoading] = useState(true);
69328
- const [topPerformerImageError, setTopPerformerImageError] = useState(false);
69329
70257
  const [todayEfficiencyByLineId, setTodayEfficiencyByLineId] = useState(/* @__PURE__ */ new Map());
69330
70258
  const [dailyLoading, setDailyLoading] = useState(false);
69331
70259
  const [dailyError, setDailyError] = useState(null);
@@ -69334,6 +70262,9 @@ var KPIsOverviewView = ({
69334
70262
  const [monthlyError, setMonthlyError] = useState(null);
69335
70263
  const dailyRequestKeyRef = useRef(null);
69336
70264
  const monthlyRequestKeyRef = useRef(null);
70265
+ const dailyFallbackRequestKeyRef = useRef(null);
70266
+ const pendingTabRouteSyncRef = useRef(null);
70267
+ const [scopedDailyFallbackEfficiencyByLineId, setScopedDailyFallbackEfficiencyByLineId] = useState(/* @__PURE__ */ new Map());
69337
70268
  const supabase = useSupabase();
69338
70269
  const { user } = useAuth();
69339
70270
  const dashboardConfig = useDashboardConfig();
@@ -69378,8 +70309,23 @@ var KPIsOverviewView = ({
69378
70309
  const assignedLineIdsForLeaderboard = isSuperAdmin ? void 0 : resolvedAssignedLineIds;
69379
70310
  const leaderboardLinesForView = React144__default.useMemo(() => {
69380
70311
  const targetMode = viewType === "machine" ? "uptime" : "output";
69381
- return leaderboardLines.filter((line) => (line.monitoring_mode ?? "output") === targetMode);
69382
- }, [leaderboardLines, viewType]);
70312
+ const metadataByLineId = new Map(lines.map((line) => [line.id, line]));
70313
+ return leaderboardLines.map((line) => {
70314
+ const metadata = metadataByLineId.get(line.id);
70315
+ return metadata ? {
70316
+ ...line,
70317
+ factory_id: line.factory_id || metadata.factory_id,
70318
+ factory_name: line.factory_name || metadata.factory_name,
70319
+ company_name: line.company_name || metadata.company_name,
70320
+ monitoring_mode: line.monitoring_mode ?? metadata.monitoring_mode,
70321
+ factory_area_id: line.factory_area_id ?? metadata.factory_area_id ?? null,
70322
+ factory_area_key: line.factory_area_key ?? metadata.factory_area_key ?? null,
70323
+ factory_area_name: line.factory_area_name ?? metadata.factory_area_name ?? null,
70324
+ factory_area_sort_order: line.factory_area_sort_order ?? metadata.factory_area_sort_order ?? null,
70325
+ factory_area_enabled: line.factory_area_enabled ?? metadata.factory_area_enabled ?? null
70326
+ } : line;
70327
+ }).filter((line) => (line.monitoring_mode ?? "output") === targetMode);
70328
+ }, [leaderboardLines, lines, viewType]);
69383
70329
  const linesForView = React144__default.useMemo(() => {
69384
70330
  const targetMode = viewType === "machine" ? "uptime" : "output";
69385
70331
  return lines.filter((line) => (line.monitoring_mode ?? "output") === targetMode);
@@ -69499,12 +70445,19 @@ var KPIsOverviewView = ({
69499
70445
  useEffect(() => {
69500
70446
  if (!router.isReady || !hasHydratedLeaderboardRouteState) return;
69501
70447
  if (activeTab === "today" && loading) return;
70448
+ const currentTab = typeof router.query.tab === "string" ? router.query.tab : void 0;
70449
+ const currentRouteTab = currentTab === "leaderboard" ? "leaderboard" : "today";
70450
+ if (currentRouteTab !== activeTab) {
70451
+ if (pendingTabRouteSyncRef.current !== activeTab) {
70452
+ return;
70453
+ }
70454
+ pendingTabRouteSyncRef.current = null;
70455
+ }
69502
70456
  const expectedTab = activeTab === "leaderboard" ? "leaderboard" : void 0;
69503
70457
  const expectedDate = activeTab === "leaderboard" && timeRange === "today" && isHistoricalLeaderboardDaily ? effectiveLeaderboardDate : void 0;
69504
70458
  const expectedShift = expectedDate !== void 0 ? effectiveLeaderboardShiftId.toString() : void 0;
69505
70459
  const expectedFactory = activeTab === "today" && selectedFactoryNode ? selectedFactoryNode.id : void 0;
69506
70460
  const expectedFactoryArea = activeTab === "today" && selectedFactoryNode && selectedFactoryAreaNode ? selectedFactoryAreaNode.id : void 0;
69507
- const currentTab = typeof router.query.tab === "string" ? router.query.tab : void 0;
69508
70461
  const currentDateQuery = typeof router.query.date === "string" ? router.query.date : void 0;
69509
70462
  const currentShiftQuery = typeof router.query.shift === "string" ? router.query.shift : void 0;
69510
70463
  const currentFactoryQuery = getSingleQueryValue(router.query[KPI_FACTORY_QUERY_PARAM]);
@@ -69564,6 +70517,35 @@ var KPIsOverviewView = ({
69564
70517
  });
69565
70518
  return map;
69566
70519
  }, [lineMetrics, lineModeById]);
70520
+ const liveDailyFallbackEfficiencyByLineId = React144__default.useMemo(() => {
70521
+ const map = /* @__PURE__ */ new Map();
70522
+ lineMetricRowsByLineId.forEach((row, lineId) => {
70523
+ const value = Number(row?.avg_efficiency);
70524
+ if (!Number.isFinite(value)) return;
70525
+ const rowDate = typeof row?.date === "string" ? row.date : typeof row?.operational_date === "string" ? row.operational_date : void 0;
70526
+ const rawShiftId = row?.shift_id ?? row?.shiftId;
70527
+ const parsedShiftId = typeof rawShiftId === "number" ? rawShiftId : Number.parseInt(String(rawShiftId ?? ""), 10);
70528
+ const hasScopedRow = rowDate !== void 0 || rawShiftId !== void 0;
70529
+ const matchesSelectedScope = rowDate === effectiveLeaderboardDate && Number.isFinite(parsedShiftId) && parsedShiftId === effectiveLeaderboardShiftId;
70530
+ const canUseUnscopedLiveFallback = !isHistoricalLeaderboardDaily && !hasScopedRow;
70531
+ if (matchesSelectedScope || canUseUnscopedLiveFallback) {
70532
+ map.set(lineId, value);
70533
+ }
70534
+ });
70535
+ return map;
70536
+ }, [
70537
+ effectiveLeaderboardDate,
70538
+ effectiveLeaderboardShiftId,
70539
+ isHistoricalLeaderboardDaily,
70540
+ lineMetricRowsByLineId
70541
+ ]);
70542
+ const dailyFallbackEfficiencyByLineId = React144__default.useMemo(() => {
70543
+ const map = new Map(liveDailyFallbackEfficiencyByLineId);
70544
+ scopedDailyFallbackEfficiencyByLineId.forEach((value, lineId) => {
70545
+ map.set(lineId, value);
70546
+ });
70547
+ return map;
70548
+ }, [liveDailyFallbackEfficiencyByLineId, scopedDailyFallbackEfficiencyByLineId]);
69567
70549
  const kpisByLineId = React144__default.useMemo(() => {
69568
70550
  const map = /* @__PURE__ */ new Map();
69569
70551
  lineMetricRowsByLineId.forEach((row, lineId) => {
@@ -69585,32 +70567,11 @@ var KPIsOverviewView = ({
69585
70567
  () => (leaderboardLines.length > 0 ? leaderboardLines : lines).map((l) => l.id),
69586
70568
  [leaderboardLines, lines]
69587
70569
  );
69588
- const { supervisorNamesByLineId, supervisorsByLineId, allSupervisorsMap } = useSupervisorsByLineIds(supervisorLineIds, {
70570
+ const { supervisorNamesByLineId, supervisorsByLineId } = useSupervisorsByLineIds(supervisorLineIds, {
69589
70571
  enabled: supervisorEnabled && supervisorLineIds.length > 0,
69590
70572
  companyId: resolvedCompanyId,
69591
70573
  useBackend: true
69592
70574
  });
69593
- useEffect(() => {
69594
- let isMounted = true;
69595
- const loadTopPerformer = async () => {
69596
- try {
69597
- const record = await awardsService.getTopPerformer(supabase, resolvedCompanyId);
69598
- if (!isMounted) return;
69599
- if (record) {
69600
- setTopPerformer(buildTopPerformerDisplay(record));
69601
- setTopPerformerImageError(false);
69602
- }
69603
- } catch (err) {
69604
- console.error("[KPIsOverviewView] Failed to load top performer:", err);
69605
- } finally {
69606
- if (isMounted) setTopPerformerLoading(false);
69607
- }
69608
- };
69609
- loadTopPerformer();
69610
- return () => {
69611
- isMounted = false;
69612
- };
69613
- }, [supabase, resolvedCompanyId]);
69614
70575
  useEffect(() => {
69615
70576
  trackCorePageView("KPIs Overview");
69616
70577
  }, []);
@@ -69660,16 +70621,25 @@ var KPIsOverviewView = ({
69660
70621
  `/api/dashboard/leaderboard-lines?company_id=${encodeURIComponent(resolvedCompanyId)}`
69661
70622
  );
69662
70623
  if (!isMounted) return;
69663
- const transformed = (data.lines || []).filter((line) => line.enable !== false).map((line) => ({
69664
- id: line.id,
69665
- line_name: line.line_name,
69666
- factory_id: line.factory_id || "",
69667
- factory_name: "N/A",
69668
- company_id: line.company_id,
69669
- company_name: "",
69670
- enable: line.enable ?? true,
69671
- monitoring_mode: line.monitoring_mode ?? "output"
69672
- }));
70624
+ const metadataByLineId = new Map(lines.map((line) => [line.id, line]));
70625
+ const transformed = (data.lines || []).filter((line) => line.enable !== false).map((line) => {
70626
+ const metadata = metadataByLineId.get(line.id);
70627
+ return {
70628
+ id: line.id,
70629
+ line_name: line.line_name,
70630
+ factory_id: line.factory_id || metadata?.factory_id || "",
70631
+ factory_name: metadata?.factory_name || "N/A",
70632
+ company_id: line.company_id,
70633
+ company_name: metadata?.company_name || "",
70634
+ enable: line.enable ?? true,
70635
+ monitoring_mode: line.monitoring_mode ?? metadata?.monitoring_mode ?? "output",
70636
+ factory_area_id: line.factory_area_id ?? metadata?.factory_area_id ?? null,
70637
+ factory_area_key: line.factory_area_key ?? metadata?.factory_area_key ?? null,
70638
+ factory_area_name: line.factory_area_name ?? metadata?.factory_area_name ?? null,
70639
+ factory_area_sort_order: line.factory_area_sort_order ?? metadata?.factory_area_sort_order ?? null,
70640
+ factory_area_enabled: line.factory_area_enabled ?? metadata?.factory_area_enabled ?? null
70641
+ };
70642
+ });
69673
70643
  setLeaderboardLines(transformed);
69674
70644
  } catch (err) {
69675
70645
  console.error("[KPIsOverviewView] Failed to load leaderboard lines:", err);
@@ -69684,6 +70654,58 @@ var KPIsOverviewView = ({
69684
70654
  isMounted = false;
69685
70655
  };
69686
70656
  }, [supabase, resolvedCompanyId, lines]);
70657
+ useEffect(() => {
70658
+ if (activeTab !== "leaderboard" || timeRange !== "today") return;
70659
+ if (!supabase || !resolvedCompanyId || !effectiveLeaderboardDate || leaderboardLinesForView.length === 0) {
70660
+ setScopedDailyFallbackEfficiencyByLineId(/* @__PURE__ */ new Map());
70661
+ return;
70662
+ }
70663
+ const targetLineIds = leaderboardLinesForView.map((line) => line.id);
70664
+ const lineIdsKey = targetLineIds.slice().sort().join(",");
70665
+ const requestKey = `${effectiveLeaderboardDate}|${effectiveLeaderboardShiftId}|${lineIdsKey}`;
70666
+ if (dailyFallbackRequestKeyRef.current === requestKey) return;
70667
+ dailyFallbackRequestKeyRef.current = requestKey;
70668
+ let isMounted = true;
70669
+ const fetchScopedFallbackEfficiencies = async () => {
70670
+ try {
70671
+ const entries = await lineLeaderboardService.getDailyLineLeaderboard(supabase, {
70672
+ companyId: resolvedCompanyId,
70673
+ date: effectiveLeaderboardDate,
70674
+ shiftId: effectiveLeaderboardShiftId,
70675
+ lineIds: targetLineIds,
70676
+ lineMode: viewType === "machine" ? "uptime" : "output",
70677
+ includeBelowThreshold: true
70678
+ });
70679
+ if (!isMounted) return;
70680
+ const nextMap = /* @__PURE__ */ new Map();
70681
+ entries.forEach((entry) => {
70682
+ const value = Number(entry.avg_efficiency);
70683
+ if (Number.isFinite(value)) {
70684
+ nextMap.set(entry.line_id, value);
70685
+ }
70686
+ });
70687
+ setScopedDailyFallbackEfficiencyByLineId(nextMap);
70688
+ } catch (err) {
70689
+ if (!isMounted) return;
70690
+ console.warn("[KPIsOverviewView] Failed to load daily fallback line efficiencies:", err);
70691
+ setScopedDailyFallbackEfficiencyByLineId(/* @__PURE__ */ new Map());
70692
+ dailyFallbackRequestKeyRef.current = null;
70693
+ }
70694
+ };
70695
+ void fetchScopedFallbackEfficiencies();
70696
+ return () => {
70697
+ isMounted = false;
70698
+ };
70699
+ }, [
70700
+ activeTab,
70701
+ effectiveLeaderboardDate,
70702
+ effectiveLeaderboardShiftId,
70703
+ leaderboardLinesForView,
70704
+ resolvedCompanyId,
70705
+ supabase,
70706
+ timeRange,
70707
+ viewType
70708
+ ]);
69687
70709
  const fetchMonthlyLeaderboard = useCallback(async () => {
69688
70710
  if (!supabase || !resolvedCompanyId || leaderboardLinesForView.length === 0) return;
69689
70711
  const targetLineIds = leaderboardLinesForView.map((line) => line.id);
@@ -69705,10 +70727,11 @@ var KPIsOverviewView = ({
69705
70727
  lineMode: viewType === "machine" ? "uptime" : "output"
69706
70728
  });
69707
70729
  const nextMap = /* @__PURE__ */ new Map();
69708
- targetLineIds.forEach((lineId) => nextMap.set(lineId, 0));
69709
70730
  entries.forEach((entry) => {
69710
70731
  const value = Number(entry.avg_efficiency);
69711
- nextMap.set(entry.line_id, Number.isFinite(value) ? value : 0);
70732
+ if (Number.isFinite(value)) {
70733
+ nextMap.set(entry.line_id, value);
70734
+ }
69712
70735
  });
69713
70736
  setMonthlyEfficiencyByLineId(nextMap);
69714
70737
  trackCoreEvent("Leaderboard Monthly Data Fetched", {
@@ -69755,10 +70778,11 @@ var KPIsOverviewView = ({
69755
70778
  lineMode: viewType === "machine" ? "uptime" : "output"
69756
70779
  });
69757
70780
  const nextMap = /* @__PURE__ */ new Map();
69758
- targetLineIds.forEach((lineId) => nextMap.set(lineId, 0));
69759
70781
  entries.forEach((entry) => {
69760
70782
  const value = Number(entry.avg_efficiency);
69761
- nextMap.set(entry.line_id, Number.isFinite(value) ? value : 0);
70783
+ if (Number.isFinite(value)) {
70784
+ nextMap.set(entry.line_id, value);
70785
+ }
69762
70786
  });
69763
70787
  setTodayEfficiencyByLineId(nextMap);
69764
70788
  } catch (err) {
@@ -69798,69 +70822,6 @@ var KPIsOverviewView = ({
69798
70822
  factoryAreaId: selectedFactoryAreaNode?.id
69799
70823
  });
69800
70824
  }, [activeTab, selectedFactoryNode, selectedFactoryAreaNode]);
69801
- const formatTopPerformerWeek = (periodStart, periodEnd) => {
69802
- const dateToUse = periodStart ? /* @__PURE__ */ new Date(`${periodStart}T00:00:00`) : /* @__PURE__ */ new Date();
69803
- if (Number.isNaN(dateToUse.getTime())) {
69804
- return (/* @__PURE__ */ new Date()).toLocaleDateString("en-US", { month: "long", year: "numeric" });
69805
- }
69806
- return dateToUse.toLocaleDateString("en-US", { month: "long", year: "numeric" });
69807
- };
69808
- const buildTopPerformerDisplay = (record) => {
69809
- const supervisorAvatars = [];
69810
- if (record.supervisors && record.supervisors.length > 0) {
69811
- for (const s of record.supervisors) {
69812
- let supervisorName = "Supervisor";
69813
- if (s.first_name) {
69814
- supervisorName = s.last_name ? `${s.first_name} ${s.last_name}` : s.first_name;
69815
- }
69816
- supervisorAvatars.push({
69817
- userId: s.user_id,
69818
- name: supervisorName,
69819
- imageUrl: s.profile_photo_url || null,
69820
- initials: getInitials(supervisorName)
69821
- });
69822
- }
69823
- }
69824
- let displayName = record.recipient_name || "Supervisor";
69825
- if (record.first_name) {
69826
- displayName = record.last_name ? `${record.first_name} ${record.last_name}` : record.first_name;
69827
- } else if (record.recipient_user_id && allSupervisorsMap?.has(record.recipient_user_id)) {
69828
- const supervisor = allSupervisorsMap.get(record.recipient_user_id);
69829
- if (supervisor) {
69830
- displayName = supervisor.displayName;
69831
- }
69832
- } else if (displayName.includes(".") || displayName.includes("@")) {
69833
- const parts = displayName.split(/[.@]/);
69834
- if (parts.length >= 2) {
69835
- const firstName = parts[0].charAt(0).toUpperCase() + parts[0].slice(1);
69836
- const lastName = parts[1].charAt(0).toUpperCase() + parts[1].slice(1);
69837
- displayName = `${firstName} ${lastName}`;
69838
- } else if (parts.length === 1) {
69839
- displayName = parts[0].charAt(0).toUpperCase() + parts[0].slice(1);
69840
- }
69841
- }
69842
- if (supervisorAvatars.length === 0 && record.recipient_user_id) {
69843
- supervisorAvatars.push({
69844
- userId: record.recipient_user_id,
69845
- name: displayName,
69846
- imageUrl: record.profile_photo_url || null,
69847
- initials: getInitials(displayName)
69848
- });
69849
- }
69850
- const efficiencyValue = typeof record.avg_efficiency === "number" ? record.avg_efficiency : Number.parseFloat(String(record.avg_efficiency));
69851
- const efficiency = Number.isFinite(efficiencyValue) ? efficiencyValue : null;
69852
- const unitLabel = record.winning_line_name || record.unit || "Line";
69853
- return {
69854
- name: displayName,
69855
- role: "Sup.",
69856
- unit: unitLabel,
69857
- periodLabel: formatTopPerformerWeek(record.period_start, record.period_end),
69858
- efficiency,
69859
- imageUrl: record.profile_photo_url || null,
69860
- initials: getInitials(displayName),
69861
- supervisors: supervisorAvatars.length > 0 ? supervisorAvatars : void 0
69862
- };
69863
- };
69864
70825
  const handleLineClick = (line, kpis) => {
69865
70826
  if (!isSuperAdmin && !assignedLineIdSet.has(line.id)) {
69866
70827
  return;
@@ -69908,6 +70869,7 @@ var KPIsOverviewView = ({
69908
70869
  from_page: "kpis_overview",
69909
70870
  lines_count: trackedLineCount
69910
70871
  });
70872
+ pendingTabRouteSyncRef.current = newTab;
69911
70873
  setActiveTab(newTab);
69912
70874
  }, [activeTab, leaderboardLines.length, lines.length]);
69913
70875
  const formatLocalDate2 = useCallback((dateKey) => {
@@ -69932,10 +70894,8 @@ var KPIsOverviewView = ({
69932
70894
  const isMonthlyMode = activeTab === "leaderboard" && timeRange === "monthly";
69933
70895
  const isLeaderboardLoading = timeRange === "today" ? dailyLoading : monthlyLoading;
69934
70896
  const currentEfficiencyMap = timeRange === "today" ? todayEfficiencyByLineId : monthlyEfficiencyByLineId;
69935
- const showLeaderboardLoader = activeTab === "leaderboard" && (leaderboardLinesLoading || isLeaderboardLoading && currentEfficiencyMap.size === 0);
69936
- const showTopPerformerImage = Boolean(topPerformer.imageUrl) && !topPerformerImageError;
69937
- typeof topPerformer.efficiency === "number" && Number.isFinite(topPerformer.efficiency);
69938
- topPerformerLoading ? "--" : typeof topPerformer.efficiency === "number" && Number.isFinite(topPerformer.efficiency) ? `${topPerformer.efficiency.toFixed(1)}%` : "--";
70897
+ const currentFallbackEfficiencyMap = timeRange === "today" ? dailyFallbackEfficiencyByLineId : void 0;
70898
+ const showLeaderboardLoader = activeTab === "leaderboard" && (leaderboardLinesLoading || isLeaderboardLoading && currentEfficiencyMap.size === 0 && (currentFallbackEfficiencyMap?.size ?? 0) === 0);
69939
70899
  const showHistoricalLeaderboardHeader = activeTab === "leaderboard" && timeRange === "today" && isHistoricalLeaderboardDaily;
69940
70900
  const headerDateKey = activeTab === "leaderboard" && timeRange === "today" ? effectiveLeaderboardDate : monthEndDateKey;
69941
70901
  const headerShiftId = showHistoricalLeaderboardHeader ? effectiveLeaderboardShiftId : currentShiftDetails.shiftId;
@@ -70140,72 +71100,6 @@ var KPIsOverviewView = ({
70140
71100
  ] }) : /* @__PURE__ */ jsx("div", { className: "inline-flex items-center px-2.5 py-1 bg-green-100 rounded-full", children: /* @__PURE__ */ jsx("span", { className: "text-xs font-medium text-green-700", children: /* @__PURE__ */ jsx(ISTTimer_default, {}) }) })
70141
71101
  ] })
70142
71102
  ] }),
70143
- activeTab !== "leaderboard" && /* @__PURE__ */ jsx("div", { className: "mt-4 bg-white shadow-md hover:shadow-lg transition-all duration-300 ease-out hover:scale-[1.01] relative rounded-2xl border border-amber-100 pl-2 pr-4 py-1.5 flex items-center justify-between group", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4 min-w-0", children: [
70144
- /* @__PURE__ */ jsxs("div", { className: "relative flex-shrink-0", children: [
70145
- (!topPerformer.supervisors || topPerformer.supervisors.length <= 1) && /* @__PURE__ */ jsx("div", { className: "w-10 h-10 rounded-full border-2 border-amber-100 overflow-hidden bg-amber-50 shadow-sm transition-transform group-hover:scale-105", children: showTopPerformerImage ? /* @__PURE__ */ jsx(
70146
- "img",
70147
- {
70148
- src: topPerformer.imageUrl || "",
70149
- alt: "Top Performer",
70150
- className: "w-full h-full object-cover",
70151
- onError: () => setTopPerformerImageError(true)
70152
- }
70153
- ) : /* @__PURE__ */ jsx("div", { className: "w-full h-full flex items-center justify-center bg-amber-50 text-sm font-bold text-amber-600", children: topPerformer.initials }) }),
70154
- topPerformer.supervisors && topPerformer.supervisors.length > 1 && /* @__PURE__ */ jsxs("div", { className: "flex -space-x-2", children: [
70155
- topPerformer.supervisors.slice(0, 3).map((supervisor, idx) => /* @__PURE__ */ jsxs(
70156
- "div",
70157
- {
70158
- className: "relative inline-block w-9 h-9 rounded-full ring-2 ring-white bg-amber-50 shadow-sm z-0 hover:z-10 transition-all hover:scale-110 group/avatar",
70159
- style: { zIndex: 3 - idx },
70160
- children: [
70161
- supervisor.imageUrl ? /* @__PURE__ */ jsx(
70162
- "img",
70163
- {
70164
- src: supervisor.imageUrl,
70165
- alt: supervisor.name,
70166
- className: "w-full h-full object-cover rounded-full"
70167
- }
70168
- ) : /* @__PURE__ */ jsx("div", { className: "w-full h-full flex items-center justify-center text-xs font-bold text-amber-600 uppercase rounded-full", children: supervisor.initials }),
70169
- /* @__PURE__ */ jsxs("div", { className: "absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-gray-900 text-white text-[10px] font-medium rounded shadow-lg opacity-0 group-hover/avatar:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-20", children: [
70170
- supervisor.name,
70171
- /* @__PURE__ */ jsx("div", { className: "absolute top-full left-1/2 -translate-x-1/2 -mt-[1px] border-4 border-transparent border-t-gray-900" })
70172
- ] })
70173
- ]
70174
- },
70175
- supervisor.userId
70176
- )),
70177
- topPerformer.supervisors.length > 3 && /* @__PURE__ */ jsxs("div", { className: "inline-flex w-9 h-9 rounded-full ring-2 ring-white bg-amber-100 items-center justify-center text-xs font-medium text-amber-700 z-0", children: [
70178
- "+",
70179
- topPerformer.supervisors.length - 3
70180
- ] })
70181
- ] })
70182
- ] }),
70183
- /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
70184
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 leading-none mb-1", children: [
70185
- /* @__PURE__ */ jsx("span", { className: "text-[10px] font-bold text-amber-600 uppercase tracking-widest", children: "Performer of the month" }),
70186
- /* @__PURE__ */ jsx("span", { className: "w-1 h-1 bg-amber-200 rounded-full" }),
70187
- /* @__PURE__ */ jsx("span", { className: "text-[10px] font-semibold text-gray-400", children: topPerformerLoading ? "Loading" : topPerformer.periodLabel })
70188
- ] }),
70189
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 leading-none", children: [
70190
- /* @__PURE__ */ jsx("div", { className: "max-w-[140px]", children: /* @__PURE__ */ jsx(
70191
- FittingTitle,
70192
- {
70193
- title: topPerformer.name,
70194
- as: "span",
70195
- className: "text-sm text-gray-900 font-bold"
70196
- }
70197
- ) }),
70198
- /* @__PURE__ */ jsx("span", { className: "w-px h-3 bg-gray-200 flex-shrink-0" }),
70199
- /* @__PURE__ */ jsx("div", { className: "max-w-[120px]", children: /* @__PURE__ */ jsx(
70200
- FittingTitle,
70201
- {
70202
- title: topPerformer.unit,
70203
- className: "text-xs font-medium text-gray-500"
70204
- }
70205
- ) })
70206
- ] })
70207
- ] })
70208
- ] }) }),
70209
71103
  /* @__PURE__ */ jsx("div", { className: "mt-4 flex justify-center", children: /* @__PURE__ */ jsxs("div", { className: "inline-flex bg-gray-100/80 p-1 rounded-xl w-full", children: [
70210
71104
  /* @__PURE__ */ jsx(
70211
71105
  "button",
@@ -70240,86 +71134,18 @@ var KPIsOverviewView = ({
70240
71134
  /* @__PURE__ */ jsx("h1", { className: "text-2xl md:text-3xl lg:text-4xl font-semibold text-gray-900 tracking-tight", children: activeTab === "leaderboard" ? "Leaderboard" : "Overview" }),
70241
71135
  !showHistoricalLeaderboardHeader && /* @__PURE__ */ jsx("div", { className: "h-2.5 w-2.5 rounded-full ring-4 flex-shrink-0 bg-emerald-500 animate-pulse ring-emerald-500/10" })
70242
71136
  ] }),
70243
- /* @__PURE__ */ jsxs("div", { className: "absolute right-0 top-1/2 -translate-y-1/2 z-10 flex items-center", children: [
70244
- !topPerformerLoading && activeTab !== "leaderboard" && /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-2xl border border-amber-200 shadow-md pl-1.5 pr-4 py-1.5 flex items-center gap-4 transition-all hover:shadow-lg hover:border-amber-300 group", children: [
70245
- /* @__PURE__ */ jsxs("div", { className: "relative", children: [
70246
- (!topPerformer.supervisors || topPerformer.supervisors.length <= 1) && /* @__PURE__ */ jsx("div", { className: "w-10 h-10 rounded-full ring-2 ring-amber-100 overflow-hidden bg-amber-50 shadow-inner flex-shrink-0 transition-transform group-hover:scale-105", children: showTopPerformerImage ? /* @__PURE__ */ jsx(
70247
- "img",
70248
- {
70249
- src: topPerformer.imageUrl || "",
70250
- alt: topPerformer.name,
70251
- className: "w-full h-full object-cover",
70252
- onError: () => setTopPerformerImageError(true)
70253
- }
70254
- ) : /* @__PURE__ */ jsx("div", { className: "w-full h-full flex items-center justify-center text-sm font-bold text-amber-600 uppercase", children: topPerformer.initials }) }),
70255
- topPerformer.supervisors && topPerformer.supervisors.length > 1 && /* @__PURE__ */ jsxs("div", { className: "flex -space-x-2", children: [
70256
- topPerformer.supervisors.slice(0, 3).map((supervisor, idx) => /* @__PURE__ */ jsxs(
70257
- "div",
70258
- {
70259
- className: "relative inline-block w-10 h-10 rounded-full ring-2 ring-white bg-amber-50 shadow-sm z-0 hover:z-10 transition-all hover:scale-110 group/avatar",
70260
- style: { zIndex: 3 - idx },
70261
- children: [
70262
- supervisor.imageUrl ? /* @__PURE__ */ jsx(
70263
- "img",
70264
- {
70265
- src: supervisor.imageUrl,
70266
- alt: supervisor.name,
70267
- className: "w-full h-full object-cover rounded-full"
70268
- }
70269
- ) : /* @__PURE__ */ jsx("div", { className: "w-full h-full flex items-center justify-center text-sm font-bold text-amber-600 uppercase rounded-full", children: supervisor.initials }),
70270
- /* @__PURE__ */ jsxs("div", { className: "absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-2 py-1 bg-gray-900 text-white text-[10px] font-medium rounded shadow-lg opacity-0 group-hover/avatar:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-20", children: [
70271
- supervisor.name,
70272
- /* @__PURE__ */ jsx("div", { className: "absolute top-full left-1/2 -translate-x-1/2 -mt-[1px] border-4 border-transparent border-t-gray-900" })
70273
- ] })
70274
- ]
70275
- },
70276
- supervisor.userId
70277
- )),
70278
- topPerformer.supervisors.length > 3 && /* @__PURE__ */ jsxs("div", { className: "inline-flex w-10 h-10 rounded-full ring-2 ring-white bg-amber-100 items-center justify-center text-sm font-medium text-amber-700 z-0", children: [
70279
- "+",
70280
- topPerformer.supervisors.length - 3
70281
- ] })
70282
- ] })
70283
- ] }),
70284
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col min-w-0", children: [
70285
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-[10px] leading-tight mb-1", children: [
70286
- /* @__PURE__ */ jsx("span", { className: "font-bold text-amber-600 uppercase tracking-widest", children: "Performer of the month" }),
70287
- /* @__PURE__ */ jsx("span", { className: "text-amber-200 opacity-50", children: "\u2022" }),
70288
- /* @__PURE__ */ jsx("span", { className: "font-semibold text-gray-400", children: topPerformer.periodLabel })
70289
- ] }),
70290
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 leading-tight", children: [
70291
- /* @__PURE__ */ jsx("div", { className: "max-w-[140px]", children: /* @__PURE__ */ jsx(
70292
- FittingTitle,
70293
- {
70294
- title: topPerformer.name,
70295
- as: "span",
70296
- className: "text-sm text-gray-900 font-bold"
70297
- }
70298
- ) }),
70299
- /* @__PURE__ */ jsx("span", { className: "w-px h-3.5 bg-gray-200 flex-shrink-0" }),
70300
- /* @__PURE__ */ jsx("div", { className: "max-w-[150px]", children: /* @__PURE__ */ jsx(
70301
- FittingTitle,
70302
- {
70303
- title: topPerformer.unit,
70304
- className: "text-xs font-medium text-gray-500"
70305
- }
70306
- ) })
70307
- ] })
70308
- ] })
70309
- ] }),
70310
- activeTab === "leaderboard" && isHistoricalLeaderboardDaily && /* @__PURE__ */ jsx(
70311
- "button",
70312
- {
70313
- type: "button",
70314
- onClick: () => {
70315
- setSelectedLeaderboardDate(currentShiftDate);
70316
- setSelectedLeaderboardShiftId(currentShiftId);
70317
- },
70318
- className: "text-xs sm:text-sm font-medium text-blue-600 bg-blue-50 border border-blue-100 hover:bg-blue-100 hover:text-blue-700 px-3 py-1.5 rounded-lg transition-colors shadow-sm ml-4 whitespace-nowrap",
70319
- children: "Return to Live"
70320
- }
70321
- )
70322
- ] })
71137
+ /* @__PURE__ */ jsx("div", { className: "absolute right-0 top-1/2 -translate-y-1/2 z-10 flex items-center", children: activeTab === "leaderboard" && isHistoricalLeaderboardDaily && /* @__PURE__ */ jsx(
71138
+ "button",
71139
+ {
71140
+ type: "button",
71141
+ onClick: () => {
71142
+ setSelectedLeaderboardDate(currentShiftDate);
71143
+ setSelectedLeaderboardShiftId(currentShiftId);
71144
+ },
71145
+ className: "text-xs sm:text-sm font-medium text-blue-600 bg-blue-50 border border-blue-100 hover:bg-blue-100 hover:text-blue-700 px-3 py-1.5 rounded-lg transition-colors shadow-sm ml-4 whitespace-nowrap",
71146
+ children: "Return to Live"
71147
+ }
71148
+ ) })
70323
71149
  ] }),
70324
71150
  /* @__PURE__ */ jsx("div", { className: "bg-blue-50/50 px-4 py-2 rounded-xl border border-blue-100/50 backdrop-blur-sm", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center gap-6", children: [
70325
71151
  !isMonthlyMode && !showHistoricalLeaderboardHeader && /* @__PURE__ */ jsxs(Fragment, { children: [
@@ -70494,6 +71320,7 @@ var KPIsOverviewView = ({
70494
71320
  timeRange,
70495
71321
  setTimeRange,
70496
71322
  todayEfficiencyByLineId,
71323
+ dailyFallbackEfficiencyByLineId,
70497
71324
  monthlyEfficiencyByLineId,
70498
71325
  supervisorsByLineId,
70499
71326
  supervisorNamesByLineId,
@@ -70526,13 +71353,23 @@ var AnimatedEfficiency = memo$1(({ value }) => {
70526
71353
  AnimatedEfficiency.displayName = "AnimatedEfficiency";
70527
71354
  var getWorkspaceLeaderboardMetricValue = (workspace) => {
70528
71355
  if (workspace.leaderboard_metric_kind === "recent_flow_shift_average") {
70529
- return toFiniteNumber(workspace.leaderboard_value) ?? toFiniteNumber(workspace.avg_recent_flow);
71356
+ const cycleRatio = getCycleRatio(workspace);
71357
+ return cycleRatio === null ? null : cycleRatio * 100;
70530
71358
  }
70531
71359
  return toFiniteNumber(workspace.leaderboard_value) ?? toFiniteNumber(workspace.efficiency);
70532
71360
  };
70533
71361
  var getWorkspaceDisplayedMetricValue = (workspace) => getWorkspaceLeaderboardMetricValue(workspace);
70534
- var getWorkspaceLeaderboardMetricLabel = (workspace, defaultLabel) => workspace.leaderboard_metric_kind === "recent_flow_shift_average" ? "Avg Flow" : defaultLabel;
71362
+ var getWorkspaceLeaderboardMetricLabel = (workspace, defaultLabel) => workspace.leaderboard_metric_kind === "recent_flow_shift_average" ? "Actual CT / Standard CT" : defaultLabel;
70535
71363
  var renderWorkspaceLeaderboardMetric = (workspace) => {
71364
+ if (workspace.leaderboard_metric_kind === "recent_flow_shift_average") {
71365
+ const actualCT = formatCycleTimeValue(workspace.avg_cycle_time);
71366
+ const standardCT = formatCycleTimeValue(workspace.ideal_cycle_time);
71367
+ return /* @__PURE__ */ jsxs("span", { className: "tabular-nums", children: [
71368
+ actualCT,
71369
+ " / ",
71370
+ standardCT
71371
+ ] });
71372
+ }
70536
71373
  const displayedMetricValue = getWorkspaceDisplayedMetricValue(workspace);
70537
71374
  if (displayedMetricValue === null) {
70538
71375
  return /* @__PURE__ */ jsx("span", { className: "tabular-nums", children: "--" });
@@ -70810,12 +71647,8 @@ var LeaderboardDetailView = memo$1(({
70810
71647
  return `Line ${lineId2.substring(0, 8)}`;
70811
71648
  }, [dbLineNames, configuredLineNames, lineNames, line1Id, line2Id]);
70812
71649
  const configuredLineIds = useMemo(() => {
70813
- const allLineIds = getConfiguredLineIds(entityConfig);
70814
- if (userAccessibleLineIds) {
70815
- return allLineIds.filter((id3) => userAccessibleLineIds.includes(id3));
70816
- }
70817
- return allLineIds;
70818
- }, [entityConfig, userAccessibleLineIds]);
71650
+ return getConfiguredLineIds(entityConfig);
71651
+ }, [entityConfig]);
70819
71652
  const accessibleLineIdSet = useMemo(
70820
71653
  () => new Set((userAccessibleLineIds || []).filter(Boolean)),
70821
71654
  [userAccessibleLineIds]
@@ -71503,7 +72336,7 @@ var LeaderboardDetailView = memo$1(({
71503
72336
  const hasEfficiencyLeaderboardRows = sortedWorkspaces.some(
71504
72337
  (workspace) => workspace.leaderboard_metric_kind !== "recent_flow_shift_average"
71505
72338
  );
71506
- const metricLabel = viewType === "machine" ? "Utilization" : hasRecentFlowLeaderboardRows && !hasEfficiencyLeaderboardRows ? "Avg Flow" : hasRecentFlowLeaderboardRows && hasEfficiencyLeaderboardRows ? "Performance" : "Efficiency";
72339
+ const metricLabel = viewType === "machine" ? "Utilization" : hasRecentFlowLeaderboardRows && !hasEfficiencyLeaderboardRows ? "Actual CT / Standard CT" : hasRecentFlowLeaderboardRows && hasEfficiencyLeaderboardRows ? "Performance" : "Efficiency";
71507
72340
  const descendingSortLabel = "Highest to Lowest";
71508
72341
  const ascendingSortLabel = "Lowest to Highest";
71509
72342
  return /* @__PURE__ */ jsxs("div", { className: `min-h-screen bg-slate-50 flex flex-col ${className}`, style: { willChange: "contents" }, children: [
@@ -86173,4 +87006,4 @@ var RecentFlowSnapshotGrid = ({
86173
87006
  );
86174
87007
  };
86175
87008
 
86176
- export { ACTION_FAMILIES, ACTION_NAMES, AIAgentView_default as AIAgentView, AcceptInvite, AcceptInviteView_default as AcceptInviteView, AdvancedFilterDialog, AdvancedFilterPanel, AudioService, AuthCallback, AuthCallbackView_default as AuthCallbackView, AuthProvider, AuthService, AuthenticatedBottleneckClipsView, AuthenticatedFactoryView, AuthenticatedHelpView, AuthenticatedHomeView, AuthenticatedShiftsView, AuthenticatedTargetsView, AuthenticatedTicketsView, AuthenticatedWorkspaceHealthView, AvatarUpload, AxelNotificationPopup, AxelOrb, BackButton, BackButtonMinimal, BarChart, BaseHistoryCalendar, BottleneckClipsModal, BottleneckClipsView_default as BottleneckClipsView, BottlenecksContent, BreakNotificationPopup, CachePrefetchStatus, Card2 as Card, CardContent2 as CardContent, CardDescription2 as CardDescription, CardFooter2 as CardFooter, CardHeader2 as CardHeader, CardTitle2 as CardTitle, ChangeRoleDialog, ClipFilterProvider, ClipsCostView_default as ClipsCostView, CompactWorkspaceHealthCard, ConfirmRemoveUserDialog, CongratulationsOverlay, CroppedHlsVideoPlayer, CroppedVideoPlayer, CycleTimeChart, CycleTimeOverTimeChart, DEFAULT_ANALYTICS_CONFIG, DEFAULT_AUTH_CONFIG, DEFAULT_CONFIG, DEFAULT_DATABASE_CONFIG, DEFAULT_DATE_TIME_CONFIG, DEFAULT_ENDPOINTS_CONFIG, DEFAULT_ENTITY_CONFIG, DEFAULT_HOME_VIEW_CONFIG, DEFAULT_MAP_VIEW_CONFIG, DEFAULT_SHIFT_CONFIG, DEFAULT_SHIFT_DATA, DEFAULT_THEME_CONFIG, DEFAULT_VIDEO_CONFIG, DEFAULT_WORKSPACE_CONFIG, DEFAULT_WORKSPACE_POSITIONS, DashboardHeader, DashboardLayout, DashboardOverridesProvider, DashboardProvider, DateDisplay_default as DateDisplay, DateTimeDisplay, DebugAuth, DebugAuthView_default as DebugAuthView, DetailedHealthStatus, DiagnosisVideoModal, EFFICIENCY_ON_TRACK_THRESHOLD, EmptyStateMessage, EncouragementOverlay, FactoryAssignmentDropdown, FactoryView_default as FactoryView, FileManagerFilters, FilterDialogTrigger, FirstTimeLoginDebug, FirstTimeLoginHandler, FittingTitle, GaugeChart, GridComponentsPlaceholder, HamburgerButton, Header, HealthDateShiftSelector, HealthStatusGrid, HealthStatusIndicator, HelpView_default as HelpView, HlsVideoPlayer, HomeView_default as HomeView, HourlyOutputChart2 as HourlyOutputChart, HourlyUptimeChart, ISTTimer_default as ISTTimer, IdleTimeVlmConfigProvider, ImprovementCenterView_default as ImprovementCenterView, InlineEditableText, InteractiveOnboardingTour, InvitationService, InvitationsTable, InviteUserDialog, KPICard, KPIDetailView_default as KPIDetailView, KPIGrid, KPIHeader, KPISection, KPIsOverviewView_default as KPIsOverviewView, LINE_1_UUID, LINE_2_UUID, LargeOutputProgressChart, LeaderboardDetailView_default as LeaderboardDetailView, Legend5 as Legend, LineAssignmentDropdown, LineChart, LineHistoryCalendar, LineMonthlyHistory, LineMonthlyPdfGenerator, LinePdfExportButton, LinePdfGenerator, LineWhatsAppShareButton, LinesService, LiveTimer, LoadingInline, LoadingOverlay_default as LoadingOverlay, LoadingPage_default as LoadingPage, LoadingSkeleton, LoadingState, LoginPage, LoginView_default as LoginView, Logo, MainLayout, MapGridView, MetricCard_default as MetricCard, MinimalOnboardingPopup, MobileMenuProvider, NewClipsNotification, NoWorkspaceData, OnboardingDemo, OnboardingTour, OptifyeAgentClient, OptifyeLogoLoader_default as OptifyeLogoLoader, OutputProgressChart, PageHeader, PieChart4 as PieChart, PlantHeadView_default as PlantHeadView, PlayPauseIndicator, PrefetchConfigurationError, PrefetchError, PrefetchEvents, PrefetchStatus, PrefetchTimeoutError, ProfileView_default as ProfileView, ROOT_DASHBOARD_EVENT_NAMES, RecentFlowSnapshotGrid, RegistryProvider, RoleBadge, S3ClipsSupabaseService as S3ClipsService, S3Service, SENTRY_HANDLED_EVENT_SESSION_LIMIT, SENTRY_HANDLED_EVENT_WINDOW_MS, SENTRY_QUOTA_STORAGE_KEY, SKUManagementView, SOPComplianceChart, SSEChatClient, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, SessionTracker, SessionTrackingContext, SessionTrackingProvider, SettingsPopup, ShiftDisplay_default as ShiftDisplay, ShiftsView_default as ShiftsView, SideNavBar, SignupWithInvitation, SilentErrorBoundary, SimpleOnboardingPopup, SingleVideoStream_default as SingleVideoStream, Skeleton, SubscriptionManager, SubscriptionManagerProvider, SupabaseProvider, SupervisorDropdown_default as SupervisorDropdown, SupervisorManagementView_default as SupervisorManagementView, SupervisorService, TargetWorkspaceGrid, TargetsView_default as TargetsView, TeamManagementView_default as TeamManagementView, ThreadSidebar, TicketHistory_default as TicketHistory, TicketHistoryService, TicketsView_default as TicketsView, TimeDisplay_default as TimeDisplay, TimePickerDropdown, Timer_default as Timer, TimezoneProvider, TimezoneService, UptimeDonutChart, UptimeLineChart, UptimeMetricCards, UserAvatar, UserManagementService, UserManagementTable, UserService, UserUsageDetailModal, UserUsageStats, VideoCard, VideoGridView, VideoPlayer, VideoPreloader, WORKSPACE_POSITIONS, WhatsAppShareButton, WorkspaceCard, WorkspaceCycleTimeMetricCards, WorkspaceDetailView_default as WorkspaceDetailView, WorkspaceDisplayNameExample, WorkspaceGrid, WorkspaceGridItem, WorkspaceHealthCard, WorkspaceHealthView_default as WorkspaceHealthView, WorkspaceHistoryCalendar, WorkspaceMetricCards, WorkspaceMetricCardsImpl, WorkspaceMonthlyDataFetcher, WorkspaceMonthlyHistory, WorkspaceMonthlyPdfGenerator, WorkspacePdfExportButton, WorkspacePdfGenerator, WorkspaceWhatsAppShareButton, actionService, addSentryBreadcrumb, aggregateKPIsFromLineMetricsRows, alertsService, apiUtils, areAllLinesOnSameShift, authCoreService, authOTPService, authRateLimitService, awardsService, buildDateKey, buildKPIsFromLineMetricsRow, buildKpiLineHierarchy, buildLineSkuBreakdown, buildShiftGroupsKey, canRoleAccessDashboardPath, canRoleAccessTeamManagement, canRoleAssignFactories, canRoleAssignLines, canRoleChangeRole, canRoleInviteRole, canRoleManageCompany, canRoleManageTargets, canRoleManageUsers, canRoleRemoveUser, canRoleViewClipsCost, canRoleViewUsageStats, captureHandledFrontendException, captureSentryException, captureSentryMessage, checkRateLimit2 as checkRateLimit, clearAllRateLimits2 as clearAllRateLimits, clearRateLimit2 as clearRateLimit, clearS3VideoCache, clearS3VideoFromCache, clearSentryContext, clearWorkspaceDisplayNamesCache, cn, combineLineMetricsRows, countRealSkus, createDefaultKPIs, createInvitationService, createLinesService, createSessionTracker, createStorageService, createStreamProxyHandler, createSupabaseClient, createSupervisorService, createThrottledReload, createUserManagementService, createUserService, dashboardService, deleteThread, fetchIdleTimeReasons, fetchLineDummySkuId, fetchLineSkuCatalog, filterDataByDateKeyRange, filterRealSkuBreakdown, forceRefreshWorkspaceDisplayNames, formatAwardMonth, formatDateInZone, formatDateKeyForDisplay, formatDateTimeInZone, formatDuration2 as formatDuration, formatISTDate, formatIdleTime, formatRangeLabel, formatReasonLabel, formatRelativeTime, formatTimeInZone, fromUrlFriendlyName, getActionDisplayName, getActiveShift, getAllLineDisplayNames, getAllThreadMessages, getAllWorkspaceDisplayNamesAsync, getAllWorkspaceDisplayNamesSnapshot, getAnonClient, getAssignableRoles, getAssignmentColumnLabel, getAvailableShiftIds, getAwardBadgeType, getAwardDescription, getAwardTitle, getBrowserName, getCameraNumber, getCompanyMetricsTableName, getConfigurableShortWorkspaceDisplayName, getConfigurableWorkspaceDisplayName, getConfiguredLineIds, getCoreSessionRecordingProperties, getCoreSessionReplayUrl, getCurrentShift, getCurrentShiftForLine, getCurrentTimeInZone, getCurrentWeekFullRange, getCurrentWeekToDateRange, getDashboardHeaderTimeInZone, getDateKeyFromDate, getDateKeyFromValue, getDayDateKey, getDaysDifferenceInZone, getDefaultCameraStreamUrl, getDefaultLineId, getDefaultTabForWorkspace, getInitials, getLineDisplayName, getManufacturingInsights, getMetricsTablePrefix, getMonthKeyBounds, getMonthWeekRanges, getMonthlyTrendComparisonLabel, getNextUpdateInterval, getOperationalDate, getRoleAssignmentKind, getRoleDescription, getRoleLabel, getRoleMetadata, getRoleNavPaths, getS3SignedUrl, getS3VideoSrc, getShiftData, getShiftNameById, getShiftWorkDurationSeconds, getShortShiftName, getShortWorkspaceDisplayName, getShortWorkspaceDisplayNameAsync, getStoredWorkspaceMappings, getSubscriptionManager, getThreadMessages, getUniformShiftGroup, getUserThreads, getUserThreadsPaginated, getVisibleRolesForCurrentUser, getWorkspaceDisplayName, getWorkspaceDisplayNameAsync, getWorkspaceDisplayNamesMap, getWorkspaceFromUrl, getWorkspaceNavigationParams, groupLinesByShift, hasAnyShiftData, identifyCoreUser, initializeCoreMixpanel, isEfficiencyOnTrack, isFactoryScopedRole, isFullMonthRange, isIgnorableFrontendError, isLegacyConfiguration, isLoopbackHostname, isPrefetchError, isRealSku, isRecentFlowVideoGridMetricMode, isSafari, isSupervisorRole, isTransitionPeriod, isUrlPermanentlyFailed, isValidFactoryViewConfiguration, isValidLineInfoPayload, isValidPrefetchParams, isValidPrefetchStatus, isValidWorkspaceDetailedMetricsPayload, isValidWorkspaceMetricsPayload, isWipGatedVideoGridMetricMode, isWorkspaceDisplayNamesLoaded, isWorkspaceDisplayNamesLoading, lineLeaderboardService, linesService, mergeWithDefaultConfig, migrateLegacyConfiguration, normalizeActionFamily, normalizeDateKeyRange, normalizeDateKeyRangeUnbounded, normalizeRoleLevel, normalizeVideoGridMetricMode, optifyeAgentClient, parseDateKeyToDate, parseS3Uri, pickPreferredLineMetricsRow, preInitializeWorkspaceDisplayNames, preloadS3Video, preloadS3VideoUrl, preloadS3VideosUrl, preloadVideoUrl, preloadVideosUrl, qualityService, realtimeService, refreshWorkspaceDisplayNames, resetCoreMixpanel, resetFailedUrl, resetSentryQuotaForTests, resetSubscriptionManager, resolveDefaultSkuId, resolveLiveSkuId, s3VideoPreloader, selectPreferredLineMetricsRow, setSentryUserContext, setSentryWorkspaceContext, shouldEnableLocalDevTestLogin, shuffleArray, simulateApiDelay, skuService, startCoreSessionRecording, stopCoreSessionRecording, storeWorkspaceMapping, streamProxyConfig, subscribeWorkspaceDisplayNames, throttledReloadDashboard, toUrlFriendlyName, trackCoreEvent, trackCorePageView, transformToChartData, updateThreadTitle, upsertWorkspaceDisplayNameInCache, useAccessControl, useActiveBreaks, useActiveLineId, useAllWorkspaceMetrics, useAnalyticsConfig, useAppTimezone, useAudioService, useAuth, useAuthConfig, useAxelNotifications, useCanSaveTargets, useClipFilter, useClipTypes, useClipTypesWithCounts, useClipsInit, useCompanyClipsCost, useCompanyFastSlowClipFiltersEnabled, useCompanyHasVlmEnabledLine, useCompanyUsersUsage, useComponentOverride, useCustomConfig, useDashboardConfig, useDashboardMetrics, useDatabaseConfig, useDateFormatter, useDateTimeConfig, useDynamicShiftConfig, useEndpointsConfig, useEntityConfig, useFactoryOverviewMetrics, useFeatureFlags, useFormatNumber, useHasLineAccess, useHideMobileHeader, useHistoricWorkspaceMetrics, useHlsStream, useHlsStreamWithCropping, useHookOverride, useHourEndTimer, useHourlyTargetAchievements, useHourlyTargetMisses, useIdleTimeClipClassifications, useIdleTimeReasons, useIdleTimeVlmConfig, useKpiTrends, useLeaderboardMetrics, useLineDetailedMetrics, useLineKPIs, useLineMetrics, useLineShiftConfig, useLineSupervisor, useLineWorkspaceMetrics, useLines, useMessages, useMetrics, useMobileMenu, useMonthlyTrend, useMultiLineShiftConfigs, useNavigation, useOperationalShiftKey, useOptionalSupabase, useOverrides, usePageOverride, usePrefetchClipCounts, useRealtimeLineMetrics, useRegistry, useSKUs, useSessionKeepAlive, useSessionTracking, useSessionTrackingContext, useShiftConfig, useShiftGroups, useShifts, useSubscriptionManager, useSubscriptionManagerSafe, useSupabase, useSupabaseClient, useSupervisorsByLineIds, useTargets, useTeamManagementPermissions, useTheme, useThemeConfig, useThreads, useTicketHistory, useTimezoneContext, useUserLineAccess, useUserUsage, useVideoConfig, useWorkspaceConfig, useWorkspaceDetailedMetrics, useWorkspaceDisplayName, useWorkspaceDisplayNames, useWorkspaceDisplayNamesMap, useWorkspaceHealthById, useWorkspaceHealthLastSeen, useWorkspaceHealthStatus, useWorkspaceMetrics, useWorkspaceNavigation, useWorkspaceOperators, useWorkspaceUptimeTimeline, useWorkspaceVideoStreams, userService, videoPrefetchManager, videoPreloader, weeklyTopPerformerService, whatsappService, withAccessControl, withAuth, withRegistry, withTimezone, workspaceHealthService, workspaceService };
87009
+ export { ACTION_FAMILIES, ACTION_NAMES, AIAgentView_default as AIAgentView, AcceptInvite, AcceptInviteView_default as AcceptInviteView, AdvancedFilterDialog, AdvancedFilterPanel, AudioService, AuthCallback, AuthCallbackView_default as AuthCallbackView, AuthProvider, AuthService, AuthenticatedBottleneckClipsView, AuthenticatedFactoryView, AuthenticatedHelpView, AuthenticatedHomeView, AuthenticatedShiftsView, AuthenticatedTargetsView, AuthenticatedTicketsView, AuthenticatedWorkspaceHealthView, AvatarUpload, AxelNotificationPopup, AxelOrb, BackButton, BackButtonMinimal, BarChart, BaseHistoryCalendar, BottleneckClipsModal, BottleneckClipsView_default as BottleneckClipsView, BottlenecksContent, BreakNotificationPopup, CachePrefetchStatus, Card2 as Card, CardContent2 as CardContent, CardDescription2 as CardDescription, CardFooter2 as CardFooter, CardHeader2 as CardHeader, CardTitle2 as CardTitle, ChangeRoleDialog, ClipFilterProvider, ClipsCostView_default as ClipsCostView, CompactWorkspaceHealthCard, ConfirmRemoveUserDialog, CongratulationsOverlay, CroppedHlsVideoPlayer, CroppedVideoPlayer, CycleTimeChart, CycleTimeOverTimeChart, DEFAULT_ANALYTICS_CONFIG, DEFAULT_AUTH_CONFIG, DEFAULT_CONFIG, DEFAULT_DATABASE_CONFIG, DEFAULT_DATE_TIME_CONFIG, DEFAULT_ENDPOINTS_CONFIG, DEFAULT_ENTITY_CONFIG, DEFAULT_HOME_VIEW_CONFIG, DEFAULT_MAP_VIEW_CONFIG, DEFAULT_SHIFT_CONFIG, DEFAULT_SHIFT_DATA, DEFAULT_THEME_CONFIG, DEFAULT_VIDEO_CONFIG, DEFAULT_WORKSPACE_CONFIG, DEFAULT_WORKSPACE_POSITIONS, DashboardHeader, DashboardLayout, DashboardOverridesProvider, DashboardProvider, DateDisplay_default as DateDisplay, DateTimeDisplay, DebugAuth, DebugAuthView_default as DebugAuthView, DetailedHealthStatus, DiagnosisVideoModal, EFFICIENCY_ON_TRACK_THRESHOLD, EmptyStateMessage, EncouragementOverlay, FactoryAssignmentDropdown, FactoryView_default as FactoryView, FileManagerFilters, FilterDialogTrigger, FirstTimeLoginDebug, FirstTimeLoginHandler, FittingTitle, GaugeChart, GridComponentsPlaceholder, HamburgerButton, Header, HealthDateShiftSelector, HealthStatusGrid, HealthStatusIndicator, HelpView_default as HelpView, HlsVideoPlayer, HomeView_default as HomeView, HourlyOutputChart2 as HourlyOutputChart, HourlyUptimeChart, ISTTimer_default as ISTTimer, IdleTimeVlmConfigProvider, ImprovementCenterView_default as ImprovementCenterView, InlineEditableText, InteractiveOnboardingTour, InvitationService, InvitationsTable, InviteUserDialog, KPICard, KPIDetailView_default as KPIDetailView, KPIGrid, KPIHeader, KPISection, KPIsOverviewView_default as KPIsOverviewView, LINE_1_UUID, LINE_2_UUID, LargeOutputProgressChart, LeaderboardDetailView_default as LeaderboardDetailView, Legend5 as Legend, LineAssignmentDropdown, LineChart, LineHistoryCalendar, LineMonthlyHistory, LineMonthlyPdfGenerator, LinePdfExportButton, LinePdfGenerator, LineWhatsAppShareButton, LinesService, LiveTimer, LoadingInline, LoadingOverlay_default as LoadingOverlay, LoadingPage_default as LoadingPage, LoadingSkeleton, LoadingState, LoginPage, LoginView_default as LoginView, Logo, MainLayout, MapGridView, MetricCard_default as MetricCard, MinimalOnboardingPopup, MobileMenuProvider, NewClipsNotification, NoWorkspaceData, OnboardingDemo, OnboardingTour, OptifyeAgentClient, OptifyeLogoLoader_default as OptifyeLogoLoader, OutputProgressChart, PageHeader, PieChart4 as PieChart, PlantHeadView_default as PlantHeadView, PlayPauseIndicator, PrefetchConfigurationError, PrefetchError, PrefetchEvents, PrefetchStatus, PrefetchTimeoutError, ProfileView_default as ProfileView, ROOT_DASHBOARD_EVENT_NAMES, RecentFlowSnapshotGrid, RegistryProvider, RoleBadge, S3ClipsSupabaseService as S3ClipsService, S3Service, SENTRY_HANDLED_EVENT_SESSION_LIMIT, SENTRY_HANDLED_EVENT_WINDOW_MS, SENTRY_QUOTA_STORAGE_KEY, SKUManagementView, SOPComplianceChart, SSEChatClient, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, SessionTracker, SessionTrackingContext, SessionTrackingProvider, SettingsPopup, ShiftDisplay_default as ShiftDisplay, ShiftsView_default as ShiftsView, SideNavBar, SignupWithInvitation, SilentErrorBoundary, SimpleOnboardingPopup, SingleVideoStream_default as SingleVideoStream, Skeleton, SubscriptionManager, SubscriptionManagerProvider, SupabaseProvider, SupervisorDropdown_default as SupervisorDropdown, SupervisorManagementView_default as SupervisorManagementView, SupervisorService, TargetWorkspaceGrid, TargetsView_default as TargetsView, TeamManagementView_default as TeamManagementView, ThreadSidebar, TicketHistory_default as TicketHistory, TicketHistoryService, TicketsView_default as TicketsView, TimeDisplay_default as TimeDisplay, TimePickerDropdown, Timer_default as Timer, TimezoneProvider, TimezoneService, UptimeDonutChart, UptimeLineChart, UptimeMetricCards, UserAvatar, UserManagementService, UserManagementTable, UserService, UserUsageDetailModal, UserUsageStats, VideoCard, VideoGridView, VideoPlayer, VideoPreloader, WORKSPACE_POSITIONS, WhatsAppShareButton, WorkspaceCard, WorkspaceCycleTimeMetricCards, WorkspaceDetailView_default as WorkspaceDetailView, WorkspaceDisplayNameExample, WorkspaceGrid, WorkspaceGridItem, WorkspaceHealthCard, WorkspaceHealthView_default as WorkspaceHealthView, WorkspaceHistoryCalendar, WorkspaceMetricCards, WorkspaceMetricCardsImpl, WorkspaceMonthlyDataFetcher, WorkspaceMonthlyHistory, WorkspaceMonthlyPdfGenerator, WorkspacePdfExportButton, WorkspacePdfGenerator, WorkspaceWhatsAppShareButton, actionService, addSentryBreadcrumb, aggregateKPIsFromLineMetricsRows, alertsService, apiUtils, areAllLinesOnSameShift, authCoreService, authOTPService, authRateLimitService, awardsService, buildDateKey, buildKPIsFromLineMetricsRow, buildKpiLineHierarchy, buildLineLeaderboardRows, buildLineSkuBreakdown, buildShiftGroupsKey, canRoleAccessDashboardPath, canRoleAccessTeamManagement, canRoleAssignFactories, canRoleAssignLines, canRoleChangeRole, canRoleInviteRole, canRoleManageCompany, canRoleManageTargets, canRoleManageUsers, canRoleRemoveUser, canRoleViewClipsCost, canRoleViewUsageStats, captureHandledFrontendException, captureSentryException, captureSentryMessage, checkRateLimit2 as checkRateLimit, clearAllRateLimits2 as clearAllRateLimits, clearRateLimit2 as clearRateLimit, clearS3VideoCache, clearS3VideoFromCache, clearSentryContext, clearWorkspaceDisplayNamesCache, cn, combineLineMetricsRows, countRealSkus, createDefaultKPIs, createInvitationService, createLinesService, createSessionTracker, createStorageService, createStreamProxyHandler, createSupabaseClient, createSupervisorService, createThrottledReload, createUserManagementService, createUserService, dashboardService, deleteThread, fetchIdleTimeReasons, fetchLineDummySkuId, fetchLineSkuCatalog, filterDataByDateKeyRange, filterRealSkuBreakdown, forceRefreshWorkspaceDisplayNames, formatAwardMonth, formatDateInZone, formatDateKeyForDisplay, formatDateTimeInZone, formatDuration2 as formatDuration, formatISTDate, formatIdleTime, formatRangeLabel, formatReasonLabel, formatRelativeTime, formatTimeInZone, fromUrlFriendlyName, getActionDisplayName, getActiveShift, getAllLineDisplayNames, getAllThreadMessages, getAllWorkspaceDisplayNamesAsync, getAllWorkspaceDisplayNamesSnapshot, getAnonClient, getAssignableRoles, getAssignmentColumnLabel, getAvailableShiftIds, getAwardBadgeType, getAwardDescription, getAwardTitle, getBrowserName, getCameraNumber, getCompanyMetricsTableName, getConfigurableShortWorkspaceDisplayName, getConfigurableWorkspaceDisplayName, getConfiguredLineIds, getCoreSessionRecordingProperties, getCoreSessionReplayUrl, getCurrentShift, getCurrentShiftForLine, getCurrentTimeInZone, getCurrentWeekFullRange, getCurrentWeekToDateRange, getDashboardHeaderTimeInZone, getDateKeyFromDate, getDateKeyFromValue, getDayDateKey, getDaysDifferenceInZone, getDefaultCameraStreamUrl, getDefaultLineId, getDefaultTabForWorkspace, getInitials, getLineDisplayName, getManufacturingInsights, getMetricsTablePrefix, getMonthKeyBounds, getMonthWeekRanges, getMonthlyTrendComparisonLabel, getNextUpdateInterval, getOperationalDate, getRoleAssignmentKind, getRoleDescription, getRoleLabel, getRoleMetadata, getRoleNavPaths, getS3SignedUrl, getS3VideoSrc, getShiftData, getShiftNameById, getShiftWorkDurationSeconds, getShortShiftName, getShortWorkspaceDisplayName, getShortWorkspaceDisplayNameAsync, getStoredWorkspaceMappings, getSubscriptionManager, getThreadMessages, getUniformShiftGroup, getUserThreads, getUserThreadsPaginated, getVisibleRolesForCurrentUser, getWorkspaceDisplayName, getWorkspaceDisplayNameAsync, getWorkspaceDisplayNamesMap, getWorkspaceFromUrl, getWorkspaceNavigationParams, groupLinesByShift, hasAnyShiftData, identifyCoreUser, initializeCoreMixpanel, isEfficiencyOnTrack, isFactoryScopedRole, isFullMonthRange, isIgnorableFrontendError, isLegacyConfiguration, isLoopbackHostname, isPrefetchError, isRealSku, isRecentFlowVideoGridMetricMode, isSafari, isSupervisorRole, isTransitionPeriod, isUrlPermanentlyFailed, isValidFactoryViewConfiguration, isValidLineInfoPayload, isValidPrefetchParams, isValidPrefetchStatus, isValidWorkspaceDetailedMetricsPayload, isValidWorkspaceMetricsPayload, isWipGatedVideoGridMetricMode, isWorkspaceDisplayNamesLoaded, isWorkspaceDisplayNamesLoading, lineLeaderboardService, linesService, mergeWithDefaultConfig, migrateLegacyConfiguration, normalizeActionFamily, normalizeDateKeyRange, normalizeDateKeyRangeUnbounded, normalizeRoleLevel, normalizeVideoGridMetricMode, optifyeAgentClient, parseDateKeyToDate, parseS3Uri, pickPreferredLineMetricsRow, preInitializeWorkspaceDisplayNames, preloadS3Video, preloadS3VideoUrl, preloadS3VideosUrl, preloadVideoUrl, preloadVideosUrl, qualityService, realtimeService, refreshWorkspaceDisplayNames, resetCoreMixpanel, resetFailedUrl, resetSentryQuotaForTests, resetSubscriptionManager, resolveDefaultSkuId, resolveLiveSkuId, s3VideoPreloader, selectPreferredLineMetricsRow, setSentryUserContext, setSentryWorkspaceContext, shouldEnableLocalDevTestLogin, shuffleArray, simulateApiDelay, skuService, startCoreSessionRecording, stopCoreSessionRecording, storeWorkspaceMapping, streamProxyConfig, subscribeWorkspaceDisplayNames, throttledReloadDashboard, toUrlFriendlyName, trackCoreEvent, trackCorePageView, transformToChartData, updateThreadTitle, upsertWorkspaceDisplayNameInCache, useAccessControl, useActiveBreaks, useActiveLineId, useAllWorkspaceMetrics, useAnalyticsConfig, useAppTimezone, useAudioService, useAuth, useAuthConfig, useAxelNotifications, useCanSaveTargets, useClipFilter, useClipTypes, useClipTypesWithCounts, useClipsInit, useCompanyClipsCost, useCompanyFastSlowClipFiltersEnabled, useCompanyHasVlmEnabledLine, useCompanyUsersUsage, useComponentOverride, useCustomConfig, useDashboardConfig, useDashboardMetrics, useDatabaseConfig, useDateFormatter, useDateTimeConfig, useDynamicShiftConfig, useEndpointsConfig, useEntityConfig, useFactoryOverviewMetrics, useFeatureFlags, useFormatNumber, useHasLineAccess, useHideMobileHeader, useHistoricWorkspaceMetrics, useHlsStream, useHlsStreamWithCropping, useHookOverride, useHourEndTimer, useHourlyTargetAchievements, useHourlyTargetMisses, useIdleTimeClipClassifications, useIdleTimeReasons, useIdleTimeVlmConfig, useKpiTrends, useLeaderboardMetrics, useLineDetailedMetrics, useLineKPIs, useLineMetrics, useLineShiftConfig, useLineSupervisor, useLineWorkspaceMetrics, useLines, useMessages, useMetrics, useMobileMenu, useMonthlyTrend, useMultiLineShiftConfigs, useNavigation, useOperationalShiftKey, useOptionalSupabase, useOverrides, usePageOverride, usePrefetchClipCounts, useRealtimeLineMetrics, useRegistry, useSKUs, useSessionKeepAlive, useSessionTracking, useSessionTrackingContext, useShiftConfig, useShiftGroups, useShifts, useSubscriptionManager, useSubscriptionManagerSafe, useSupabase, useSupabaseClient, useSupervisorsByLineIds, useTargets, useTeamManagementPermissions, useTheme, useThemeConfig, useThreads, useTicketHistory, useTimezoneContext, useUserLineAccess, useUserUsage, useVideoConfig, useWorkspaceConfig, useWorkspaceDetailedMetrics, useWorkspaceDisplayName, useWorkspaceDisplayNames, useWorkspaceDisplayNamesMap, useWorkspaceHealthById, useWorkspaceHealthLastSeen, useWorkspaceHealthStatus, useWorkspaceMetrics, useWorkspaceNavigation, useWorkspaceOperators, useWorkspaceUptimeTimeline, useWorkspaceVideoStreams, userService, videoPrefetchManager, videoPreloader, weeklyTopPerformerService, whatsappService, withAccessControl, withAuth, withRegistry, withTimezone, workspaceHealthService, workspaceService };