@optifye/dashboard-core 6.4.2 → 6.5.0

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.js CHANGED
@@ -7,7 +7,6 @@ var dateFnsTz = require('date-fns-tz');
7
7
  var dateFns = require('date-fns');
8
8
  var mixpanel = require('mixpanel-browser');
9
9
  var events = require('events');
10
- var clientS3 = require('@aws-sdk/client-s3');
11
10
  var supabaseJs = require('@supabase/supabase-js');
12
11
  var Hls2 = require('hls.js');
13
12
  var useSWR = require('swr');
@@ -25,6 +24,7 @@ var SelectPrimitive = require('@radix-ui/react-select');
25
24
  var videojs = require('video.js');
26
25
  require('video.js/dist/video-js.css');
27
26
  var sonner = require('sonner');
27
+ var clientS3 = require('@aws-sdk/client-s3');
28
28
  var s3RequestPresigner = require('@aws-sdk/s3-request-presigner');
29
29
  var stream = require('stream');
30
30
 
@@ -1704,6 +1704,25 @@ var workspaceService = {
1704
1704
  this._workspaceDisplayNamesCache.clear();
1705
1705
  this._cacheTimestamp = 0;
1706
1706
  },
1707
+ /**
1708
+ * Updates the display name for a workspace
1709
+ * @param workspaceId - The workspace UUID
1710
+ * @param displayName - The new display name
1711
+ * @returns Promise<void>
1712
+ */
1713
+ async updateWorkspaceDisplayName(workspaceId, displayName) {
1714
+ const supabase = _getSupabaseInstance();
1715
+ if (!supabase) throw new Error("Supabase client not initialized");
1716
+ const config = _getDashboardConfigInstance();
1717
+ const dbConfig = config?.databaseConfig;
1718
+ const workspacesTable = getTable3(dbConfig, "workspaces");
1719
+ const { error } = await supabase.from(workspacesTable).update({ display_name: displayName.trim() }).eq("id", workspaceId);
1720
+ if (error) {
1721
+ console.error(`Error updating workspace display name for ${workspaceId}:`, error);
1722
+ throw error;
1723
+ }
1724
+ this.clearWorkspaceDisplayNamesCache();
1725
+ },
1707
1726
  async updateWorkspaceAction(updates) {
1708
1727
  const supabase = _getSupabaseInstance();
1709
1728
  if (!supabase) throw new Error("Supabase client not initialized");
@@ -1847,6 +1866,209 @@ var workspaceService = {
1847
1866
  }
1848
1867
  }
1849
1868
  };
1869
+ var WorkspaceHealthService = class _WorkspaceHealthService {
1870
+ constructor() {
1871
+ this.cache = /* @__PURE__ */ new Map();
1872
+ this.cacheExpiryMs = 30 * 1e3;
1873
+ }
1874
+ // 30 seconds cache
1875
+ static getInstance() {
1876
+ if (!_WorkspaceHealthService.instance) {
1877
+ _WorkspaceHealthService.instance = new _WorkspaceHealthService();
1878
+ }
1879
+ return _WorkspaceHealthService.instance;
1880
+ }
1881
+ getFromCache(key) {
1882
+ const cached = this.cache.get(key);
1883
+ if (cached && Date.now() - cached.timestamp < this.cacheExpiryMs) {
1884
+ return cached.data;
1885
+ }
1886
+ this.cache.delete(key);
1887
+ return null;
1888
+ }
1889
+ setCache(key, data) {
1890
+ this.cache.set(key, { data, timestamp: Date.now() });
1891
+ }
1892
+ async getWorkspaceHealthStatus(options = {}) {
1893
+ const supabase = _getSupabaseInstance();
1894
+ if (!supabase) throw new Error("Supabase client not initialized");
1895
+ let query = supabase.from("workspace_health_status").select("*").order("workspace_display_name", { ascending: true });
1896
+ if (options.lineId) {
1897
+ query = query.eq("line_id", options.lineId);
1898
+ }
1899
+ if (options.companyId) {
1900
+ query = query.eq("company_id", options.companyId);
1901
+ }
1902
+ const { data, error } = await query;
1903
+ if (error) {
1904
+ console.error("Error fetching workspace health status:", error);
1905
+ throw error;
1906
+ }
1907
+ const processedData = (data || []).map((item) => this.processHealthStatus(item));
1908
+ let filteredData = processedData;
1909
+ try {
1910
+ const { data: enabledWorkspaces, error: workspaceError } = await supabase.from("workspaces").select("workspace_id, display_name").eq("enable", true);
1911
+ if (!workspaceError && enabledWorkspaces && enabledWorkspaces.length > 0) {
1912
+ const enabledWorkspaceNames = /* @__PURE__ */ new Set();
1913
+ enabledWorkspaces.forEach((w) => {
1914
+ if (w.workspace_id) enabledWorkspaceNames.add(w.workspace_id);
1915
+ if (w.display_name) enabledWorkspaceNames.add(w.display_name);
1916
+ });
1917
+ filteredData = filteredData.filter((item) => {
1918
+ const displayName = item.workspace_display_name || "";
1919
+ return enabledWorkspaceNames.has(displayName);
1920
+ });
1921
+ } else if (!workspaceError && enabledWorkspaces && enabledWorkspaces.length === 0) {
1922
+ return [];
1923
+ } else if (workspaceError) {
1924
+ console.error("Error fetching enabled workspaces:", workspaceError);
1925
+ }
1926
+ } catch (e) {
1927
+ console.error("Error filtering workspaces:", e);
1928
+ }
1929
+ if (options.status) {
1930
+ filteredData = filteredData.filter((item) => item.status === options.status);
1931
+ }
1932
+ if (options.searchTerm) {
1933
+ const searchLower = options.searchTerm.toLowerCase();
1934
+ filteredData = filteredData.filter(
1935
+ (item) => item.workspace_display_name?.toLowerCase().includes(searchLower) || item.line_name?.toLowerCase().includes(searchLower) || item.company_name?.toLowerCase().includes(searchLower)
1936
+ );
1937
+ }
1938
+ if (options.sortBy) {
1939
+ filteredData.sort((a, b) => {
1940
+ let compareValue = 0;
1941
+ switch (options.sortBy) {
1942
+ case "name":
1943
+ compareValue = (a.workspace_display_name || "").localeCompare(b.workspace_display_name || "");
1944
+ break;
1945
+ case "status":
1946
+ compareValue = this.getStatusPriority(a.status) - this.getStatusPriority(b.status);
1947
+ break;
1948
+ case "lastUpdate":
1949
+ compareValue = new Date(b.last_heartbeat).getTime() - new Date(a.last_heartbeat).getTime();
1950
+ break;
1951
+ }
1952
+ return options.sortOrder === "desc" ? -compareValue : compareValue;
1953
+ });
1954
+ }
1955
+ return filteredData;
1956
+ }
1957
+ async getWorkspaceHealthById(workspaceId) {
1958
+ const cacheKey = `health-${workspaceId}`;
1959
+ const cached = this.getFromCache(cacheKey);
1960
+ if (cached) return cached;
1961
+ const supabase = _getSupabaseInstance();
1962
+ if (!supabase) throw new Error("Supabase client not initialized");
1963
+ const { data, error } = await supabase.from("workspace_health_status").select("*").eq("workspace_id", workspaceId).single();
1964
+ if (error) {
1965
+ if (error.code === "PGRST116") {
1966
+ return null;
1967
+ }
1968
+ console.error("Error fetching workspace health:", error);
1969
+ throw error;
1970
+ }
1971
+ const processedData = data ? this.processHealthStatus(data) : null;
1972
+ if (processedData) {
1973
+ this.setCache(cacheKey, processedData);
1974
+ }
1975
+ return processedData;
1976
+ }
1977
+ async getHealthSummary(lineId, companyId) {
1978
+ this.clearCache();
1979
+ const workspaces = await this.getWorkspaceHealthStatus({ lineId, companyId });
1980
+ const totalWorkspaces = workspaces.length;
1981
+ const healthyWorkspaces = workspaces.filter((w) => w.status === "healthy").length;
1982
+ const unhealthyWorkspaces = workspaces.filter((w) => w.status === "unhealthy").length;
1983
+ const warningWorkspaces = workspaces.filter((w) => w.status === "warning").length;
1984
+ const uptimePercentage = totalWorkspaces > 0 ? healthyWorkspaces / totalWorkspaces * 100 : 0;
1985
+ return {
1986
+ totalWorkspaces,
1987
+ healthyWorkspaces,
1988
+ unhealthyWorkspaces,
1989
+ warningWorkspaces,
1990
+ uptimePercentage,
1991
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
1992
+ };
1993
+ }
1994
+ async getHealthMetrics(workspaceId, startDate, endDate) {
1995
+ const supabase = _getSupabaseInstance();
1996
+ if (!supabase) throw new Error("Supabase client not initialized");
1997
+ return {
1998
+ avgResponseTime: 250,
1999
+ totalDowntime: 0,
2000
+ incidentCount: 0,
2001
+ mttr: 0
2002
+ };
2003
+ }
2004
+ processHealthStatus(data) {
2005
+ const now2 = /* @__PURE__ */ new Date();
2006
+ const lastHeartbeat = new Date(data.last_heartbeat);
2007
+ const minutesSinceUpdate = Math.floor((now2.getTime() - lastHeartbeat.getTime()) / (1e3 * 60));
2008
+ let status = "unknown";
2009
+ let isStale = false;
2010
+ if (data.is_healthy) {
2011
+ if (minutesSinceUpdate < 3) {
2012
+ status = "healthy";
2013
+ } else if (minutesSinceUpdate < 5) {
2014
+ status = "warning";
2015
+ isStale = true;
2016
+ } else {
2017
+ status = "unhealthy";
2018
+ isStale = true;
2019
+ }
2020
+ } else {
2021
+ status = "unhealthy";
2022
+ if (minutesSinceUpdate > 5) {
2023
+ isStale = true;
2024
+ }
2025
+ }
2026
+ const timeSinceLastUpdate = dateFns.formatDistanceToNow(lastHeartbeat, { addSuffix: true });
2027
+ return {
2028
+ ...data,
2029
+ status,
2030
+ timeSinceLastUpdate,
2031
+ isStale
2032
+ };
2033
+ }
2034
+ getStatusPriority(status) {
2035
+ const priorities = {
2036
+ unhealthy: 0,
2037
+ warning: 1,
2038
+ unknown: 2,
2039
+ healthy: 3
2040
+ };
2041
+ return priorities[status];
2042
+ }
2043
+ subscribeToHealthUpdates(callback, filters) {
2044
+ const supabase = _getSupabaseInstance();
2045
+ if (!supabase) throw new Error("Supabase client not initialized");
2046
+ let subscription = supabase.channel("workspace-health-updates").on(
2047
+ "postgres_changes",
2048
+ {
2049
+ event: "*",
2050
+ schema: "public",
2051
+ table: "workspace_health_status"
2052
+ },
2053
+ (payload) => {
2054
+ if (payload.new) {
2055
+ const newData = payload.new;
2056
+ if (filters?.lineId && newData.line_id !== filters.lineId) return;
2057
+ if (filters?.companyId && newData.company_id !== filters.companyId) return;
2058
+ this.clearCache();
2059
+ callback(newData);
2060
+ }
2061
+ }
2062
+ ).subscribe();
2063
+ return () => {
2064
+ subscription.unsubscribe();
2065
+ };
2066
+ }
2067
+ clearCache() {
2068
+ this.cache.clear();
2069
+ }
2070
+ };
2071
+ var workspaceHealthService = WorkspaceHealthService.getInstance();
1850
2072
 
1851
2073
  // src/lib/services/skuService.ts
1852
2074
  var getTable4 = (dbConfig, tableName) => {
@@ -3241,6 +3463,14 @@ function parseS3Uri(s3Uri, sopCategories) {
3241
3463
  return null;
3242
3464
  }
3243
3465
  }
3466
+ function shuffleArray(array) {
3467
+ const shuffled = [...array];
3468
+ for (let i = shuffled.length - 1; i > 0; i--) {
3469
+ const j = Math.floor(Math.random() * (i + 1));
3470
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
3471
+ }
3472
+ return shuffled;
3473
+ }
3244
3474
 
3245
3475
  // src/lib/cache/clipsCache.ts
3246
3476
  var LRUCache = class _LRUCache {
@@ -3753,300 +3983,321 @@ if (typeof window !== "undefined") {
3753
3983
  });
3754
3984
  });
3755
3985
  }
3756
-
3757
- // src/lib/api/s3-clips.ts
3758
- var RequestDeduplicationCache = class {
3759
- constructor() {
3760
- this.pendingRequests = /* @__PURE__ */ new Map();
3761
- this.maxCacheSize = 1e3;
3762
- this.cleanupInterval = 3e5;
3763
- // 5 minutes
3764
- this.lastCleanup = Date.now();
3986
+ var getSupabaseClient = () => {
3987
+ const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
3988
+ const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
3989
+ if (!url || !key) {
3990
+ throw new Error("Supabase configuration missing");
3991
+ }
3992
+ return supabaseJs.createClient(url, key);
3993
+ };
3994
+ var getAuthToken = async () => {
3995
+ try {
3996
+ const supabase = getSupabaseClient();
3997
+ const { data: { session } } = await supabase.auth.getSession();
3998
+ return session?.access_token || null;
3999
+ } catch (error) {
4000
+ console.error("[S3ClipsAPIClient] Error getting auth token:", error);
4001
+ return null;
4002
+ }
4003
+ };
4004
+ var S3ClipsAPIClient = class {
4005
+ constructor(sopCategories) {
4006
+ this.baseUrl = "/api/clips";
4007
+ this.requestCache = /* @__PURE__ */ new Map();
4008
+ this.sopCategories = sopCategories;
4009
+ console.log("[S3ClipsAPIClient] \u2705 Initialized - Using secure API routes (no direct S3 access)");
3765
4010
  }
3766
4011
  /**
3767
- * Get or create a deduplicated request
4012
+ * Fetch with authentication and error handling
3768
4013
  */
3769
- async deduplicate(key, factory, logPrefix = "Request") {
3770
- this.periodicCleanup();
3771
- const existingRequest = this.pendingRequests.get(key);
3772
- if (existingRequest) {
3773
- console.log(`[${logPrefix}] Deduplicating request for key: ${key}`);
3774
- return existingRequest;
4014
+ async fetchWithAuth(endpoint, body) {
4015
+ const token = await getAuthToken();
4016
+ if (!token) {
4017
+ throw new Error("Authentication required");
4018
+ }
4019
+ const response = await fetch(endpoint, {
4020
+ method: "POST",
4021
+ headers: {
4022
+ "Authorization": `Bearer ${token}`,
4023
+ "Content-Type": "application/json"
4024
+ },
4025
+ body: JSON.stringify(body)
4026
+ });
4027
+ if (!response.ok) {
4028
+ const error = await response.json().catch(() => ({ error: "Request failed" }));
4029
+ throw new Error(error.error || `API error: ${response.status}`);
4030
+ }
4031
+ return response.json();
4032
+ }
4033
+ /**
4034
+ * Deduplicate requests to prevent multiple API calls
4035
+ */
4036
+ async deduplicate(key, factory) {
4037
+ if (this.requestCache.has(key)) {
4038
+ console.log(`[S3ClipsAPIClient] Deduplicating request: ${key}`);
4039
+ return this.requestCache.get(key);
3775
4040
  }
3776
- console.log(`[${logPrefix}] Creating new request for key: ${key}`);
3777
4041
  const promise = factory().finally(() => {
3778
- this.pendingRequests.delete(key);
3779
- console.log(`[${logPrefix}] Completed and cleaned up request: ${key}`);
4042
+ this.requestCache.delete(key);
3780
4043
  });
3781
- this.pendingRequests.set(key, promise);
4044
+ this.requestCache.set(key, promise);
3782
4045
  return promise;
3783
4046
  }
3784
4047
  /**
3785
- * Clear all pending requests (useful for cleanup)
4048
+ * List S3 clips
3786
4049
  */
3787
- clear() {
3788
- console.log(`[RequestCache] Clearing ${this.pendingRequests.size} pending requests`);
3789
- this.pendingRequests.clear();
4050
+ async listS3Clips(params) {
4051
+ const cacheKey = `list:${JSON.stringify(params)}`;
4052
+ return this.deduplicate(cacheKey, async () => {
4053
+ const response = await this.fetchWithAuth(this.baseUrl, {
4054
+ action: "list",
4055
+ workspaceId: params.workspaceId,
4056
+ date: params.date,
4057
+ shift: params.shiftId,
4058
+ maxKeys: params.maxKeys
4059
+ });
4060
+ return response.clips.map((clip) => clip.originalUri);
4061
+ });
3790
4062
  }
3791
4063
  /**
3792
- * Get current cache stats
4064
+ * Get clip counts
3793
4065
  */
3794
- getStats() {
3795
- return {
3796
- pendingCount: this.pendingRequests.size,
3797
- maxSize: this.maxCacheSize
4066
+ async getClipCounts(workspaceId, date, shiftId) {
4067
+ const cacheKey = `counts:${workspaceId}:${date}:${shiftId}`;
4068
+ return this.deduplicate(cacheKey, async () => {
4069
+ const response = await this.fetchWithAuth(this.baseUrl, {
4070
+ action: "count",
4071
+ workspaceId,
4072
+ date,
4073
+ shift: shiftId.toString()
4074
+ });
4075
+ return response.counts;
4076
+ });
4077
+ }
4078
+ /**
4079
+ * Get clip counts with index (for compatibility)
4080
+ */
4081
+ async getClipCountsWithIndex(workspaceId, date, shiftId) {
4082
+ const counts = await this.getClipCounts(workspaceId, date, shiftId.toString());
4083
+ const videoIndex = {
4084
+ byCategory: /* @__PURE__ */ new Map(),
4085
+ allVideos: [],
4086
+ counts,
4087
+ workspaceId,
4088
+ date,
4089
+ shiftId: shiftId.toString(),
4090
+ lastUpdated: /* @__PURE__ */ new Date()
3798
4091
  };
4092
+ return { counts, videoIndex };
3799
4093
  }
3800
4094
  /**
3801
- * Periodic cleanup to prevent memory leaks
4095
+ * Get metadata for a video
3802
4096
  */
3803
- periodicCleanup() {
3804
- const now2 = Date.now();
3805
- if (now2 - this.lastCleanup > this.cleanupInterval) {
3806
- if (this.pendingRequests.size > this.maxCacheSize) {
3807
- console.warn(`[RequestCache] Cache size exceeded ${this.maxCacheSize}, clearing oldest entries`);
3808
- const entries = Array.from(this.pendingRequests.entries());
3809
- this.pendingRequests.clear();
3810
- entries.slice(-Math.floor(this.maxCacheSize / 2)).forEach(([key, promise]) => {
3811
- this.pendingRequests.set(key, promise);
3812
- });
4097
+ async getMetadata(playlistUri) {
4098
+ const cacheKey = `metadata:${playlistUri}`;
4099
+ return this.deduplicate(cacheKey, async () => {
4100
+ const response = await this.fetchWithAuth(this.baseUrl, {
4101
+ action: "metadata",
4102
+ playlistUri
4103
+ });
4104
+ return response.metadata;
4105
+ });
4106
+ }
4107
+ /**
4108
+ * Get metadata cycle time
4109
+ */
4110
+ async getMetadataCycleTime(playlistUri) {
4111
+ const metadata = await this.getMetadata(playlistUri);
4112
+ return metadata?.cycle_time_seconds || null;
4113
+ }
4114
+ /**
4115
+ * Get first clip for category
4116
+ */
4117
+ async getFirstClipForCategory(workspaceId, date, shiftId, category) {
4118
+ const cacheKey = `first:${workspaceId}:${date}:${shiftId}:${category}`;
4119
+ return this.deduplicate(cacheKey, async () => {
4120
+ const response = await this.fetchWithAuth(this.baseUrl, {
4121
+ action: "first",
4122
+ workspaceId,
4123
+ date,
4124
+ shift: shiftId.toString(),
4125
+ category,
4126
+ sopCategories: this.sopCategories
4127
+ });
4128
+ return response.video;
4129
+ });
4130
+ }
4131
+ /**
4132
+ * Get clip by index
4133
+ */
4134
+ async getClipByIndex(workspaceId, date, shiftId, category, index, includeCycleTime = true, includeMetadata = false) {
4135
+ const cacheKey = `by-index:${workspaceId}:${date}:${shiftId}:${category}:${index}`;
4136
+ return this.deduplicate(cacheKey, async () => {
4137
+ const response = await this.fetchWithAuth(this.baseUrl, {
4138
+ action: "by-index",
4139
+ workspaceId,
4140
+ date,
4141
+ shift: shiftId.toString(),
4142
+ category,
4143
+ index,
4144
+ sopCategories: this.sopCategories
4145
+ });
4146
+ const video = response.video;
4147
+ if (video && includeMetadata && video.originalUri) {
4148
+ try {
4149
+ const metadata = await this.getMetadata(video.originalUri);
4150
+ if (metadata) {
4151
+ video.cycle_time_seconds = metadata.cycle_time_seconds;
4152
+ video.creation_timestamp = metadata.creation_timestamp;
4153
+ }
4154
+ } catch (error) {
4155
+ console.warn("[S3ClipsAPIClient] Failed to fetch metadata:", error);
4156
+ }
3813
4157
  }
3814
- this.lastCleanup = now2;
3815
- }
4158
+ return video;
4159
+ });
4160
+ }
4161
+ /**
4162
+ * Get videos page with pagination
4163
+ */
4164
+ async getVideosPage(workspaceId, date, shiftId, category, pageSize = 5, startAfter) {
4165
+ const cacheKey = `page:${workspaceId}:${date}:${shiftId}:${category}:${pageSize}:${startAfter || "first"}`;
4166
+ return this.deduplicate(cacheKey, async () => {
4167
+ const response = await this.fetchWithAuth(this.baseUrl, {
4168
+ action: "page",
4169
+ workspaceId,
4170
+ date,
4171
+ shift: shiftId.toString(),
4172
+ category,
4173
+ pageSize,
4174
+ startAfter,
4175
+ sopCategories: this.sopCategories
4176
+ });
4177
+ return {
4178
+ videos: response.videos,
4179
+ nextToken: response.nextToken,
4180
+ hasMore: response.hasMore
4181
+ };
4182
+ });
4183
+ }
4184
+ /**
4185
+ * Convert S3 URI to CloudFront URL
4186
+ * In the API client, URLs are already signed from the server
4187
+ */
4188
+ s3UriToCloudfront(s3Uri) {
4189
+ return s3Uri;
4190
+ }
4191
+ /**
4192
+ * Clean up resources
4193
+ */
4194
+ dispose() {
4195
+ this.requestCache.clear();
4196
+ }
4197
+ /**
4198
+ * Get service statistics
4199
+ */
4200
+ getStats() {
4201
+ return {
4202
+ requestCache: {
4203
+ pendingCount: this.requestCache.size,
4204
+ maxSize: 1e3
4205
+ }
4206
+ };
3816
4207
  }
3817
4208
  };
4209
+
4210
+ // src/lib/api/s3-clips-secure.ts
3818
4211
  var S3ClipsService = class {
3819
4212
  constructor(config) {
3820
- // Request deduplication cache
3821
- this.requestCache = new RequestDeduplicationCache();
3822
- // Flag to prevent metadata fetching during index building
4213
+ // Flags for compatibility
3823
4214
  this.isIndexBuilding = false;
3824
- // Flag to prevent metadata fetching during entire prefetch operation
3825
4215
  this.isPrefetching = false;
3826
- // Global safeguard: limit concurrent metadata fetches to prevent flooding
3827
4216
  this.currentMetadataFetches = 0;
3828
4217
  this.MAX_CONCURRENT_METADATA = 3;
3829
4218
  this.config = config;
3830
4219
  if (!config.s3Config) {
3831
4220
  throw new Error("S3 configuration is required");
3832
4221
  }
4222
+ const sopCategories = config.s3Config.sopCategories?.default;
4223
+ this.apiClient = new S3ClipsAPIClient(sopCategories);
3833
4224
  const processing = config.s3Config.processing || {};
3834
4225
  this.defaultLimitPerCategory = processing.defaultLimitPerCategory || 30;
3835
4226
  this.maxLimitPerCategory = processing.maxLimitPerCategory || 1e3;
3836
4227
  this.concurrencyLimit = processing.concurrencyLimit || 10;
3837
4228
  this.maxInitialFetch = processing.maxInitialFetch || 60;
3838
- const region = this.validateAndSanitizeRegion(config.s3Config.region);
3839
- console.log(`S3ClipsService: Using AWS region: ${region}`);
3840
- this.s3Client = new clientS3.S3Client({
3841
- region,
3842
- credentials: config.s3Config.credentials ? {
3843
- accessKeyId: config.s3Config.credentials.accessKeyId,
3844
- secretAccessKey: config.s3Config.credentials.secretAccessKey
3845
- } : void 0
3846
- });
4229
+ console.log("[S3ClipsService] \u2705 Initialized with secure API client - AWS credentials are now server-side only!");
3847
4230
  }
3848
4231
  /**
3849
- * Validates and sanitizes the AWS region
3850
- */
3851
- validateAndSanitizeRegion(region) {
3852
- const defaultRegion = "us-east-1";
3853
- if (!region || typeof region !== "string") {
3854
- console.warn(`S3ClipsService: Invalid region provided (${region}), using default: ${defaultRegion}`);
3855
- return defaultRegion;
3856
- }
3857
- const sanitizedRegion = region.trim().toLowerCase();
3858
- if (!sanitizedRegion) {
3859
- console.warn(`S3ClipsService: Empty region provided, using default: ${defaultRegion}`);
3860
- return defaultRegion;
3861
- }
3862
- const regionPattern = /^[a-z]{2,3}-[a-z]+-\d+$/;
3863
- if (!regionPattern.test(sanitizedRegion)) {
3864
- console.warn(`S3ClipsService: Invalid region format (${sanitizedRegion}), using default: ${defaultRegion}`);
3865
- return defaultRegion;
3866
- }
3867
- return sanitizedRegion;
3868
- }
3869
- /**
3870
- * Lists S3 clips for a workspace, date, and shift with request deduplication
4232
+ * Lists S3 clips using API
3871
4233
  */
3872
4234
  async listS3Clips(params) {
3873
- const { workspaceId, date, shiftId, maxKeys } = params;
4235
+ const { workspaceId, date, shiftId } = params;
3874
4236
  if (!isValidShiftId(shiftId)) {
3875
- console.error(`[S3ClipsService] Invalid shift ID: ${shiftId}. Must be 0 (day) or 1 (night)`);
4237
+ console.error(`[S3ClipsService] Invalid shift ID: ${shiftId}`);
3876
4238
  return [];
3877
4239
  }
3878
- const prefix = `sop_violations/${workspaceId}/${date}/${shiftId}/`;
3879
- console.log(`[S3ClipsService] Listing clips for workspace: ${workspaceId}, date: ${date}, shift: ${shiftId}`);
3880
- const deduplicationKey = `list-s3-clips:${prefix}:${maxKeys || "all"}`;
3881
- return this.requestCache.deduplicate(
3882
- deduplicationKey,
3883
- () => this.executeListS3Clips(params),
3884
- "ListS3Clips"
3885
- );
3886
- }
3887
- /**
3888
- * Internal implementation of S3 listing (called through deduplication)
3889
- */
3890
- async executeListS3Clips(params) {
3891
- const { workspaceId, date, shiftId, maxKeys } = params;
3892
- const prefix = `sop_violations/${workspaceId}/${date}/${shiftId}/`;
3893
- console.log(`[S3ClipsService] Executing S3 list for prefix: ${prefix}`);
4240
+ console.log(`[S3ClipsService] Listing clips via API for workspace: ${workspaceId}`);
3894
4241
  try {
3895
- let playlists = [];
3896
- let continuationToken = void 0;
3897
- do {
3898
- const command = new clientS3.ListObjectsV2Command({
3899
- Bucket: this.config.s3Config.bucketName,
3900
- Prefix: prefix,
3901
- ContinuationToken: continuationToken,
3902
- MaxKeys: maxKeys ?? 1e3
3903
- });
3904
- const response = await this.s3Client.send(command);
3905
- console.log(`Got S3 response for ${prefix}:`, {
3906
- keyCount: response.KeyCount,
3907
- contentsLength: response.Contents?.length || 0,
3908
- hasContinuation: !!response.NextContinuationToken
3909
- });
3910
- if (response.Contents) {
3911
- if (response.Contents.length > 0) {
3912
- console.log("Sample Keys:", response.Contents.slice(0, 3).map((obj) => obj.Key));
3913
- }
3914
- for (const obj of response.Contents) {
3915
- if (obj.Key && obj.Key.endsWith("playlist.m3u8")) {
3916
- if (obj.Key.includes("missed_qchecks")) {
3917
- console.log(`Skipping missed_qchecks path: ${obj.Key}`);
3918
- continue;
3919
- }
3920
- playlists.push(`s3://${this.config.s3Config.bucketName}/${obj.Key}`);
3921
- }
3922
- }
3923
- }
3924
- continuationToken = response.NextContinuationToken;
3925
- if (maxKeys && playlists.length >= maxKeys) {
3926
- break;
3927
- }
3928
- } while (continuationToken && (!maxKeys || playlists.length < maxKeys));
3929
- console.log(`Found ${playlists.length} HLS playlists in ${prefix}`);
3930
- if (playlists.length > 0) {
3931
- console.log("First playlist URI:", playlists[0]);
3932
- }
3933
- return playlists;
4242
+ return await this.apiClient.listS3Clips(params);
3934
4243
  } catch (error) {
3935
- console.error(`Error listing S3 objects with prefix '${prefix}':`, error);
4244
+ console.error("[S3ClipsService] Error listing clips:", error);
3936
4245
  return [];
3937
4246
  }
3938
4247
  }
3939
4248
  /**
3940
- * Fetches and extracts cycle time from metadata.json with deduplication
4249
+ * Get metadata cycle time
3941
4250
  */
3942
4251
  async getMetadataCycleTime(playlistUri) {
3943
- const deduplicationKey = `metadata-cycle-time:${playlistUri}`;
3944
- return this.requestCache.deduplicate(
3945
- deduplicationKey,
3946
- () => this.executeGetMetadataCycleTime(playlistUri),
3947
- "MetadataCycleTime"
3948
- );
3949
- }
3950
- /**
3951
- * Internal implementation of metadata cycle time fetching
3952
- */
3953
- async executeGetMetadataCycleTime(playlistUri) {
3954
4252
  try {
3955
- const metadataUri = playlistUri.replace(/playlist\.m3u8$/, "metadata.json");
3956
- const url = new URL(metadataUri);
3957
- const bucket = url.hostname;
3958
- const key = url.pathname.substring(1);
3959
- console.log(`[S3ClipsService] Fetching metadata cycle time for: ${key}`);
3960
- const command = new clientS3.GetObjectCommand({
3961
- Bucket: bucket,
3962
- Key: key
3963
- });
3964
- const response = await this.s3Client.send(command);
3965
- if (!response.Body) {
3966
- console.warn(`Empty response body for metadata file: ${key}`);
3967
- return null;
3968
- }
3969
- const metadataContent = await response.Body.transformToString();
3970
- const metadata = JSON.parse(metadataContent);
3971
- const cycleTimeFrames = metadata?.original_task_metadata?.cycle_time;
3972
- if (typeof cycleTimeFrames === "number") {
3973
- return cycleTimeFrames;
3974
- }
3975
- return null;
4253
+ return await this.apiClient.getMetadataCycleTime(playlistUri);
3976
4254
  } catch (error) {
3977
- console.error(`Error fetching or parsing metadata:`, error);
4255
+ console.error("[S3ClipsService] Error fetching metadata cycle time:", error);
3978
4256
  return null;
3979
4257
  }
3980
4258
  }
3981
4259
  /**
3982
- * Control prefetch mode to prevent metadata fetching during background operations
4260
+ * Control prefetch mode
3983
4261
  */
3984
4262
  setPrefetchMode(enabled) {
3985
4263
  this.isPrefetching = enabled;
3986
- console.log(`[S3ClipsService] Prefetch mode ${enabled ? "enabled" : "disabled"} - metadata fetching ${enabled ? "blocked" : "allowed"}`);
4264
+ console.log(`[S3ClipsService] Prefetch mode ${enabled ? "enabled" : "disabled"}`);
3987
4265
  }
3988
4266
  /**
3989
- * Fetches full metadata including timestamps with deduplication
4267
+ * Get full metadata
3990
4268
  */
3991
4269
  async getFullMetadata(playlistUri) {
3992
4270
  if (this.isIndexBuilding || this.isPrefetching) {
3993
- console.warn(`[S3ClipsService] Skipping metadata fetch - building: ${this.isIndexBuilding}, prefetching: ${this.isPrefetching}`);
4271
+ console.warn("[S3ClipsService] Skipping metadata - operation in progress");
3994
4272
  return null;
3995
4273
  }
3996
4274
  if (this.currentMetadataFetches >= this.MAX_CONCURRENT_METADATA) {
3997
- console.warn(`[S3ClipsService] Skipping metadata - max concurrent fetches (${this.MAX_CONCURRENT_METADATA}) reached`);
4275
+ console.warn("[S3ClipsService] Skipping metadata - max concurrent fetches reached");
3998
4276
  return null;
3999
4277
  }
4000
4278
  this.currentMetadataFetches++;
4001
4279
  try {
4002
- const deduplicationKey = `full-metadata:${playlistUri}`;
4003
- return await this.requestCache.deduplicate(
4004
- deduplicationKey,
4005
- () => this.executeGetFullMetadata(playlistUri),
4006
- "FullMetadata"
4007
- );
4008
- } finally {
4009
- this.currentMetadataFetches--;
4010
- }
4011
- }
4012
- /**
4013
- * Internal implementation of full metadata fetching
4014
- */
4015
- async executeGetFullMetadata(playlistUri) {
4016
- try {
4017
- const metadataUri = playlistUri.replace(/playlist\.m3u8$/, "metadata.json");
4018
- const url = new URL(metadataUri);
4019
- const bucket = url.hostname;
4020
- const key = url.pathname.substring(1);
4021
- console.log(`[S3ClipsService] Fetching full metadata for: ${key}`);
4022
- const command = new clientS3.GetObjectCommand({
4023
- Bucket: bucket,
4024
- Key: key
4025
- });
4026
- const response = await this.s3Client.send(command);
4027
- if (!response.Body) {
4028
- console.warn(`Empty response body for metadata file: ${key}`);
4029
- return null;
4030
- }
4031
- const metadataContent = await response.Body.transformToString();
4032
- const metadata = JSON.parse(metadataContent);
4033
- return metadata;
4280
+ return await this.apiClient.getMetadata(playlistUri);
4034
4281
  } catch (error) {
4035
- console.error(`Error fetching or parsing metadata:`, error);
4282
+ console.error("[S3ClipsService] Error fetching metadata:", error);
4036
4283
  return null;
4284
+ } finally {
4285
+ this.currentMetadataFetches--;
4037
4286
  }
4038
4287
  }
4039
4288
  /**
4040
- * Converts S3 URI to CloudFront URL
4289
+ * Convert S3 URI to CloudFront URL
4290
+ * URLs from API are already signed
4041
4291
  */
4042
4292
  s3UriToCloudfront(s3Uri) {
4043
- const url = new URL(s3Uri);
4044
- const key = url.pathname.startsWith("/") ? url.pathname.substring(1) : url.pathname;
4045
- const cloudfrontUrl = `${this.config.s3Config.cloudFrontDomain}/${key}`;
4046
- return cloudfrontUrl;
4293
+ if (s3Uri.startsWith("http")) {
4294
+ return s3Uri;
4295
+ }
4296
+ console.warn("[S3ClipsService] Unexpected S3 URI in secure mode:", s3Uri);
4297
+ return s3Uri;
4047
4298
  }
4048
4299
  /**
4049
- * Gets SOP categories for a specific workspace
4300
+ * Get SOP categories for workspace
4050
4301
  */
4051
4302
  getSOPCategories(workspaceId) {
4052
4303
  const sopConfig = this.config.s3Config?.sopCategories;
@@ -4058,299 +4309,85 @@ var S3ClipsService = class {
4058
4309
  }
4059
4310
  async getClipCounts(workspaceId, date, shiftId, buildIndex) {
4060
4311
  if (!isValidShiftId(shiftId)) {
4061
- console.error(`[S3ClipsService] getClipCounts - Invalid shift ID: ${shiftId}. Must be 0 (day) or 1 (night)`);
4062
- return buildIndex ? { counts: {}, videoIndex: { byCategory: /* @__PURE__ */ new Map(), allVideos: [], counts: {}, workspaceId, date, shiftId: "0", lastUpdated: /* @__PURE__ */ new Date() } } : {};
4063
- }
4064
- const deduplicationKey = `clip-counts:${workspaceId}:${date}:${shiftId}:${buildIndex ? "with-index" : "counts-only"}`;
4065
- return this.requestCache.deduplicate(
4066
- deduplicationKey,
4067
- () => this.executeGetClipCounts(workspaceId, date, shiftId, buildIndex),
4068
- "ClipCounts"
4069
- );
4070
- }
4071
- /**
4072
- * Internal implementation of clip counts fetching
4073
- */
4074
- async executeGetClipCounts(workspaceId, date, shiftId, buildIndex) {
4075
- const effectiveBuildIndex = false;
4312
+ console.error(`[S3ClipsService] Invalid shift ID: ${shiftId}`);
4313
+ return buildIndex ? { counts: {}, videoIndex: this.createEmptyVideoIndex(workspaceId, date, shiftId.toString()) } : {};
4314
+ }
4076
4315
  try {
4077
- const basePrefix = `sop_violations/${workspaceId}/${date}/${shiftId}/`;
4078
- const counts = { total: 0 };
4079
- const categoryFolders = [
4080
- "idle_time",
4081
- "low_value",
4082
- "sop_deviation",
4083
- "missing_quality_check",
4084
- "best_cycle_time",
4085
- "worst_cycle_time",
4086
- "long_cycle_time",
4087
- "cycle_completion",
4088
- "bottleneck"
4089
- ];
4090
- const shiftName = shiftId === 0 || shiftId === "0" ? "Day" : "Night";
4091
- console.log(`[S3ClipsService] Fast counting clips for ${workspaceId} on ${date}, shift ${shiftId} (${shiftName} Shift)`);
4092
- const startTime = performance.now();
4093
- const videoIndex = effectiveBuildIndex ? {
4094
- byCategory: /* @__PURE__ */ new Map(),
4095
- allVideos: [],
4096
- counts: {},
4097
- workspaceId,
4098
- date,
4099
- shiftId: shiftId.toString(),
4100
- lastUpdated: /* @__PURE__ */ new Date(),
4101
- _debugId: `vid_${Date.now()}_${Math.random().toString(36).substring(7)}`
4102
- } : null;
4103
- const countPromises = categoryFolders.map(async (category) => {
4104
- const categoryPrefix = `${basePrefix}${category}/videos/`;
4105
- const categoryVideos = [];
4106
- try {
4107
- if (effectiveBuildIndex) ; else {
4108
- const command = new clientS3.ListObjectsV2Command({
4109
- Bucket: this.config.s3Config.bucketName,
4110
- Prefix: categoryPrefix,
4111
- Delimiter: "/",
4112
- MaxKeys: 1e3
4113
- });
4114
- let folderCount = 0;
4115
- let continuationToken;
4116
- do {
4117
- if (continuationToken) {
4118
- command.input.ContinuationToken = continuationToken;
4119
- }
4120
- const response = await this.s3Client.send(command);
4121
- if (response.CommonPrefixes) {
4122
- folderCount += response.CommonPrefixes.length;
4123
- }
4124
- continuationToken = response.NextContinuationToken;
4125
- } while (continuationToken);
4126
- return { category, count: folderCount, videos: [] };
4127
- }
4128
- } catch (error) {
4129
- console.error(`Error ${buildIndex ? "building index for" : "counting folders for"} category ${category}:`, error);
4130
- return { category, count: 0, videos: [] };
4131
- }
4132
- });
4133
- const results = await Promise.all(countPromises);
4134
- for (const { category, count, videos } of results) {
4135
- counts[category] = count;
4136
- counts.total += count;
4137
- if (effectiveBuildIndex && videoIndex && videos) ;
4138
- }
4139
- if (effectiveBuildIndex && videoIndex) ;
4140
- const elapsed = performance.now() - startTime;
4141
- console.log(`[S3ClipsService] Clip counts completed in ${elapsed.toFixed(2)}ms - Total: ${counts.total}`);
4142
- if (effectiveBuildIndex && videoIndex) ;
4143
- return counts;
4144
- } finally {
4316
+ if (buildIndex) {
4317
+ const result = await this.apiClient.getClipCountsWithIndex(workspaceId, date, shiftId);
4318
+ const cacheKey = `clip-counts:${workspaceId}:${date}:${shiftId}`;
4319
+ await smartVideoCache.setClipCounts(cacheKey, result);
4320
+ return result;
4321
+ } else {
4322
+ const counts = await this.apiClient.getClipCounts(workspaceId, date, shiftId);
4323
+ return counts;
4324
+ }
4325
+ } catch (error) {
4326
+ console.error("[S3ClipsService] Error fetching clip counts:", error);
4327
+ return buildIndex ? { counts: {}, videoIndex: this.createEmptyVideoIndex(workspaceId, date, shiftId.toString()) } : {};
4145
4328
  }
4146
4329
  }
4147
4330
  async getClipCountsCacheFirst(workspaceId, date, shiftId, buildIndex) {
4148
4331
  const cacheKey = `clip-counts:${workspaceId}:${date}:${shiftId}`;
4149
4332
  const cachedResult = await smartVideoCache.getClipCounts(cacheKey);
4150
4333
  if (cachedResult) {
4151
- console.log(`[S3ClipsService] Using cached clip counts for ${workspaceId}`);
4152
- if (buildIndex) {
4153
- return cachedResult;
4154
- } else {
4155
- return cachedResult.counts;
4156
- }
4334
+ console.log("[S3ClipsService] Using cached clip counts");
4335
+ return buildIndex ? cachedResult : cachedResult.counts;
4157
4336
  }
4158
- console.log(`[S3ClipsService] Cache miss - fetching clip counts for ${workspaceId}`);
4337
+ console.log("[S3ClipsService] Cache miss - fetching from API");
4159
4338
  return buildIndex ? this.getClipCounts(workspaceId, date, shiftId, true) : this.getClipCounts(workspaceId, date, shiftId);
4160
4339
  }
4161
4340
  /**
4162
- * Get first clip for a specific category with deduplication
4341
+ * Get first clip for category
4163
4342
  */
4164
4343
  async getFirstClipForCategory(workspaceId, date, shiftId, category) {
4165
4344
  if (!isValidShiftId(shiftId)) {
4166
- console.error(`[S3ClipsService] getFirstClipForCategory - Invalid shift ID: ${shiftId}. Must be 0 (day) or 1 (night)`);
4345
+ console.error(`[S3ClipsService] Invalid shift ID: ${shiftId}`);
4167
4346
  return null;
4168
4347
  }
4169
- const deduplicationKey = `first-clip:${workspaceId}:${date}:${shiftId}:${category}`;
4170
- return this.requestCache.deduplicate(
4171
- deduplicationKey,
4172
- () => this.executeGetFirstClipForCategory(workspaceId, date, shiftId, category),
4173
- "FirstClip"
4174
- );
4175
- }
4176
- /**
4177
- * Internal implementation of first clip fetching
4178
- */
4179
- async executeGetFirstClipForCategory(workspaceId, date, shiftId, category) {
4180
- const categoryPrefix = `sop_violations/${workspaceId}/${date}/${shiftId}/${category}/videos/`;
4181
4348
  try {
4182
- const command = new clientS3.ListObjectsV2Command({
4183
- Bucket: this.config.s3Config.bucketName,
4184
- Prefix: categoryPrefix,
4185
- MaxKeys: 10
4186
- // Small limit since we only need one
4187
- });
4188
- const response = await this.s3Client.send(command);
4189
- if (response.Contents) {
4190
- const playlistObj = response.Contents.find((obj) => obj.Key?.endsWith("playlist.m3u8"));
4191
- if (playlistObj && playlistObj.Key) {
4192
- const s3Uri = `s3://${this.config.s3Config.bucketName}/${playlistObj.Key}`;
4193
- const sopCategories = this.getSOPCategories(workspaceId);
4194
- const parsedInfo = parseS3Uri(s3Uri, sopCategories);
4195
- if (parsedInfo) {
4196
- const cloudfrontUrl = this.s3UriToCloudfront(s3Uri);
4197
- return {
4198
- id: `${workspaceId}-${date}-${shiftId}-${category}-first`,
4199
- src: cloudfrontUrl,
4200
- ...parsedInfo,
4201
- originalUri: s3Uri
4202
- };
4203
- }
4204
- }
4205
- }
4349
+ return await this.apiClient.getFirstClipForCategory(workspaceId, date, shiftId, category);
4206
4350
  } catch (error) {
4207
- console.error(`Error getting first clip for category ${category}:`, error);
4351
+ console.error("[S3ClipsService] Error fetching first clip:", error);
4352
+ return null;
4208
4353
  }
4209
- return null;
4210
4354
  }
4211
4355
  /**
4212
- * Get a specific video from the pre-built video index - O(1) lookup performance
4356
+ * Get video from index (for compatibility)
4213
4357
  */
4214
4358
  async getVideoFromIndex(videoIndex, category, index, includeCycleTime = true, includeMetadata = true) {
4359
+ const { workspaceId, date, shiftId } = videoIndex;
4360
+ return this.getClipByIndex(
4361
+ workspaceId,
4362
+ date,
4363
+ shiftId,
4364
+ category,
4365
+ index,
4366
+ includeCycleTime,
4367
+ includeMetadata
4368
+ );
4369
+ }
4370
+ /**
4371
+ * Get clip by index
4372
+ */
4373
+ async getClipByIndex(workspaceId, date, shiftId, category, index, includeCycleTime = true, includeMetadata = false) {
4215
4374
  try {
4216
- const categoryVideos = videoIndex.byCategory.get(category);
4217
- if (!categoryVideos || index < 0 || index >= categoryVideos.length) {
4218
- console.warn(`Invalid index ${index} for category '${category}'. Available: ${categoryVideos?.length || 0}`);
4219
- console.warn(`Video index ID: ${videoIndex._debugId || "NO_ID"}`);
4220
- console.warn(`Video index categories available: [${Array.from(videoIndex.byCategory.keys()).join(", ")}]`);
4221
- console.warn(`Video index total videos: ${videoIndex.allVideos.length}`);
4222
- return null;
4223
- }
4224
- const videoEntry = categoryVideos[index];
4225
- return this.processFullVideo(
4226
- videoEntry.uri,
4375
+ return await this.apiClient.getClipByIndex(
4376
+ workspaceId,
4377
+ date,
4378
+ shiftId,
4379
+ category,
4227
4380
  index,
4228
- videoEntry.workspaceId,
4229
- videoEntry.date,
4230
- videoEntry.shiftId,
4231
4381
  includeCycleTime,
4232
4382
  includeMetadata
4233
4383
  );
4234
4384
  } catch (error) {
4235
- console.error(`Error getting video from index at ${index} for category ${category}:`, error);
4385
+ console.error("[S3ClipsService] Error fetching clip by index:", error);
4236
4386
  return null;
4237
4387
  }
4238
4388
  }
4239
4389
  /**
4240
- * Get a specific clip by index for a category with deduplication
4241
- * @deprecated Use getVideoFromIndex with a pre-built VideoIndex for better performance
4242
- */
4243
- async getClipByIndex(workspaceId, date, shiftId, category, index, includeCycleTime = true, includeMetadata = false) {
4244
- const deduplicationKey = `clip-by-index:${workspaceId}:${date}:${shiftId}:${category}:${index}:${includeCycleTime}:${includeMetadata}`;
4245
- return this.requestCache.deduplicate(
4246
- deduplicationKey,
4247
- () => this.executeGetClipByIndex(workspaceId, date, shiftId, category, index, includeCycleTime, includeMetadata),
4248
- "ClipByIndex"
4249
- );
4250
- }
4251
- /**
4252
- * Internal implementation of clip by index fetching
4253
- */
4254
- async executeGetClipByIndex(workspaceId, date, shiftId, category, index, includeCycleTime = true, includeMetadata = false) {
4255
- const categoryPrefix = `sop_violations/${workspaceId}/${date}/${shiftId}/${category}/videos/`;
4256
- try {
4257
- const command = new clientS3.ListObjectsV2Command({
4258
- Bucket: this.config.s3Config.bucketName,
4259
- Prefix: categoryPrefix,
4260
- MaxKeys: 1e3
4261
- });
4262
- let playlists = [];
4263
- let continuationToken = void 0;
4264
- do {
4265
- if (continuationToken) {
4266
- command.input.ContinuationToken = continuationToken;
4267
- }
4268
- const response = await this.s3Client.send(command);
4269
- if (response.Contents) {
4270
- for (const obj of response.Contents) {
4271
- if (obj.Key && obj.Key.endsWith("playlist.m3u8")) {
4272
- playlists.push(`s3://${this.config.s3Config.bucketName}/${obj.Key}`);
4273
- }
4274
- }
4275
- }
4276
- continuationToken = response.NextContinuationToken;
4277
- } while (continuationToken && playlists.length < index + 10);
4278
- playlists.sort((a, b) => {
4279
- const parsedA = parseS3Uri(a);
4280
- const parsedB = parseS3Uri(b);
4281
- if (!parsedA || !parsedB) return 0;
4282
- return parsedB.timestamp.localeCompare(parsedA.timestamp);
4283
- });
4284
- if (index < playlists.length) {
4285
- const uri = playlists[index];
4286
- return this.processFullVideo(
4287
- uri,
4288
- index,
4289
- workspaceId,
4290
- date,
4291
- shiftId.toString(),
4292
- includeCycleTime,
4293
- includeMetadata
4294
- );
4295
- }
4296
- } catch (error) {
4297
- console.error(`[getClipByIndex] Error getting clip at index ${index} for category ${category}:`, error);
4298
- }
4299
- return null;
4300
- }
4301
- /**
4302
- * Get one sample video from each category for preloading
4303
- */
4304
- async getSampleVideos(workspaceId, date, shiftId) {
4305
- const basePrefix = `sop_violations/${workspaceId}/${date}/${shiftId}/`;
4306
- const samples = {};
4307
- const sopCategories = this.getSOPCategories(workspaceId);
4308
- const categoriesToSample = sopCategories ? sopCategories.map((cat) => cat.id) : ["low_value", "best_cycle_time", "worst_cycle_time", "long_cycle_time", "cycle_completion"];
4309
- console.log(`[S3ClipsService] Getting sample videos for categories:`, categoriesToSample);
4310
- const samplePromises = categoriesToSample.map(async (category) => {
4311
- const categoryPrefix = `${basePrefix}${category}/`;
4312
- try {
4313
- const command = new clientS3.ListObjectsV2Command({
4314
- Bucket: this.config.s3Config.bucketName,
4315
- Prefix: categoryPrefix,
4316
- MaxKeys: 20
4317
- // Small limit since we only need one
4318
- });
4319
- const response = await this.s3Client.send(command);
4320
- if (response.Contents) {
4321
- const playlistObj = response.Contents.find((obj) => obj.Key?.endsWith("playlist.m3u8"));
4322
- if (playlistObj && playlistObj.Key) {
4323
- const s3Uri = `s3://${this.config.s3Config.bucketName}/${playlistObj.Key}`;
4324
- const parsedInfo = parseS3Uri(s3Uri, sopCategories);
4325
- if (parsedInfo) {
4326
- return {
4327
- category,
4328
- sample: {
4329
- id: `${workspaceId}-${date}-${shiftId}-${category}-sample`,
4330
- src: this.s3UriToCloudfront(s3Uri),
4331
- // Pre-convert to CloudFront URL
4332
- ...parsedInfo,
4333
- originalUri: s3Uri
4334
- }
4335
- };
4336
- }
4337
- }
4338
- }
4339
- } catch (error) {
4340
- console.error(`Error getting sample for category ${category}:`, error);
4341
- }
4342
- return { category, sample: null };
4343
- });
4344
- const sampleResults = await Promise.all(samplePromises);
4345
- for (const { category, sample } of sampleResults) {
4346
- if (sample) {
4347
- samples[category] = sample;
4348
- }
4349
- }
4350
- return samples;
4351
- }
4352
- /**
4353
- * Processes a single video completely
4390
+ * Process full video (for compatibility)
4354
4391
  */
4355
4392
  async processFullVideo(uri, index, workspaceId, date, shiftId, includeCycleTime, includeMetadata = false) {
4356
4393
  const sopCategories = this.getSOPCategories(workspaceId);
@@ -4359,35 +4396,35 @@ var S3ClipsService = class {
4359
4396
  console.warn(`Skipping URI due to parsing failure: ${uri}`);
4360
4397
  return null;
4361
4398
  }
4362
- let cycleTimeSeconds = null;
4363
- let creationTimestamp = void 0;
4399
+ const video = {
4400
+ id: `${workspaceId}-${date}-${shiftId}-${index}`,
4401
+ src: uri,
4402
+ // Already signed from API
4403
+ ...parsedInfo,
4404
+ originalUri: uri
4405
+ };
4364
4406
  if (includeMetadata) {
4365
4407
  const metadata = await this.getFullMetadata(uri);
4366
4408
  if (metadata) {
4367
- if (metadata.original_task_metadata?.cycle_time) {
4368
- cycleTimeSeconds = metadata.original_task_metadata.cycle_time;
4369
- }
4370
- creationTimestamp = metadata.upload_timestamp || metadata.original_task_metadata?.timestamp || metadata.creation_timestamp || metadata[""];
4409
+ video.cycle_time_seconds = metadata.original_task_metadata?.cycle_time;
4410
+ video.creation_timestamp = metadata.upload_timestamp || metadata.original_task_metadata?.timestamp || metadata.creation_timestamp;
4371
4411
  }
4372
- } else if (includeCycleTime && (parsedInfo.type === "bottleneck" && parsedInfo.description.toLowerCase().includes("cycle time") || parsedInfo.type === "best_cycle_time" || parsedInfo.type === "worst_cycle_time" || parsedInfo.type === "cycle_completion")) {
4373
- cycleTimeSeconds = null;
4374
4412
  }
4375
- const cloudfrontPlaylistUrl = this.s3UriToCloudfront(uri);
4376
- const { type: videoType, timestamp: videoTimestamp } = parsedInfo;
4377
- return {
4378
- id: `${workspaceId}-${date}-${shiftId}-${videoType}-${videoTimestamp.replace(/:/g, "")}-${index}`,
4379
- src: cloudfrontPlaylistUrl,
4380
- // Direct CloudFront playlist URL
4381
- ...parsedInfo,
4382
- cycle_time_seconds: cycleTimeSeconds || void 0,
4383
- creation_timestamp: creationTimestamp
4384
- };
4413
+ return video;
4385
4414
  }
4386
4415
  /**
4387
- * Simplified method to fetch clips based on parameters
4416
+ * Fetch clips (main method for compatibility)
4388
4417
  */
4389
4418
  async fetchClips(params) {
4390
- const { workspaceId, date: inputDate, shift, category, limit, offset = 0, mode, includeCycleTime, includeMetadata, timestampStart, timestampEnd } = params;
4419
+ const {
4420
+ workspaceId,
4421
+ date: inputDate,
4422
+ shift,
4423
+ category,
4424
+ limit,
4425
+ offset = 0,
4426
+ mode
4427
+ } = params;
4391
4428
  if (!workspaceId) {
4392
4429
  throw new Error("Valid Workspace ID is required");
4393
4430
  }
@@ -4405,157 +4442,66 @@ var S3ClipsService = class {
4405
4442
  const { shiftId: currentShiftId } = getCurrentShift2(this.config.dateTimeConfig?.defaultTimezone);
4406
4443
  shiftId = currentShiftId;
4407
4444
  }
4408
- console.log(`S3ClipsService: Fetching clips for workspace ${workspaceId} on date ${date}, shift ${shiftId}`);
4445
+ console.log(`[S3ClipsService] Fetching clips for workspace ${workspaceId}`);
4409
4446
  if (mode === "summary") {
4410
4447
  const counts = await this.getClipCounts(workspaceId, date, shiftId.toString());
4411
4448
  return { counts, samples: {} };
4412
4449
  }
4413
4450
  const effectiveLimit = limit || this.defaultLimitPerCategory;
4414
- const s3Uris = await this.listS3Clips({
4451
+ const result = await this.getVideosPage(
4415
4452
  workspaceId,
4416
4453
  date,
4417
4454
  shiftId,
4418
- maxKeys: category ? effectiveLimit * 2 : void 0
4419
- // Fetch extra for filtering
4420
- });
4421
- if (s3Uris.length === 0) {
4422
- console.log(`S3ClipsService: No HLS playlists found`);
4423
- return [];
4424
- }
4425
- let filteredUris = s3Uris;
4426
- if (category) {
4427
- filteredUris = s3Uris.filter((uri) => {
4428
- const parsedInfo = parseS3Uri(uri);
4429
- if (!parsedInfo) return false;
4430
- if (category === "long_cycle_time") {
4431
- return parsedInfo.type === "long_cycle_time" || parsedInfo.type === "bottleneck" && parsedInfo.description.toLowerCase().includes("cycle time");
4432
- }
4433
- return parsedInfo.type === category;
4434
- });
4435
- filteredUris = filteredUris.slice(offset, offset + effectiveLimit);
4436
- }
4437
- const videoPromises = filteredUris.map(async (uri, index) => {
4438
- return this.processFullVideo(
4439
- uri,
4440
- index,
4455
+ category || "all",
4456
+ effectiveLimit
4457
+ );
4458
+ return result.videos;
4459
+ }
4460
+ /**
4461
+ * Get videos page using pagination API
4462
+ */
4463
+ async getVideosPage(workspaceId, date, shiftId, category, pageSize = 5, startAfter) {
4464
+ try {
4465
+ return await this.apiClient.getVideosPage(
4441
4466
  workspaceId,
4442
4467
  date,
4443
- shiftId.toString(),
4444
- includeCycleTime || false,
4445
- includeMetadata || false
4446
- // Never fetch metadata for timestamp filtering to prevent flooding
4468
+ shiftId,
4469
+ category,
4470
+ pageSize,
4471
+ startAfter
4447
4472
  );
4448
- });
4449
- const videoResults = await Promise.all(videoPromises);
4450
- let videos = videoResults.filter((v) => v !== null);
4451
- if (timestampStart || timestampEnd) {
4452
- videos = videos.filter((video) => {
4453
- if (!video.creation_timestamp) return false;
4454
- const videoTimestamp = new Date(video.creation_timestamp).getTime();
4455
- if (timestampStart && timestampEnd) {
4456
- const start = new Date(timestampStart).getTime();
4457
- const end = new Date(timestampEnd).getTime();
4458
- return videoTimestamp >= start && videoTimestamp <= end;
4459
- } else if (timestampStart) {
4460
- const start = new Date(timestampStart).getTime();
4461
- return videoTimestamp >= start;
4462
- } else if (timestampEnd) {
4463
- const end = new Date(timestampEnd).getTime();
4464
- return videoTimestamp <= end;
4465
- }
4466
- return true;
4467
- });
4468
- }
4469
- videos.sort((a, b) => b.timestamp.localeCompare(a.timestamp));
4470
- const cacheKey = `videos:${workspaceId}:${date}:${shiftId}:${category || "all"}`;
4471
- if (videos.length > 0) {
4472
- smartVideoCache.setVideos(cacheKey, videos);
4473
+ } catch (error) {
4474
+ console.error("[S3ClipsService] Error fetching videos page:", error);
4475
+ return { videos: [], hasMore: false };
4473
4476
  }
4474
- return videos;
4475
4477
  }
4476
4478
  /**
4477
- * Get a page of videos for a specific category using efficient pagination
4478
- * This method replaces the need for full video indexing
4479
- * @param workspaceId - Workspace ID
4480
- * @param date - Date in YYYY-MM-DD format
4481
- * @param shiftId - Shift ID (0 for day, 1 for night)
4482
- * @param category - Category to fetch videos from
4483
- * @param pageSize - Number of videos to fetch per page (default 5)
4484
- * @param startAfter - Optional key to start after for pagination
4485
- * @returns Page of videos with continuation token
4479
+ * Create empty video index for compatibility
4486
4480
  */
4487
- async getVideosPage(workspaceId, date, shiftId, category, pageSize = 5, startAfter) {
4488
- if (!isValidShiftId(shiftId)) {
4489
- console.error(`[S3ClipsService] getVideosPage - Invalid shift ID: ${shiftId}`);
4490
- return { videos: [], hasMore: false };
4491
- }
4492
- const categoryPrefix = `sop_violations/${workspaceId}/${date}/${shiftId}/${category}/videos/`;
4493
- const deduplicationKey = `videos-page:${categoryPrefix}:${pageSize}:${startAfter || "first"}`;
4494
- return this.requestCache.deduplicate(
4495
- deduplicationKey,
4496
- async () => {
4497
- try {
4498
- console.log(`[S3ClipsService] Fetching page of ${pageSize} videos for category '${category}'`);
4499
- const command = new clientS3.ListObjectsV2Command({
4500
- Bucket: this.config.s3Config.bucketName,
4501
- Prefix: categoryPrefix,
4502
- MaxKeys: pageSize * 10,
4503
- // Fetch extra to account for non-playlist files
4504
- StartAfter: startAfter
4505
- });
4506
- const response = await this.s3Client.send(command);
4507
- const videos = [];
4508
- if (response.Contents) {
4509
- const sopCategories = this.getSOPCategories(workspaceId);
4510
- for (const obj of response.Contents) {
4511
- if (videos.length >= pageSize) break;
4512
- if (obj.Key && obj.Key.endsWith("playlist.m3u8")) {
4513
- if (obj.Key.includes("missed_qchecks")) continue;
4514
- const s3Uri = `s3://${this.config.s3Config.bucketName}/${obj.Key}`;
4515
- const parsedInfo = parseS3Uri(s3Uri, sopCategories);
4516
- if (parsedInfo) {
4517
- const cloudfrontUrl = this.s3UriToCloudfront(s3Uri);
4518
- videos.push({
4519
- id: `${workspaceId}-${date}-${shiftId}-${category}-${videos.length}`,
4520
- src: cloudfrontUrl,
4521
- ...parsedInfo,
4522
- originalUri: s3Uri
4523
- });
4524
- }
4525
- }
4526
- }
4527
- const lastKey = response.Contents[response.Contents.length - 1]?.Key;
4528
- const hasMore = !!response.IsTruncated || response.Contents.length === pageSize * 10;
4529
- console.log(`[S3ClipsService] Fetched ${videos.length} videos, hasMore: ${hasMore}`);
4530
- return {
4531
- videos,
4532
- nextToken: hasMore ? lastKey : void 0,
4533
- hasMore
4534
- };
4535
- }
4536
- return { videos: [], hasMore: false };
4537
- } catch (error) {
4538
- console.error(`[S3ClipsService] Error fetching videos page:`, error);
4539
- return { videos: [], hasMore: false };
4540
- }
4541
- },
4542
- "VideosPage"
4543
- );
4481
+ createEmptyVideoIndex(workspaceId, date, shiftId) {
4482
+ return {
4483
+ byCategory: /* @__PURE__ */ new Map(),
4484
+ allVideos: [],
4485
+ counts: {},
4486
+ workspaceId,
4487
+ date,
4488
+ shiftId,
4489
+ lastUpdated: /* @__PURE__ */ new Date(),
4490
+ _debugId: `empty_${Date.now()}`
4491
+ };
4544
4492
  }
4545
4493
  /**
4546
- * Cleanup method for proper resource management
4494
+ * Cleanup
4547
4495
  */
4548
4496
  dispose() {
4549
- console.log("[S3ClipsService] Disposing service and clearing request cache");
4550
- this.requestCache.clear();
4497
+ console.log("[S3ClipsService] Disposing service");
4498
+ this.apiClient.dispose();
4551
4499
  }
4552
4500
  /**
4553
- * Get service statistics for monitoring
4501
+ * Get statistics
4554
4502
  */
4555
4503
  getStats() {
4556
- return {
4557
- requestCache: this.requestCache.getStats()
4558
- };
4504
+ return this.apiClient.getStats();
4559
4505
  }
4560
4506
  };
4561
4507
 
@@ -12144,6 +12090,140 @@ function useWorkspaceNavigation() {
12144
12090
  getWorkspaceNavigationParams: getWorkspaceNavigationParams2
12145
12091
  };
12146
12092
  }
12093
+ function useWorkspaceHealth(options = {}) {
12094
+ const [workspaces, setWorkspaces] = React19.useState([]);
12095
+ const [summary, setSummary] = React19.useState(null);
12096
+ const [loading, setLoading] = React19.useState(true);
12097
+ const [error, setError] = React19.useState(null);
12098
+ const unsubscribeRef = React19.useRef(null);
12099
+ const refreshIntervalRef = React19.useRef(null);
12100
+ const {
12101
+ enableRealtime = true,
12102
+ refreshInterval = 3e4,
12103
+ // 30 seconds default
12104
+ ...filterOptions
12105
+ } = options;
12106
+ const fetchData = React19.useCallback(async () => {
12107
+ try {
12108
+ setError(null);
12109
+ workspaceHealthService.clearCache();
12110
+ const [workspacesData, summaryData] = await Promise.all([
12111
+ workspaceHealthService.getWorkspaceHealthStatus(filterOptions),
12112
+ workspaceHealthService.getHealthSummary(filterOptions.lineId, filterOptions.companyId)
12113
+ ]);
12114
+ setWorkspaces(workspacesData);
12115
+ setSummary(summaryData);
12116
+ } catch (err) {
12117
+ console.error("Error fetching workspace health:", err);
12118
+ setError(err);
12119
+ } finally {
12120
+ setLoading(false);
12121
+ }
12122
+ }, [filterOptions.lineId, filterOptions.companyId, filterOptions.status, filterOptions.searchTerm, filterOptions.sortBy, filterOptions.sortOrder]);
12123
+ const handleRealtimeUpdate = React19.useCallback(async (data) => {
12124
+ try {
12125
+ const [workspacesData, summaryData] = await Promise.all([
12126
+ workspaceHealthService.getWorkspaceHealthStatus(filterOptions),
12127
+ workspaceHealthService.getHealthSummary(filterOptions.lineId, filterOptions.companyId)
12128
+ ]);
12129
+ setWorkspaces(workspacesData);
12130
+ setSummary(summaryData);
12131
+ } catch (err) {
12132
+ console.error("Error updating real-time health data:", err);
12133
+ }
12134
+ }, [filterOptions]);
12135
+ React19.useEffect(() => {
12136
+ fetchData();
12137
+ if (refreshInterval > 0) {
12138
+ refreshIntervalRef.current = setInterval(fetchData, 1e4);
12139
+ }
12140
+ if (enableRealtime) {
12141
+ unsubscribeRef.current = workspaceHealthService.subscribeToHealthUpdates(
12142
+ handleRealtimeUpdate,
12143
+ { lineId: filterOptions.lineId, companyId: filterOptions.companyId }
12144
+ );
12145
+ }
12146
+ return () => {
12147
+ if (refreshIntervalRef.current) {
12148
+ clearInterval(refreshIntervalRef.current);
12149
+ }
12150
+ if (unsubscribeRef.current) {
12151
+ unsubscribeRef.current();
12152
+ }
12153
+ };
12154
+ }, [fetchData, enableRealtime, refreshInterval, handleRealtimeUpdate, filterOptions.lineId, filterOptions.companyId]);
12155
+ return {
12156
+ workspaces,
12157
+ summary,
12158
+ loading,
12159
+ error,
12160
+ refetch: fetchData
12161
+ };
12162
+ }
12163
+ function useWorkspaceHealthById(workspaceId, options = {}) {
12164
+ const [workspace, setWorkspace] = React19.useState(null);
12165
+ const [metrics2, setMetrics] = React19.useState(null);
12166
+ const [loading, setLoading] = React19.useState(true);
12167
+ const [error, setError] = React19.useState(null);
12168
+ const unsubscribeRef = React19.useRef(null);
12169
+ const refreshIntervalRef = React19.useRef(null);
12170
+ const { enableRealtime = true, refreshInterval = 3e4 } = options;
12171
+ const fetchData = React19.useCallback(async () => {
12172
+ if (!workspaceId) {
12173
+ setWorkspace(null);
12174
+ setMetrics(null);
12175
+ setLoading(false);
12176
+ return;
12177
+ }
12178
+ try {
12179
+ setLoading(true);
12180
+ setError(null);
12181
+ const [workspaceData, metricsData] = await Promise.all([
12182
+ workspaceHealthService.getWorkspaceHealthById(workspaceId),
12183
+ workspaceHealthService.getHealthMetrics(workspaceId)
12184
+ ]);
12185
+ setWorkspace(workspaceData);
12186
+ setMetrics(metricsData);
12187
+ } catch (err) {
12188
+ console.error("Error fetching workspace health by ID:", err);
12189
+ setError(err);
12190
+ } finally {
12191
+ setLoading(false);
12192
+ }
12193
+ }, [workspaceId]);
12194
+ const handleRealtimeUpdate = React19.useCallback((data) => {
12195
+ if (data.workspace_id === workspaceId) {
12196
+ const updatedWorkspace = workspaceHealthService["processHealthStatus"](data);
12197
+ setWorkspace(updatedWorkspace);
12198
+ }
12199
+ }, [workspaceId]);
12200
+ React19.useEffect(() => {
12201
+ fetchData();
12202
+ if (refreshInterval > 0) {
12203
+ refreshIntervalRef.current = setInterval(fetchData, 1e4);
12204
+ }
12205
+ if (enableRealtime && workspaceId) {
12206
+ unsubscribeRef.current = workspaceHealthService.subscribeToHealthUpdates(
12207
+ handleRealtimeUpdate
12208
+ );
12209
+ }
12210
+ return () => {
12211
+ if (refreshIntervalRef.current) {
12212
+ clearInterval(refreshIntervalRef.current);
12213
+ }
12214
+ if (unsubscribeRef.current) {
12215
+ unsubscribeRef.current();
12216
+ }
12217
+ };
12218
+ }, [fetchData, enableRealtime, refreshInterval, handleRealtimeUpdate, workspaceId]);
12219
+ return {
12220
+ workspace,
12221
+ metrics: metrics2,
12222
+ loading,
12223
+ error,
12224
+ refetch: fetchData
12225
+ };
12226
+ }
12147
12227
  function useDateFormatter() {
12148
12228
  const { defaultTimezone, defaultLocale, dateFormatOptions, timeFormatOptions, dateTimeFormatOptions } = useDateTimeConfig();
12149
12229
  const formatDate = React19.useCallback(
@@ -23552,6 +23632,165 @@ var TicketHistory = ({ companyId }) => {
23552
23632
  ] });
23553
23633
  };
23554
23634
  var TicketHistory_default = TicketHistory;
23635
+ var HealthStatusIndicator = ({
23636
+ status,
23637
+ lastUpdated,
23638
+ showLabel = false,
23639
+ showTime = true,
23640
+ size = "md",
23641
+ className = "",
23642
+ inline = true,
23643
+ pulse = true
23644
+ }) => {
23645
+ const getStatusConfig = () => {
23646
+ switch (status) {
23647
+ case "healthy":
23648
+ return {
23649
+ color: "text-green-500",
23650
+ bgColor: "bg-green-500",
23651
+ borderColor: "border-green-500",
23652
+ label: "Healthy",
23653
+ icon: lucideReact.CheckCircle,
23654
+ shouldPulse: pulse
23655
+ };
23656
+ case "unhealthy":
23657
+ return {
23658
+ color: "text-red-500",
23659
+ bgColor: "bg-red-500",
23660
+ borderColor: "border-red-500",
23661
+ label: "Unhealthy",
23662
+ icon: lucideReact.XCircle,
23663
+ shouldPulse: false
23664
+ };
23665
+ case "warning":
23666
+ return {
23667
+ color: "text-yellow-500",
23668
+ bgColor: "bg-yellow-500",
23669
+ borderColor: "border-yellow-500",
23670
+ label: "Warning",
23671
+ icon: lucideReact.AlertTriangle,
23672
+ shouldPulse: true
23673
+ };
23674
+ case "unknown":
23675
+ default:
23676
+ return {
23677
+ color: "text-gray-400",
23678
+ bgColor: "bg-gray-400",
23679
+ borderColor: "border-gray-400",
23680
+ label: "Unknown",
23681
+ icon: lucideReact.Activity,
23682
+ shouldPulse: false
23683
+ };
23684
+ }
23685
+ };
23686
+ const config = getStatusConfig();
23687
+ config.icon;
23688
+ const sizeClasses = {
23689
+ sm: {
23690
+ dot: "h-2 w-2",
23691
+ icon: "h-3 w-3",
23692
+ text: "text-xs",
23693
+ spacing: "gap-1"
23694
+ },
23695
+ md: {
23696
+ dot: "h-3 w-3",
23697
+ icon: "h-4 w-4",
23698
+ text: "text-sm",
23699
+ spacing: "gap-1.5"
23700
+ },
23701
+ lg: {
23702
+ dot: "h-4 w-4",
23703
+ icon: "h-5 w-5",
23704
+ text: "text-base",
23705
+ spacing: "gap-2"
23706
+ }
23707
+ };
23708
+ const currentSize = sizeClasses[size];
23709
+ const containerClasses = clsx(
23710
+ "flex items-center",
23711
+ currentSize.spacing,
23712
+ inline ? "inline-flex" : "flex",
23713
+ className
23714
+ );
23715
+ const dotClasses = clsx(
23716
+ "rounded-full",
23717
+ currentSize.dot,
23718
+ config.bgColor,
23719
+ config.shouldPulse && "animate-pulse"
23720
+ );
23721
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: containerClasses, children: [
23722
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative flex items-center justify-center", children: [
23723
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: dotClasses }),
23724
+ config.shouldPulse && status === "healthy" && /* @__PURE__ */ jsxRuntime.jsx(
23725
+ "div",
23726
+ {
23727
+ className: clsx(
23728
+ "absolute rounded-full opacity-25",
23729
+ currentSize.dot,
23730
+ config.bgColor,
23731
+ "animate-ping"
23732
+ )
23733
+ }
23734
+ )
23735
+ ] }),
23736
+ showLabel && /* @__PURE__ */ jsxRuntime.jsx("span", { className: clsx(currentSize.text, "font-medium", config.color), children: config.label }),
23737
+ showTime && lastUpdated && /* @__PURE__ */ jsxRuntime.jsx("span", { className: clsx(currentSize.text, "text-gray-500 dark:text-gray-400"), children: lastUpdated })
23738
+ ] });
23739
+ };
23740
+ var DetailedHealthStatus = ({
23741
+ workspaceName,
23742
+ lineName,
23743
+ consecutiveMisses,
23744
+ showDetails = true,
23745
+ ...indicatorProps
23746
+ }) => {
23747
+ const getStatusConfig = () => {
23748
+ switch (indicatorProps.status) {
23749
+ case "healthy":
23750
+ return {
23751
+ bgClass: "bg-green-50 dark:bg-green-900/20",
23752
+ borderClass: "border-green-200 dark:border-green-800"
23753
+ };
23754
+ case "unhealthy":
23755
+ return {
23756
+ bgClass: "bg-red-50 dark:bg-red-900/20",
23757
+ borderClass: "border-red-200 dark:border-red-800"
23758
+ };
23759
+ case "warning":
23760
+ return {
23761
+ bgClass: "bg-yellow-50 dark:bg-yellow-900/20",
23762
+ borderClass: "border-yellow-200 dark:border-yellow-800"
23763
+ };
23764
+ default:
23765
+ return {
23766
+ bgClass: "bg-gray-50 dark:bg-gray-900/20",
23767
+ borderClass: "border-gray-200 dark:border-gray-800"
23768
+ };
23769
+ }
23770
+ };
23771
+ const config = getStatusConfig();
23772
+ return /* @__PURE__ */ jsxRuntime.jsx(
23773
+ "div",
23774
+ {
23775
+ className: clsx(
23776
+ "rounded-lg border p-3",
23777
+ config.bgClass,
23778
+ config.borderClass
23779
+ ),
23780
+ children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start justify-between", children: [
23781
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1", children: [
23782
+ showDetails && workspaceName && /* @__PURE__ */ jsxRuntime.jsx("h4", { className: "text-sm font-semibold text-gray-900 dark:text-gray-100", children: workspaceName }),
23783
+ showDetails && lineName && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-0.5", children: lineName }),
23784
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-2", children: /* @__PURE__ */ jsxRuntime.jsx(HealthStatusIndicator, { ...indicatorProps, showLabel: true }) })
23785
+ ] }),
23786
+ showDetails && consecutiveMisses !== void 0 && consecutiveMisses > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "ml-3 text-right", children: [
23787
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs font-medium text-gray-500 dark:text-gray-400", children: "Missed" }),
23788
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-bold text-gray-900 dark:text-gray-100", children: consecutiveMisses })
23789
+ ] })
23790
+ ] })
23791
+ }
23792
+ );
23793
+ };
23555
23794
  var LinePdfExportButton = ({
23556
23795
  targetElement,
23557
23796
  fileName = "line-export",
@@ -24674,6 +24913,8 @@ var WorkspaceCard = ({
24674
24913
  cycleTime,
24675
24914
  operators,
24676
24915
  status = "normal",
24916
+ healthStatus,
24917
+ healthLastUpdated,
24677
24918
  onCardClick,
24678
24919
  headerActions,
24679
24920
  footerContent,
@@ -24766,6 +25007,19 @@ var WorkspaceCard = ({
24766
25007
  ] })
24767
25008
  ] })
24768
25009
  ] }),
25010
+ healthStatus && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "pt-2 mt-auto border-t dark:border-gray-700", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
25011
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: "System Health" }),
25012
+ /* @__PURE__ */ jsxRuntime.jsx(
25013
+ HealthStatusIndicator,
25014
+ {
25015
+ status: healthStatus,
25016
+ lastUpdated: healthLastUpdated,
25017
+ showTime: false,
25018
+ size: "sm",
25019
+ pulse: healthStatus === "healthy"
25020
+ }
25021
+ )
25022
+ ] }) }),
24769
25023
  chartData && chartData.data && chartData.data.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(
24770
25024
  "div",
24771
25025
  {
@@ -26424,6 +26678,194 @@ var BackButtonMinimal = ({
26424
26678
  }
26425
26679
  );
26426
26680
  };
26681
+ var InlineEditableText = ({
26682
+ value,
26683
+ onSave,
26684
+ placeholder = "Click to edit",
26685
+ className = "",
26686
+ editIconClassName = "",
26687
+ inputClassName = "",
26688
+ debounceDelay = 750,
26689
+ // 750ms for quick auto-save
26690
+ disabled = false
26691
+ }) => {
26692
+ const [isEditing, setIsEditing] = React19.useState(false);
26693
+ const [editValue, setEditValue] = React19.useState(value);
26694
+ const [saveStatus, setSaveStatus] = React19.useState("idle");
26695
+ const [lastSavedValue, setLastSavedValue] = React19.useState(value);
26696
+ const [hasUnsavedChanges, setHasUnsavedChanges] = React19.useState(false);
26697
+ const inputRef = React19.useRef(null);
26698
+ const containerRef = React19.useRef(null);
26699
+ const debounceTimeout = React19.useRef(void 0);
26700
+ const saveStatusTimeout = React19.useRef(void 0);
26701
+ React19.useEffect(() => {
26702
+ if (!isEditing) {
26703
+ setEditValue(value);
26704
+ setLastSavedValue(value);
26705
+ }
26706
+ }, [value, isEditing]);
26707
+ React19.useEffect(() => {
26708
+ if (isEditing && inputRef.current) {
26709
+ requestAnimationFrame(() => {
26710
+ inputRef.current?.focus();
26711
+ inputRef.current?.select();
26712
+ });
26713
+ }
26714
+ }, [isEditing]);
26715
+ React19.useEffect(() => {
26716
+ return () => {
26717
+ if (debounceTimeout.current) clearTimeout(debounceTimeout.current);
26718
+ if (saveStatusTimeout.current) clearTimeout(saveStatusTimeout.current);
26719
+ };
26720
+ }, []);
26721
+ const performSave = React19.useCallback(async (valueToSave, shouldClose = false) => {
26722
+ const trimmedValue = valueToSave.trim();
26723
+ if (trimmedValue === lastSavedValue.trim()) {
26724
+ setHasUnsavedChanges(false);
26725
+ if (shouldClose) {
26726
+ setIsEditing(false);
26727
+ setSaveStatus("idle");
26728
+ }
26729
+ return;
26730
+ }
26731
+ setSaveStatus("saving");
26732
+ setHasUnsavedChanges(false);
26733
+ try {
26734
+ await onSave(trimmedValue);
26735
+ setLastSavedValue(trimmedValue);
26736
+ setSaveStatus("saved");
26737
+ if (!shouldClose && inputRef.current) {
26738
+ requestAnimationFrame(() => {
26739
+ inputRef.current?.focus();
26740
+ });
26741
+ }
26742
+ if (saveStatusTimeout.current) clearTimeout(saveStatusTimeout.current);
26743
+ saveStatusTimeout.current = setTimeout(() => {
26744
+ setSaveStatus("idle");
26745
+ }, 2e3);
26746
+ if (shouldClose) {
26747
+ setIsEditing(false);
26748
+ }
26749
+ } catch (error) {
26750
+ console.error("Failed to save:", error);
26751
+ setSaveStatus("error");
26752
+ setHasUnsavedChanges(true);
26753
+ if (saveStatusTimeout.current) clearTimeout(saveStatusTimeout.current);
26754
+ saveStatusTimeout.current = setTimeout(() => {
26755
+ setSaveStatus("idle");
26756
+ }, 3e3);
26757
+ if (!shouldClose && inputRef.current) {
26758
+ requestAnimationFrame(() => {
26759
+ inputRef.current?.focus();
26760
+ });
26761
+ }
26762
+ }
26763
+ }, [lastSavedValue, onSave]);
26764
+ React19.useEffect(() => {
26765
+ const handleClickOutside = (event) => {
26766
+ if (isEditing && containerRef.current && !containerRef.current.contains(event.target)) {
26767
+ if (debounceTimeout.current) {
26768
+ clearTimeout(debounceTimeout.current);
26769
+ }
26770
+ performSave(editValue, true);
26771
+ }
26772
+ };
26773
+ if (isEditing) {
26774
+ document.addEventListener("mousedown", handleClickOutside);
26775
+ return () => document.removeEventListener("mousedown", handleClickOutside);
26776
+ }
26777
+ }, [isEditing, editValue, performSave]);
26778
+ const handleInputChange = (e) => {
26779
+ const newValue = e.target.value;
26780
+ setEditValue(newValue);
26781
+ if (newValue.trim() !== lastSavedValue.trim()) {
26782
+ setHasUnsavedChanges(true);
26783
+ setSaveStatus("idle");
26784
+ } else {
26785
+ setHasUnsavedChanges(false);
26786
+ }
26787
+ if (debounceTimeout.current) {
26788
+ clearTimeout(debounceTimeout.current);
26789
+ }
26790
+ if (newValue.trim() !== lastSavedValue.trim()) {
26791
+ debounceTimeout.current = setTimeout(() => {
26792
+ performSave(newValue, false);
26793
+ }, debounceDelay);
26794
+ }
26795
+ };
26796
+ const handleKeyDown = (e) => {
26797
+ if (e.key === "Enter") {
26798
+ e.preventDefault();
26799
+ if (debounceTimeout.current) {
26800
+ clearTimeout(debounceTimeout.current);
26801
+ }
26802
+ performSave(editValue, true);
26803
+ } else if (e.key === "Escape") {
26804
+ e.preventDefault();
26805
+ if (debounceTimeout.current) {
26806
+ clearTimeout(debounceTimeout.current);
26807
+ }
26808
+ setEditValue(lastSavedValue);
26809
+ setHasUnsavedChanges(false);
26810
+ setSaveStatus("idle");
26811
+ setIsEditing(false);
26812
+ }
26813
+ };
26814
+ const handleClick = () => {
26815
+ if (!disabled && !isEditing) {
26816
+ setIsEditing(true);
26817
+ setSaveStatus("idle");
26818
+ }
26819
+ };
26820
+ if (isEditing) {
26821
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "inline-flex items-center gap-1.5", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative", children: [
26822
+ /* @__PURE__ */ jsxRuntime.jsx(
26823
+ "input",
26824
+ {
26825
+ ref: inputRef,
26826
+ type: "text",
26827
+ value: editValue,
26828
+ onChange: handleInputChange,
26829
+ onKeyDown: handleKeyDown,
26830
+ className: `px-2 py-1 pr-7 text-sm border rounded-md transition-colors duration-200
26831
+ ${saveStatus === "error" ? "border-red-400 focus:ring-red-500 focus:border-red-500" : hasUnsavedChanges ? "border-yellow-400 focus:ring-yellow-500 focus:border-yellow-500" : saveStatus === "saved" ? "border-green-400 focus:ring-green-500 focus:border-green-500" : "border-blue-400 focus:ring-blue-500 focus:border-blue-500"}
26832
+ focus:outline-none focus:ring-2 bg-white
26833
+ ${inputClassName}`,
26834
+ placeholder,
26835
+ autoComplete: "off"
26836
+ }
26837
+ ),
26838
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "absolute right-1.5 top-1/2 -translate-y-1/2", children: [
26839
+ saveStatus === "saving" && /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: "w-3.5 h-3.5 text-blue-500 animate-spin" }),
26840
+ saveStatus === "saved" && /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Check, { className: "w-3.5 h-3.5 text-green-500" }),
26841
+ saveStatus === "error" && /* @__PURE__ */ jsxRuntime.jsx(lucideReact.AlertCircle, { className: "w-3.5 h-3.5 text-red-500" }),
26842
+ saveStatus === "idle" && hasUnsavedChanges && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-1.5 h-1.5 bg-yellow-400 rounded-full" })
26843
+ ] })
26844
+ ] }) });
26845
+ }
26846
+ return /* @__PURE__ */ jsxRuntime.jsxs(
26847
+ "div",
26848
+ {
26849
+ onClick: handleClick,
26850
+ className: `inline-flex items-center gap-1.5 cursor-pointer px-2 py-1 rounded-md
26851
+ transition-all duration-200 hover:bg-gray-50 group
26852
+ ${disabled ? "cursor-not-allowed opacity-50" : ""}
26853
+ ${className}`,
26854
+ children: [
26855
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-medium text-gray-900", children: editValue || placeholder }),
26856
+ /* @__PURE__ */ jsxRuntime.jsx(
26857
+ lucideReact.Edit2,
26858
+ {
26859
+ className: `w-3.5 h-3.5 text-gray-400 transition-opacity duration-200
26860
+ opacity-0 group-hover:opacity-100
26861
+ ${disabled ? "hidden" : ""}
26862
+ ${editIconClassName}`
26863
+ }
26864
+ )
26865
+ ]
26866
+ }
26867
+ );
26868
+ };
26427
26869
  var BottlenecksContent = ({
26428
26870
  workspaceId,
26429
26871
  workspaceName,
@@ -28169,6 +28611,451 @@ var KPISection = React19.memo(({
28169
28611
  return true;
28170
28612
  });
28171
28613
  KPISection.displayName = "KPISection";
28614
+ var WorkspaceHealthCard = ({
28615
+ workspace,
28616
+ onClick,
28617
+ showDetails = true,
28618
+ className = ""
28619
+ }) => {
28620
+ const getStatusConfig = () => {
28621
+ switch (workspace.status) {
28622
+ case "healthy":
28623
+ return {
28624
+ gradient: "from-emerald-50 to-green-50 dark:from-emerald-950/30 dark:to-green-950/30",
28625
+ border: "border-emerald-200 dark:border-emerald-800",
28626
+ icon: lucideReact.CheckCircle2,
28627
+ iconColor: "text-emerald-600 dark:text-emerald-400",
28628
+ badge: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/50 dark:text-emerald-300",
28629
+ statusText: "Online",
28630
+ pulse: true
28631
+ };
28632
+ case "unhealthy":
28633
+ return {
28634
+ gradient: "from-rose-50 to-red-50 dark:from-rose-950/30 dark:to-red-950/30",
28635
+ border: "border-rose-200 dark:border-rose-800",
28636
+ icon: lucideReact.XCircle,
28637
+ iconColor: "text-rose-600 dark:text-rose-400",
28638
+ badge: "bg-rose-100 text-rose-700 dark:bg-rose-900/50 dark:text-rose-300",
28639
+ statusText: "Offline",
28640
+ pulse: false
28641
+ };
28642
+ case "warning":
28643
+ return {
28644
+ gradient: "from-amber-50 to-yellow-50 dark:from-amber-950/30 dark:to-yellow-950/30",
28645
+ border: "border-amber-200 dark:border-amber-800",
28646
+ icon: lucideReact.AlertTriangle,
28647
+ iconColor: "text-amber-600 dark:text-amber-400",
28648
+ badge: "bg-amber-100 text-amber-700 dark:bg-amber-900/50 dark:text-amber-300",
28649
+ statusText: "Degraded",
28650
+ pulse: true
28651
+ };
28652
+ default:
28653
+ return {
28654
+ gradient: "from-gray-50 to-slate-50 dark:from-gray-950/30 dark:to-slate-950/30",
28655
+ border: "border-gray-200 dark:border-gray-800",
28656
+ icon: lucideReact.Activity,
28657
+ iconColor: "text-gray-500 dark:text-gray-400",
28658
+ badge: "bg-gray-100 text-gray-700 dark:bg-gray-900/50 dark:text-gray-300",
28659
+ statusText: "Unknown",
28660
+ pulse: false
28661
+ };
28662
+ }
28663
+ };
28664
+ const config = getStatusConfig();
28665
+ const StatusIcon = config.icon;
28666
+ workspace.isStale ? lucideReact.WifiOff : lucideReact.Wifi;
28667
+ const handleClick = () => {
28668
+ if (onClick) {
28669
+ onClick(workspace);
28670
+ }
28671
+ };
28672
+ const handleKeyDown = (event) => {
28673
+ if (onClick && (event.key === "Enter" || event.key === " ")) {
28674
+ event.preventDefault();
28675
+ onClick(workspace);
28676
+ }
28677
+ };
28678
+ const formatTimeAgo = (timeString) => {
28679
+ return timeString.replace("about ", "").replace(" ago", "");
28680
+ };
28681
+ return /* @__PURE__ */ jsxRuntime.jsx(
28682
+ Card2,
28683
+ {
28684
+ className: clsx(
28685
+ "relative overflow-hidden transition-all duration-300",
28686
+ "bg-gradient-to-br",
28687
+ config.gradient,
28688
+ "border",
28689
+ config.border,
28690
+ "shadow-sm hover:shadow-md",
28691
+ onClick && "cursor-pointer hover:scale-[1.01]",
28692
+ workspace.isStale && "opacity-90",
28693
+ className
28694
+ ),
28695
+ onClick: handleClick,
28696
+ onKeyDown: handleKeyDown,
28697
+ tabIndex: onClick ? 0 : void 0,
28698
+ role: onClick ? "button" : void 0,
28699
+ "aria-label": `Workspace ${workspace.workspace_display_name} status: ${workspace.status}`,
28700
+ children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "p-4", children: [
28701
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start justify-between mb-3", children: [
28702
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1", children: [
28703
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-gray-100 mb-1", children: workspace.workspace_display_name || `Workspace ${workspace.workspace_id.slice(0, 8)}` }),
28704
+ showDetails && workspace.line_name && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: workspace.line_name })
28705
+ ] }),
28706
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: clsx(
28707
+ "flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium",
28708
+ config.badge
28709
+ ), children: [
28710
+ /* @__PURE__ */ jsxRuntime.jsx(StatusIcon, { className: "h-3.5 w-3.5" }),
28711
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: config.statusText })
28712
+ ] })
28713
+ ] }),
28714
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
28715
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-1", children: [
28716
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1.5", children: [
28717
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Clock, { className: "h-3.5 w-3.5 text-gray-400" }),
28718
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-sm text-gray-600 dark:text-gray-400 whitespace-nowrap", children: [
28719
+ "Last seen: ",
28720
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-medium", children: formatTimeAgo(workspace.timeSinceLastUpdate) })
28721
+ ] })
28722
+ ] }),
28723
+ workspace.isStale && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1.5", children: [
28724
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.WifiOff, { className: "h-3.5 w-3.5 text-amber-500" }),
28725
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-amber-600 dark:text-amber-400 text-xs", children: "No recent updates" })
28726
+ ] })
28727
+ ] }),
28728
+ config.pulse && !workspace.isStale && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1.5", children: [
28729
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative flex h-2 w-2", children: [
28730
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: clsx(
28731
+ "animate-ping absolute inline-flex h-full w-full rounded-full opacity-75",
28732
+ workspace.status === "healthy" ? "bg-emerald-400" : "bg-amber-400"
28733
+ ) }),
28734
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: clsx(
28735
+ "relative inline-flex rounded-full h-2 w-2",
28736
+ workspace.status === "healthy" ? "bg-emerald-500" : "bg-amber-500"
28737
+ ) })
28738
+ ] }),
28739
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-gray-500 dark:text-gray-400", children: "Live" })
28740
+ ] })
28741
+ ] })
28742
+ ] })
28743
+ }
28744
+ );
28745
+ };
28746
+ var CompactWorkspaceHealthCard = ({
28747
+ workspace,
28748
+ onClick,
28749
+ className = ""
28750
+ }) => {
28751
+ const getStatusConfig = () => {
28752
+ switch (workspace.status) {
28753
+ case "healthy":
28754
+ return {
28755
+ dot: "bg-emerald-500",
28756
+ icon: lucideReact.CheckCircle2,
28757
+ iconColor: "text-emerald-600 dark:text-emerald-400",
28758
+ bg: "hover:bg-emerald-50 dark:hover:bg-emerald-950/20"
28759
+ };
28760
+ case "unhealthy":
28761
+ return {
28762
+ dot: "bg-rose-500",
28763
+ icon: lucideReact.XCircle,
28764
+ iconColor: "text-rose-600 dark:text-rose-400",
28765
+ bg: "hover:bg-rose-50 dark:hover:bg-rose-950/20"
28766
+ };
28767
+ case "warning":
28768
+ return {
28769
+ dot: "bg-amber-500",
28770
+ icon: lucideReact.AlertTriangle,
28771
+ iconColor: "text-amber-600 dark:text-amber-400",
28772
+ bg: "hover:bg-amber-50 dark:hover:bg-amber-950/20"
28773
+ };
28774
+ default:
28775
+ return {
28776
+ dot: "bg-gray-400",
28777
+ icon: lucideReact.Activity,
28778
+ iconColor: "text-gray-500 dark:text-gray-400",
28779
+ bg: "hover:bg-gray-50 dark:hover:bg-gray-950/20"
28780
+ };
28781
+ }
28782
+ };
28783
+ const config = getStatusConfig();
28784
+ const StatusIcon = config.icon;
28785
+ const handleClick = () => {
28786
+ if (onClick) {
28787
+ onClick(workspace);
28788
+ }
28789
+ };
28790
+ return /* @__PURE__ */ jsxRuntime.jsxs(
28791
+ "div",
28792
+ {
28793
+ className: clsx(
28794
+ "flex items-center justify-between px-4 py-3 rounded-lg border",
28795
+ "bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700",
28796
+ "transition-all duration-200",
28797
+ onClick && `cursor-pointer ${config.bg}`,
28798
+ className
28799
+ ),
28800
+ onClick: handleClick,
28801
+ role: onClick ? "button" : void 0,
28802
+ tabIndex: onClick ? 0 : void 0,
28803
+ children: [
28804
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3", children: [
28805
+ /* @__PURE__ */ jsxRuntime.jsx(StatusIcon, { className: clsx("h-5 w-5", config.iconColor) }),
28806
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
28807
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium text-gray-900 dark:text-gray-100", children: workspace.workspace_display_name || `WS-${workspace.workspace_id.slice(0, 6)}` }),
28808
+ workspace.line_name && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: workspace.line_name })
28809
+ ] })
28810
+ ] }),
28811
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3", children: [
28812
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400", children: workspace.timeSinceLastUpdate }),
28813
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: clsx("h-2 w-2 rounded-full", config.dot) })
28814
+ ] })
28815
+ ]
28816
+ }
28817
+ );
28818
+ };
28819
+ var HealthStatusGrid = ({
28820
+ workspaces,
28821
+ onWorkspaceClick,
28822
+ viewMode: initialViewMode = "grid",
28823
+ showFilters = true,
28824
+ groupBy: initialGroupBy = "none",
28825
+ className = ""
28826
+ }) => {
28827
+ const [viewMode, setViewMode] = React19.useState(initialViewMode);
28828
+ const [searchTerm, setSearchTerm] = React19.useState("");
28829
+ const [statusFilter, setStatusFilter] = React19.useState("all");
28830
+ const [groupBy, setGroupBy] = React19.useState(initialGroupBy);
28831
+ const [expandedGroups, setExpandedGroups] = React19.useState(/* @__PURE__ */ new Set());
28832
+ const filteredWorkspaces = React19.useMemo(() => {
28833
+ let filtered = [...workspaces];
28834
+ if (searchTerm) {
28835
+ const search = searchTerm.toLowerCase();
28836
+ filtered = filtered.filter(
28837
+ (w) => w.workspace_display_name?.toLowerCase().includes(search) || w.line_name?.toLowerCase().includes(search) || w.company_name?.toLowerCase().includes(search)
28838
+ );
28839
+ }
28840
+ if (statusFilter !== "all") {
28841
+ filtered = filtered.filter((w) => w.status === statusFilter);
28842
+ }
28843
+ return filtered;
28844
+ }, [workspaces, searchTerm, statusFilter]);
28845
+ const groupedWorkspaces = React19.useMemo(() => {
28846
+ if (groupBy === "none") {
28847
+ return { "All Workspaces": filteredWorkspaces };
28848
+ }
28849
+ const groups = {};
28850
+ filteredWorkspaces.forEach((workspace) => {
28851
+ let key = "Unknown";
28852
+ switch (groupBy) {
28853
+ case "line":
28854
+ key = workspace.line_name || "Unknown Line";
28855
+ break;
28856
+ case "status":
28857
+ key = workspace.status;
28858
+ break;
28859
+ }
28860
+ if (!groups[key]) {
28861
+ groups[key] = [];
28862
+ }
28863
+ groups[key].push(workspace);
28864
+ });
28865
+ const sortedGroups = {};
28866
+ Object.keys(groups).sort().forEach((key) => {
28867
+ sortedGroups[key] = groups[key];
28868
+ });
28869
+ return sortedGroups;
28870
+ }, [filteredWorkspaces, groupBy]);
28871
+ React19.useEffect(() => {
28872
+ if (groupBy !== "none") {
28873
+ setExpandedGroups(new Set(Object.keys(groupedWorkspaces)));
28874
+ }
28875
+ }, [groupBy, groupedWorkspaces]);
28876
+ const toggleGroup = (groupName) => {
28877
+ const newExpanded = new Set(expandedGroups);
28878
+ if (newExpanded.has(groupName)) {
28879
+ newExpanded.delete(groupName);
28880
+ } else {
28881
+ newExpanded.add(groupName);
28882
+ }
28883
+ setExpandedGroups(newExpanded);
28884
+ };
28885
+ const getStatusCounts = () => {
28886
+ const counts = {
28887
+ healthy: 0,
28888
+ unhealthy: 0,
28889
+ warning: 0,
28890
+ unknown: 0
28891
+ };
28892
+ workspaces.forEach((w) => {
28893
+ counts[w.status]++;
28894
+ });
28895
+ return counts;
28896
+ };
28897
+ const statusCounts = getStatusCounts();
28898
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: clsx("space-y-4", className), children: [
28899
+ showFilters && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4", children: [
28900
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col sm:flex-row gap-3 flex-wrap", children: [
28901
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex-1 min-w-[200px]", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative", children: [
28902
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Search, { className: "absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" }),
28903
+ /* @__PURE__ */ jsxRuntime.jsx(
28904
+ "input",
28905
+ {
28906
+ type: "text",
28907
+ placeholder: "Search workspaces...",
28908
+ value: searchTerm,
28909
+ onChange: (e) => setSearchTerm(e.target.value),
28910
+ className: "w-full pl-10 pr-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100"
28911
+ }
28912
+ )
28913
+ ] }) }),
28914
+ /* @__PURE__ */ jsxRuntime.jsxs(Select, { value: statusFilter, onValueChange: (value) => setStatusFilter(value), children: [
28915
+ /* @__PURE__ */ jsxRuntime.jsx(SelectTrigger, { className: "w-full sm:w-[180px] bg-white border-gray-200", children: /* @__PURE__ */ jsxRuntime.jsx(SelectValue, { placeholder: "All statuses" }) }),
28916
+ /* @__PURE__ */ jsxRuntime.jsxs(SelectContent, { children: [
28917
+ /* @__PURE__ */ jsxRuntime.jsxs(SelectItem, { value: "all", children: [
28918
+ "All (",
28919
+ workspaces.length,
28920
+ ")"
28921
+ ] }),
28922
+ /* @__PURE__ */ jsxRuntime.jsx(SelectItem, { value: "healthy", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
28923
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-2 w-2 rounded-full bg-green-500" }),
28924
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
28925
+ "Healthy (",
28926
+ statusCounts.healthy,
28927
+ ")"
28928
+ ] })
28929
+ ] }) }),
28930
+ /* @__PURE__ */ jsxRuntime.jsx(SelectItem, { value: "unhealthy", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
28931
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-2 w-2 rounded-full bg-red-500" }),
28932
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
28933
+ "Unhealthy (",
28934
+ statusCounts.unhealthy,
28935
+ ")"
28936
+ ] })
28937
+ ] }) }),
28938
+ /* @__PURE__ */ jsxRuntime.jsx(SelectItem, { value: "warning", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
28939
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-2 w-2 rounded-full bg-yellow-500" }),
28940
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
28941
+ "Warning (",
28942
+ statusCounts.warning,
28943
+ ")"
28944
+ ] })
28945
+ ] }) }),
28946
+ /* @__PURE__ */ jsxRuntime.jsx(SelectItem, { value: "unknown", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
28947
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-2 w-2 rounded-full bg-gray-400" }),
28948
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
28949
+ "Unknown (",
28950
+ statusCounts.unknown,
28951
+ ")"
28952
+ ] })
28953
+ ] }) })
28954
+ ] })
28955
+ ] }),
28956
+ /* @__PURE__ */ jsxRuntime.jsxs(Select, { value: groupBy, onValueChange: (value) => setGroupBy(value), children: [
28957
+ /* @__PURE__ */ jsxRuntime.jsx(SelectTrigger, { className: "w-full sm:w-[160px] bg-white border-gray-200", children: /* @__PURE__ */ jsxRuntime.jsx(SelectValue, { placeholder: "Group by" }) }),
28958
+ /* @__PURE__ */ jsxRuntime.jsxs(SelectContent, { children: [
28959
+ /* @__PURE__ */ jsxRuntime.jsx(SelectItem, { value: "none", children: "No grouping" }),
28960
+ /* @__PURE__ */ jsxRuntime.jsx(SelectItem, { value: "line", children: "Group by Line" }),
28961
+ /* @__PURE__ */ jsxRuntime.jsx(SelectItem, { value: "status", children: "Group by Status" })
28962
+ ] })
28963
+ ] }),
28964
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2", children: [
28965
+ /* @__PURE__ */ jsxRuntime.jsx(
28966
+ "button",
28967
+ {
28968
+ onClick: () => setViewMode("grid"),
28969
+ className: clsx(
28970
+ "p-2 rounded-lg transition-colors",
28971
+ viewMode === "grid" ? "bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400" : "text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700"
28972
+ ),
28973
+ "aria-label": "Grid view",
28974
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Grid3x3, { className: "h-5 w-5" })
28975
+ }
28976
+ ),
28977
+ /* @__PURE__ */ jsxRuntime.jsx(
28978
+ "button",
28979
+ {
28980
+ onClick: () => setViewMode("list"),
28981
+ className: clsx(
28982
+ "p-2 rounded-lg transition-colors",
28983
+ viewMode === "list" ? "bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400" : "text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700"
28984
+ ),
28985
+ "aria-label": "List view",
28986
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.List, { className: "h-5 w-5" })
28987
+ }
28988
+ )
28989
+ ] })
28990
+ ] }),
28991
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mt-3 text-sm text-gray-500 dark:text-gray-400", children: [
28992
+ "Showing ",
28993
+ filteredWorkspaces.length,
28994
+ " of ",
28995
+ workspaces.length,
28996
+ " workspaces"
28997
+ ] })
28998
+ ] }),
28999
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-6", children: Object.entries(groupedWorkspaces).map(([groupName, groupWorkspaces]) => {
29000
+ const isExpanded = groupBy === "none" || expandedGroups.has(groupName);
29001
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-3", children: [
29002
+ groupBy !== "none" && /* @__PURE__ */ jsxRuntime.jsxs(
29003
+ "div",
29004
+ {
29005
+ className: "flex items-center justify-between cursor-pointer group",
29006
+ onClick: () => toggleGroup(groupName),
29007
+ children: [
29008
+ /* @__PURE__ */ jsxRuntime.jsxs("h3", { className: "text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2", children: [
29009
+ groupName,
29010
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-sm font-normal text-gray-500 dark:text-gray-400", children: [
29011
+ "(",
29012
+ groupWorkspaces.length,
29013
+ ")"
29014
+ ] })
29015
+ ] }),
29016
+ /* @__PURE__ */ jsxRuntime.jsx(
29017
+ lucideReact.ChevronDown,
29018
+ {
29019
+ className: clsx(
29020
+ "h-5 w-5 text-gray-400 transition-transform",
29021
+ isExpanded && "rotate-180"
29022
+ )
29023
+ }
29024
+ )
29025
+ ]
29026
+ }
29027
+ ),
29028
+ isExpanded && /* @__PURE__ */ jsxRuntime.jsx(
29029
+ "div",
29030
+ {
29031
+ className: clsx(
29032
+ viewMode === "grid" ? "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4" : "space-y-2"
29033
+ ),
29034
+ children: groupWorkspaces.map(
29035
+ (workspace) => viewMode === "grid" ? /* @__PURE__ */ jsxRuntime.jsx(
29036
+ WorkspaceHealthCard,
29037
+ {
29038
+ workspace,
29039
+ onClick: onWorkspaceClick,
29040
+ showDetails: true
29041
+ },
29042
+ workspace.workspace_id
29043
+ ) : /* @__PURE__ */ jsxRuntime.jsx(
29044
+ CompactWorkspaceHealthCard,
29045
+ {
29046
+ workspace,
29047
+ onClick: onWorkspaceClick
29048
+ },
29049
+ workspace.workspace_id
29050
+ )
29051
+ )
29052
+ }
29053
+ )
29054
+ ] }, groupName);
29055
+ }) }),
29056
+ filteredWorkspaces.length === 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "text-center py-12", children: /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-gray-500 dark:text-gray-400", children: searchTerm || statusFilter !== "all" ? "No workspaces found matching your filters." : "No workspaces available." }) })
29057
+ ] });
29058
+ };
28172
29059
  var ISTTimer2 = ISTTimer_default;
28173
29060
  var DashboardHeader = React19.memo(({ lineTitle, className = "", headerControls }) => {
28174
29061
  const getShiftName = () => {
@@ -28666,6 +29553,17 @@ var SideNavBar = React19.memo(({
28666
29553
  });
28667
29554
  onMobileMenuClose?.();
28668
29555
  }, [navigate, onMobileMenuClose]);
29556
+ const handleHealthClick = React19.useCallback(() => {
29557
+ navigate("/health", {
29558
+ trackingEvent: {
29559
+ name: "Health Status Page Clicked",
29560
+ properties: {
29561
+ source: "side_nav"
29562
+ }
29563
+ }
29564
+ });
29565
+ onMobileMenuClose?.();
29566
+ }, [navigate, onMobileMenuClose]);
28669
29567
  const handleLogoClick = React19.useCallback(() => {
28670
29568
  navigate("/");
28671
29569
  onMobileMenuClose?.();
@@ -28679,6 +29577,7 @@ var SideNavBar = React19.memo(({
28679
29577
  const profileButtonClasses = React19.useMemo(() => getButtonClasses("/profile"), [getButtonClasses, pathname]);
28680
29578
  const helpButtonClasses = React19.useMemo(() => getButtonClasses("/help"), [getButtonClasses, pathname]);
28681
29579
  const skusButtonClasses = React19.useMemo(() => getButtonClasses("/skus"), [getButtonClasses, pathname]);
29580
+ const healthButtonClasses = React19.useMemo(() => getButtonClasses("/health"), [getButtonClasses, pathname]);
28682
29581
  const NavigationContent = () => /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
28683
29582
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full py-6 px-4 flex-shrink-0", children: /* @__PURE__ */ jsxRuntime.jsx(
28684
29583
  "button",
@@ -28823,6 +29722,21 @@ var SideNavBar = React19.memo(({
28823
29722
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-[10px] font-medium leading-tight", children: "Help" })
28824
29723
  ]
28825
29724
  }
29725
+ ),
29726
+ /* @__PURE__ */ jsxRuntime.jsxs(
29727
+ "button",
29728
+ {
29729
+ onClick: handleHealthClick,
29730
+ className: healthButtonClasses,
29731
+ "aria-label": "System Health",
29732
+ tabIndex: 0,
29733
+ role: "tab",
29734
+ "aria-selected": pathname === "/health" || pathname.startsWith("/health/"),
29735
+ children: [
29736
+ /* @__PURE__ */ jsxRuntime.jsx(outline.HeartIcon, { className: "w-5 h-5 mb-1" }),
29737
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-[10px] font-medium leading-tight", children: "Health" })
29738
+ ]
29739
+ }
28826
29740
  )
28827
29741
  ] })
28828
29742
  ] }),
@@ -35448,6 +36362,7 @@ var TargetsViewUI = ({
35448
36362
  onSaveLine,
35449
36363
  onToggleBulkConfigure,
35450
36364
  onBulkConfigure,
36365
+ onUpdateWorkspaceDisplayName,
35451
36366
  // SKU props
35452
36367
  skuEnabled = false,
35453
36368
  skus = [],
@@ -35613,7 +36528,18 @@ var TargetsViewUI = ({
35613
36528
  {
35614
36529
  className: "px-6 py-4 hover:bg-gray-50 transition-all duration-200",
35615
36530
  children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-12 gap-6 items-center", children: [
35616
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "col-span-2", children: /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-medium text-gray-900", children: formattedName }) }),
36531
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "col-span-2", children: onUpdateWorkspaceDisplayName ? /* @__PURE__ */ jsxRuntime.jsx(
36532
+ InlineEditableText,
36533
+ {
36534
+ value: formattedName,
36535
+ onSave: async (newName) => {
36536
+ await onUpdateWorkspaceDisplayName(workspace.id, newName);
36537
+ },
36538
+ placeholder: "Workspace name",
36539
+ className: "font-medium text-gray-900",
36540
+ inputClassName: "min-w-[120px]"
36541
+ }
36542
+ ) : /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-medium text-gray-900", children: formattedName }) }),
35617
36543
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "col-span-2", children: /* @__PURE__ */ jsxRuntime.jsxs(
35618
36544
  "select",
35619
36545
  {
@@ -36354,6 +37280,17 @@ var TargetsView = ({
36354
37280
  router.push("/");
36355
37281
  }
36356
37282
  };
37283
+ const handleUpdateWorkspaceDisplayName = React19.useCallback(async (workspaceId, displayName) => {
37284
+ try {
37285
+ await workspaceService.updateWorkspaceDisplayName(workspaceId, displayName);
37286
+ await forceRefreshWorkspaceDisplayNames();
37287
+ sonner.toast.success("Workspace name updated successfully");
37288
+ } catch (error) {
37289
+ console.error("Error updating workspace display name:", error);
37290
+ sonner.toast.error("Failed to update workspace name");
37291
+ throw error;
37292
+ }
37293
+ }, []);
36357
37294
  return /* @__PURE__ */ jsxRuntime.jsx(
36358
37295
  TargetsViewUI_default,
36359
37296
  {
@@ -36376,6 +37313,7 @@ var TargetsView = ({
36376
37313
  onSaveLine: handleSaveLine,
36377
37314
  onToggleBulkConfigure: handleToggleBulkConfigure,
36378
37315
  onBulkConfigure: handleBulkConfigure,
37316
+ onUpdateWorkspaceDisplayName: handleUpdateWorkspaceDisplayName,
36379
37317
  skuEnabled,
36380
37318
  skus,
36381
37319
  onUpdateSelectedSKU: updateSelectedSKU,
@@ -36474,6 +37412,14 @@ var WorkspaceDetailView = ({
36474
37412
  const [usingFallbackData, setUsingFallbackData] = React19.useState(false);
36475
37413
  const [showIdleTime, setShowIdleTime] = React19.useState(false);
36476
37414
  const dashboardConfig = useDashboardConfig();
37415
+ const {
37416
+ workspace: workspaceHealth,
37417
+ loading: healthLoading,
37418
+ error: healthError
37419
+ } = useWorkspaceHealthById(workspaceId, {
37420
+ enableRealtime: true,
37421
+ refreshInterval: 3e4
37422
+ });
36477
37423
  const {
36478
37424
  status: prefetchStatus,
36479
37425
  data: prefetchData,
@@ -36826,10 +37772,7 @@ var WorkspaceDetailView = ({
36826
37772
  "aria-label": "Navigate back to previous page"
36827
37773
  }
36828
37774
  ) }),
36829
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "absolute left-1/2 transform -translate-x-1/2 flex items-center gap-3", children: [
36830
- /* @__PURE__ */ jsxRuntime.jsx("h1", { className: "text-3xl font-semibold text-gray-900", children: formattedWorkspaceName }),
36831
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-2 w-2 rounded-full bg-green-500 animate-pulse ring-2 ring-green-500/30 ring-offset-1" })
36832
- ] }),
37775
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "absolute left-1/2 transform -translate-x-1/2", children: /* @__PURE__ */ jsxRuntime.jsx("h1", { className: "text-3xl font-semibold text-gray-900", children: formattedWorkspaceName }) }),
36833
37776
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full h-8" })
36834
37777
  ] }),
36835
37778
  activeTab !== "monthly_history" && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-3 bg-blue-50 px-3 py-2 rounded-lg", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-center gap-4", children: [
@@ -36857,6 +37800,19 @@ var WorkspaceDetailView = ({
36857
37800
  workspace.shift_type,
36858
37801
  " Shift"
36859
37802
  ] })
37803
+ ] }),
37804
+ workspaceHealth && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
37805
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-px h-4 bg-blue-300" }),
37806
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1.5", children: [
37807
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: clsx(
37808
+ "h-1.5 w-1.5 rounded-full",
37809
+ workspaceHealth.status === "healthy" ? "bg-green-600" : workspaceHealth.status === "unhealthy" ? "bg-red-600" : workspaceHealth.status === "warning" ? "bg-amber-600" : "bg-gray-500"
37810
+ ) }),
37811
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-xs text-blue-700", children: [
37812
+ "Last update: ",
37813
+ workspaceHealth.timeSinceLastUpdate
37814
+ ] })
37815
+ ] })
36860
37816
  ] })
36861
37817
  ] }) }),
36862
37818
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mt-1 sm:mt-1.5 lg:mt-2 flex items-center justify-between", children: [
@@ -37393,6 +38349,255 @@ var SKUManagementView = () => {
37393
38349
  )
37394
38350
  ] });
37395
38351
  };
38352
+ var WorkspaceHealthView = ({
38353
+ lineId,
38354
+ companyId,
38355
+ onNavigate,
38356
+ className = ""
38357
+ }) => {
38358
+ const router$1 = router.useRouter();
38359
+ const [viewMode, setViewMode] = React19.useState("grid");
38360
+ const [groupBy, setGroupBy] = React19.useState("line");
38361
+ const operationalDate = getOperationalDate();
38362
+ const currentHour = (/* @__PURE__ */ new Date()).getHours();
38363
+ const isNightShift = currentHour >= 18 || currentHour < 6;
38364
+ const shiftType = isNightShift ? "Night" : "Day";
38365
+ const formatDate = (date) => {
38366
+ const d = new Date(date);
38367
+ return d.toLocaleDateString("en-IN", {
38368
+ month: "long",
38369
+ day: "numeric",
38370
+ year: "numeric",
38371
+ timeZone: "Asia/Kolkata"
38372
+ });
38373
+ };
38374
+ const getShiftIcon = (shift) => {
38375
+ return shift === "Night" ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Moon, { className: "h-4 w-4" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Sun, { className: "h-4 w-4" });
38376
+ };
38377
+ const {
38378
+ workspaces,
38379
+ summary,
38380
+ loading,
38381
+ error,
38382
+ refetch
38383
+ } = useWorkspaceHealth({
38384
+ lineId,
38385
+ companyId,
38386
+ enableRealtime: true,
38387
+ refreshInterval: 1e4
38388
+ // Refresh every 10 seconds for more responsive updates
38389
+ });
38390
+ const handleWorkspaceClick = React19.useCallback(
38391
+ (workspace) => {
38392
+ const url = `/workspace/${workspace.workspace_id}`;
38393
+ if (onNavigate) {
38394
+ onNavigate(url);
38395
+ } else {
38396
+ router$1.push(url);
38397
+ }
38398
+ },
38399
+ [router$1, onNavigate]
38400
+ );
38401
+ const handleExport = React19.useCallback(() => {
38402
+ const csv = [
38403
+ ["Workspace", "Line", "Company", "Status", "Last Heartbeat", "Consecutive Misses"],
38404
+ ...workspaces.map((w) => [
38405
+ w.workspace_display_name || "",
38406
+ w.line_name || "",
38407
+ w.company_name || "",
38408
+ w.status,
38409
+ w.last_heartbeat,
38410
+ w.consecutive_misses?.toString() || "0"
38411
+ ])
38412
+ ].map((row) => row.join(",")).join("\n");
38413
+ const blob = new Blob([csv], { type: "text/csv" });
38414
+ const url = window.URL.createObjectURL(blob);
38415
+ const a = document.createElement("a");
38416
+ a.href = url;
38417
+ a.download = `workspace-health-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.csv`;
38418
+ document.body.appendChild(a);
38419
+ a.click();
38420
+ document.body.removeChild(a);
38421
+ window.URL.revokeObjectURL(url);
38422
+ }, [workspaces]);
38423
+ const getStatusIcon = (status) => {
38424
+ switch (status) {
38425
+ case "healthy":
38426
+ return /* @__PURE__ */ jsxRuntime.jsx(lucideReact.CheckCircle, { className: "h-5 w-5 text-green-500" });
38427
+ case "unhealthy":
38428
+ return /* @__PURE__ */ jsxRuntime.jsx(lucideReact.XCircle, { className: "h-5 w-5 text-red-500" });
38429
+ case "warning":
38430
+ return /* @__PURE__ */ jsxRuntime.jsx(lucideReact.AlertTriangle, { className: "h-5 w-5 text-yellow-500" });
38431
+ default:
38432
+ return /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Activity, { className: "h-5 w-5 text-gray-400" });
38433
+ }
38434
+ };
38435
+ const getUptimeColor = (percentage) => {
38436
+ if (percentage >= 99) return "text-green-600 dark:text-green-400";
38437
+ if (percentage >= 95) return "text-yellow-600 dark:text-yellow-400";
38438
+ return "text-red-600 dark:text-red-400";
38439
+ };
38440
+ if (loading && !summary) {
38441
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "min-h-screen bg-gray-50 dark:bg-gray-900 p-4", children: /* @__PURE__ */ jsxRuntime.jsx(LoadingState, {}) });
38442
+ }
38443
+ if (error) {
38444
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "min-h-screen bg-gray-50 dark:bg-gray-900 p-4", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "max-w-7xl mx-auto", children: /* @__PURE__ */ jsxRuntime.jsx(Card2, { className: "border-red-200 dark:border-red-800", children: /* @__PURE__ */ jsxRuntime.jsxs(CardContent2, { className: "p-8 text-center", children: [
38445
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.XCircle, { className: "h-12 w-12 text-red-500 mx-auto mb-4" }),
38446
+ /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "text-xl font-semibold text-gray-900 dark:text-gray-100 mb-2", children: "Error Loading Health Status" }),
38447
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-gray-600 dark:text-gray-400 mb-4", children: error.message || "Unable to load workspace health status" }),
38448
+ /* @__PURE__ */ jsxRuntime.jsx(
38449
+ "button",
38450
+ {
38451
+ onClick: () => refetch(),
38452
+ className: "px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",
38453
+ children: "Try Again"
38454
+ }
38455
+ )
38456
+ ] }) }) }) });
38457
+ }
38458
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: clsx("min-h-screen bg-slate-50", className), children: [
38459
+ /* @__PURE__ */ jsxRuntime.jsxs("header", { className: "sticky top-0 z-10 px-2 sm:px-2.5 lg:px-3 py-1.5 sm:py-2 lg:py-3 flex flex-col shadow-sm bg-white", children: [
38460
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative flex items-center", children: [
38461
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "absolute left-0 z-10", children: /* @__PURE__ */ jsxRuntime.jsx(
38462
+ BackButtonMinimal,
38463
+ {
38464
+ onClick: () => router$1.push("/"),
38465
+ text: "Back",
38466
+ size: "default",
38467
+ "aria-label": "Navigate back to dashboard"
38468
+ }
38469
+ ) }),
38470
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "absolute left-1/2 transform -translate-x-1/2", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3", children: [
38471
+ /* @__PURE__ */ jsxRuntime.jsx("h1", { className: "text-3xl font-semibold text-gray-900", children: "System Health" }),
38472
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative flex h-2.5 w-2.5", children: [
38473
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" }),
38474
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "relative inline-flex rounded-full h-2.5 w-2.5 bg-emerald-500" })
38475
+ ] })
38476
+ ] }) }),
38477
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "absolute right-0 flex gap-2", children: [
38478
+ /* @__PURE__ */ jsxRuntime.jsx(
38479
+ "button",
38480
+ {
38481
+ onClick: () => {
38482
+ refetch();
38483
+ },
38484
+ className: "p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors",
38485
+ "aria-label": "Refresh",
38486
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.RefreshCw, { className: "h-5 w-5" })
38487
+ }
38488
+ ),
38489
+ /* @__PURE__ */ jsxRuntime.jsx(
38490
+ "button",
38491
+ {
38492
+ onClick: handleExport,
38493
+ className: "p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors",
38494
+ "aria-label": "Export CSV",
38495
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Download, { className: "h-5 w-5" })
38496
+ }
38497
+ )
38498
+ ] }),
38499
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full h-8" })
38500
+ ] }),
38501
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-3 bg-blue-50 px-3 py-2 rounded-lg", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-center gap-4", children: [
38502
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "text-lg font-medium text-blue-600", children: /* @__PURE__ */ jsxRuntime.jsx(LiveTimer, {}) }),
38503
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-px h-4 bg-blue-300" }),
38504
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-base font-medium text-blue-600", children: formatDate(operationalDate) }),
38505
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-px h-4 bg-blue-300" }),
38506
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
38507
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "text-blue-600", children: getShiftIcon(shiftType) }),
38508
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-base font-medium text-blue-600", children: [
38509
+ shiftType,
38510
+ " Shift"
38511
+ ] })
38512
+ ] })
38513
+ ] }) })
38514
+ ] }),
38515
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "max-w-7xl mx-auto p-4 space-y-6", children: [
38516
+ summary && /* @__PURE__ */ jsxRuntime.jsxs(
38517
+ motion.div,
38518
+ {
38519
+ initial: { opacity: 0, y: 20 },
38520
+ animate: { opacity: 1, y: 0 },
38521
+ transition: { duration: 0.3, delay: 0.1 },
38522
+ className: "grid grid-cols-2 sm:grid-cols-2 md:grid-cols-5 gap-2 sm:gap-3 lg:gap-4",
38523
+ children: [
38524
+ /* @__PURE__ */ jsxRuntime.jsxs(Card2, { className: "col-span-2 sm:col-span-2 md:col-span-2", children: [
38525
+ /* @__PURE__ */ jsxRuntime.jsx(CardHeader2, { className: "pb-3", children: /* @__PURE__ */ jsxRuntime.jsx(CardTitle2, { className: "text-sm font-medium text-gray-500 dark:text-gray-400", children: "Overall System Status" }) }),
38526
+ /* @__PURE__ */ jsxRuntime.jsxs(CardContent2, { children: [
38527
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-baseline gap-2", children: [
38528
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: clsx("text-3xl font-bold", getUptimeColor(summary.uptimePercentage)), children: [
38529
+ summary.uptimePercentage.toFixed(1),
38530
+ "%"
38531
+ ] }),
38532
+ summary.uptimePercentage >= 99 ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.TrendingUp, { className: "h-5 w-5 text-green-500" }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.TrendingDown, { className: "h-5 w-5 text-red-500" })
38533
+ ] }),
38534
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: [
38535
+ summary.healthyWorkspaces,
38536
+ " of ",
38537
+ summary.totalWorkspaces,
38538
+ " workspaces healthy"
38539
+ ] })
38540
+ ] })
38541
+ ] }),
38542
+ /* @__PURE__ */ jsxRuntime.jsxs(Card2, { children: [
38543
+ /* @__PURE__ */ jsxRuntime.jsx(CardHeader2, { className: "pb-3", children: /* @__PURE__ */ jsxRuntime.jsxs(CardTitle2, { className: "text-sm font-medium text-gray-500 dark:text-gray-400 flex items-center gap-2", children: [
38544
+ getStatusIcon("healthy"),
38545
+ "Healthy"
38546
+ ] }) }),
38547
+ /* @__PURE__ */ jsxRuntime.jsxs(CardContent2, { children: [
38548
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-2xl font-bold text-green-600 dark:text-green-400", children: summary.healthyWorkspaces }),
38549
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: "Operating normally" })
38550
+ ] })
38551
+ ] }),
38552
+ /* @__PURE__ */ jsxRuntime.jsxs(Card2, { children: [
38553
+ /* @__PURE__ */ jsxRuntime.jsx(CardHeader2, { className: "pb-3", children: /* @__PURE__ */ jsxRuntime.jsxs(CardTitle2, { className: "text-sm font-medium text-gray-500 dark:text-gray-400 flex items-center gap-2", children: [
38554
+ getStatusIcon("warning"),
38555
+ "Warning"
38556
+ ] }) }),
38557
+ /* @__PURE__ */ jsxRuntime.jsxs(CardContent2, { children: [
38558
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-2xl font-bold text-yellow-600 dark:text-yellow-400", children: summary.warningWorkspaces }),
38559
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: "Delayed updates" })
38560
+ ] })
38561
+ ] }),
38562
+ /* @__PURE__ */ jsxRuntime.jsxs(Card2, { children: [
38563
+ /* @__PURE__ */ jsxRuntime.jsx(CardHeader2, { className: "pb-3", children: /* @__PURE__ */ jsxRuntime.jsxs(CardTitle2, { className: "text-sm font-medium text-gray-500 dark:text-gray-400 flex items-center gap-2", children: [
38564
+ getStatusIcon("unhealthy"),
38565
+ "Unhealthy"
38566
+ ] }) }),
38567
+ /* @__PURE__ */ jsxRuntime.jsxs(CardContent2, { children: [
38568
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-2xl font-bold text-red-600 dark:text-red-400", children: summary.unhealthyWorkspaces }),
38569
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-gray-500 dark:text-gray-400 mt-1", children: "Requires attention" })
38570
+ ] })
38571
+ ] })
38572
+ ]
38573
+ }
38574
+ ),
38575
+ /* @__PURE__ */ jsxRuntime.jsx(
38576
+ motion.div,
38577
+ {
38578
+ initial: { opacity: 0, y: 20 },
38579
+ animate: { opacity: 1, y: 0 },
38580
+ transition: { duration: 0.3, delay: 0.2 },
38581
+ children: /* @__PURE__ */ jsxRuntime.jsx(
38582
+ HealthStatusGrid,
38583
+ {
38584
+ workspaces,
38585
+ onWorkspaceClick: handleWorkspaceClick,
38586
+ viewMode,
38587
+ showFilters: true,
38588
+ groupBy
38589
+ }
38590
+ )
38591
+ }
38592
+ )
38593
+ ] })
38594
+ ] });
38595
+ };
38596
+ var WorkspaceHealthView_default = withAuth(WorkspaceHealthView, {
38597
+ redirectTo: "/login",
38598
+ requireAuth: true
38599
+ });
38600
+ var AuthenticatedWorkspaceHealthView = WorkspaceHealthView;
37396
38601
  var S3Service = class {
37397
38602
  constructor(config) {
37398
38603
  this.s3Client = null;
@@ -37859,6 +39064,7 @@ exports.AuthenticatedHelpView = AuthenticatedHelpView;
37859
39064
  exports.AuthenticatedHomeView = AuthenticatedHomeView;
37860
39065
  exports.AuthenticatedShiftsView = AuthenticatedShiftsView;
37861
39066
  exports.AuthenticatedTargetsView = AuthenticatedTargetsView;
39067
+ exports.AuthenticatedWorkspaceHealthView = AuthenticatedWorkspaceHealthView;
37862
39068
  exports.BackButton = BackButton;
37863
39069
  exports.BackButtonMinimal = BackButtonMinimal;
37864
39070
  exports.BarChart = BarChart;
@@ -37872,6 +39078,7 @@ exports.CardDescription = CardDescription2;
37872
39078
  exports.CardFooter = CardFooter2;
37873
39079
  exports.CardHeader = CardHeader2;
37874
39080
  exports.CardTitle = CardTitle2;
39081
+ exports.CompactWorkspaceHealthCard = CompactWorkspaceHealthCard;
37875
39082
  exports.CongratulationsOverlay = CongratulationsOverlay;
37876
39083
  exports.CycleTimeChart = CycleTimeChart;
37877
39084
  exports.CycleTimeOverTimeChart = CycleTimeOverTimeChart;
@@ -37895,6 +39102,7 @@ exports.DateDisplay = DateDisplay_default;
37895
39102
  exports.DateTimeDisplay = DateTimeDisplay;
37896
39103
  exports.DebugAuth = DebugAuth;
37897
39104
  exports.DebugAuthView = DebugAuthView_default;
39105
+ exports.DetailedHealthStatus = DetailedHealthStatus;
37898
39106
  exports.EmptyStateMessage = EmptyStateMessage;
37899
39107
  exports.EncouragementOverlay = EncouragementOverlay;
37900
39108
  exports.FactoryView = FactoryView_default;
@@ -37902,10 +39110,13 @@ exports.GaugeChart = GaugeChart;
37902
39110
  exports.GridComponentsPlaceholder = GridComponentsPlaceholder;
37903
39111
  exports.HamburgerButton = HamburgerButton;
37904
39112
  exports.Header = Header;
39113
+ exports.HealthStatusGrid = HealthStatusGrid;
39114
+ exports.HealthStatusIndicator = HealthStatusIndicator;
37905
39115
  exports.HelpView = HelpView_default;
37906
39116
  exports.HomeView = HomeView_default;
37907
39117
  exports.HourlyOutputChart = HourlyOutputChart2;
37908
39118
  exports.ISTTimer = ISTTimer_default;
39119
+ exports.InlineEditableText = InlineEditableText;
37909
39120
  exports.KPICard = KPICard;
37910
39121
  exports.KPIDetailView = KPIDetailView_default;
37911
39122
  exports.KPIGrid = KPIGrid;
@@ -37947,6 +39158,7 @@ exports.PrefetchStatus = PrefetchStatus;
37947
39158
  exports.PrefetchTimeoutError = PrefetchTimeoutError;
37948
39159
  exports.ProfileView = ProfileView_default;
37949
39160
  exports.RegistryProvider = RegistryProvider;
39161
+ exports.S3ClipsService = S3ClipsService;
37950
39162
  exports.S3Service = S3Service;
37951
39163
  exports.SKUManagementView = SKUManagementView;
37952
39164
  exports.SOPComplianceChart = SOPComplianceChart;
@@ -37987,6 +39199,8 @@ exports.WorkspaceDetailView = WorkspaceDetailView_default;
37987
39199
  exports.WorkspaceDisplayNameExample = WorkspaceDisplayNameExample;
37988
39200
  exports.WorkspaceGrid = WorkspaceGrid;
37989
39201
  exports.WorkspaceGridItem = WorkspaceGridItem;
39202
+ exports.WorkspaceHealthCard = WorkspaceHealthCard;
39203
+ exports.WorkspaceHealthView = WorkspaceHealthView_default;
37990
39204
  exports.WorkspaceHistoryCalendar = WorkspaceHistoryCalendar;
37991
39205
  exports.WorkspaceMetricCards = WorkspaceMetricCards;
37992
39206
  exports.WorkspaceMonthlyDataFetcher = WorkspaceMonthlyDataFetcher;
@@ -38071,6 +39285,7 @@ exports.isWorkspaceDisplayNamesLoading = isWorkspaceDisplayNamesLoading;
38071
39285
  exports.mergeWithDefaultConfig = mergeWithDefaultConfig;
38072
39286
  exports.migrateLegacyConfiguration = migrateLegacyConfiguration;
38073
39287
  exports.optifyeAgentClient = optifyeAgentClient;
39288
+ exports.parseS3Uri = parseS3Uri;
38074
39289
  exports.preInitializeWorkspaceDisplayNames = preInitializeWorkspaceDisplayNames;
38075
39290
  exports.preloadS3Video = preloadS3Video;
38076
39291
  exports.preloadS3VideoUrl = preloadS3VideoUrl;
@@ -38084,6 +39299,7 @@ exports.resetCoreMixpanel = resetCoreMixpanel;
38084
39299
  exports.resetFailedUrl = resetFailedUrl;
38085
39300
  exports.resetSubscriptionManager = resetSubscriptionManager;
38086
39301
  exports.s3VideoPreloader = s3VideoPreloader;
39302
+ exports.shuffleArray = shuffleArray;
38087
39303
  exports.skuService = skuService;
38088
39304
  exports.startCoreSessionRecording = startCoreSessionRecording;
38089
39305
  exports.stopCoreSessionRecording = stopCoreSessionRecording;
@@ -38150,6 +39366,8 @@ exports.useWorkspaceDetailedMetrics = useWorkspaceDetailedMetrics;
38150
39366
  exports.useWorkspaceDisplayName = useWorkspaceDisplayName;
38151
39367
  exports.useWorkspaceDisplayNames = useWorkspaceDisplayNames;
38152
39368
  exports.useWorkspaceDisplayNamesMap = useWorkspaceDisplayNamesMap;
39369
+ exports.useWorkspaceHealth = useWorkspaceHealth;
39370
+ exports.useWorkspaceHealthById = useWorkspaceHealthById;
38153
39371
  exports.useWorkspaceMetrics = useWorkspaceMetrics;
38154
39372
  exports.useWorkspaceNavigation = useWorkspaceNavigation;
38155
39373
  exports.useWorkspaceOperators = useWorkspaceOperators;
@@ -38158,4 +39376,5 @@ exports.videoPreloader = videoPreloader;
38158
39376
  exports.whatsappService = whatsappService;
38159
39377
  exports.withAuth = withAuth;
38160
39378
  exports.withRegistry = withRegistry;
39379
+ exports.workspaceHealthService = workspaceHealthService;
38161
39380
  exports.workspaceService = workspaceService;