@@ -288,10 +288,77 @@ public function scopeFilter($query, $filterStr)
288288 /**
289289 * Return the label to be used in grafana reports
290290 *
291- * @return string
291+ * @return string
292292 */
293293 public function getPrometheusMetricLabel (): string
294294 {
295295 return 'screen. ' . $ this ->id ;
296296 }
297+
298+ public static function getScreenByKey (string $ key ) : ?self
299+ {
300+ $ screen = self ::firstWhere ('key ' , $ key );
301+ if (!$ screen ) {
302+ $ screen = self ::createScreenByKey ($ key );
303+ }
304+
305+ return $ screen ;
306+ }
307+
308+ private static function createScreenByKey (string $ key , bool $ isSystem = true , string $ path = null ): self
309+ {
310+ // If no path is provided, use the default path
311+ if (!$ path ) {
312+ $ path = database_path ('processes/screens/ ' . "{$ key }.json " );
313+ }
314+
315+ // Check if file exists
316+ if (!file_exists ($ path )) {
317+ throw new \RuntimeException ("Screen configuration file not found: {$ path }" );
318+ }
319+
320+ // Read and decode JSON with validation
321+ $ jsonContent = file_get_contents ($ path );
322+ $ json = json_decode ($ jsonContent , true );
323+
324+ if (json_last_error () !== JSON_ERROR_NONE ) {
325+ throw new \RuntimeException ('Invalid JSON in screen configuration: ' . json_last_error_msg ());
326+ }
327+
328+ if (!isset ($ json ['screens ' ]) || !is_array ($ json ['screens ' ])) {
329+ throw new \RuntimeException ("Invalid screen configuration format: 'screens' array is required " );
330+ }
331+
332+ $ screen = collect ($ json ['screens ' ])->first ();
333+ if (!$ screen ) {
334+ throw new \RuntimeException ('No screen configuration found in JSON ' );
335+ }
336+
337+ // Look for existing screen by title
338+ $ newScreen = self ::firstWhere ('title ' , $ screen ['title ' ]);
339+ // Create new screen
340+ unset($ screen ['categories ' ]);
341+ $ screen ['screen_category_id ' ] = null ;
342+
343+ if ($ newScreen ) {
344+ $ newScreen ->fill ($ screen );
345+ $ newScreen ->save ();
346+ } else {
347+ $ newScreen = self ::updateOrCreate (
348+ ['key ' => $ screen ['key ' ]],
349+ $ screen
350+ );
351+ }
352+
353+ // Assign system category if needed
354+ if ($ isSystem && $ newScreen ) {
355+ $ screenCategory = ScreenCategory::firstOrCreate ([
356+ 'name ' => 'System ' ,
357+ 'is_system ' => 1 ,
358+ ]);
359+ $ newScreen ->categories ()->attach ([$ screenCategory ->id ]);
360+ }
361+
362+ return $ newScreen ;
363+ }
297364}
0 commit comments