Repository navigation
Expand file tree
/
Copy pathapp.R
More file actions
2686 lines (2435 loc) · 90.9 KB
/
Copy pathapp.R
File metadata and controls
2686 lines (2435 loc) · 90.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
library(shiny)
library(shinyjs)
library(DT)
library(DBI)
library(RSQLite)
library(reticulate)
library(bslib)
library(dplyr)
library(plotly)
# Configure Python environment (use project venv)
use_virtualenv(file.path(getwd(), "venv_311"), required = TRUE)
# Source all R scripts
source("R/config.R")
source("R/db_setup.R")
source("R/seed_db.R")
# Initialize DB and Seed
if (!is_db_initialized()) {
init_database()
}
seed_database()
# Theme
theme <- bs_theme(
version = 5,
preset = "darkly",
bg = "#1a1a2e",
fg = "#eaeaea",
primary = "#6366f1",
secondary = "#8b5cf6",
success = "#10b981",
info = "#3b82f6",
warning = "#f59e0b",
danger = "#ef4444",
base_font = font_google("Inter"),
heading_font = font_google("Poppins"),
font_scale = 0.95
)
ui <- tagList(
useShinyjs(),
div(
id = "main_view",
page_navbar(
title = span(icon("graduation-cap"), "Attendance System"),
id = "navbar",
theme = theme,
fillable = FALSE,
header = tags$head(
tags$meta(name = "viewport", content = "width=device-width, initial-scale=1, maximum-scale=1"),
tags$link(rel = "stylesheet", type = "text/css", href = "www/custom.css")
),
# Login Panel
nav_panel(
title = span(icon("sign-in-alt"), "Login"),
value = "login",
div(
style = "max-width: 500px; margin: 0 auto;",
card(
class = "login-card",
max_height = "500px",
card_header(
class = "text-center",
h2(icon("user-md"), "Doctor Login", style = "margin: 0;")
),
card_body(
textInput("email",
label = tags$span(icon("envelope"), "Email"),
placeholder = "doctor@test.com",
width = "100%"
),
passwordInput("password",
label = tags$span(icon("lock"), "Password"),
placeholder = "Enter password",
width = "100%"
),
actionButton("login_btn",
span(icon("sign-in-alt"), "Sign In"),
class = "btn-primary w-100 mt-3",
style = "height: 45px; font-size: 16px;"
),
br(),
uiOutput("login_msg_ui")
)
)
)
),
# Dashboard Panel
nav_panel(
title = span(icon("tachometer-alt"), "Dashboard"),
value = "dashboard",
fluidRow(
column(4, value_box(
title = "Total Courses",
value = textOutput("total_courses_text"),
showcase = icon("book"),
theme = "primary",
showcase_layout = "left center"
)),
column(4, value_box(
title = "Total Sessions",
value = textOutput("total_sessions_text"),
showcase = icon("calendar-check"),
theme = "success",
showcase_layout = "left center"
)),
column(4, value_box(
title = "Total Students",
value = textOutput("total_students_text"),
showcase = icon("users"),
theme = "info",
showcase_layout = "left center"
))
),
br(),
card(
card_header("Quick Actions"),
card_body(
fluidRow(
column(4, actionButton("quick_start_session",
span(icon("play-circle"), "Start Session"),
class = "btn-success w-100",
style = "height: 50px;"
)),
column(4, actionButton("quick_view_courses",
span(icon("book-open"), "My Courses"),
class = "btn-primary w-100",
style = "height: 50px;"
)),
column(4, actionButton("quick_view_reports",
span(icon("chart-bar"), "Reports"),
class = "btn-info w-100",
style = "height: 50px;"
))
)
)
)
),
# Courses Panel
nav_panel(
title = span(icon("book"), "Courses"),
value = "courses",
card(
full_screen = TRUE,
card_header(
class = "d-flex justify-content-between align-items-center",
h4(icon("book"), "My Courses", style = "margin: 0;"),
actionButton("refresh_courses", icon("sync"), class = "btn-sm btn-outline-primary")
),
card_body(
DTOutput("courses_table")
)
)
),
# Sessions Panel
nav_panel(
title = span(icon("calendar-check"), "Sessions"),
value = "sessions",
div(
style = "max-width: 1200px; margin: 0 auto; padding: 20px;",
uiOutput("start_session_container"),
uiOutput("active_session_container")
)
),
# Statistics & Analytics Panel
nav_panel(
title = span(icon("chart-line"), "Statistics & Analytics"),
value = "statistics",
div(
style = "padding: 20px;",
# Course Selection View (shown when no course selected)
uiOutput("course_selection_ui"),
# Statistics View (shown when course selected)
uiOutput("statistics_content_ui")
)
),
# Sidebar with user info and logout
nav_spacer(),
nav_item(uiOutput("user_info_ui")),
nav_item(uiOutput("logout_btn_ui"))
)
),
div(
div(
id = "student_list_view", style = "display: none; padding: 20px; background: #f8f9fa; min-height: 100vh;",
div(
class = "d-flex justify-content-between align-items-center mb-4",
actionButton("back_to_session_btn", span(icon("arrow-left"), "Back to Session"), class = "btn-secondary"),
h2("Mark Attendance", style = "margin:0; color: #333;")
),
# Search Bar
div(
class = "row justify-content-center mb-4",
div(
class = "col-md-6",
textInput("student_search_input", label = NULL, placeholder = "Search by name or ID...", width = "100%")
)
),
# Grid of Toggle Buttons
uiOutput("student_grid_ui")
)
)
)
# ==============================================================================
# SERVER
# ==============================================================================
server <- function(input, output, session) {
# Reactive values to store user state
user_state <- reactiveValues(
logged_in = FALSE,
doctor_id = NULL,
doctor_name = NULL,
active_session = NULL,
current_notes = "",
session_start_time = NULL, # Track start time for auto-end
manual_attendance = list(), # Store manually marked students: list(student_id = TRUE/FALSE)
student_exits = list(), # Track exit times for alerts: list(student_id = timestamp)
detection_log = list() # Track recent detection events for log view
)
# Track last attendance marking time per student (for cooldown)
last_attendance_time <- reactiveVal(list())
# Track first detection time per student
first_detection_time <- reactiveVal(list())
# Current detection info
current_detection <- reactiveVal(NULL)
# Camera recognizer
camera_recognizer <- reactiveVal(NULL)
# Persistent login using DB app_session table
try(
{
persisted_id <- get_persistent_login()
if (!is.null(persisted_id) && nzchar(persisted_id)) {
conn <- get_db_connection()
d <- dbGetQuery(conn, "SELECT * FROM Doctor WHERE doctor_id = ?", params = list(persisted_id))
dbDisconnect(conn)
if (nrow(d) > 0) {
user_state$logged_in <- TRUE
user_state$doctor_id <- d$doctor_id[1]
user_state$doctor_name <- d$name[1]
# Resume any pending session for this doctor
conn2 <- get_db_connection()
active_sess <- dbGetQuery(conn2,
"SELECT * FROM sessions WHERE started_by = ? AND session_status = 'pending'",
params = list(user_state$doctor_id)
)
dbDisconnect(conn2)
if (nrow(active_sess) > 0) {
user_state$active_session <- active_sess$session_id[1]
user_state$current_notes <- if (!is.na(active_sess$notes[1])) active_sess$notes[1] else ""
user_state$session_start_time <- as.POSIXct(active_sess$started_at[1])
# Reset manual attendance when resuming a session to avoid stale toggles
user_state$manual_attendance <- list()
try(
{
session$sendCustomMessage("updateAttendanceState", user_state$manual_attendance)
},
silent = TRUE
)
}
} else {
# stale persisted id, clear
try(clear_persistent_login(), silent = TRUE)
}
}
},
silent = TRUE
)
# Auto-end session timer (100 minutes)
observe({
invalidateLater(60000) # Check every minute
if (!is.null(user_state$active_session) && !is.null(user_state$session_start_time)) {
elapsed_mins <- as.numeric(difftime(Sys.time(), user_state$session_start_time, units = "mins"))
if (elapsed_mins >= 100) {
# Auto-save notes first
if (nchar(trimws(user_state$current_notes)) > 0) {
update_session_notes(user_state$active_session, user_state$current_notes)
}
# End session
success <- end_session(user_state$active_session)
if (success) {
user_state$active_session <- NULL
user_state$current_notes <- ""
user_state$session_start_time <- NULL
showNotification("⏰ Session auto-ended (100 min limit reached)", type = "warning", duration = 10)
}
}
}
})
# Logout Button UI - Only show when logged in
output$logout_btn_ui <- renderUI({
if (user_state$logged_in) {
actionButton("logout_btn",
span(icon("sign-out-alt"), "Logout"),
class = "btn-danger btn-sm"
)
} else {
NULL
}
})
# User info display
output$user_info_ui <- renderUI({
if (user_state$logged_in) {
span(
icon("user-md"),
user_state$doctor_name,
style = "margin-right: 10px; color: #6366f1;"
)
} else {
NULL
}
})
# Login message output
output$login_msg_ui <- renderUI({
if (!is.null(input$login_btn) && input$login_btn > 0) {
if (!user_state$logged_in) {
div(
class = "alert alert-danger mt-3",
icon("exclamation-circle"),
"Invalid email or password"
)
}
}
})
# Initial state: Manage nav panel visibility
observe({
if (!user_state$logged_in) {
# Navigate to login and hide other panels
nav_select("navbar", "login")
shinyjs::hide(selector = "a[data-value='dashboard']")
shinyjs::hide(selector = "a[data-value='courses']")
shinyjs::hide(selector = "a[data-value='sessions']")
} else {
# Show all panels and navigate to dashboard
shinyjs::show(selector = "a[data-value='dashboard']")
shinyjs::show(selector = "a[data-value='courses']")
shinyjs::show(selector = "a[data-value='sessions']")
nav_select("navbar", "dashboard")
shinyjs::hide(selector = "a[data-value='login']")
}
})
# Login Logic
observeEvent(input$login_btn, {
req(input$email, input$password)
conn <- get_db_connection()
res <- dbGetQuery(conn, "SELECT * FROM Doctor WHERE email = ? AND password_hash = ?",
params = list(input$email, input$password)
)
dbDisconnect(conn)
if (nrow(res) > 0) {
user_state$logged_in <- TRUE
user_state$doctor_id <- res$doctor_id[1]
user_state$doctor_name <- res$name[1]
output$login_msg <- renderText("")
# Persist this login so the app auto-logins next run
try(
{
set_persistent_login(user_state$doctor_id)
},
silent = TRUE
)
# Check for any existing active session for this doctor
conn <- get_db_connection()
active_sess <- dbGetQuery(conn,
"SELECT * FROM sessions WHERE started_by = ? AND session_status = 'pending'",
params = list(user_state$doctor_id)
)
dbDisconnect(conn)
if (nrow(active_sess) > 0) {
user_state$active_session <- active_sess$session_id[1]
user_state$current_notes <- if (!is.na(active_sess$notes[1])) active_sess$notes[1] else ""
# Populate the textarea without re-rendering the UI component
updateTextAreaInput(session, "active_session_notes", value = user_state$current_notes)
user_state$session_start_time <- as.POSIXct(active_sess$started_at[1])
showNotification("🔄 Resumed active session", type = "message")
}
# Load data for this doctor
# load_doctor_data() -- Replaced by individual observers
}
})
# Logout Logic
observeEvent(input$logout_btn, {
user_state$logged_in <- FALSE
user_state$doctor_id <- NULL
user_state$doctor_name <- NULL
user_state$active_session <- NULL
user_state$current_notes <- ""
updateTextAreaInput(session, "active_session_notes", value = "")
user_state$session_start_time <- NULL
updateTextInput(session, "email", value = "")
updateTextInput(session, "password", value = "")
# Clear persisted login
try(
{
clear_persistent_login()
},
silent = TRUE
)
showNotification("✅ Logged out successfully", type = "message")
})
# Render Courses Table
observe({
if (user_state$logged_in && !is.null(user_state$doctor_id)) {
courses <- get_courses_by_doctor(user_state$doctor_id)
output$courses_table <- renderDT({
datatable(courses[, c("course_id", "course_name", "semester", "credits")],
options = list(dom = "t")
)
})
} else {
output$courses_table <- renderDT(NULL)
}
})
# Render Dashboard Stats (bslib value_box format)
output$total_courses_text <- renderText({
if (user_state$logged_in && !is.null(user_state$doctor_id)) {
courses <- get_courses_by_doctor(user_state$doctor_id)
as.character(nrow(courses))
} else {
"0"
}
})
output$total_sessions_text <- renderText({
if (user_state$logged_in && !is.null(user_state$doctor_id)) {
conn <- get_db_connection()
sessions <- dbGetQuery(conn,
"SELECT COUNT(*) as cnt FROM sessions WHERE started_by = ?",
params = list(user_state$doctor_id)
)
dbDisconnect(conn)
as.character(sessions$cnt[1])
} else {
"0"
}
})
output$total_students_text <- renderText({
if (user_state$logged_in) {
conn <- get_db_connection()
students <- dbGetQuery(conn, "SELECT COUNT(*) as cnt FROM students")
dbDisconnect(conn)
as.character(students$cnt[1])
} else {
"0"
}
})
# Quick action buttons
observeEvent(input$quick_start_session, {
nav_select("navbar", "sessions")
})
observeEvent(input$quick_view_courses, {
nav_select("navbar", "courses")
})
observeEvent(input$quick_view_reports, {
nav_select("navbar", "statistics")
})
# Refresh courses button
observeEvent(input$refresh_courses, {
showNotification("🔄 Refreshing courses...", type = "message", duration = 2)
})
# --------------------------------------------------------------------------
# UI RENDERERS for Sessions Tab
# --------------------------------------------------------------------------
# 1. Start Session Container
output$start_session_container <- renderUI({
if (user_state$logged_in && is.null(user_state$active_session)) {
# Fetch courses directly here to ensure dropdown is populated immediately
course_choices <- NULL
if (!is.null(user_state$doctor_id)) {
courses <- get_courses_by_doctor(user_state$doctor_id)
if (nrow(courses) > 0) {
course_choices <- setNames(courses$course_id, courses$course_name)
}
}
card(
card_header(
class = "d-flex justify-content-between align-items-center",
h4(icon("play-circle"), "Start New Session", style = "margin: 0;")
),
card_body(
selectInput("course_select",
label = span(icon("book"), "Select Course"),
choices = course_choices,
width = "100%"
),
fluidRow(
column(
6,
selectInput("building_select",
label = span(icon("building"), "Building"),
choices = c("CS", "B"),
width = "100%"
)
),
column(
6,
selectInput("room_select",
label = span(icon("door-open"), "Room Number"),
choices = c(
"101", "102", "103", "104", "105", "106", "107", "108",
"201", "202", "203", "204", "205", "206", "207", "208",
"301", "302", "303", "304", "305", "306", "307", "308",
"401", "402", "403", "404", "405", "406", "407", "408"
),
width = "100%"
)
)
),
actionButton("start_session_btn",
span(icon("rocket"), "Start Session Now"),
class = "btn-success w-100",
style = "height: 50px; font-size: 18px;"
)
)
)
} else {
NULL # Hide if not logged in or session active
}
})
# 2. Active Session Container
output$active_session_container <- renderUI({
# Only re-render when active_session state changes
if (user_state$logged_in && !is.null(user_state$active_session)) {
# Get session info
session_info <- get_session(user_state$active_session)
course_name <- "Unknown Course"
if (nrow(session_info) > 0) {
conn <- get_db_connection()
course <- dbGetQuery(conn, "SELECT course_name FROM courses WHERE course_id = ?",
params = list(session_info$course_id)
)
dbDisconnect(conn)
if (nrow(course) > 0) course_name <- course$course_name
}
main_card <- card(
card_header(
class = "d-flex justify-content-between align-items-center",
h4(icon("check-circle"), "Active Session: ", course_name, style = "margin: 0;"),
# Session Timer Display in Header
span(icon("clock"), strong("Duration: "), span(id = "session_timer_display", "00:00:00"), style = "font-size: 1.2rem; color: #10b981;")
),
card_body(
fluidRow(
# LEFT COLUMN (Width 4): Info, Timer, Notes
column(
4,
div(
class = "d-grid gap-3",
# Session Info Card
card(
card_header(h5(icon("info-circle"), "Session Details", style = "margin:0;")),
card_body(
div(strong("Session ID:"), br(), span(user_state$active_session, style = "color: #6366f1; word-break: break-all;")),
hr(),
div(strong("Location:"), br(), span(if (nrow(session_info) > 0) session_info$location else "N/A")),
hr(),
div(strong("Started At:"), br(), span(if (nrow(session_info) > 0) format(as.POSIXct(session_info$started_at), "%I:%M %p") else "N/A")),
hr(),
div(strong("Current Time:"), br(), textOutput("current_time_display", inline = TRUE))
)
),
# Notes Card
card(
card_header(h5(icon("sticky-note"), "Notes", style = "margin: 0;")),
card_body(
textAreaInput(
"active_session_notes",
label = NULL, value = NULL,
placeholder = "Type notes here...", rows = 10, width = "100%", resize = "vertical"
)
)
)
)
),
# RIGHT COLUMN (Width 8): Camera, Manual Attendance, Buttons
column(
8,
div(
class = "d-grid gap-3",
# Camera Section
card(
card_header(
div(
class = "d-flex justify-content-between",
h5(icon("camera"), "Attendance Camera", style = "margin:0;"),
uiOutput("camera_controls_ui", inline = TRUE)
)
),
card_body(
padding = 0,
uiOutput("camera_preview_ui")
)
),
# Current Detection Status (shows name, ID, entry time, cooldown)
uiOutput("current_detection_ui"),
# Detection Log and Absence Warnings
uiOutput("detection_log_ui"),
# Action Buttons
fluidRow(
column(
6,
actionButton("open_student_search", span(icon("search"), "Attendance List"),
class = "btn-primary w-100"
)
),
column(
6,
actionButton("end_session_btn", span(icon("stop-circle"), "End Session"), class = "btn-danger w-100")
)
)
)
)
)
)
)
# Return both card and script
elapsed_ms <- 0
if (nrow(session_info) > 0) {
# Calculate elapsed time in seconds on server
# SQLite stores CURRENT_TIMESTAMP in UTC. R reads as char.
# We must parse it as UTC, then compare to Sys.time() (which is Local but aware)
start_time_utc <- as.POSIXct(session_info$started_at, tz = "UTC")
current_time_utc <- as.POSIXct(Sys.time(), tz = "UTC") # Convert local to UTC for clean diff
# Or simply use difftime, R handles TZ conversion if attributes are set
# But Sys.time() might not match DB server time if different machines,
# assume same machine.
elapsed_sec <- as.numeric(difftime(Sys.time(), start_time_utc, units = "secs"))
elapsed_ms <- elapsed_sec * 1000
}
tagList(
main_card,
tags$script(HTML(sprintf("
var elapsed = %f;
var startTime = new Date().getTime() - elapsed;
var timerInterval = setInterval(function() {
var now = new Date().getTime();
var distance = now - startTime;
if (distance < 0) distance = 0;
var hours = Math.floor((distance %% (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance %% (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance %% (1000 * 60)) / 1000);
var el = document.getElementById('session_timer_display');
if (el) {
el.innerHTML =
(hours < 10 ? '0' + hours : hours) + ':' +
(minutes < 10 ? '0' + minutes : minutes) + ':' +
(seconds < 10 ? '0' + seconds : seconds);
}
}, 1000);
Shiny.addCustomMessageHandler('updateAttendanceState', function(states) {
// Reset all toggles to false first
document.querySelectorAll('input[type=\"checkbox\"][id^=\"chk_\"]').forEach(function(toggle) {
toggle.checked = false;
});
// Reset all labels to Absent
document.querySelectorAll('[id^=\"lbl_\"]').forEach(function(lbl) {
lbl.innerHTML = '<span style=\"color:#9ca3af\">Absent</span>';
});
for (var sid in states) {
var is_present = states[sid];
// Update legacy checkbox/label elements if present
var chk = document.getElementById('chk_' + sid);
if (chk) { chk.checked = is_present; }
var lbl = document.getElementById('lbl_' + sid);
if (lbl) {
lbl.innerHTML = is_present ? '<span style=\"color:#10b981\">Present</span>' : '<span style=\"color:#9ca3af\">Absent</span>';
}
// Update toggle switch
var toggle = document.getElementById('toggle_' + sid);
if (toggle) { toggle.checked = is_present; }
// Also update actionButton used by manual attendance UI (mark_student_<id>)
var btn = document.getElementById('mark_student_' + sid);
if (btn) {
// normalize classes
var cls = btn.className || '';
if (is_present) {
cls = cls.replace('btn-outline-secondary', 'btn-success');
} else {
cls = cls.replace('btn-success', 'btn-outline-secondary');
}
btn.className = cls;
// update inner icon (uses FontAwesome classes)
try {
var text = btn.textContent || '';
text = text.replace(/^[\\u2713\\u25CB\\s]+/, '').trim();
if (is_present) {
btn.innerHTML = '<span class=\"fa fa-check-circle\" style=\"margin-right:6px;color:#10b981\"></span>' + text;
} else {
btn.innerHTML = '<span class=\"fa fa-circle\" style=\"margin-right:6px;color:#9ca3af\"></span>' + text;
}
} catch (e) {
// ignore DOM update errors
}
}
}
});
", elapsed_ms)))
)
} else {
NULL
}
})
# Update camera frame without recreating DOM (prevents blinking)
observe({
frame <- camera_frame()
if (!is.null(frame) && nchar(frame) > 0) {
session$sendCustomMessage("updateCameraFrame", frame)
}
})
# Attendance status with modern design
output$attendance_status_ui <- renderUI({
if (!is.null(user_state$active_session)) {
card(
card_body(
class = "text-center",
h4(icon("users"), "Attendance Status"),
h2("Ready", style = "color: #10b981;"),
p("Camera ready to capture attendance", style = "color: #6b7280;")
)
)
}
})
# Camera controls for attendance (Start/Stop) and stream UI using reticulate
# Initialize Python recognizer reference
camera_recognizer <- reactiveVal(NULL)
# attendance list to display confirmed names (right panel)
attendance_list <- reactiveVal(character(0))
# Cache last frame to prevent blinking
last_frame <- reactiveVal(NULL)
# Camera ready state for loading UI
camera_ready <- reactiveVal(FALSE)
# Track first detection time per student
first_detection_time <- reactiveVal(list())
# Reactive frame source (updates automatically without blinking)
camera_frame <- reactive({
recognizer <- camera_recognizer()
if (!is.null(recognizer)) {
invalidateLater(200)
frame_b64 <- tryCatch(recognizer$get_frame(), error = function(e) NULL)
if (!is.null(frame_b64) && nchar(frame_b64) > 0) {
last_frame(frame_b64)
if (!camera_ready()) camera_ready(TRUE)
return(frame_b64)
}
return(last_frame())
}
return(NULL)
})
# Modern camera preview UI (static structure, only image updates)
output$camera_preview_ui <- renderUI({
recognizer <- camera_recognizer()
if (!is.null(recognizer)) {
if (!camera_ready()) {
# Show loading while camera initializes
fluidRow(
column(
12,
card(
card_header(h5(icon("video"), "Live Camera Feed", style = "margin: 0;")),
card_body(
div(
class = "text-center p-4",
icon("spinner", class = "fa-spin fa-2x", style = "color: #6366f1;"),
h5("Initializing camera...", style = "margin-top: 10px; color: #6b7280;")
)
)
)
)
)
} else {
# Show camera feed
tagList(
fluidRow(
column(
12,
card(
card_header(h5(icon("video"), "Live Camera Feed", style = "margin: 0;")),
card_body(
padding = 0,
tags$img(
id = "camera_feed_img",
src = "",
width = "100%",
style = "display: block; border-radius: 8px; background: #000;"
),
tags$script(HTML("
(function() {
var img = document.getElementById('camera_feed_img');
if (img) {
Shiny.addCustomMessageHandler('updateCameraFrame', function(data) {
if (data && data.length > 0) {
img.src = 'data:image/jpeg;base64,' + data;
}
});
}
})();
"))
)
)
)
)
)
}
} else {
div(
class = "alert alert-secondary",
icon("camera-retro"),
" Camera is not active. Click 'Start Camera' to begin."
)
}
})
# Current Detection Status Display (positioned between camera and log)
output$current_detection_ui <- renderUI({
invalidateLater(1000) # Update every second for cooldown timer
det <- current_detection()
last_times <- last_attendance_time()
first_times <- first_detection_time()
if (is.null(det) || is.null(det$name)) {
# No current detection
card(
card_body(
style = "padding: 15px; text-align: center; background: #f9fafb;",
icon("user-clock", class = "fa-2x", style = "color: #9ca3af; margin-bottom: 8px;"),
p("Waiting for detection...", style = "margin: 0; color: #6b7280; font-size: 14px;")
)
)
} else {
# Current detection exists
sid <- det$id
current_time <- Sys.time()
# Calculate cooldown remaining
cooldown_text <- ""
cooldown_color <- "#10b981" # green when ready
if (!is.null(sid) && !is.null(last_times[[sid]])) {
last_epoch <- as.numeric(last_times[[sid]])
current_epoch <- as.numeric(current_time)
elapsed <- current_epoch - last_epoch
remaining <- max(0, 30 - elapsed)
if (remaining > 0) {
cooldown_text <- sprintf("Cooldown: %d sec", ceiling(remaining))
cooldown_color <- "#f59e0b" # orange during cooldown
} else {
cooldown_text <- "Ready"
cooldown_color <- "#10b981" # green
}
} else {
cooldown_text <- "Ready"
}
# Get entry time for this student
entry_time_text <- "N/A"
if (!is.null(sid) && !is.null(first_times[[sid]]) && !is.null(user_state$session_start_time)) {
first_time <- first_times[[sid]]
tas <- as.numeric(difftime(first_time, user_state$session_start_time, units = "secs"))
if (!is.na(tas) && is.finite(tas)) {
h <- floor(tas / 3600)
m <- floor((tas %% 3600) / 60)
s <- floor(tas %% 60)
entry_time_text <- sprintf("%02d:%02d:%02d", h, m, s)
}
}
# Status icon and color
status_icon <- if (det$status == "Entry") "sign-in-alt" else if (det$status == "Exit") "sign-out-alt" else "user"
status_color <- if (det$status == "Entry") "#10b981" else if (det$status == "Exit") "#f59e0b" else "#6366f1"
card(
card_body(
style = "padding: 15px;",
div(
style = "display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px;",
# Name
div(
div(
style = "font-size: 11px; color: #4b5563; text-transform: uppercase; margin-bottom: 4px; font-weight: 700; letter-spacing: 0.5px;",
"Student Name"
),
div(
style = "font-size: 16px; font-weight: 700; color: #111827;",
icon(status_icon, style = paste0("margin-right: 8px; color: ", status_color, "; font-size: 18px;")),
det$name
)
),
# ID
div(
div(
style = "font-size: 11px; color: #4b5563; text-transform: uppercase; margin-bottom: 4px; font-weight: 700; letter-spacing: 0.5px;",
"Student ID"
),
div(
style = "font-size: 16px; font-weight: 700; color: #111827;",
if (!is.null(sid) && nzchar(sid)) sid else "N/A"
)
),
# Entry Time
div(
div(
style = "font-size: 11px; color: #4b5563; text-transform: uppercase; margin-bottom: 4px; font-weight: 700; letter-spacing: 0.5px;",
"Entry Time"
),
div(
style = "font-size: 16px; font-weight: 700; color: #111827;",
entry_time_text
)
),
# Cooldown Status
div(
div(
style = "font-size: 11px; color: #4b5563; text-transform: uppercase; margin-bottom: 4px; font-weight: 700; letter-spacing: 0.5px;",
"Status"
),
div(
style = paste0("font-size: 16px; font-weight: 700; color: ", cooldown_color, ";"),
cooldown_text
)
)
)
)
)
}
})
# Render confirmed attendance list with modern badges
output$confirmed_list_ui <- renderUI({
invalidateLater(2000)
items <- attendance_list()
if (length(items) == 0) {
p(icon("user-slash"), "No detections yet",
style = "color: #6b7280; text-align: center;"
)
} else {