@optifye/dashboard-core 6.12.5 → 6.12.7

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, 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, 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';
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';
@@ -5228,46 +5228,83 @@ var dashboardService = {
5228
5228
  const dbConfig = config.databaseConfig ?? DEFAULT_DATABASE_CONFIG;
5229
5229
  const linesTable = getTable(dbConfig, "lines");
5230
5230
  const companyId = config.entityConfig?.companyId;
5231
+ const baseLineSelect = `
5232
+ id,
5233
+ line_name,
5234
+ factory_id,
5235
+ factories!lines_factory_id_fkey(factory_name),
5236
+ company_id,
5237
+ companies!lines_company_id_fkey(company_name:name),
5238
+ enable,
5239
+ monitoring_mode,
5240
+ assembly,
5241
+ video_grid_metric_mode,
5242
+ recent_flow_window_minutes
5243
+ `;
5244
+ const lineSelectWithArea = `
5245
+ ${baseLineSelect},
5246
+ factory_area_id,
5247
+ factory_line_areas!lines_factory_area_id_factory_id_fkey(
5248
+ area_key,
5249
+ area_name,
5250
+ sort_order,
5251
+ enabled
5252
+ )
5253
+ `;
5254
+ const shouldRetryWithoutFactoryArea = (error) => {
5255
+ const errorText = [
5256
+ error?.message,
5257
+ error?.details,
5258
+ error?.hint,
5259
+ error?.code
5260
+ ].filter(Boolean).join(" ").toLowerCase();
5261
+ return errorText.includes("factory_area_id") || errorText.includes("factory_line_areas") || errorText.includes("lines_factory_area_id_factory_id_fkey");
5262
+ };
5231
5263
  try {
5232
- let query = supabase.from(linesTable).select(`
5233
- id,
5234
- line_name,
5235
- factory_id,
5236
- factories!lines_factory_id_fkey(factory_name),
5237
- company_id,
5238
- companies!lines_company_id_fkey(company_name:name),
5239
- enable,
5240
- monitoring_mode,
5241
- assembly,
5242
- video_grid_metric_mode,
5243
- recent_flow_window_minutes
5244
- `).eq("enable", true);
5245
- if (companyId) {
5246
- query = query.eq("company_id", companyId);
5247
- }
5248
- const { data, error } = await query;
5264
+ const fetchLines = async (selectClause) => {
5265
+ let query = supabase.from(linesTable).select(selectClause).eq("enable", true);
5266
+ if (companyId) {
5267
+ query = query.eq("company_id", companyId);
5268
+ }
5269
+ return await query;
5270
+ };
5271
+ let { data, error } = await fetchLines(lineSelectWithArea);
5272
+ if (error && shouldRetryWithoutFactoryArea(error)) {
5273
+ console.warn("[dashboardService.getAllLines] Factory area metadata unavailable, falling back to line-only metadata:", error);
5274
+ const fallbackResult = await fetchLines(baseLineSelect);
5275
+ data = fallbackResult.data;
5276
+ error = fallbackResult.error;
5277
+ }
5249
5278
  if (error) {
5250
5279
  console.error("Error fetching all lines:", error);
5251
5280
  throw error;
5252
5281
  }
5253
5282
  if (!data) return [];
5254
- const transformedLines = data.map((line) => ({
5255
- id: line.id,
5256
- line_name: line.line_name,
5257
- factory_id: line.factory_id,
5258
- factory_name: line.factories?.factory_name ?? "N/A",
5259
- company_id: line.company_id,
5260
- company_name: line.companies?.company_name ?? "N/A",
5261
- enable: line.enable ?? true,
5262
- // Default to true if not specified
5263
- monitoring_mode: line.monitoring_mode ?? "output",
5264
- assembly: line.assembly ?? false,
5265
- video_grid_metric_mode: normalizeVideoGridMetricMode(
5266
- line.video_grid_metric_mode,
5267
- line.assembly ?? false
5268
- ),
5269
- recent_flow_window_minutes: line.recent_flow_window_minutes ?? 7
5270
- }));
5283
+ const transformedLines = data.map((line) => {
5284
+ const factoryArea = Array.isArray(line.factory_line_areas) ? line.factory_line_areas[0] : line.factory_line_areas;
5285
+ return {
5286
+ id: line.id,
5287
+ line_name: line.line_name,
5288
+ factory_id: line.factory_id,
5289
+ factory_name: line.factories?.factory_name ?? "N/A",
5290
+ company_id: line.company_id,
5291
+ company_name: line.companies?.company_name ?? "N/A",
5292
+ enable: line.enable ?? true,
5293
+ // Default to true if not specified
5294
+ monitoring_mode: line.monitoring_mode ?? "output",
5295
+ assembly: line.assembly ?? false,
5296
+ video_grid_metric_mode: normalizeVideoGridMetricMode(
5297
+ line.video_grid_metric_mode,
5298
+ line.assembly ?? false
5299
+ ),
5300
+ recent_flow_window_minutes: line.recent_flow_window_minutes ?? 7,
5301
+ factory_area_id: line.factory_area_id ?? null,
5302
+ factory_area_key: factoryArea?.area_key ?? null,
5303
+ factory_area_name: factoryArea?.area_name ?? null,
5304
+ factory_area_sort_order: factoryArea?.sort_order ?? null,
5305
+ factory_area_enabled: factoryArea?.enabled ?? null
5306
+ };
5307
+ });
5271
5308
  return transformedLines;
5272
5309
  } catch (err) {
5273
5310
  console.error("Exception in getAllLines:", err);
@@ -14236,7 +14273,9 @@ var useLeaderboardMetrics = (date, shiftId, limit = 10, filter2 = "all") => {
14236
14273
  `/api/dashboard/leaderboard?${params.toString()}`
14237
14274
  );
14238
14275
  let entries = (data.entries || []).slice();
14239
- entries.sort((a, b) => (b.efficiency || 0) - (a.efficiency || 0));
14276
+ entries.sort(
14277
+ (a, b) => (b.leaderboard_value ?? b.efficiency ?? 0) - (a.leaderboard_value ?? a.efficiency ?? 0)
14278
+ );
14240
14279
  if (filter2 === "top") {
14241
14280
  entries = entries.slice(0, limit);
14242
14281
  } else if (filter2 === "bottom") {
@@ -21873,6 +21912,24 @@ var getConfigurableShortWorkspaceDisplayName = (workspaceId, workspaceConfig, li
21873
21912
  return fullName;
21874
21913
  };
21875
21914
 
21915
+ // src/lib/utils/efficiencyValidity.ts
21916
+ var MIN_VALID_OUTPUT_EFFICIENCY = 5;
21917
+ var MIN_VALID_UPTIME_EFFICIENCY = 1;
21918
+ var normalizeMonitoringMode = (mode) => String(mode ?? "").trim().toLowerCase() === "uptime" ? "uptime" : "output";
21919
+ var toFiniteNumberOrNull = (value) => {
21920
+ if (typeof value === "number" && Number.isFinite(value)) return value;
21921
+ if (typeof value === "string" && value.trim() !== "") {
21922
+ const parsed = Number(value);
21923
+ return Number.isFinite(parsed) ? parsed : null;
21924
+ }
21925
+ return null;
21926
+ };
21927
+ var isValidAggregateEfficiency = (monitoringMode, efficiency) => {
21928
+ const value = toFiniteNumberOrNull(efficiency);
21929
+ if (value === null) return false;
21930
+ return normalizeMonitoringMode(monitoringMode) === "uptime" ? value >= MIN_VALID_UPTIME_EFFICIENCY : value >= MIN_VALID_OUTPUT_EFFICIENCY;
21931
+ };
21932
+
21876
21933
  // src/lib/utils/kpis.ts
21877
21934
  var toNumber = (value) => {
21878
21935
  if (typeof value === "number" && Number.isFinite(value)) return value;
@@ -21928,7 +21985,9 @@ var buildKPIsFromLineMetricsRow = (row) => {
21928
21985
  };
21929
21986
  var aggregateKPIsFromLineMetricsRows = (rows) => {
21930
21987
  if (!rows || rows.length === 0) return createDefaultKPIs();
21931
- const eligibleRows = rows.filter((row) => toNumber(row?.avg_efficiency) >= 5);
21988
+ const eligibleRows = rows.filter(
21989
+ (row) => isValidAggregateEfficiency(row?.monitoring_mode ?? row?.monitoringMode, row?.avg_efficiency)
21990
+ );
21932
21991
  if (eligibleRows.length === 0) return createDefaultKPIs();
21933
21992
  const currentOutputSum = eligibleRows.reduce((sum, row) => sum + toNumber(row.current_output), 0);
21934
21993
  const lineThresholdSum = eligibleRows.reduce(
@@ -21980,6 +22039,84 @@ var aggregateKPIsFromLineMetricsRows = (rows) => {
21980
22039
  };
21981
22040
  };
21982
22041
 
22042
+ // src/lib/utils/kpiHierarchy.ts
22043
+ var FACTORY_LEVEL_MIN_FACTORY_COUNT = 3;
22044
+ var compareText = (left, right) => left.localeCompare(right, void 0, { sensitivity: "base", numeric: true });
22045
+ var compareLinesByName = (left, right) => compareText(left.line_name || "", right.line_name || "");
22046
+ var normalizeAreaSortOrder = (value) => {
22047
+ if (typeof value === "number" && Number.isFinite(value)) return value;
22048
+ if (typeof value === "string" && value.trim() !== "") {
22049
+ const parsed = Number(value);
22050
+ return Number.isFinite(parsed) ? parsed : null;
22051
+ }
22052
+ return null;
22053
+ };
22054
+ var getEnabledAreaInfo = (line) => {
22055
+ if (!line.factory_area_id) return null;
22056
+ if (line.factory_area_enabled !== true) return null;
22057
+ if (!line.factory_area_name || line.factory_area_name.trim().length === 0) return null;
22058
+ return {
22059
+ id: line.factory_area_id,
22060
+ areaName: line.factory_area_name,
22061
+ areaKey: line.factory_area_key ?? null,
22062
+ sortOrder: normalizeAreaSortOrder(line.factory_area_sort_order)
22063
+ };
22064
+ };
22065
+ var buildKpiLineHierarchy = (lines) => {
22066
+ const factoryMap = /* @__PURE__ */ new Map();
22067
+ lines.forEach((line) => {
22068
+ const factoryId = line.factory_id || "unknown-factory";
22069
+ let factory = factoryMap.get(factoryId);
22070
+ if (!factory) {
22071
+ factory = {
22072
+ id: factoryId,
22073
+ factoryName: line.factory_name || "Factory",
22074
+ lines: [],
22075
+ areas: [],
22076
+ ungroupedLines: [],
22077
+ areaMap: /* @__PURE__ */ new Map()
22078
+ };
22079
+ factoryMap.set(factoryId, factory);
22080
+ }
22081
+ factory.lines.push(line);
22082
+ const areaInfo = getEnabledAreaInfo(line);
22083
+ if (!areaInfo) {
22084
+ factory.ungroupedLines.push(line);
22085
+ return;
22086
+ }
22087
+ let area = factory.areaMap.get(areaInfo.id);
22088
+ if (!area) {
22089
+ area = {
22090
+ id: areaInfo.id,
22091
+ areaName: areaInfo.areaName,
22092
+ areaKey: areaInfo.areaKey,
22093
+ sortOrder: areaInfo.sortOrder,
22094
+ lines: []
22095
+ };
22096
+ factory.areaMap.set(areaInfo.id, area);
22097
+ factory.areas.push(area);
22098
+ }
22099
+ area.lines.push(line);
22100
+ });
22101
+ const factories = Array.from(factoryMap.values()).map(({ areaMap: _areaMap, ...factory }) => {
22102
+ factory.lines.sort(compareLinesByName);
22103
+ factory.ungroupedLines.sort(compareLinesByName);
22104
+ factory.areas.forEach((area) => area.lines.sort(compareLinesByName));
22105
+ factory.areas.sort((left, right) => {
22106
+ const leftOrder = left.sortOrder ?? Number.POSITIVE_INFINITY;
22107
+ const rightOrder = right.sortOrder ?? Number.POSITIVE_INFINITY;
22108
+ if (leftOrder !== rightOrder) return leftOrder - rightOrder;
22109
+ return compareText(left.areaName, right.areaName);
22110
+ });
22111
+ return factory;
22112
+ });
22113
+ factories.sort((left, right) => compareText(left.factoryName, right.factoryName));
22114
+ return {
22115
+ factories,
22116
+ showFactoryLevel: factories.length >= FACTORY_LEVEL_MIN_FACTORY_COUNT
22117
+ };
22118
+ };
22119
+
21983
22120
  // src/lib/utils/awards.ts
21984
22121
  var toNumber2 = (value) => {
21985
22122
  if (typeof value === "number" && Number.isFinite(value)) return value;
@@ -37256,8 +37393,8 @@ var HourlyOutputChart = React144__default.memo(
37256
37393
  HourlyOutputChart.displayName = "HourlyOutputChart";
37257
37394
 
37258
37395
  // src/components/dashboard/grid/videoGridMetricUtils.ts
37396
+ var VIDEO_GRID_LEGEND_LABEL = "Real-Time efficiency";
37259
37397
  var MAP_GRID_LEGEND_LABEL = "Efficiency";
37260
- var MIXED_VIDEO_GRID_LEGEND_LABEL = "Live Efficiency";
37261
37398
  var isFiniteNumber2 = (value) => typeof value === "number" && Number.isFinite(value);
37262
37399
  var isVideoGridRecentFlowEnabled = (workspace) => isRecentFlowVideoGridMetricMode(
37263
37400
  workspace.video_grid_metric_mode,
@@ -37269,7 +37406,7 @@ var isVideoGridWipGated = (workspace) => isWipGatedVideoGridMetricMode(
37269
37406
  );
37270
37407
  var hasVideoGridRecentFlow = (workspace) => isVideoGridRecentFlowEnabled(workspace) && isFiniteNumber2(workspace.recent_flow_percent);
37271
37408
  var isVideoGridRecentFlowUnavailable = (workspace) => isVideoGridRecentFlowEnabled(workspace) && !hasVideoGridRecentFlow(workspace);
37272
- var getVideoGridMetricValue = (workspace) => {
37409
+ var getRawVideoGridMetricValue = (workspace) => {
37273
37410
  const recentFlowPercent = workspace.recent_flow_percent;
37274
37411
  if (hasVideoGridRecentFlow(workspace) && isFiniteNumber2(recentFlowPercent)) {
37275
37412
  return recentFlowPercent;
@@ -37281,7 +37418,7 @@ var getVideoGridMetricValue = (workspace) => {
37281
37418
  };
37282
37419
  var hasIncomingWipMapping = (workspace) => Boolean(workspace.incoming_wip_buffer_name);
37283
37420
  var getVideoGridBaseColorState = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) => {
37284
- const metricValue = getVideoGridMetricValue(workspace);
37421
+ const metricValue = getRawVideoGridMetricValue(workspace);
37285
37422
  if (!isFiniteNumber2(metricValue)) {
37286
37423
  return "neutral";
37287
37424
  }
@@ -37305,6 +37442,25 @@ var isLowWipGreenOverride = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) => {
37305
37442
  }
37306
37443
  return isFiniteNumber2(workspace.incoming_wip_current) && workspace.incoming_wip_current <= 1;
37307
37444
  };
37445
+ var isHighEfficiencyRedFlowOverride = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) => {
37446
+ if (workspace.scheduled_break_active === true) {
37447
+ return false;
37448
+ }
37449
+ if (workspace.recent_flow_forced_zero_after_shift === true) {
37450
+ return false;
37451
+ }
37452
+ if (!hasVideoGridRecentFlow(workspace) || !isVideoGridWipGated(workspace)) {
37453
+ return false;
37454
+ }
37455
+ if (isLowWipGreenOverride(workspace, legend)) {
37456
+ return false;
37457
+ }
37458
+ if (getVideoGridBaseColorState(workspace, legend) !== "red") {
37459
+ return false;
37460
+ }
37461
+ return isFiniteNumber2(workspace.efficiency) && workspace.efficiency > 100;
37462
+ };
37463
+ var getVideoGridMetricValue = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) => isHighEfficiencyRedFlowOverride(workspace, legend) ? workspace.efficiency : getRawVideoGridMetricValue(workspace);
37308
37464
  var toMinuteBucket = (minuteBucket) => Number.isFinite(minuteBucket) ? Math.floor(minuteBucket) : Math.floor(Date.now() / 6e4);
37309
37465
  var getEffectiveFlowMinuteBucket = (workspace) => {
37310
37466
  const effectiveAt = workspace.recent_flow_effective_end_at;
@@ -37330,7 +37486,7 @@ var getSyntheticLowWipDisplayValue = (workspace, minuteBucket) => {
37330
37486
  const offset = (hashWorkspaceKey(workspace) % 11 + bucket % 11 + 11) % 11;
37331
37487
  return 100 + offset;
37332
37488
  };
37333
- var getVideoGridDisplayValue = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND, minuteBucket) => isLowWipGreenOverride(workspace, legend) ? getSyntheticLowWipDisplayValue(workspace, minuteBucket) : getVideoGridMetricValue(workspace);
37489
+ var getVideoGridDisplayValue = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND, minuteBucket) => isLowWipGreenOverride(workspace, legend) ? getSyntheticLowWipDisplayValue(workspace, minuteBucket) : getVideoGridMetricValue(workspace, legend);
37334
37490
  var getVideoGridColorState = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) => {
37335
37491
  const baseColor = getVideoGridBaseColorState(workspace, legend);
37336
37492
  if (!hasVideoGridRecentFlow(workspace)) {
@@ -37342,15 +37498,18 @@ var getVideoGridColorState = (workspace, legend = DEFAULT_EFFICIENCY_LEGEND) =>
37342
37498
  if (baseColor !== "red") {
37343
37499
  return baseColor;
37344
37500
  }
37501
+ if (isLowWipGreenOverride(workspace, legend)) {
37502
+ return "green";
37503
+ }
37504
+ if (isHighEfficiencyRedFlowOverride(workspace, legend)) {
37505
+ return getEfficiencyColor(workspace.efficiency, legend);
37506
+ }
37345
37507
  if (!hasIncomingWipMapping(workspace)) {
37346
37508
  return baseColor;
37347
37509
  }
37348
37510
  if (!isFiniteNumber2(workspace.incoming_wip_current)) {
37349
37511
  return "neutral";
37350
37512
  }
37351
- if (isLowWipGreenOverride(workspace, legend)) {
37352
- return "green";
37353
- }
37354
37513
  return baseColor;
37355
37514
  };
37356
37515
  var getVideoGridLegendLabel = (workspaces) => {
@@ -37358,21 +37517,7 @@ var getVideoGridLegendLabel = (workspaces) => {
37358
37517
  if (visibleWorkspaces.length === 0) {
37359
37518
  return MAP_GRID_LEGEND_LABEL;
37360
37519
  }
37361
- const recentFlowEnabledCount = visibleWorkspaces.filter(isVideoGridRecentFlowEnabled).length;
37362
- if (recentFlowEnabledCount === 0) {
37363
- return MAP_GRID_LEGEND_LABEL;
37364
- }
37365
- const recentFlowWindows = new Set(
37366
- visibleWorkspaces.filter(isVideoGridRecentFlowEnabled).map((workspace) => workspace.recent_flow_window_minutes ?? 7).filter((value) => typeof value === "number" && Number.isFinite(value))
37367
- );
37368
- if (recentFlowEnabledCount === visibleWorkspaces.length) {
37369
- if (recentFlowWindows.size === 1) {
37370
- const [windowMinutes] = Array.from(recentFlowWindows);
37371
- return `${windowMinutes} Minute Efficiency`;
37372
- }
37373
- return MIXED_VIDEO_GRID_LEGEND_LABEL;
37374
- }
37375
- return MIXED_VIDEO_GRID_LEGEND_LABEL;
37520
+ return visibleWorkspaces.some(isVideoGridRecentFlowEnabled) ? VIDEO_GRID_LEGEND_LABEL : MAP_GRID_LEGEND_LABEL;
37376
37521
  };
37377
37522
  function getTrendArrowAndColor(trend) {
37378
37523
  if (trend > 0) {
@@ -37415,14 +37560,15 @@ var VideoCard = React144__default.memo(({
37415
37560
  const showOffline = Boolean(isStreamStale);
37416
37561
  const lastSeenText = lastSeenLabel || "Unknown";
37417
37562
  const workspaceDisplayName = displayName || workspace.displayName || workspace.workspace_name;
37418
- const videoGridMetricValue = getVideoGridMetricValue(workspace);
37563
+ const videoGridMetricValue = getVideoGridMetricValue(workspace, effectiveLegend);
37419
37564
  const videoGridDisplayValue = getVideoGridDisplayValue(workspace, effectiveLegend, displayMinuteBucket);
37420
37565
  const videoGridColorState = getVideoGridColorState(workspace, effectiveLegend);
37421
37566
  const isRecentFlowCard = isVideoGridRecentFlowEnabled(workspace);
37567
+ const isHighEfficiencyOverride = isHighEfficiencyRedFlowOverride(workspace, effectiveLegend);
37422
37568
  const hasDisplayMetric = typeof videoGridDisplayValue === "number" && Number.isFinite(videoGridDisplayValue);
37423
37569
  const hasBarMetric = typeof videoGridMetricValue === "number" && Number.isFinite(videoGridMetricValue);
37424
37570
  const shouldRenderMetricBadge = hasDisplayMetric;
37425
- const badgeTitle = hasVideoGridRecentFlow(workspace) ? `Flow ${Math.round(videoGridDisplayValue ?? 0)}%` : isRecentFlowCard ? "Flow unavailable" : `Efficiency ${Math.round(videoGridDisplayValue ?? 0)}%`;
37571
+ const badgeTitle = isHighEfficiencyOverride ? `Efficiency ${Math.round(videoGridDisplayValue ?? 0)}%` : hasVideoGridRecentFlow(workspace) ? `Flow ${Math.round(videoGridDisplayValue ?? 0)}%` : isRecentFlowCard ? "Flow unavailable" : `Efficiency ${Math.round(videoGridDisplayValue ?? 0)}%`;
37426
37572
  const badgeLabel = `${Math.round(videoGridDisplayValue ?? 0)}%`;
37427
37573
  const efficiencyOverlayClass = videoGridColorState === "green" ? "bg-[#00D654]/25" : videoGridColorState === "yellow" ? "bg-[#FFD700]/30" : videoGridColorState === "red" ? "bg-[#FF2D0A]/30" : "bg-transparent";
37428
37574
  const efficiencyBarClass = videoGridColorState === "green" ? "bg-[#00AB45]" : videoGridColorState === "yellow" ? "bg-[#FFB020]" : videoGridColorState === "red" ? "bg-[#E34329]" : "bg-gray-500/70";
@@ -38205,7 +38351,8 @@ var WorkspaceMetricCardsImpl = ({
38205
38351
  legend,
38206
38352
  skuAware,
38207
38353
  skuBreakdown,
38208
- activeSkuId
38354
+ activeSkuId,
38355
+ liveSkuId
38209
38356
  }) => {
38210
38357
  const effectiveLegend = legend || DEFAULT_EFFICIENCY_LEGEND;
38211
38358
  const activeSku = React144__default.useMemo(() => {
@@ -38214,6 +38361,13 @@ var WorkspaceMetricCardsImpl = ({
38214
38361
  }
38215
38362
  return null;
38216
38363
  }, [skuAware, activeSkuId, skuBreakdown]);
38364
+ const displaySku = React144__default.useMemo(() => {
38365
+ if (activeSku) return activeSku;
38366
+ if (skuAware && !activeSkuId && liveSkuId && skuBreakdown) {
38367
+ return skuBreakdown.find((s) => s.sku_id === liveSkuId) ?? null;
38368
+ }
38369
+ return null;
38370
+ }, [activeSku, skuAware, activeSkuId, liveSkuId, skuBreakdown]);
38217
38371
  const pphValue = activeSku ? activeSku.avg_pph : workspace.avg_pph;
38218
38372
  const pphThreshold = activeSku ? activeSku.pph_threshold : workspace.pph_threshold;
38219
38373
  const cycleValue = activeSku ? activeSku.avg_cycle_time : workspace.avg_cycle_time;
@@ -38248,7 +38402,7 @@ var WorkspaceMetricCardsImpl = ({
38248
38402
  /* @__PURE__ */ jsxs(Card2, { className: "flex flex-col bg-white shadow-sm h-full min-h-[150px] sm:min-h-0", children: [
38249
38403
  /* @__PURE__ */ jsxs(CardHeader2, { className: "pb-2 flex-none text-center", children: [
38250
38404
  /* @__PURE__ */ jsx(CardTitle2, { className: "text-lg", children: "PPH" }),
38251
- activeSku && /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-blue-600 mt-1 truncate px-2", title: activeSku.sku_code, children: activeSku.sku_code })
38405
+ displaySku && /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-blue-600 mt-1 truncate px-2", title: displaySku.sku_code, children: displaySku.sku_code })
38252
38406
  ] }),
38253
38407
  /* @__PURE__ */ jsx(CardContent2, { className: "flex-1 flex items-center justify-center py-6 sm:py-3", children: /* @__PURE__ */ jsxs("div", { className: "text-center", children: [
38254
38408
  /* @__PURE__ */ jsx("p", { className: `text-5xl font-bold ${pphValue >= pphThreshold ? "text-green-500" : "text-red-500"}`, children: pphValue.toFixed(1) }),
@@ -38261,7 +38415,7 @@ var WorkspaceMetricCardsImpl = ({
38261
38415
  /* @__PURE__ */ jsxs(Card2, { className: "flex flex-col bg-white shadow-sm h-full min-h-[150px] sm:min-h-0", children: [
38262
38416
  /* @__PURE__ */ jsxs(CardHeader2, { className: "pb-2 flex-none text-center", children: [
38263
38417
  /* @__PURE__ */ jsx(CardTitle2, { className: "text-lg", children: "Avg. Cycle Time" }),
38264
- activeSku && /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-blue-600 mt-1 truncate px-2", title: activeSku.sku_code, children: activeSku.sku_code })
38418
+ displaySku && /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-blue-600 mt-1 truncate px-2", title: displaySku.sku_code, children: displaySku.sku_code })
38265
38419
  ] }),
38266
38420
  /* @__PURE__ */ jsx(CardContent2, { className: "flex-1 flex items-center justify-center py-6 sm:py-3", children: /* @__PURE__ */ jsxs("div", { className: "text-center", children: [
38267
38421
  /* @__PURE__ */ jsx("p", { className: `text-5xl font-bold ${cycleValue > (cycleStandard || 0) ? "text-red-500" : "text-green-500"}`, children: cycleValue.toFixed(1) }),
@@ -43259,6 +43413,21 @@ var parseCycleTime = (value) => {
43259
43413
  var extractCycleTimeSeconds = (clip) => {
43260
43414
  return parseCycleTime(clip?.cycleTimeSeconds) ?? parseCycleTime(clip?.cycle_time_seconds) ?? parseCycleTime(clip?.duration) ?? parseCycleTime(clip?.original_task_metadata?.cycle_time) ?? null;
43261
43415
  };
43416
+ var formatDurationLabel = (seconds) => {
43417
+ if (typeof seconds !== "number" || !Number.isFinite(seconds) || seconds <= 0) {
43418
+ return null;
43419
+ }
43420
+ const roundedSeconds = Math.round(seconds);
43421
+ if (roundedSeconds < 60) {
43422
+ return `${roundedSeconds}s`;
43423
+ }
43424
+ const minutes = Math.floor(roundedSeconds / 60);
43425
+ const remainingSeconds = roundedSeconds % 60;
43426
+ if (minutes < 10) {
43427
+ return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`;
43428
+ }
43429
+ return `${Math.round(roundedSeconds / 60)} min`;
43430
+ };
43262
43431
  var getSeverityIcon = (severity, categoryId, cycleTimeSeconds, targetCycleTime, clipId) => {
43263
43432
  if (categoryId === "idle_time" || categoryId === "low_value" || categoryId === "longest-idles") {
43264
43433
  return null;
@@ -43334,7 +43503,9 @@ var FileManagerFilters = ({
43334
43503
  idleTimeVlmEnabled = false,
43335
43504
  showPercentileCycleFilters = true,
43336
43505
  prefetchedClipMetadata,
43337
- activeCategoryLoading
43506
+ activeCategoryLoading,
43507
+ idleClipSort = "latest",
43508
+ onIdleClipSortChange
43338
43509
  }) => {
43339
43510
  const [expandedNodes, setExpandedNodes] = useState(/* @__PURE__ */ new Set());
43340
43511
  const [startTime, setStartTime] = useState("");
@@ -43357,6 +43528,7 @@ var FileManagerFilters = ({
43357
43528
  const [localClipClassifications, setLocalClipClassifications] = useState({});
43358
43529
  const clipMetadataRef = useRef({});
43359
43530
  const inFlightMetadataRequestsRef = useRef(/* @__PURE__ */ new Set());
43531
+ const previousIdleClipSortRef = useRef(idleClipSort);
43360
43532
  const mergedClipClassifications = useMemo(() => ({
43361
43533
  ...clipClassifications || {},
43362
43534
  ...localClipClassifications
@@ -43364,6 +43536,36 @@ var FileManagerFilters = ({
43364
43536
  useEffect(() => {
43365
43537
  clipMetadataRef.current = clipMetadata;
43366
43538
  }, [clipMetadata]);
43539
+ useEffect(() => {
43540
+ if (previousIdleClipSortRef.current === idleClipSort) {
43541
+ return;
43542
+ }
43543
+ previousIdleClipSortRef.current = idleClipSort;
43544
+ setClipMetadata((prev) => {
43545
+ if (!prev.idle_time) {
43546
+ return prev;
43547
+ }
43548
+ const next = { ...prev };
43549
+ delete next.idle_time;
43550
+ return next;
43551
+ });
43552
+ setCategoryPages((prev) => {
43553
+ if (prev.idle_time === void 0) {
43554
+ return prev;
43555
+ }
43556
+ const next = { ...prev };
43557
+ delete next.idle_time;
43558
+ return next;
43559
+ });
43560
+ setCategoryHasMore((prev) => {
43561
+ if (prev.idle_time === void 0) {
43562
+ return prev;
43563
+ }
43564
+ const next = { ...prev };
43565
+ delete next.idle_time;
43566
+ return next;
43567
+ });
43568
+ }, [idleClipSort]);
43367
43569
  const isCategoryExternallyManaged = useCallback((categoryId) => {
43368
43570
  if (!categoryId) {
43369
43571
  return false;
@@ -43522,6 +43724,7 @@ var FileManagerFilters = ({
43522
43724
  return null;
43523
43725
  }
43524
43726
  }, [supabase]);
43727
+ const getMetadataLoadingKey = useCallback((categoryId, page) => `${categoryId}-${page}-${categoryId === "idle_time" ? idleClipSort : "latest"}`, [idleClipSort]);
43525
43728
  const fetchClipMetadataPage = useCallback(async (categoryId, page = 1) => {
43526
43729
  if (!workspaceId || !date || shift === void 0) {
43527
43730
  throw new Error("Missing required params for clip metadata fetch");
@@ -43541,7 +43744,8 @@ var FileManagerFilters = ({
43541
43744
  limit: CLIP_METADATA_PAGE_SIZE,
43542
43745
  knownTotal: typeof counts?.[categoryId] === "number" ? counts[categoryId] : null,
43543
43746
  snapshotDateTime,
43544
- snapshotClipId
43747
+ snapshotClipId,
43748
+ sort: categoryId === "idle_time" ? idleClipSort : "latest"
43545
43749
  }),
43546
43750
  redirectReason: "session_expired"
43547
43751
  });
@@ -43549,7 +43753,7 @@ var FileManagerFilters = ({
43549
43753
  throw new Error(`API error: ${response.status}`);
43550
43754
  }
43551
43755
  return response.json();
43552
- }, [workspaceId, date, shift, counts, snapshotDateTime, snapshotClipId, supabase]);
43756
+ }, [workspaceId, date, shift, counts, snapshotDateTime, snapshotClipId, idleClipSort, supabase]);
43553
43757
  const seedIdleClassifications = useCallback(async (clips) => {
43554
43758
  if (!idleTimeVlmEnabled || clips.length === 0) {
43555
43759
  return;
@@ -43605,7 +43809,7 @@ var FileManagerFilters = ({
43605
43809
  console.warn("[FileManager] Missing required params for clip metadata fetch");
43606
43810
  return;
43607
43811
  }
43608
- const loadingKey = `${categoryId}-${page}`;
43812
+ const loadingKey = getMetadataLoadingKey(categoryId, page);
43609
43813
  if (inFlightMetadataRequestsRef.current.has(loadingKey)) {
43610
43814
  return;
43611
43815
  }
@@ -43633,7 +43837,7 @@ var FileManagerFilters = ({
43633
43837
  return newSet;
43634
43838
  });
43635
43839
  }
43636
- }, [workspaceId, date, shift, fetchClipMetadataPage, idleTimeVlmEnabled, seedIdleClassifications]);
43840
+ }, [workspaceId, date, shift, fetchClipMetadataPage, idleTimeVlmEnabled, seedIdleClassifications, getMetadataLoadingKey]);
43637
43841
  const ensureAllIdleTimeClipMetadataLoaded = useCallback(async () => {
43638
43842
  if (!workspaceId || !date || shift === void 0) {
43639
43843
  return;
@@ -44007,15 +44211,17 @@ var FileManagerFilters = ({
44007
44211
  const colorClasses = getColorClasses(category.color);
44008
44212
  const clipNodes = filteredClips.map((clip, index) => {
44009
44213
  const cycleTime = extractCycleTimeSeconds(clip);
44214
+ const idleDuration = category.id === "idle_time" ? clip.idle_duration_seconds ?? clip.duration : null;
44215
+ const idleDurationLabel = formatDurationLabel(idleDuration);
44010
44216
  const baseTimeLabel = formatClipExplorerTimeLabel({
44011
44217
  categoryId: category.id,
44012
44218
  clipTimestamp: clip.clip_timestamp,
44013
44219
  timezone,
44014
- durationSeconds: clip.duration,
44220
+ durationSeconds: idleDuration ?? clip.duration,
44015
44221
  idleStartTime: clip.idle_start_time,
44016
44222
  idleEndTime: clip.idle_end_time
44017
44223
  });
44018
- const displayLabel = `${baseTimeLabel}${clip.duration && category.id !== "idle_time" && category.id !== "low_value" ? ` - (${clip.duration.toFixed(1)}s)` : ""}`;
44224
+ const displayLabel = `${baseTimeLabel}${idleDurationLabel && category.id === "idle_time" ? ` - (${idleDurationLabel})` : ""}${clip.duration && category.id !== "idle_time" && category.id !== "low_value" ? ` - (${clip.duration.toFixed(1)}s)` : ""}`;
44019
44225
  return {
44020
44226
  id: clip.id,
44021
44227
  label: displayLabel,
@@ -44029,7 +44235,7 @@ var FileManagerFilters = ({
44029
44235
  clipPosition: index + 1,
44030
44236
  // Store 1-based position
44031
44237
  cycleTimeSeconds: cycleTime,
44032
- duration: clip.duration,
44238
+ duration: idleDuration ?? clip.duration,
44033
44239
  // Store duration for custom badge rendering
44034
44240
  cycleItemCount: clip.cycle_item_count ?? null
44035
44241
  };
@@ -44351,11 +44557,11 @@ var FileManagerFilters = ({
44351
44557
  /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }),
44352
44558
  "Loading clips..."
44353
44559
  ] }) }),
44354
- loadingCategories.has(`${node.id}-${(categoryPages[node.id] || 0) + 1}`) && /* @__PURE__ */ jsx("div", { className: "py-2 px-3 text-center", children: /* @__PURE__ */ jsxs("div", { className: "inline-flex items-center text-sm text-slate-500", children: [
44560
+ loadingCategories.has(getMetadataLoadingKey(node.id, (categoryPages[node.id] || 0) + 1)) && /* @__PURE__ */ jsx("div", { className: "py-2 px-3 text-center", children: /* @__PURE__ */ jsxs("div", { className: "inline-flex items-center text-sm text-slate-500", children: [
44355
44561
  /* @__PURE__ */ jsx("div", { className: "animate-spin mr-2 h-4 w-4 border-2 border-slate-300 border-t-blue-500 rounded-full" }),
44356
44562
  "Loading more clips..."
44357
44563
  ] }) }),
44358
- categoryHasMore[node.id] && !loadingCategories.has(`${node.id}-${(categoryPages[node.id] || 0) + 1}`) && /* @__PURE__ */ jsxs(
44564
+ categoryHasMore[node.id] && !loadingCategories.has(getMetadataLoadingKey(node.id, (categoryPages[node.id] || 0) + 1)) && /* @__PURE__ */ jsxs(
44359
44565
  "button",
44360
44566
  {
44361
44567
  onClick: (e) => {
@@ -44382,6 +44588,18 @@ var FileManagerFilters = ({
44382
44588
  /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx("h2", { className: "text-lg font-bold text-slate-900 tracking-tight", children: "Clips Explorer" }) })
44383
44589
  ] }),
44384
44590
  /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
44591
+ activeFilter === "idle_time" && /* @__PURE__ */ jsx(
44592
+ "button",
44593
+ {
44594
+ onClick: () => {
44595
+ onIdleClipSortChange?.(idleClipSort === "latest" ? "idle_duration_desc" : "latest");
44596
+ },
44597
+ className: `p-2 rounded-xl transition-all duration-200 ${idleClipSort === "idle_duration_desc" ? "bg-orange-100 text-orange-600 hover:bg-orange-200 shadow-sm" : "bg-slate-100 text-slate-600 hover:bg-slate-200"}`,
44598
+ title: idleClipSort === "idle_duration_desc" ? "Sort by newest first" : "Sort by longest idle first",
44599
+ "aria-label": idleClipSort === "idle_duration_desc" ? "Sort idle clips by newest first" : "Sort idle clips by longest idle first",
44600
+ children: /* @__PURE__ */ jsx(ArrowDownWideNarrow, { className: "h-5 w-5" })
44601
+ }
44602
+ ),
44385
44603
  activeFilter === "idle_time" && idleTimeVlmEnabled && /* @__PURE__ */ jsx(
44386
44604
  "button",
44387
44605
  {
@@ -44402,8 +44620,8 @@ var FileManagerFilters = ({
44402
44620
  )
44403
44621
  ] })
44404
44622
  ] }),
44405
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 mt-3", children: [
44406
- isTimeFilterActive && startTime && endTime && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2 text-xs text-blue-600 bg-blue-50/60 px-3 py-1.5 rounded-lg border border-blue-100", children: [
44623
+ /* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-wrap items-center gap-2", children: [
44624
+ isTimeFilterActive && startTime && endTime && /* @__PURE__ */ jsxs("div", { className: "inline-flex w-fit items-center gap-2 rounded-full border border-blue-100 bg-blue-50/70 px-2.5 py-1 text-xs text-blue-700 shadow-sm", children: [
44407
44625
  /* @__PURE__ */ jsxs("span", { className: "font-medium", children: [
44408
44626
  "Time: ",
44409
44627
  getDisplayValue(startTime),
@@ -44419,13 +44637,13 @@ var FileManagerFilters = ({
44419
44637
  setEndTime("");
44420
44638
  setIsTimeFilterActive(false);
44421
44639
  },
44422
- className: "ml-2 hover:bg-blue-100 rounded p-0.5 transition-colors",
44640
+ className: "rounded-full p-0.5 transition-colors hover:bg-blue-100",
44423
44641
  title: "Clear time filter",
44424
44642
  children: /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5" })
44425
44643
  }
44426
44644
  )
44427
44645
  ] }),
44428
- idleLabelFilter && activeFilter === "idle_time" && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2 text-xs text-purple-600 bg-purple-50/60 px-3 py-1.5 rounded-lg border border-purple-100", children: [
44646
+ idleLabelFilter && activeFilter === "idle_time" && /* @__PURE__ */ jsxs("div", { className: "inline-flex w-fit items-center gap-2 rounded-full border border-purple-100 bg-purple-50/70 px-2.5 py-1 text-xs text-purple-700 shadow-sm", children: [
44429
44647
  /* @__PURE__ */ jsxs("span", { className: "font-medium", children: [
44430
44648
  "Reason: ",
44431
44649
  selectedIdleReasonOption?.displayName || idleLabelFilter.replace(/_/g, " ")
@@ -44437,11 +44655,27 @@ var FileManagerFilters = ({
44437
44655
  e.stopPropagation();
44438
44656
  setIdleLabelFilter(null);
44439
44657
  },
44440
- className: "ml-2 hover:bg-purple-100 rounded p-0.5 transition-colors",
44658
+ className: "rounded-full p-0.5 transition-colors hover:bg-purple-100",
44441
44659
  title: "Clear label filter",
44442
44660
  children: /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5" })
44443
44661
  }
44444
44662
  )
44663
+ ] }),
44664
+ activeFilter === "idle_time" && idleClipSort === "idle_duration_desc" && /* @__PURE__ */ jsxs("div", { className: "inline-flex w-fit items-center gap-2 rounded-full border border-orange-100 bg-orange-50/70 px-2.5 py-1 text-xs text-orange-700 shadow-sm", children: [
44665
+ /* @__PURE__ */ jsx(ArrowDownWideNarrow, { className: "h-3.5 w-3.5" }),
44666
+ /* @__PURE__ */ jsx("span", { className: "font-medium", children: "Longest idle first" }),
44667
+ /* @__PURE__ */ jsx(
44668
+ "button",
44669
+ {
44670
+ onClick: (e) => {
44671
+ e.stopPropagation();
44672
+ onIdleClipSortChange?.("latest");
44673
+ },
44674
+ className: "rounded-full p-0.5 transition-colors hover:bg-orange-100",
44675
+ title: "Clear idle sort",
44676
+ children: /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5" })
44677
+ }
44678
+ )
44445
44679
  ] })
44446
44680
  ] })
44447
44681
  ] }),
@@ -45205,8 +45439,10 @@ var BottlenecksContent = ({
45205
45439
  const [clipClassifications, setClipClassifications] = useState({});
45206
45440
  const [categoryMetadata, setCategoryMetadata] = useState([]);
45207
45441
  const [categoryMetadataCategoryId, setCategoryMetadataCategoryId] = useState(null);
45442
+ const [categoryMetadataSort, setCategoryMetadataSort] = useState(null);
45208
45443
  const [currentMetadataIndex, setCurrentMetadataIndex] = useState(0);
45209
45444
  const [metadataCache, setMetadataCache] = useState({});
45445
+ const [idleClipSort, setIdleClipSort] = useState("latest");
45210
45446
  const invalidateMetadataCache = useCallback((categories) => {
45211
45447
  setMetadataCache((prevCache) => {
45212
45448
  if (!prevCache || Object.keys(prevCache).length === 0) {
@@ -45237,6 +45473,7 @@ var BottlenecksContent = ({
45237
45473
  const [isFullscreen, setIsFullscreen] = useState(false);
45238
45474
  const categoryMetadataRef = useRef([]);
45239
45475
  const currentMetadataIndexRef = useRef(0);
45476
+ const previousIdleClipSortRef = useRef(idleClipSort);
45240
45477
  const clearRetryTimeout = useCallback(() => {
45241
45478
  if (retryTimeoutRef.current) {
45242
45479
  clearTimeout(retryTimeoutRef.current);
@@ -45683,9 +45920,13 @@ var BottlenecksContent = ({
45683
45920
  }
45684
45921
  return ["fast-cycles", "slow-cycles", "longest-idles"].includes(categoryId);
45685
45922
  }, [isFastSlowClipFiltersEnabled]);
45923
+ const shouldUseMetadataNavigation = useCallback((categoryId) => {
45924
+ return isPercentileCategory(categoryId) || categoryId === "idle_time" && idleClipSort === "idle_duration_desc";
45925
+ }, [idleClipSort, isPercentileCategory]);
45686
45926
  const getMetadataCacheKey = useCallback((categoryId) => {
45687
- return `${categoryId}-${effectiveDateString}-${effectiveShiftId}-${snapshotDateTime ?? "nosnap"}-${snapshotClipId ?? "nosnap"}`;
45688
- }, [effectiveDateString, effectiveShiftId, snapshotDateTime, snapshotClipId]);
45927
+ const sortKey = categoryId === "idle_time" ? idleClipSort : "latest";
45928
+ return `${categoryId}-${effectiveDateString}-${effectiveShiftId}-${snapshotDateTime ?? "nosnap"}-${snapshotClipId ?? "nosnap"}-${sortKey}`;
45929
+ }, [effectiveDateString, effectiveShiftId, snapshotDateTime, snapshotClipId, idleClipSort]);
45689
45930
  const setVisibleCategoryMetadata = useCallback((categoryId, clips) => {
45690
45931
  if (activeFilterRef.current !== categoryId) {
45691
45932
  return false;
@@ -45693,8 +45934,9 @@ var BottlenecksContent = ({
45693
45934
  categoryMetadataRef.current = clips;
45694
45935
  setCategoryMetadata(clips);
45695
45936
  setCategoryMetadataCategoryId(clips.length > 0 ? categoryId : null);
45937
+ setCategoryMetadataSort(clips.length > 0 ? categoryId === "idle_time" ? idleClipSort : "latest" : null);
45696
45938
  return true;
45697
- }, []);
45939
+ }, [idleClipSort]);
45698
45940
  const applyMetadataSnapshot = useCallback((categoryId, clips, total) => {
45699
45941
  if (!clips || clips.length === 0) {
45700
45942
  return;
@@ -45705,11 +45947,11 @@ var BottlenecksContent = ({
45705
45947
  [cacheKey]: clips
45706
45948
  }));
45707
45949
  setVisibleCategoryMetadata(categoryId, clips);
45708
- if (!isPercentileCategory(categoryId) && typeof total === "number") {
45950
+ if (!shouldUseMetadataNavigation(categoryId) && typeof total === "number") {
45709
45951
  currentTotalRef.current = total;
45710
45952
  setCurrentTotal(total);
45711
45953
  }
45712
- }, [getMetadataCacheKey, isPercentileCategory, setVisibleCategoryMetadata]);
45954
+ }, [getMetadataCacheKey, shouldUseMetadataNavigation, setVisibleCategoryMetadata]);
45713
45955
  const getClipTypesForPercentileCategory = useCallback((categoryId) => {
45714
45956
  switch (categoryId) {
45715
45957
  case "fast-cycles":
@@ -45735,6 +45977,7 @@ var BottlenecksContent = ({
45735
45977
  }
45736
45978
  setCategoryMetadata([]);
45737
45979
  setCategoryMetadataCategoryId(null);
45980
+ setCategoryMetadataSort(null);
45738
45981
  categoryMetadataRef.current = [];
45739
45982
  updateActiveFilter(fallbackFilter);
45740
45983
  }, [isFastSlowClipFiltersEnabled, activeFilter, dynamicCounts, clipTypes, updateActiveFilter]);
@@ -45782,6 +46025,7 @@ var BottlenecksContent = ({
45782
46025
  if (!isFastSlowClipFiltersEnabled && (categoryId === "fast-cycles" || categoryId === "slow-cycles")) {
45783
46026
  setCategoryMetadata([]);
45784
46027
  setCategoryMetadataCategoryId(null);
46028
+ setCategoryMetadataSort(null);
45785
46029
  categoryMetadataRef.current = [];
45786
46030
  return;
45787
46031
  }
@@ -45852,7 +46096,8 @@ var BottlenecksContent = ({
45852
46096
  limit: 100,
45853
46097
  knownTotal: mergedCounts[categoryId] ?? null,
45854
46098
  snapshotDateTime,
45855
- snapshotClipId
46099
+ snapshotClipId,
46100
+ sort: categoryId === "idle_time" ? idleClipSort : "latest"
45856
46101
  }),
45857
46102
  redirectReason: "session_expired"
45858
46103
  });
@@ -45931,6 +46176,7 @@ var BottlenecksContent = ({
45931
46176
  if (activeFilterRef.current === categoryId) {
45932
46177
  setCategoryMetadata([]);
45933
46178
  setCategoryMetadataCategoryId(null);
46179
+ setCategoryMetadataSort(null);
45934
46180
  categoryMetadataRef.current = [];
45935
46181
  }
45936
46182
  }
@@ -45939,7 +46185,26 @@ var BottlenecksContent = ({
45939
46185
  } finally {
45940
46186
  setIsCategoryLoading(false);
45941
46187
  }
45942
- }, [workspaceId, effectiveDateString, effectiveShiftId, getMetadataCacheKey, isPercentileCategory, isFastSlowClipFiltersEnabled, metadataCache, s3ClipsService, clearLoadingState, isEffectiveShiftReady, snapshotDateTime, snapshotClipId, supabase, setVisibleCategoryMetadata]);
46188
+ }, [workspaceId, effectiveDateString, effectiveShiftId, getMetadataCacheKey, isPercentileCategory, isFastSlowClipFiltersEnabled, metadataCache, s3ClipsService, clearLoadingState, isEffectiveShiftReady, snapshotDateTime, snapshotClipId, idleClipSort, supabase, setVisibleCategoryMetadata]);
46189
+ useEffect(() => {
46190
+ if (previousIdleClipSortRef.current === idleClipSort) {
46191
+ return;
46192
+ }
46193
+ previousIdleClipSortRef.current = idleClipSort;
46194
+ if (activeFilterRef.current !== "idle_time") {
46195
+ return;
46196
+ }
46197
+ setCategoryMetadata([]);
46198
+ setCategoryMetadataCategoryId(null);
46199
+ setCategoryMetadataSort(null);
46200
+ categoryMetadataRef.current = [];
46201
+ setCurrentMetadataIndex(0);
46202
+ currentMetadataIndexRef.current = 0;
46203
+ setCurrentPosition(0);
46204
+ currentPositionRef.current = 0;
46205
+ setIsCategoryLoading(true);
46206
+ void loadCategoryMetadata("idle_time", true, true);
46207
+ }, [idleClipSort, loadCategoryMetadata]);
45943
46208
  useEffect(() => {
45944
46209
  if (previousFilterRef.current !== activeFilter) {
45945
46210
  console.log(`Filter changed from ${previousFilterRef.current} to ${activeFilter} - resetting to first video`);
@@ -45950,6 +46215,7 @@ var BottlenecksContent = ({
45950
46215
  loadingCategoryRef.current = null;
45951
46216
  setCategoryMetadata([]);
45952
46217
  setCategoryMetadataCategoryId(null);
46218
+ setCategoryMetadataSort(null);
45953
46219
  setCurrentMetadataIndex(0);
45954
46220
  categoryMetadataRef.current = [];
45955
46221
  currentMetadataIndexRef.current = 0;
@@ -46048,7 +46314,7 @@ var BottlenecksContent = ({
46048
46314
  }
46049
46315
  if (metadataArray.length === 0) {
46050
46316
  console.warn(`[BottlenecksContent] No metadata available for category ${categoryId} after refresh`);
46051
- if (!isPercentileCategory(categoryId)) {
46317
+ if (!shouldUseMetadataNavigation(categoryId)) {
46052
46318
  const resolvedPosition = typeof position === "number" ? position : 1;
46053
46319
  currentPositionRef.current = resolvedPosition;
46054
46320
  setCurrentPosition(resolvedPosition);
@@ -46061,7 +46327,7 @@ var BottlenecksContent = ({
46061
46327
  const clickedClipIndex = metadataArray.findIndex((clip) => clip.clipId === clipId);
46062
46328
  if (clickedClipIndex === -1) {
46063
46329
  console.warn(`[BottlenecksContent] Clip ${clipId} not found after metadata refresh`);
46064
- if (!isPercentileCategory(categoryId)) {
46330
+ if (!shouldUseMetadataNavigation(categoryId)) {
46065
46331
  const resolvedPosition = typeof position === "number" ? position : 1;
46066
46332
  currentPositionRef.current = resolvedPosition;
46067
46333
  setCurrentPosition(resolvedPosition);
@@ -46073,7 +46339,7 @@ var BottlenecksContent = ({
46073
46339
  }
46074
46340
  setCurrentMetadataIndex(clickedClipIndex);
46075
46341
  currentMetadataIndexRef.current = clickedClipIndex;
46076
- if (!isPercentileCategory(categoryId)) {
46342
+ if (!shouldUseMetadataNavigation(categoryId)) {
46077
46343
  const position2 = clickedClipIndex + 1;
46078
46344
  currentPositionRef.current = position2;
46079
46345
  setCurrentPosition(position2);
@@ -46103,7 +46369,7 @@ var BottlenecksContent = ({
46103
46369
  clearLoadingState();
46104
46370
  }
46105
46371
  }
46106
- }, [workspaceId, s3ClipsService, updateActiveFilter, clearLoadingState, clearRetryTimeout, loadCategoryMetadata, applyMetadataSnapshot, mergedCounts, isPercentileCategory]);
46372
+ }, [workspaceId, s3ClipsService, updateActiveFilter, clearLoadingState, clearRetryTimeout, loadCategoryMetadata, applyMetadataSnapshot, mergedCounts, shouldUseMetadataNavigation]);
46107
46373
  const restartCurrentClipPlayback = useCallback(() => {
46108
46374
  if (!currentClipId) {
46109
46375
  return;
@@ -46124,7 +46390,7 @@ var BottlenecksContent = ({
46124
46390
  return;
46125
46391
  }
46126
46392
  const activeCategory = activeFilterRef.current;
46127
- if (!activeCategory || activeCategory === "all" || isPercentileCategory(activeCategory)) {
46393
+ if (!activeCategory || activeCategory === "all" || shouldUseMetadataNavigation(activeCategory)) {
46128
46394
  return;
46129
46395
  }
46130
46396
  let cancelled = false;
@@ -46157,7 +46423,7 @@ var BottlenecksContent = ({
46157
46423
  }, [
46158
46424
  newClipsNotification,
46159
46425
  s3ClipsService,
46160
- isPercentileCategory,
46426
+ shouldUseMetadataNavigation,
46161
46427
  currentClipId,
46162
46428
  invalidateMetadataCache,
46163
46429
  loadAndPlayClipById,
@@ -46209,7 +46475,7 @@ var BottlenecksContent = ({
46209
46475
  }
46210
46476
  }
46211
46477
  try {
46212
- if (!isPercentileCategory(currentFilter)) {
46478
+ if (!shouldUseMetadataNavigation(currentFilter)) {
46213
46479
  if (!s3ClipsService || !workspaceId || !currentClipId) {
46214
46480
  throw new Error("S3 clips service not available");
46215
46481
  }
@@ -46309,7 +46575,7 @@ var BottlenecksContent = ({
46309
46575
  } else {
46310
46576
  const firstClipMeta = metadataArray[0];
46311
46577
  if (firstClipMeta?.clipId && firstClipMeta.clipId !== currentClipId) {
46312
- console.log(`[handleNext] Reached end of ${currentFilter}, looping back to newest percentile clip ${firstClipMeta.clipId}`);
46578
+ console.log(`[handleNext] Reached end of ${currentFilter}, looping back to first metadata clip ${firstClipMeta.clipId}`);
46313
46579
  await loadAndPlayClipById(firstClipMeta.clipId, currentFilter, 1, {
46314
46580
  clips: metadataArray,
46315
46581
  total: metadataArray.length
@@ -46335,7 +46601,7 @@ var BottlenecksContent = ({
46335
46601
  });
46336
46602
  clearLoadingState();
46337
46603
  }
46338
- }, [clearLoadingState, clearRetryTimeout, s3ClipsService, loadCategoryMetadata, loadAndPlayClipById, isPercentileCategory, workspaceId, currentClipId, effectiveDateString, effectiveShiftId, snapshotDateTime, snapshotClipId, mergedCounts]);
46604
+ }, [clearLoadingState, clearRetryTimeout, s3ClipsService, loadCategoryMetadata, loadAndPlayClipById, shouldUseMetadataNavigation, workspaceId, currentClipId, effectiveDateString, effectiveShiftId, snapshotDateTime, snapshotClipId, mergedCounts]);
46339
46605
  const handlePrevious = useCallback(async () => {
46340
46606
  if (!isMountedRef.current || navigationLockRef.current) return;
46341
46607
  const currentFilter = activeFilterRef.current;
@@ -46354,7 +46620,7 @@ var BottlenecksContent = ({
46354
46620
  }
46355
46621
  }
46356
46622
  try {
46357
- if (!isPercentileCategory(currentFilter)) {
46623
+ if (!shouldUseMetadataNavigation(currentFilter)) {
46358
46624
  if (!s3ClipsService || !workspaceId || !currentClipId) {
46359
46625
  throw new Error("S3 clips service not available");
46360
46626
  }
@@ -46439,7 +46705,7 @@ var BottlenecksContent = ({
46439
46705
  });
46440
46706
  clearLoadingState();
46441
46707
  }
46442
- }, [clearLoadingState, clearRetryTimeout, s3ClipsService, loadCategoryMetadata, isPercentileCategory, workspaceId, currentClipId, effectiveDateString, effectiveShiftId, snapshotDateTime, snapshotClipId, mergedCounts]);
46708
+ }, [clearLoadingState, clearRetryTimeout, s3ClipsService, loadCategoryMetadata, shouldUseMetadataNavigation, workspaceId, currentClipId, effectiveDateString, effectiveShiftId, snapshotDateTime, snapshotClipId, mergedCounts]);
46443
46709
  const currentVideo = useMemo(() => {
46444
46710
  if (!filteredVideos || filteredVideos.length === 0 || currentIndex >= filteredVideos.length) {
46445
46711
  return null;
@@ -46506,22 +46772,22 @@ var BottlenecksContent = ({
46506
46772
  }
46507
46773
  }, [currentVideo?.id, isShareLoading, supabase, workspaceId, workspaceName]);
46508
46774
  useMemo(() => {
46509
- if (isPercentileCategory(activeFilter)) {
46775
+ if (shouldUseMetadataNavigation(activeFilter)) {
46510
46776
  return categoryMetadata.length;
46511
46777
  }
46512
46778
  return currentTotal || mergedCounts[activeFilter] || 0;
46513
- }, [activeFilter, categoryMetadata.length, currentTotal, mergedCounts, isPercentileCategory]);
46779
+ }, [activeFilter, categoryMetadata.length, currentTotal, mergedCounts, shouldUseMetadataNavigation]);
46514
46780
  useMemo(() => {
46515
- if (isPercentileCategory(activeFilter)) {
46781
+ if (shouldUseMetadataNavigation(activeFilter)) {
46516
46782
  return categoryMetadata.length > 0 ? currentMetadataIndex + 1 : 0;
46517
46783
  }
46518
46784
  return currentPosition;
46519
- }, [activeFilter, categoryMetadata.length, currentMetadataIndex, currentPosition, isPercentileCategory]);
46520
- const prefetchedExplorerMetadata = useMemo(() => buildPrefetchedExplorerMetadata(
46785
+ }, [activeFilter, categoryMetadata.length, currentMetadataIndex, currentPosition, shouldUseMetadataNavigation]);
46786
+ const prefetchedExplorerMetadata = useMemo(() => activeFilter === "idle_time" && categoryMetadataSort !== idleClipSort ? void 0 : buildPrefetchedExplorerMetadata(
46521
46787
  activeFilter,
46522
46788
  categoryMetadataCategoryId,
46523
46789
  categoryMetadata
46524
- ), [activeFilter, categoryMetadata, categoryMetadataCategoryId]);
46790
+ ), [activeFilter, categoryMetadata, categoryMetadataCategoryId, categoryMetadataSort, idleClipSort]);
46525
46791
  const classificationClipIds = useMemo(() => {
46526
46792
  if (!idleTimeVlmEnabled) {
46527
46793
  return [];
@@ -47270,7 +47536,12 @@ var BottlenecksContent = ({
47270
47536
  showPercentileCycleFilters: isFastSlowClipFiltersEnabled,
47271
47537
  prefetchedClipMetadata: prefetchedExplorerMetadata,
47272
47538
  activeCategoryLoading: isCategoryLoading,
47539
+ idleClipSort,
47540
+ onIdleClipSortChange: setIdleClipSort,
47273
47541
  onFilterChange: (filterId) => {
47542
+ if (filterId !== "idle_time") {
47543
+ setIdleClipSort("latest");
47544
+ }
47274
47545
  updateActiveFilter(filterId);
47275
47546
  const category = categoriesToShow.find((cat) => cat.type === filterId);
47276
47547
  if (category) {
@@ -49193,6 +49464,11 @@ var LineHistoryCalendar = ({
49193
49464
  return calendar;
49194
49465
  }, [data, month, year, configuredTimezone]);
49195
49466
  const hasRealData = (shift) => {
49467
+ if (isUptimeMode) {
49468
+ if (shift.hasData === true) return true;
49469
+ const efficiency = Number(shift.avg_efficiency);
49470
+ return shift.total_workspaces > 0 || shift.underperforming_workspaces > 0 || (shift.output || 0) > 0 || (shift.available_time_seconds || 0) > 0 || (shift.active_time_seconds || 0) > 0 || (shift.idle_time_seconds || 0) > 0 || Number.isFinite(efficiency) && efficiency > 0;
49471
+ }
49196
49472
  if (shift.hasData !== void 0) return shift.hasData;
49197
49473
  return shift.total_workspaces > 0 || shift.avg_efficiency > 0 || shift.underperforming_workspaces > 0;
49198
49474
  };
@@ -49825,13 +50101,18 @@ var LineMonthlyHistory = ({
49825
50101
  enabled: !!lineId && idleTimeVlmEnabled
49826
50102
  });
49827
50103
  const hasRealData = (shift) => {
50104
+ if (isUptimeMode) {
50105
+ if (shift.hasData === true) return true;
50106
+ const efficiency = Number(shift.avg_efficiency);
50107
+ return shift.total_workspaces > 0 || shift.underperforming_workspaces > 0 || (shift.output || 0) > 0 || (shift.idealOutput || 0) > 0 || (shift.idle_time_seconds || 0) > 0 || (shift.active_time_seconds || 0) > 0 || (shift.available_time_seconds || 0) > 0 || Number.isFinite(efficiency) && efficiency > 0;
50108
+ }
49828
50109
  if (shift.hasData !== void 0) return shift.hasData;
49829
50110
  return shift.avg_efficiency > 0 || shift.underperforming_workspaces > 0 || shift.total_workspaces > 0 || (shift.output || 0) > 0 || (shift.idealOutput || 0) > 0 || (shift.idle_time_seconds || 0) > 0 || (shift.active_time_seconds || 0) > 0 || (shift.available_time_seconds || 0) > 0;
49830
50111
  };
49831
50112
  const averages = (analysisMonthlyData || []).reduce(
49832
50113
  (acc, day) => {
49833
50114
  const shiftData = getShiftData2(day, selectedShiftId);
49834
- if (!shiftData || shiftData?.avg_efficiency < 5) {
50115
+ if (!shiftData || !isValidAggregateEfficiency(isUptimeMode ? "uptime" : "output", shiftData.avg_efficiency)) {
49835
50116
  return acc;
49836
50117
  }
49837
50118
  return {
@@ -49860,7 +50141,9 @@ var LineMonthlyHistory = ({
49860
50141
  const avgOutput = outputAverages.count > 0 ? outputAverages.output / outputAverages.count : 0;
49861
50142
  const uptimeSummary = useMemo(() => {
49862
50143
  if (!isUptimeMode) return null;
49863
- const validDays = (analysisMonthlyData || []).map((day) => getShiftData2(day, selectedShiftId)).filter((shiftData) => shiftData && hasRealData(shiftData)).map((shiftData) => ({ shiftData, totals: getUptimeTotals(shiftData) }));
50144
+ const validDays = (analysisMonthlyData || []).map((day) => getShiftData2(day, selectedShiftId)).filter(
50145
+ (shiftData) => shiftData && hasRealData(shiftData) && isValidAggregateEfficiency("uptime", shiftData.avg_efficiency)
50146
+ ).map((shiftData) => ({ shiftData, totals: getUptimeTotals(shiftData) }));
49864
50147
  if (!validDays.length) {
49865
50148
  return { avgUtilization: 0, avgIdleTime: 0, avgDailyStoppages: 0 };
49866
50149
  }
@@ -50008,7 +50291,9 @@ var LineMonthlyHistory = ({
50008
50291
  }, [chartData.yAxisMax, chartData.lastSetTarget]);
50009
50292
  const pieChartData = useMemo(() => {
50010
50293
  if (!isUptimeMode) return [];
50011
- const validShifts = (analysisMonthlyData || []).map((day) => getShiftData2(day, selectedShiftId)).filter(hasRealData);
50294
+ const validShifts = (analysisMonthlyData || []).map((day) => getShiftData2(day, selectedShiftId)).filter(
50295
+ (shift) => shift && hasRealData(shift) && isValidAggregateEfficiency("uptime", shift.avg_efficiency)
50296
+ );
50012
50297
  if (!validShifts.length) return [];
50013
50298
  const efficiencyValues = validShifts.map((shift) => Number.isFinite(shift.avg_efficiency) ? Number(shift.avg_efficiency) : null).filter((value) => value !== null);
50014
50299
  if (!efficiencyValues.length) return [];
@@ -50618,7 +50903,9 @@ var LineMonthlyPdfGenerator = ({
50618
50903
  const productiveSeconds = activeSecondsRaw > 0 ? Math.min(activeSecondsRaw, availableSeconds) : Math.max(availableSeconds - idleSeconds, 0);
50619
50904
  return { availableSeconds, productiveSeconds, idleSeconds };
50620
50905
  };
50621
- const validShifts = validDays.map((day) => getLineShiftData2(day, selectedShiftId)).filter((shift) => isUptimeMode ? hasShiftData(shift) : shift.avg_efficiency >= 5);
50906
+ const validShifts = validDays.map((day) => getLineShiftData2(day, selectedShiftId)).filter(
50907
+ (shift) => hasShiftData(shift) && isValidAggregateEfficiency(isUptimeMode ? "uptime" : "output", shift.avg_efficiency)
50908
+ );
50622
50909
  const monthlyMetrics = validShifts.length > 0 ? isUptimeMode ? (() => {
50623
50910
  let utilizationSum = 0;
50624
50911
  let idleTimeSum = 0;
@@ -52603,7 +52890,10 @@ var WorkspaceMonthlyHistory = ({
52603
52890
  return ticks.filter((v) => v >= 0 && v <= max * 1.05).sort((a, b) => a - b);
52604
52891
  }, [chartData.yAxisMax, chartData.lastSetTarget, isUptimeMode]);
52605
52892
  const pieChartData = useMemo(() => {
52606
- const validShifts = analysisMonthlyData.map((d) => getShiftData(d, selectedShiftId)).filter(hasRealData);
52893
+ const aggregateMode = isUptimeMode ? "uptime" : "output";
52894
+ const validShifts = analysisMonthlyData.map((d) => getShiftData(d, selectedShiftId)).filter(
52895
+ (shift) => shift && hasRealData(shift) && isValidAggregateEfficiency(aggregateMode, shift.efficiency)
52896
+ );
52607
52897
  if (validShifts.length === 0) return [];
52608
52898
  const efficiencyValues = validShifts.map((shift) => Number.isFinite(shift.efficiency) ? Number(shift.efficiency) : null).filter((value) => value !== null);
52609
52899
  if (!efficiencyValues.length) return [];
@@ -52614,10 +52904,10 @@ var WorkspaceMonthlyHistory = ({
52614
52904
  { name: "Productive", value: productivePercent },
52615
52905
  { name: "Idle", value: idlePercent }
52616
52906
  ];
52617
- }, [analysisMonthlyData, selectedShiftId, shiftWorkSeconds]);
52907
+ }, [analysisMonthlyData, selectedShiftId, isUptimeMode]);
52618
52908
  const metrics2 = useMemo(() => {
52619
52909
  const validShifts = analysisMonthlyData.map((d) => getShiftData(d, selectedShiftId)).filter(hasRealData);
52620
- const filteredShifts = isUptimeMode ? validShifts : validShifts.filter((shift) => (shift.efficiency ?? 0) >= 5);
52910
+ const filteredShifts = isUptimeMode ? validShifts.filter((shift) => isValidAggregateEfficiency("uptime", shift.efficiency)) : validShifts.filter((shift) => isValidAggregateEfficiency("output", shift.efficiency));
52621
52911
  if (filteredShifts.length === 0) return null;
52622
52912
  const totalEfficiency = filteredShifts.reduce((sum, shift) => sum + (shift.efficiency || 0), 0);
52623
52913
  const totalUtilization = filteredShifts.reduce(
@@ -53837,7 +54127,7 @@ var WorkspaceMonthlyPdfGenerator = ({
53837
54127
  const shift = getShiftData(dayData, selectedShiftId);
53838
54128
  return { dayData, shift };
53839
54129
  }).filter(({ shift }) => hasShiftData(shift)).sort((left, right) => getDayDateKey(right.dayData).localeCompare(getDayDateKey(left.dayData)));
53840
- const filteredShifts = isUptimeMode ? validShifts : validShifts.filter((shift) => (shift.efficiency ?? 0) >= 5);
54130
+ const filteredShifts = isUptimeMode ? validShifts.filter((shift) => isValidAggregateEfficiency("uptime", shift.efficiency)) : validShifts.filter((shift) => isValidAggregateEfficiency("output", shift.efficiency));
53841
54131
  const monthlyMetrics = filteredShifts.length > 0 ? isUptimeMode ? (() => {
53842
54132
  const totalIdleTime = filteredShifts.reduce((sum, shift) => sum + shift.idleTime, 0);
53843
54133
  const totalCycleTime = filteredShifts.reduce((sum, shift) => sum + shift.cycleTime, 0);
@@ -54107,7 +54397,8 @@ var WorkspaceCycleTimeMetricCards = ({
54107
54397
  idleTimeData,
54108
54398
  skuAware,
54109
54399
  skuBreakdown,
54110
- activeSkuId
54400
+ activeSkuId,
54401
+ liveSkuId
54111
54402
  }) => {
54112
54403
  const effectiveLegend = legend || DEFAULT_EFFICIENCY_LEGEND;
54113
54404
  const activeSku = React144__default.useMemo(() => {
@@ -54116,6 +54407,13 @@ var WorkspaceCycleTimeMetricCards = ({
54116
54407
  }
54117
54408
  return null;
54118
54409
  }, [skuAware, activeSkuId, skuBreakdown]);
54410
+ const displaySku = React144__default.useMemo(() => {
54411
+ if (activeSku) return activeSku;
54412
+ if (skuAware && !activeSkuId && liveSkuId && skuBreakdown) {
54413
+ return skuBreakdown.find((s) => s.sku_id === liveSkuId) ?? null;
54414
+ }
54415
+ return null;
54416
+ }, [activeSku, skuAware, activeSkuId, liveSkuId, skuBreakdown]);
54119
54417
  const cycleValue = activeSku ? activeSku.avg_cycle_time : workspace.avg_cycle_time;
54120
54418
  const cycleStandard = activeSku ? activeSku.ideal_cycle_time : workspace.ideal_cycle_time;
54121
54419
  const efficiencyValue = workspace.avg_efficiency || 0;
@@ -54145,7 +54443,7 @@ var WorkspaceCycleTimeMetricCards = ({
54145
54443
  /* @__PURE__ */ jsxs(Card2, { className: "flex flex-col bg-white shadow-sm border border-gray-200 h-full min-h-[150px] sm:min-h-0 rounded-xl", children: [
54146
54444
  /* @__PURE__ */ jsxs(CardHeader2, { className: "pb-1 pt-5 flex-none text-center", children: [
54147
54445
  /* @__PURE__ */ jsx(CardTitle2, { className: "text-[15px] font-bold text-gray-900 tracking-wide", children: "Cycle Time (s)" }),
54148
- activeSku && /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-blue-600 mt-1 truncate px-2", title: activeSku.sku_code, children: activeSku.sku_code })
54446
+ displaySku && /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-blue-600 mt-1 truncate px-2", title: displaySku.sku_code, children: displaySku.sku_code })
54149
54447
  ] }),
54150
54448
  /* @__PURE__ */ jsxs(CardContent2, { className: "flex-1 flex flex-col items-center justify-center pb-6", children: [
54151
54449
  /* @__PURE__ */ jsx("p", { className: `text-5xl font-bold tracking-tight ${cycleValue > (cycleStandard || 0) ? "text-red-500" : "text-[#34C759]"}`, children: cycleValue.toFixed(1) }),
@@ -67009,7 +67307,15 @@ var KPIDetailView = ({
67009
67307
  const fallbackTimes = resolveMonthlyShiftTimes(metric.shift_id);
67010
67308
  const resolvedShiftStart = metric.shift_start || fallbackTimes.start;
67011
67309
  const resolvedShiftEnd = metric.shift_end || fallbackTimes.end;
67012
- const hasBackendUptimeSeconds = isUptimeMode && (Number.isFinite(metric.active_time_seconds) || Number.isFinite(metric.idle_time_seconds) || Number.isFinite(metric.available_time_seconds));
67310
+ const coerceOptionalNumber2 = (value) => {
67311
+ if (value === void 0 || value === null || value === "") return null;
67312
+ const parsed = Number(value);
67313
+ return Number.isFinite(parsed) ? parsed : null;
67314
+ };
67315
+ const metricActiveTimeSeconds = coerceOptionalNumber2(metric.active_time_seconds);
67316
+ const metricIdleTimeSeconds = coerceOptionalNumber2(metric.idle_time_seconds);
67317
+ const metricAvailableTimeSeconds = coerceOptionalNumber2(metric.available_time_seconds);
67318
+ const hasBackendUptimeSeconds = isUptimeMode && (metricActiveTimeSeconds !== null || metricIdleTimeSeconds !== null || metricAvailableTimeSeconds !== null);
67013
67319
  const uptimeSeries2 = isUptimeMode && !hasBackendUptimeSeconds ? buildUptimeSeries({
67014
67320
  idleTimeHourly: metric.idle_time_hourly || {},
67015
67321
  shiftStart: resolvedShiftStart || void 0,
@@ -67017,9 +67323,13 @@ var KPIDetailView = ({
67017
67323
  shiftDate: metric.date,
67018
67324
  timezone: configuredTimezone
67019
67325
  }) : null;
67020
- const idleTimeSeconds = isUptimeMode ? hasBackendUptimeSeconds ? metric.idle_time_seconds || 0 : (uptimeSeries2?.idleMinutes || 0) * 60 : 0;
67021
- const activeTimeSeconds = isUptimeMode ? hasBackendUptimeSeconds ? metric.active_time_seconds || 0 : (uptimeSeries2?.activeMinutes || 0) * 60 : 0;
67022
- const availableTimeSeconds = isUptimeMode ? hasBackendUptimeSeconds ? metric.available_time_seconds || activeTimeSeconds + idleTimeSeconds : (uptimeSeries2?.availableMinutes || 0) * 60 : 0;
67326
+ const idleTimeSeconds = isUptimeMode ? hasBackendUptimeSeconds ? metricIdleTimeSeconds ?? 0 : (uptimeSeries2?.idleMinutes || 0) * 60 : 0;
67327
+ const activeTimeSeconds = isUptimeMode ? hasBackendUptimeSeconds ? metricActiveTimeSeconds ?? 0 : (uptimeSeries2?.activeMinutes || 0) * 60 : 0;
67328
+ const availableTimeSeconds = isUptimeMode ? hasBackendUptimeSeconds ? metricAvailableTimeSeconds ?? activeTimeSeconds + idleTimeSeconds : (uptimeSeries2?.availableMinutes || 0) * 60 : 0;
67329
+ const metricAvgEfficiency = Number(metric.avg_efficiency);
67330
+ const metricTotalWorkspaces = Number(metric.total_workspaces || 0);
67331
+ const metricCurrentOutput = Number(metric.current_output || 0);
67332
+ const hasUptimeMetricData = isUptimeMode && (availableTimeSeconds > 0 || metricTotalWorkspaces > 0 || metricCurrentOutput > 0 || Number.isFinite(metricAvgEfficiency) && metricAvgEfficiency > 0);
67023
67333
  const computedUptimeEfficiency = (() => {
67024
67334
  const availableMinutes = availableTimeSeconds / 60;
67025
67335
  if (!availableMinutes || availableMinutes <= 0) return 0;
@@ -67039,7 +67349,7 @@ var KPIDetailView = ({
67039
67349
  targetOutput: Number(metric.line_threshold ?? metric.ideal_output ?? 0),
67040
67350
  compliance_percentage: 95 + Math.random() * 5,
67041
67351
  // Mock data: random value between 95-100%
67042
- hasData: isUptimeMode ? availableTimeSeconds > 0 : true,
67352
+ hasData: isUptimeMode ? hasUptimeMetricData : true,
67043
67353
  idle_time_seconds: idleTimeSeconds,
67044
67354
  active_time_seconds: activeTimeSeconds,
67045
67355
  available_time_seconds: availableTimeSeconds,
@@ -68223,6 +68533,9 @@ var KPIDetailView = ({
68223
68533
  var KPIDetailViewWithDisplayNames = withSelectedLineDisplayNames(KPIDetailView);
68224
68534
  var KPIDetailView_default = KPIDetailViewWithDisplayNames;
68225
68535
  var isNonEmptyString = (value) => typeof value === "string" && value.trim().length > 0;
68536
+ var KPI_FACTORY_QUERY_PARAM = "factory_id";
68537
+ var KPI_FACTORY_AREA_QUERY_PARAM = "factory_area_id";
68538
+ var getSingleQueryValue = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
68226
68539
  var resolveCompanyId = (...candidates) => candidates.find(isNonEmptyString);
68227
68540
  var parseTimeToMinutes3 = (value) => {
68228
68541
  if (!value) return null;
@@ -68259,7 +68572,9 @@ var getMonthDateInfo = (timezone) => {
68259
68572
  var createKpisOverviewUrl = ({
68260
68573
  tab,
68261
68574
  date,
68262
- shift
68575
+ shift,
68576
+ factoryId,
68577
+ factoryAreaId
68263
68578
  }) => {
68264
68579
  const params = new URLSearchParams();
68265
68580
  if (tab) {
@@ -68271,6 +68586,12 @@ var createKpisOverviewUrl = ({
68271
68586
  if (typeof shift === "number" && Number.isFinite(shift)) {
68272
68587
  params.set("shift", shift.toString());
68273
68588
  }
68589
+ if (!tab && factoryId) {
68590
+ params.set(KPI_FACTORY_QUERY_PARAM, factoryId);
68591
+ }
68592
+ if (!tab && factoryId && factoryAreaId) {
68593
+ params.set(KPI_FACTORY_AREA_QUERY_PARAM, factoryAreaId);
68594
+ }
68274
68595
  const queryString = params.toString();
68275
68596
  return queryString ? `/kpis?${queryString}` : "/kpis";
68276
68597
  };
@@ -68792,6 +69113,101 @@ var LineCard = ({
68792
69113
  }
68793
69114
  );
68794
69115
  };
69116
+ var KpiGroupCard = ({
69117
+ title,
69118
+ subtitle,
69119
+ kpis,
69120
+ isLoading,
69121
+ error,
69122
+ isUptimeMode,
69123
+ onClick
69124
+ }) => {
69125
+ const isOnTrack = React144__default.useMemo(() => {
69126
+ if (!kpis) return null;
69127
+ return isEfficiencyOnTrack(kpis.efficiency.value);
69128
+ }, [kpis]);
69129
+ const outputTarget = Number(kpis?.outputProgress?.target ?? 0);
69130
+ const outputCurrent = Number(kpis?.outputProgress?.current ?? 0);
69131
+ const progressPercent = outputTarget > 0 ? Math.min(outputCurrent / outputTarget * 100, 100) : 0;
69132
+ return /* @__PURE__ */ jsxs(
69133
+ motion.div,
69134
+ {
69135
+ initial: { opacity: 0, y: 20 },
69136
+ animate: { opacity: 1, y: 0 },
69137
+ transition: { duration: 0.3 },
69138
+ onClick,
69139
+ className: "relative bg-white border border-gray-200/80 shadow-sm hover:shadow-lg \n rounded-xl p-4 sm:p-5 md:p-6 transition-all duration-200 cursor-pointer \n hover:scale-[1.01] active:scale-[0.99] group",
69140
+ children: [
69141
+ /* @__PURE__ */ jsx("div", { className: "mb-4 sm:mb-5 md:mb-6", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-start gap-2 sm:gap-3", children: [
69142
+ /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
69143
+ /* @__PURE__ */ jsx(
69144
+ FittingTitle,
69145
+ {
69146
+ title,
69147
+ className: "text-[10px] sm:text-xs md:text-sm"
69148
+ }
69149
+ ),
69150
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs font-medium text-gray-500", children: subtitle })
69151
+ ] }),
69152
+ !isUptimeMode && kpis && isOnTrack !== null && /* @__PURE__ */ jsxs("div", { className: `flex items-center gap-1.5 px-2.5 sm:px-3 py-1 sm:py-1.5 rounded-full text-xs font-medium flex-shrink-0 ${isOnTrack ? "bg-emerald-100 text-emerald-700 border border-emerald-200" : "bg-red-100 text-red-700 border border-red-200"}`, style: { minWidth: "fit-content" }, children: [
69153
+ /* @__PURE__ */ jsx("div", { className: `w-2 h-2 rounded-full ${isOnTrack ? "bg-emerald-500" : "bg-red-500"} animate-pulse` }),
69154
+ /* @__PURE__ */ jsx("span", { children: isOnTrack ? "On Track" : "Behind" })
69155
+ ] })
69156
+ ] }) }),
69157
+ isLoading && !kpis && /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
69158
+ /* @__PURE__ */ jsxs("div", { className: "animate-pulse", children: [
69159
+ /* @__PURE__ */ jsx("div", { className: "h-4 bg-gray-200 rounded w-1/3 mb-2" }),
69160
+ /* @__PURE__ */ jsx("div", { className: "h-8 bg-gray-200 rounded w-1/2" })
69161
+ ] }),
69162
+ /* @__PURE__ */ jsxs("div", { className: "animate-pulse", children: [
69163
+ /* @__PURE__ */ jsx("div", { className: "h-4 bg-gray-200 rounded w-1/3 mb-2" }),
69164
+ /* @__PURE__ */ jsx("div", { className: "h-8 bg-gray-200 rounded w-3/4" })
69165
+ ] }),
69166
+ /* @__PURE__ */ jsxs("div", { className: "animate-pulse", children: [
69167
+ /* @__PURE__ */ jsx("div", { className: "h-4 bg-gray-200 rounded w-1/3 mb-2" }),
69168
+ /* @__PURE__ */ jsx("div", { className: "h-8 bg-gray-200 rounded w-1/2" })
69169
+ ] })
69170
+ ] }),
69171
+ error && !kpis && /* @__PURE__ */ jsx("div", { className: "text-center py-8", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-500", children: "Unable to load metrics" }) }),
69172
+ kpis && /* @__PURE__ */ jsxs("div", { className: "space-y-4 sm:space-y-5 pb-8 sm:pb-10", children: [
69173
+ /* @__PURE__ */ jsxs("div", { children: [
69174
+ /* @__PURE__ */ jsx("div", { className: "text-xs font-medium text-gray-500 uppercase tracking-wider mb-1.5 sm:mb-2", children: isUptimeMode ? "Utilization" : "Efficiency" }),
69175
+ /* @__PURE__ */ jsxs("div", { className: "flex items-baseline justify-between", children: [
69176
+ /* @__PURE__ */ jsxs("span", { className: "text-2xl sm:text-3xl font-semibold text-gray-900", children: [
69177
+ kpis.efficiency.value.toFixed(1),
69178
+ "%"
69179
+ ] }),
69180
+ kpis.efficiency.change !== 0 && /* @__PURE__ */ jsxs("span", { className: `text-xs sm:text-sm font-medium ${kpis.efficiency.change > 0 ? "text-emerald-600" : "text-red-600"}`, children: [
69181
+ kpis.efficiency.change > 0 ? "+" : "",
69182
+ kpis.efficiency.change.toFixed(1),
69183
+ "%"
69184
+ ] })
69185
+ ] })
69186
+ ] }),
69187
+ /* @__PURE__ */ jsxs("div", { children: [
69188
+ /* @__PURE__ */ jsx("div", { className: "text-xs font-medium text-gray-500 uppercase tracking-wider mb-1.5 sm:mb-2", children: isUptimeMode ? "Stoppages" : "Output Progress" }),
69189
+ /* @__PURE__ */ jsxs("div", { className: "flex items-baseline justify-between mb-2 sm:mb-3", children: [
69190
+ /* @__PURE__ */ jsx("span", { className: `${isUptimeMode ? "text-2xl sm:text-3xl font-bold text-red-600" : "text-xl sm:text-2xl font-semibold text-gray-900"}`, children: kpis.outputProgress.current }),
69191
+ !isUptimeMode && /* @__PURE__ */ jsxs("span", { className: "text-xs sm:text-sm text-gray-500 font-medium", children: [
69192
+ "/ ",
69193
+ kpis.outputProgress.target,
69194
+ " units"
69195
+ ] })
69196
+ ] }),
69197
+ !isUptimeMode && /* @__PURE__ */ jsx("div", { className: "w-full bg-gray-200 rounded-full h-2 sm:h-2.5", children: /* @__PURE__ */ jsx(
69198
+ "div",
69199
+ {
69200
+ className: "bg-blue-600 h-2 sm:h-2.5 rounded-full transition-all duration-500 ease-out",
69201
+ style: { width: `${progressPercent}%` }
69202
+ }
69203
+ ) })
69204
+ ] })
69205
+ ] }),
69206
+ /* @__PURE__ */ jsx("div", { className: "absolute bottom-3 right-3 sm:bottom-4 sm:right-4", children: /* @__PURE__ */ jsx("div", { className: "p-2 sm:p-2.5 rounded-full bg-gray-50 group-hover:bg-blue-50 transition-colors shadow-sm", children: /* @__PURE__ */ jsx(ArrowRightIcon, { className: "w-4 h-4 sm:w-5 sm:h-5 text-gray-400 group-hover:text-blue-600 transition-colors" }) }) })
69207
+ ]
69208
+ }
69209
+ );
69210
+ };
68795
69211
  var KPIsOverviewView = ({
68796
69212
  companyId,
68797
69213
  navigate,
@@ -68957,6 +69373,20 @@ var KPIsOverviewView = ({
68957
69373
  const effectiveLeaderboardDate = selectedLeaderboardDate || currentShiftDate;
68958
69374
  const effectiveLeaderboardShiftId = Number.isFinite(selectedLeaderboardShiftId) ? selectedLeaderboardShiftId : currentShiftId;
68959
69375
  const isHistoricalLeaderboardDaily = activeTab === "leaderboard" && timeRange === "today" && (effectiveLeaderboardDate !== currentShiftDate || effectiveLeaderboardShiftId !== currentShiftId);
69376
+ const selectedFactoryIdFromUrl = getSingleQueryValue(router.query[KPI_FACTORY_QUERY_PARAM]);
69377
+ const selectedFactoryAreaIdFromUrl = getSingleQueryValue(router.query[KPI_FACTORY_AREA_QUERY_PARAM]);
69378
+ const kpiLineHierarchy = React144__default.useMemo(
69379
+ () => buildKpiLineHierarchy(linesForView),
69380
+ [linesForView]
69381
+ );
69382
+ const selectedFactoryNode = React144__default.useMemo(
69383
+ () => kpiLineHierarchy.showFactoryLevel && selectedFactoryIdFromUrl ? kpiLineHierarchy.factories.find((factory) => factory.id === selectedFactoryIdFromUrl) : void 0,
69384
+ [kpiLineHierarchy, selectedFactoryIdFromUrl]
69385
+ );
69386
+ const selectedFactoryAreaNode = React144__default.useMemo(
69387
+ () => selectedFactoryNode && selectedFactoryAreaIdFromUrl ? selectedFactoryNode.areas.find((area) => area.id === selectedFactoryAreaIdFromUrl) : void 0,
69388
+ [selectedFactoryNode, selectedFactoryAreaIdFromUrl]
69389
+ );
68960
69390
  useEffect(() => {
68961
69391
  if (!router.isReady) return;
68962
69392
  const tabQuery = router.query.tab;
@@ -68984,20 +69414,27 @@ var KPIsOverviewView = ({
68984
69414
  ]);
68985
69415
  useEffect(() => {
68986
69416
  if (!router.isReady || !hasHydratedLeaderboardRouteState) return;
69417
+ if (activeTab === "today" && loading) return;
68987
69418
  const expectedTab = activeTab === "leaderboard" ? "leaderboard" : void 0;
68988
69419
  const expectedDate = activeTab === "leaderboard" && timeRange === "today" && isHistoricalLeaderboardDaily ? effectiveLeaderboardDate : void 0;
68989
69420
  const expectedShift = expectedDate !== void 0 ? effectiveLeaderboardShiftId.toString() : void 0;
69421
+ const expectedFactory = activeTab === "today" && selectedFactoryNode ? selectedFactoryNode.id : void 0;
69422
+ const expectedFactoryArea = activeTab === "today" && selectedFactoryNode && selectedFactoryAreaNode ? selectedFactoryAreaNode.id : void 0;
68990
69423
  const currentTab = typeof router.query.tab === "string" ? router.query.tab : void 0;
68991
69424
  const currentDateQuery = typeof router.query.date === "string" ? router.query.date : void 0;
68992
69425
  const currentShiftQuery = typeof router.query.shift === "string" ? router.query.shift : void 0;
68993
- if (currentTab === expectedTab && currentDateQuery === expectedDate && currentShiftQuery === expectedShift) {
69426
+ const currentFactoryQuery = getSingleQueryValue(router.query[KPI_FACTORY_QUERY_PARAM]);
69427
+ const currentFactoryAreaQuery = getSingleQueryValue(router.query[KPI_FACTORY_AREA_QUERY_PARAM]);
69428
+ if (currentTab === expectedTab && currentDateQuery === expectedDate && currentShiftQuery === expectedShift && currentFactoryQuery === expectedFactory && currentFactoryAreaQuery === expectedFactoryArea) {
68994
69429
  return;
68995
69430
  }
68996
69431
  void router.replace(
68997
69432
  createKpisOverviewUrl({
68998
69433
  tab: expectedTab === "leaderboard" ? "leaderboard" : void 0,
68999
69434
  date: expectedDate,
69000
- shift: expectedShift !== void 0 ? Number.parseInt(expectedShift, 10) : void 0
69435
+ shift: expectedShift !== void 0 ? Number.parseInt(expectedShift, 10) : void 0,
69436
+ factoryId: expectedFactory,
69437
+ factoryAreaId: expectedFactoryArea
69001
69438
  }),
69002
69439
  void 0,
69003
69440
  { shallow: true }
@@ -69009,7 +69446,10 @@ var KPIsOverviewView = ({
69009
69446
  effectiveLeaderboardDate,
69010
69447
  effectiveLeaderboardShiftId,
69011
69448
  hasHydratedLeaderboardRouteState,
69012
- isHistoricalLeaderboardDaily
69449
+ isHistoricalLeaderboardDaily,
69450
+ loading,
69451
+ selectedFactoryNode,
69452
+ selectedFactoryAreaNode
69013
69453
  ]);
69014
69454
  const factoryViewId = entityConfig.factoryViewId || "factory";
69015
69455
  const {
@@ -69021,13 +69461,42 @@ var KPIsOverviewView = ({
69021
69461
  userAccessibleLineIds: metricsLineIds
69022
69462
  });
69023
69463
  const defaultKPIs = React144__default.useMemo(() => createDefaultKPIs(), []);
69024
- const kpisByLineId = React144__default.useMemo(() => {
69464
+ const lineModeById = React144__default.useMemo(() => {
69465
+ const map = /* @__PURE__ */ new Map();
69466
+ linesForView.forEach((line) => {
69467
+ map.set(line.id, line.monitoring_mode ?? "output");
69468
+ });
69469
+ return map;
69470
+ }, [linesForView]);
69471
+ const lineMetricRowsByLineId = React144__default.useMemo(() => {
69025
69472
  const map = /* @__PURE__ */ new Map();
69026
69473
  lineMetrics.forEach((row) => {
69027
- if (row?.line_id) map.set(row.line_id, buildKPIsFromLineMetricsRow(row));
69474
+ if (!row?.line_id) return;
69475
+ const monitoringMode = lineModeById.get(row.line_id);
69476
+ map.set(
69477
+ row.line_id,
69478
+ monitoringMode ? { ...row, monitoring_mode: monitoringMode } : row
69479
+ );
69028
69480
  });
69029
69481
  return map;
69030
- }, [lineMetrics]);
69482
+ }, [lineMetrics, lineModeById]);
69483
+ const kpisByLineId = React144__default.useMemo(() => {
69484
+ const map = /* @__PURE__ */ new Map();
69485
+ lineMetricRowsByLineId.forEach((row, lineId) => {
69486
+ map.set(lineId, buildKPIsFromLineMetricsRow(row));
69487
+ });
69488
+ return map;
69489
+ }, [lineMetricRowsByLineId]);
69490
+ const getLineCardKpis = React144__default.useCallback((line) => {
69491
+ if (metricsError) return null;
69492
+ return kpisByLineId.get(line.id) ?? (metricsLoading ? null : defaultKPIs);
69493
+ }, [defaultKPIs, kpisByLineId, metricsError, metricsLoading]);
69494
+ const getAggregateCardKpis = React144__default.useCallback((cardLines) => {
69495
+ if (metricsError) return null;
69496
+ const rows = cardLines.map((line) => lineMetricRowsByLineId.get(line.id)).filter(Boolean);
69497
+ if (metricsLoading && rows.length === 0) return null;
69498
+ return aggregateKPIsFromLineMetricsRows(rows);
69499
+ }, [lineMetricRowsByLineId, metricsError, metricsLoading]);
69031
69500
  const supervisorLineIds = React144__default.useMemo(
69032
69501
  () => (leaderboardLines.length > 0 ? leaderboardLines : lines).map((l) => l.id),
69033
69502
  [leaderboardLines, lines]
@@ -69231,6 +69700,20 @@ var KPIsOverviewView = ({
69231
69700
  if (activeTab !== "leaderboard" || timeRange !== "today") return;
69232
69701
  fetchDailyLeaderboard();
69233
69702
  }, [activeTab, timeRange, fetchDailyLeaderboard]);
69703
+ const navigateTodayHierarchy = useCallback((factoryId, factoryAreaId) => {
69704
+ void router.push(
69705
+ createKpisOverviewUrl({ factoryId, factoryAreaId }),
69706
+ void 0,
69707
+ { shallow: true }
69708
+ );
69709
+ }, [router]);
69710
+ const lineDetailReturnTo = React144__default.useMemo(() => {
69711
+ if (activeTab !== "today" || !selectedFactoryNode) return void 0;
69712
+ return createKpisOverviewUrl({
69713
+ factoryId: selectedFactoryNode.id,
69714
+ factoryAreaId: selectedFactoryAreaNode?.id
69715
+ });
69716
+ }, [activeTab, selectedFactoryNode, selectedFactoryAreaNode]);
69234
69717
  const formatTopPerformerWeek = (periodStart, periodEnd) => {
69235
69718
  const dateToUse = periodStart ? /* @__PURE__ */ new Date(`${periodStart}T00:00:00`) : /* @__PURE__ */ new Date();
69236
69719
  if (Number.isNaN(dateToUse.getTime())) {
@@ -69317,7 +69800,8 @@ var KPIsOverviewView = ({
69317
69800
  );
69318
69801
  return;
69319
69802
  }
69320
- navigation.navigate(`/kpis/${line.id}`);
69803
+ const returnToQuery = lineDetailReturnTo ? `?returnTo=${encodeURIComponent(lineDetailReturnTo)}` : "";
69804
+ navigation.navigate(`/kpis/${line.id}${returnToQuery}`);
69321
69805
  };
69322
69806
  const handleBackClick = useCallback(() => {
69323
69807
  trackCoreEvent("Back Button Clicked", {
@@ -69386,6 +69870,70 @@ var KPIsOverviewView = ({
69386
69870
  }
69387
69871
  return /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" }) });
69388
69872
  };
69873
+ const renderLineCard = (line) => /* @__PURE__ */ jsx(
69874
+ LineCard,
69875
+ {
69876
+ line,
69877
+ kpis: getLineCardKpis(line),
69878
+ isLoading: metricsLoading,
69879
+ error: metricsError,
69880
+ onClick: (kpis) => handleLineClick(line, kpis),
69881
+ supervisorEnabled,
69882
+ supervisorName: supervisorNamesByLineId.get(line.id) || null,
69883
+ supervisors: supervisorsByLineId?.get(line.id)
69884
+ },
69885
+ line.id
69886
+ );
69887
+ const renderGroupCard = ({
69888
+ key,
69889
+ title,
69890
+ subtitle,
69891
+ lines: cardLines,
69892
+ onClick
69893
+ }) => /* @__PURE__ */ jsx(
69894
+ KpiGroupCard,
69895
+ {
69896
+ title,
69897
+ subtitle,
69898
+ kpis: getAggregateCardKpis(cardLines),
69899
+ isLoading: metricsLoading,
69900
+ error: metricsError,
69901
+ isUptimeMode: viewType === "machine",
69902
+ onClick
69903
+ },
69904
+ key
69905
+ );
69906
+ const renderTodayCards = () => {
69907
+ if (!kpiLineHierarchy.showFactoryLevel) {
69908
+ return linesForView.map(renderLineCard);
69909
+ }
69910
+ if (selectedFactoryNode && selectedFactoryAreaNode) {
69911
+ return selectedFactoryAreaNode.lines.map(renderLineCard);
69912
+ }
69913
+ if (selectedFactoryNode) {
69914
+ return [
69915
+ ...selectedFactoryNode.areas.map(
69916
+ (area) => renderGroupCard({
69917
+ key: `area-${area.id}`,
69918
+ title: area.areaName,
69919
+ subtitle: `${area.lines.length} ${area.lines.length === 1 ? "line" : "lines"}`,
69920
+ lines: area.lines,
69921
+ onClick: () => navigateTodayHierarchy(selectedFactoryNode.id, area.id)
69922
+ })
69923
+ ),
69924
+ ...selectedFactoryNode.ungroupedLines.map(renderLineCard)
69925
+ ];
69926
+ }
69927
+ return kpiLineHierarchy.factories.map(
69928
+ (factory) => renderGroupCard({
69929
+ key: `factory-${factory.id}`,
69930
+ title: factory.factoryName,
69931
+ subtitle: `${factory.lines.length} ${factory.lines.length === 1 ? "line" : "lines"}`,
69932
+ lines: factory.lines,
69933
+ onClick: () => navigateTodayHierarchy(factory.id)
69934
+ })
69935
+ );
69936
+ };
69389
69937
  if (loading || isShiftConfigLoading) {
69390
69938
  return /* @__PURE__ */ jsx(LoadingPage, { message: "Loading production lines..." });
69391
69939
  }
@@ -69818,23 +70366,34 @@ var KPIsOverviewView = ({
69818
70366
  ] })
69819
70367
  ] })
69820
70368
  ] }) }),
69821
- /* @__PURE__ */ jsx("main", { className: `flex-1 p-3 sm:p-4 md:p-6 bg-slate-50 ${activeTab === "leaderboard" ? "overflow-hidden flex flex-col" : "overflow-y-auto"}`, children: activeTab === "today" ? (
69822
- /* Line Cards Grid */
69823
- /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4 md:gap-6", children: linesForView.map((line) => /* @__PURE__ */ jsx(
69824
- LineCard,
69825
- {
69826
- line,
69827
- kpis: metricsError ? null : kpisByLineId.get(line.id) ?? (metricsLoading ? null : defaultKPIs),
69828
- isLoading: metricsLoading,
69829
- error: metricsError,
69830
- onClick: (kpis) => handleLineClick(line, kpis),
69831
- supervisorEnabled,
69832
- supervisorName: supervisorNamesByLineId.get(line.id) || null,
69833
- supervisors: supervisorsByLineId?.get(line.id)
69834
- },
69835
- line.id
69836
- )) })
69837
- ) : showLeaderboardLoader ? /* @__PURE__ */ jsx("div", { className: "flex-1 flex flex-col items-center justify-center bg-white rounded-2xl border border-gray-100 shadow-sm m-2 sm:m-4", children: /* @__PURE__ */ jsx(
70369
+ /* @__PURE__ */ jsx("main", { className: `flex-1 p-3 sm:p-4 md:p-6 bg-slate-50 ${activeTab === "leaderboard" ? "overflow-hidden flex flex-col" : "overflow-y-auto"}`, children: activeTab === "today" ? /* @__PURE__ */ jsxs("div", { className: "space-y-3 sm:space-y-4", children: [
70370
+ kpiLineHierarchy.showFactoryLevel && selectedFactoryNode && /* @__PURE__ */ jsxs("nav", { className: "flex flex-wrap items-center gap-2 text-sm", "aria-label": "KPI hierarchy", children: [
70371
+ /* @__PURE__ */ jsx(
70372
+ "button",
70373
+ {
70374
+ type: "button",
70375
+ onClick: () => navigateTodayHierarchy(),
70376
+ className: "font-medium text-gray-500 hover:text-blue-600 transition-colors",
70377
+ children: "Factories"
70378
+ }
70379
+ ),
70380
+ /* @__PURE__ */ jsx("span", { className: "text-gray-300", children: "/" }),
70381
+ selectedFactoryAreaNode ? /* @__PURE__ */ jsx(
70382
+ "button",
70383
+ {
70384
+ type: "button",
70385
+ onClick: () => navigateTodayHierarchy(selectedFactoryNode.id),
70386
+ className: "font-medium text-gray-500 hover:text-blue-600 transition-colors",
70387
+ children: selectedFactoryNode.factoryName
70388
+ }
70389
+ ) : /* @__PURE__ */ jsx("span", { className: "font-semibold text-gray-900", children: selectedFactoryNode.factoryName }),
70390
+ selectedFactoryAreaNode && /* @__PURE__ */ jsxs(Fragment, { children: [
70391
+ /* @__PURE__ */ jsx("span", { className: "text-gray-300", children: "/" }),
70392
+ /* @__PURE__ */ jsx("span", { className: "font-semibold text-gray-900", children: selectedFactoryAreaNode.areaName })
70393
+ ] })
70394
+ ] }),
70395
+ /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4 md:gap-6", children: renderTodayCards() })
70396
+ ] }) : showLeaderboardLoader ? /* @__PURE__ */ jsx("div", { className: "flex-1 flex flex-col items-center justify-center bg-white rounded-2xl border border-gray-100 shadow-sm m-2 sm:m-4", children: /* @__PURE__ */ jsx(
69838
70397
  OptifyeLogoLoader_default,
69839
70398
  {
69840
70399
  size: "lg",
@@ -69881,6 +70440,27 @@ var AnimatedEfficiency = memo$1(({ value }) => {
69881
70440
  return prevProps.value === nextProps.value;
69882
70441
  });
69883
70442
  AnimatedEfficiency.displayName = "AnimatedEfficiency";
70443
+ var getWorkspaceLeaderboardMetricValue = (workspace) => {
70444
+ if (workspace.monitoring_mode === "output") {
70445
+ return toFiniteNumber(workspace.efficiency);
70446
+ }
70447
+ if (workspace.leaderboard_metric_kind === "recent_flow_shift_average") {
70448
+ return toFiniteNumber(workspace.leaderboard_value);
70449
+ }
70450
+ return toFiniteNumber(workspace.leaderboard_value) ?? toFiniteNumber(workspace.efficiency);
70451
+ };
70452
+ var getWorkspaceDisplayedMetricValue = (workspace) => getWorkspaceLeaderboardMetricValue(workspace);
70453
+ var getWorkspaceLeaderboardMetricLabel = (workspace, defaultLabel) => workspace.monitoring_mode !== "output" && workspace.leaderboard_metric_kind === "recent_flow_shift_average" ? "Avg Flow" : defaultLabel;
70454
+ var renderWorkspaceLeaderboardMetric = (workspace, isAssemblyMode) => {
70455
+ if (isAssemblyMode) {
70456
+ return /* @__PURE__ */ jsx(CycleTimeComparison, { workspace });
70457
+ }
70458
+ const displayedMetricValue = getWorkspaceDisplayedMetricValue(workspace);
70459
+ if (displayedMetricValue === null) {
70460
+ return /* @__PURE__ */ jsx("span", { className: "tabular-nums", children: "--" });
70461
+ }
70462
+ return /* @__PURE__ */ jsx(AnimatedEfficiency, { value: displayedMetricValue });
70463
+ };
69884
70464
  var HeaderRibbon = memo$1(({
69885
70465
  currentDate,
69886
70466
  currentMobileDate,
@@ -69959,13 +70539,13 @@ var MobileWorkspaceCard = memo$1(({
69959
70539
  ] })
69960
70540
  ] }),
69961
70541
  /* @__PURE__ */ jsxs("div", { className: "text-right", children: [
69962
- /* @__PURE__ */ jsx("div", { className: "font-bold text-gray-900 text-lg flex justify-end", children: isAssemblyMode ? /* @__PURE__ */ jsx(CycleTimeComparison, { workspace }) : /* @__PURE__ */ jsx(AnimatedEfficiency, { value: workspace.efficiency || 0 }) }),
69963
- /* @__PURE__ */ jsx("div", { className: "text-xs text-gray-500", children: metricLabel })
70542
+ /* @__PURE__ */ jsx("div", { className: "font-bold text-gray-900 text-lg flex justify-end", children: renderWorkspaceLeaderboardMetric(workspace, isAssemblyMode) }),
70543
+ /* @__PURE__ */ jsx("div", { className: "text-xs text-gray-500", children: getWorkspaceLeaderboardMetricLabel(workspace, metricLabel) })
69964
70544
  ] })
69965
70545
  ] })
69966
70546
  }
69967
70547
  ), (prevProps, nextProps) => {
69968
- return prevProps.metricLabel === nextProps.metricLabel && prevProps.isAssemblyMode === nextProps.isAssemblyMode && prevProps.rank === nextProps.rank && prevProps.cardClass === nextProps.cardClass && prevProps.isClickable === nextProps.isClickable && prevProps.workspace.workspace_uuid === nextProps.workspace.workspace_uuid && prevProps.workspace.efficiency === nextProps.workspace.efficiency && prevProps.workspace.ideal_cycle_time === nextProps.workspace.ideal_cycle_time && prevProps.workspace.action_count === nextProps.workspace.action_count && prevProps.workspace.action_threshold === nextProps.workspace.action_threshold && prevProps.workspace.avg_cycle_time === nextProps.workspace.avg_cycle_time && prevProps.workspace.displayName === nextProps.workspace.displayName && prevProps.workspace.lineName === nextProps.workspace.lineName;
70548
+ return prevProps.metricLabel === nextProps.metricLabel && prevProps.isAssemblyMode === nextProps.isAssemblyMode && prevProps.rank === nextProps.rank && prevProps.cardClass === nextProps.cardClass && prevProps.isClickable === nextProps.isClickable && prevProps.workspace.workspace_uuid === nextProps.workspace.workspace_uuid && prevProps.workspace.leaderboard_value === nextProps.workspace.leaderboard_value && prevProps.workspace.leaderboard_metric_kind === nextProps.workspace.leaderboard_metric_kind && prevProps.workspace.efficiency === nextProps.workspace.efficiency && prevProps.workspace.ideal_cycle_time === nextProps.workspace.ideal_cycle_time && prevProps.workspace.action_count === nextProps.workspace.action_count && prevProps.workspace.action_threshold === nextProps.workspace.action_threshold && prevProps.workspace.avg_cycle_time === nextProps.workspace.avg_cycle_time && prevProps.workspace.displayName === nextProps.workspace.displayName && prevProps.workspace.lineName === nextProps.workspace.lineName;
69969
70549
  });
69970
70550
  MobileWorkspaceCard.displayName = "MobileWorkspaceCard";
69971
70551
  var DesktopWorkspaceRow = memo$1(({
@@ -69992,11 +70572,11 @@ var DesktopWorkspaceRow = memo$1(({
69992
70572
  ] }) }),
69993
70573
  /* @__PURE__ */ jsx("td", { className: "px-3 py-2.5 sm:p-4 text-sm sm:text-base whitespace-nowrap", children: /* @__PURE__ */ jsx("div", { className: "font-medium", children: workspace.displayName }) }),
69994
70574
  /* @__PURE__ */ jsx("td", { className: "px-3 py-2.5 sm:p-4 text-sm sm:text-base whitespace-nowrap", children: /* @__PURE__ */ jsx("div", { className: "font-medium", children: workspace.lineName }) }),
69995
- /* @__PURE__ */ jsx("td", { className: `px-3 py-2.5 sm:p-4 text-sm sm:text-base font-medium ${isAssemblyMode ? "" : "whitespace-nowrap"}`, children: isAssemblyMode ? /* @__PURE__ */ jsx(CycleTimeComparison, { workspace }) : /* @__PURE__ */ jsx(AnimatedEfficiency, { value: workspace.efficiency || 0 }) })
70575
+ /* @__PURE__ */ jsx("td", { className: `px-3 py-2.5 sm:p-4 text-sm sm:text-base font-medium ${isAssemblyMode ? "" : "whitespace-nowrap"}`, children: isAssemblyMode ? renderWorkspaceLeaderboardMetric(workspace, true) : /* @__PURE__ */ jsx("div", { className: "flex flex-col", children: renderWorkspaceLeaderboardMetric(workspace, false) }) })
69996
70576
  ]
69997
70577
  }
69998
70578
  ), (prevProps, nextProps) => {
69999
- return prevProps.index === nextProps.index && prevProps.rowClass === nextProps.rowClass && prevProps.isClickable === nextProps.isClickable && prevProps.isAssemblyMode === nextProps.isAssemblyMode && prevProps.workspace.workspace_uuid === nextProps.workspace.workspace_uuid && prevProps.workspace.efficiency === nextProps.workspace.efficiency && prevProps.workspace.ideal_cycle_time === nextProps.workspace.ideal_cycle_time && prevProps.workspace.avg_cycle_time === nextProps.workspace.avg_cycle_time && prevProps.workspace.displayName === nextProps.workspace.displayName && prevProps.workspace.lineName === nextProps.workspace.lineName;
70579
+ return prevProps.index === nextProps.index && prevProps.rowClass === nextProps.rowClass && prevProps.isClickable === nextProps.isClickable && prevProps.isAssemblyMode === nextProps.isAssemblyMode && prevProps.workspace.workspace_uuid === nextProps.workspace.workspace_uuid && prevProps.workspace.leaderboard_value === nextProps.workspace.leaderboard_value && prevProps.workspace.leaderboard_metric_kind === nextProps.workspace.leaderboard_metric_kind && prevProps.workspace.efficiency === nextProps.workspace.efficiency && prevProps.workspace.ideal_cycle_time === nextProps.workspace.ideal_cycle_time && prevProps.workspace.avg_cycle_time === nextProps.workspace.avg_cycle_time && prevProps.workspace.displayName === nextProps.workspace.displayName && prevProps.workspace.lineName === nextProps.workspace.lineName;
70000
70580
  });
70001
70581
  DesktopWorkspaceRow.displayName = "DesktopWorkspaceRow";
70002
70582
  var LeaderboardDetailView = memo$1(({
@@ -70095,6 +70675,8 @@ var LeaderboardDetailView = memo$1(({
70095
70675
  const [monthlyError, setMonthlyError] = useState(null);
70096
70676
  const todayRequestKeyRef = useRef(null);
70097
70677
  const monthlyRequestKeyRef = useRef(null);
70678
+ const monthlyLoadKeyRef = useRef(null);
70679
+ const monthlyLoadPromiseRef = useRef(null);
70098
70680
  const leaderboardUpdateQueuedRef = useRef(false);
70099
70681
  const leaderboardUpdateTimerRef = useRef(null);
70100
70682
  const leaderboardViewTrackedRef = useRef(null);
@@ -70369,6 +70951,9 @@ var LeaderboardDetailView = memo$1(({
70369
70951
  trend: 0,
70370
70952
  predicted_output: 0,
70371
70953
  efficiency: entry.efficiency || 0,
70954
+ avg_recent_flow: toFiniteNumber(entry.avg_recent_flow),
70955
+ leaderboard_value: toFiniteNumber(entry.leaderboard_value),
70956
+ leaderboard_metric_kind: entry.leaderboard_metric_kind ?? "efficiency",
70372
70957
  action_threshold: entry.total_day_output || 0,
70373
70958
  displayName: entry.workspace_display_name,
70374
70959
  monitoring_mode: entry.monitoring_mode ?? "output"
@@ -70399,7 +70984,10 @@ var LeaderboardDetailView = memo$1(({
70399
70984
  searchParams.set("monitoring_mode", viewType === "machine" ? "uptime" : "output");
70400
70985
  const data = await fetchBackendJson(
70401
70986
  supabase,
70402
- `/api/dashboard/leaderboard?${searchParams.toString()}`
70987
+ `/api/dashboard/leaderboard?${searchParams.toString()}`,
70988
+ {
70989
+ timeoutMs: params.startDate && params.endDate ? 3e4 : void 0
70990
+ }
70403
70991
  );
70404
70992
  return data.entries || [];
70405
70993
  }, [supabase, entityConfig.companyId, configuredLineIds, viewType]);
@@ -70477,15 +71065,21 @@ var LeaderboardDetailView = memo$1(({
70477
71065
  setMonthlyLoading(true);
70478
71066
  setMonthlyError(null);
70479
71067
  try {
70480
- const entries = await fetchLeaderboardEntries({
70481
- startDate: normalizedRange.startKey,
70482
- endDate: normalizedRange.endKey,
70483
- shiftId: monthlyShiftId
70484
- });
71068
+ const loadPromise = monthlyLoadPromiseRef.current && monthlyLoadKeyRef.current === requestKey ? monthlyLoadPromiseRef.current : (async () => {
71069
+ const entries = await fetchLeaderboardEntries({
71070
+ startDate: normalizedRange.startKey,
71071
+ endDate: normalizedRange.endKey,
71072
+ shiftId: monthlyShiftId
71073
+ });
71074
+ return mapEntriesToWorkspaces(entries, normalizedRange.endKey, monthlyShiftId);
71075
+ })();
71076
+ monthlyLoadKeyRef.current = requestKey;
71077
+ monthlyLoadPromiseRef.current = loadPromise;
71078
+ const workspaces = await loadPromise;
70485
71079
  if (monthlyRequestKeyRef.current !== requestKey) {
70486
71080
  return;
70487
71081
  }
70488
- setMonthlyEntries(mapEntriesToWorkspaces(entries, normalizedRange.endKey, monthlyShiftId));
71082
+ setMonthlyEntries(workspaces);
70489
71083
  } catch (err) {
70490
71084
  console.error("[LeaderboardDetailView] Error fetching monthly leaderboard:", err);
70491
71085
  if (monthlyRequestKeyRef.current !== requestKey) {
@@ -70494,6 +71088,9 @@ var LeaderboardDetailView = memo$1(({
70494
71088
  setMonthlyError({ message: err.message, code: err.code || "FETCH_ERROR" });
70495
71089
  setMonthlyEntries([]);
70496
71090
  } finally {
71091
+ if (monthlyLoadKeyRef.current === requestKey && monthlyLoadPromiseRef.current) {
71092
+ monthlyLoadPromiseRef.current = null;
71093
+ }
70497
71094
  if (monthlyRequestKeyRef.current === requestKey) {
70498
71095
  setMonthlyLoading(false);
70499
71096
  }
@@ -70506,6 +71103,46 @@ var LeaderboardDetailView = memo$1(({
70506
71103
  monthlyShiftId,
70507
71104
  lineKey
70508
71105
  ]);
71106
+ useEffect(() => {
71107
+ if (activeTab !== "today") {
71108
+ return;
71109
+ }
71110
+ const requestKey = `${normalizedRange.startKey}|${normalizedRange.endKey}|${monthlyShiftId}|${lineKey}|${viewType}`;
71111
+ let cancelled = false;
71112
+ const loadPromise = monthlyLoadPromiseRef.current && monthlyLoadKeyRef.current === requestKey ? monthlyLoadPromiseRef.current : (async () => {
71113
+ const entries = await fetchLeaderboardEntries({
71114
+ startDate: normalizedRange.startKey,
71115
+ endDate: normalizedRange.endKey,
71116
+ shiftId: monthlyShiftId
71117
+ });
71118
+ return mapEntriesToWorkspaces(entries, normalizedRange.endKey, monthlyShiftId);
71119
+ })();
71120
+ monthlyLoadKeyRef.current = requestKey;
71121
+ monthlyLoadPromiseRef.current = loadPromise;
71122
+ loadPromise.then((workspaces) => {
71123
+ if (cancelled) {
71124
+ return;
71125
+ }
71126
+ setMonthlyEntries(workspaces);
71127
+ }).catch(() => {
71128
+ }).finally(() => {
71129
+ if (!cancelled && monthlyLoadKeyRef.current === requestKey && monthlyLoadPromiseRef.current === loadPromise) {
71130
+ monthlyLoadPromiseRef.current = null;
71131
+ }
71132
+ });
71133
+ return () => {
71134
+ cancelled = true;
71135
+ };
71136
+ }, [
71137
+ activeTab,
71138
+ fetchLeaderboardEntries,
71139
+ mapEntriesToWorkspaces,
71140
+ normalizedRange.endKey,
71141
+ normalizedRange.startKey,
71142
+ monthlyShiftId,
71143
+ lineKey,
71144
+ viewType
71145
+ ]);
70509
71146
  useEffect(() => {
70510
71147
  if (activeTab === "today") {
70511
71148
  fetchTodayLeaderboard();
@@ -70640,6 +71277,9 @@ var LeaderboardDetailView = memo$1(({
70640
71277
  total_workspaces: workspacesLengthRef.current,
70641
71278
  // Use ref instead of state to avoid dependency
70642
71279
  metric_context: viewType === "machine" ? "machine" : outputCategory,
71280
+ leaderboard_value: getWorkspaceLeaderboardMetricValue(workspace),
71281
+ leaderboard_metric_kind: workspace.leaderboard_metric_kind ?? "efficiency",
71282
+ avg_recent_flow: workspace.avg_recent_flow ?? null,
70643
71283
  efficiency: workspace.efficiency,
70644
71284
  action_count: workspace.action_count,
70645
71285
  action_threshold: workspace.action_threshold,
@@ -70720,9 +71360,12 @@ var LeaderboardDetailView = memo$1(({
70720
71360
  if (ratioB === null) return -1;
70721
71361
  return sortAscending ? ratioA - ratioB : ratioB - ratioA;
70722
71362
  }
70723
- const effA = a.efficiency || 0;
70724
- const effB = b.efficiency || 0;
70725
- return sortAscending ? effA - effB : effB - effA;
71363
+ const metricA = getWorkspaceLeaderboardMetricValue(a);
71364
+ const metricB = getWorkspaceLeaderboardMetricValue(b);
71365
+ if (metricA === null && metricB === null) return 0;
71366
+ if (metricA === null) return 1;
71367
+ if (metricB === null) return -1;
71368
+ return sortAscending ? metricA - metricB : metricB - metricA;
70726
71369
  });
70727
71370
  }, [workspaceDisplayData, sortAscending, selectedLineFilter, selectedShiftFilter, activeTab, viewType, isAssemblyMode]);
70728
71371
  const loading = activeTab === "today" ? todayLoading : monthlyLoading;
@@ -70751,6 +71394,8 @@ var LeaderboardDetailView = memo$1(({
70751
71394
  workspace_count: sortedWorkspaces.length,
70752
71395
  top_workspace_id: topWorkspace?.workspace_uuid ?? null,
70753
71396
  top_workspace_name: topWorkspace?.workspace_name ?? null,
71397
+ top_leaderboard_value: topWorkspace ? getWorkspaceLeaderboardMetricValue(topWorkspace) : null,
71398
+ top_leaderboard_metric_kind: topWorkspace?.leaderboard_metric_kind ?? null,
70754
71399
  top_efficiency: topWorkspace?.efficiency ?? null,
70755
71400
  top_avg_cycle_time: topWorkspace?.avg_cycle_time ?? null,
70756
71401
  top_ideal_cycle_time: topWorkspace?.ideal_cycle_time ?? null,
@@ -75896,7 +76541,11 @@ var WorkspaceDetailView = ({
75896
76541
  workspace,
75897
76542
  legend: efficiencyLegend,
75898
76543
  layout: "stack",
75899
- idleTimeData: idleTimeVlmEnabled ? idleTimeData : void 0
76544
+ idleTimeData: idleTimeVlmEnabled ? idleTimeData : void 0,
76545
+ skuAware: isSkuAware,
76546
+ skuBreakdown: isSkuAware ? realSkuBreakdown : void 0,
76547
+ activeSkuId,
76548
+ liveSkuId: isHistoricView ? null : liveSkuId
75900
76549
  }
75901
76550
  ) : /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(
75902
76551
  WorkspaceMetricCards,
@@ -75906,7 +76555,8 @@ var WorkspaceDetailView = ({
75906
76555
  className: "flex-1",
75907
76556
  skuAware: isSkuAware,
75908
76557
  skuBreakdown: isSkuAware ? realSkuBreakdown : void 0,
75909
- activeSkuId
76558
+ activeSkuId,
76559
+ liveSkuId: isHistoricView ? null : liveSkuId
75910
76560
  }
75911
76561
  ) })
75912
76562
  ] }),
@@ -76049,7 +76699,11 @@ var WorkspaceDetailView = ({
76049
76699
  legend: efficiencyLegend,
76050
76700
  layout: "grid",
76051
76701
  className: desktopBottomSectionClass,
76052
- idleTimeData: idleTimeVlmEnabled ? idleTimeData : void 0
76702
+ idleTimeData: idleTimeVlmEnabled ? idleTimeData : void 0,
76703
+ skuAware: isSkuAware,
76704
+ skuBreakdown: isSkuAware ? realSkuBreakdown : void 0,
76705
+ activeSkuId,
76706
+ liveSkuId: isHistoricView ? null : liveSkuId
76053
76707
  }
76054
76708
  ) : /* @__PURE__ */ jsx("div", { className: clsx("flex min-h-0", desktopBottomSectionClass), children: /* @__PURE__ */ jsx(
76055
76709
  WorkspaceMetricCards,
@@ -76059,7 +76713,8 @@ var WorkspaceDetailView = ({
76059
76713
  className: "flex-1",
76060
76714
  skuAware: isSkuAware,
76061
76715
  skuBreakdown: isSkuAware ? realSkuBreakdown : void 0,
76062
- activeSkuId
76716
+ activeSkuId,
76717
+ liveSkuId: isHistoricView ? null : liveSkuId
76063
76718
  }
76064
76719
  ) })
76065
76720
  ] })
@@ -85098,4 +85753,4 @@ var streamProxyConfig = {
85098
85753
  }
85099
85754
  };
85100
85755
 
85101
- 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, 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, 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, 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 };
85756
+ 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, 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, 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 };