-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1995 lines (1804 loc) · 59.8 KB
/
main.go
File metadata and controls
1995 lines (1804 loc) · 59.8 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
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gorilla/sessions"
"golang.org/x/crypto/bcrypt"
)
// WorkHoursData is a struct that represents the data needed to display work hours
type WorkHoursData struct {
UserName string
WorkDate string
WorkHours float64
}
// CurrentStatusData is a struct that represents the data needed to display the current status
type CurrentStatusData struct {
UserName string
Status string
Date string
}
// AuthUser is a struct that represents a user in the CSV-based auth store
type AuthUser struct {
Username string
Password string
Role string
}
// BulkClockRequest represents the JSON payload for bulk clocking via barcode
type BulkClockRequest struct {
ActivityCode string `json:"activityCode"`
UserCodes []string `json:"userCodes"`
}
// Calendar data structures for the calendar view
type CalendarDay struct {
Day int
Date string
IsToday bool
IsOtherMonth bool
Entries []CalendarEntry
TotalHours float64
}
type CalendarEntry struct {
Date string
UserName string
Activity string
Hours float64
IsWork bool
}
type CalendarWeek struct {
Days []CalendarDay
}
type CalendarMonth struct {
Year int
Month time.Month
MonthName string
Weeks []CalendarWeek
}
// Weekly visualization structures
type WeekViewDay struct {
Date string
Weekday string
Day int
Segments []WeekSegment // ordered segments during the day
WorkHours float64
BreakHours float64
IsToday bool
}
type WeekSegment struct {
StartHour float64 // hours since 0:00 (e.g., 8.5)
EndHour float64
IsWork bool
LeftPct float64 // 0..100
WidthPct float64 // 0..100
LeftCSS string // e.g., "12.5%"
WidthCSS string // e.g., "33.3%"
}
// loadCredentials loads the credentials from a CSV file
func loadCredentials(filename string) (map[string]AuthUser, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
reader := csv.NewReader(file)
reader.Comma = ';'
reader.FieldsPerRecord = 3
records, err := reader.ReadAll()
if err != nil {
return nil, err
}
users := make(map[string]AuthUser)
for _, record := range records {
users[record[0]] = AuthUser{
Username: record[0],
Password: record[1],
Role: record[2],
}
}
return users, nil
}
var store = sessions.NewCookieStore([]byte("change-me-very-secret"))
// Session duration in minutes
const sessionDuration = 30
// resolve DB user from session; falls back to matching by username
func currentDBUserFromSession(r *http.Request) (User, bool) {
session, _ := store.Get(r, "session")
if idVal, ok := session.Values["db_user_id"]; ok {
switch v := idVal.(type) {
case int:
return getUser(strconv.Itoa(v)), true
case int64:
return getUser(strconv.Itoa(int(v))), true
case string:
return getUser(v), true
}
}
if uname, ok := session.Values["username"].(string); ok && uname != "" {
if u, ok2 := getUserByName(uname); ok2 {
return u, true
}
}
return User{}, false
}
func humanizeDuration(d time.Duration) string {
if d < 0 {
d = -d
}
hrs := int(d.Hours())
mins := int(d.Minutes()) % 60
if hrs > 0 {
return strconv.Itoa(hrs) + "h " + strconv.Itoa(mins) + "m"
}
return strconv.Itoa(mins) + "m"
}
func basicAuthMiddleware(_ map[string]AuthUser, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session")
username, ok := session.Values["username"].(string)
if !ok || username == "" {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
// Accept either CSV or DB-backed users; role is carried in session
next.ServeHTTP(w, r)
})
}
func init() {
// ensure schema is in place
createDatabaseAndTables()
}
func main() {
// load auth users
log.Printf("Starting WorkingTime with %s…", dbBackend)
log.Printf(" DB_BACKEND = %s", dbBackend)
if dbBackend == "sqlite" {
log.Printf(" SQLITE_PATH = %s", os.Getenv("SQLITE_PATH"))
} else {
log.Printf(" MSSQL_SERVER = %s", os.Getenv("MSSQL_SERVER"))
log.Printf(" MSSQL_DATABASE = %s", os.Getenv("MSSQL_DATABASE"))
log.Printf(" MSSQL_USER = %s", os.Getenv("MSSQL_USER"))
}
users, err := loadCredentials("credentials.csv")
if err != nil {
log.Printf("Error loading credentials: %v (continuing with empty CSV users)", err)
users = map[string]AuthUser{}
}
log.Printf(" Credentials file = %s", "credentials.csv")
mux := http.NewServeMux()
// Login & Logout
mux.Handle("/login", loginHandler(users))
mux.HandleFunc("/logout", logoutHandler)
// Password-based stamping page
mux.HandleFunc("/passwordStamp", passwordStampHandler)
// Self-service password change for logged-in users
mux.Handle("/change_password", basicAuthMiddleware(users, http.HandlerFunc(changePasswordHandler)))
// core pages (unprotected)
mux.Handle("/", basicAuthMiddleware(users, http.HandlerFunc(indexHandler)))
mux.Handle("/addUser", basicAuthMiddleware(users, http.HandlerFunc(addUserHandler)))
mux.Handle("/addActivity", basicAuthMiddleware(users, http.HandlerFunc(addActivityHandler)))
mux.Handle("/addDepartment", basicAuthMiddleware(users, http.HandlerFunc(addDepartmentHandler)))
mux.Handle("/clockInOutForm", http.HandlerFunc(clockInOutForm))
mux.Handle("/current_status", basicAuthMiddleware(users, http.HandlerFunc(currentStatusHandler)))
// protected actions
mux.Handle("/createUser", basicAuthMiddleware(users, http.HandlerFunc(createUserHandler)))
mux.Handle("/editUser", basicAuthMiddleware(users, http.HandlerFunc(editUserHandler)))
mux.Handle("/createActivity", basicAuthMiddleware(users, http.HandlerFunc(createActivityHandler)))
mux.Handle("/createDepartment", basicAuthMiddleware(users, http.HandlerFunc(createDepartmentHandler)))
mux.Handle("/work_hours", basicAuthMiddleware(users, http.HandlerFunc(workHoursHandler)))
mux.Handle("/work_status", basicAuthMiddleware(users, http.HandlerFunc(workStatusHandler)))
//mux.Handle("/entries_view", basicAuthMiddleware(users, http.HandlerFunc(entriesViewHandler)))
// Enhanced statistics and management
mux.Handle("/dashboard", basicAuthMiddleware(users, http.HandlerFunc(dashboardHandler)))
mux.Handle("/entries", basicAuthMiddleware(users, http.HandlerFunc(entriesHandler)))
mux.Handle("/editEntry", basicAuthMiddleware(users, http.HandlerFunc(editEntryHandler)))
mux.Handle("/editActivity", basicAuthMiddleware(users, http.HandlerFunc(editActivityHandler)))
mux.Handle("/editDepartment", basicAuthMiddleware(users, http.HandlerFunc(editDepartmentHandler)))
mux.Handle("/deleteEntry", basicAuthMiddleware(users, http.HandlerFunc(deleteEntryHandler)))
mux.Handle("/deleteActivity", basicAuthMiddleware(users, http.HandlerFunc(deleteActivityHandler)))
mux.Handle("/deleteDepartment", basicAuthMiddleware(users, http.HandlerFunc(deleteDepartmentHandler)))
mux.Handle("/deleteUser", basicAuthMiddleware(users, http.HandlerFunc(deleteUserHandler)))
// barcodes page
mux.Handle("/barcodes", basicAuthMiddleware(users, http.HandlerFunc(barcodesHandler)))
// calendar page
mux.Handle("/calendar", basicAuthMiddleware(users, http.HandlerFunc(calendarHandler)))
// weekly page
mux.Handle("/calendar/week", basicAuthMiddleware(users, http.HandlerFunc(weekHandler)))
// Admin downloads page
mux.Handle("/admin/downloads", adminOnly(http.HandlerFunc(adminDownloadsHandler)))
// Enhanced download endpoints with filtering
mux.Handle("/admin/download/entries", adminOnly(http.HandlerFunc(downloadEntriesEnhanced)))
mux.Handle("/admin/download/workhours", adminOnly(http.HandlerFunc(downloadWorkHoursEnhanced)))
mux.Handle("/admin/download/departments", adminOnly(http.HandlerFunc(downloadDepartmentSummary)))
mux.Handle("/admin/download/useractivity", adminOnly(http.HandlerFunc(downloadUserActivity)))
mux.Handle("/admin/download/trends", adminOnly(http.HandlerFunc(downloadTimeTrends)))
mux.Handle("/admin/download/entries.csv", adminOnly(http.HandlerFunc(downloadEntriesCSV)))
mux.Handle("/admin/download/work_hours.csv", adminOnly(http.HandlerFunc(downloadWorkHoursCSV)))
// User self history (no session required; verifies by email+password per request)
mux.HandleFunc("/myHistory", myHistoryHandler)
// static files (CSS, JS, images) with tenant override
defaultStatic := http.StripPrefix("/static/", http.FileServer(http.Dir("static")))
mux.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
rel := strings.TrimPrefix(r.URL.Path, "/static/")
host := r.Host
if idx := strings.IndexByte(host, ':'); idx >= 0 {
host = host[:idx]
}
safe := strings.ToLower(strings.ReplaceAll(host, "/", "-"))
tenantPath := filepath.Join("tenant", safe, "static", rel)
if info, err := os.Stat(tenantPath); err == nil && !info.IsDir() {
http.ServeFile(w, r, tenantPath)
return
}
defaultStatic.ServeHTTP(w, r)
})
// clock in/out via dropdown
mux.Handle("/clockInOut", http.HandlerFunc(clockInOut))
// barcode-driven bulk clock
mux.Handle("/scan", http.HandlerFunc(scanHandler))
mux.Handle("/bulkClock", http.HandlerFunc(bulkClockHandler))
log.Printf("App will listen on http://localhost:8083")
log.Printf("Starting server on :8083…")
// Root wrapper to bind request host for multi-tenant SQLite
root := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
log.Printf("Recovered from panic: %v", rec)
renderInternalServerError(w, fmt.Errorf("unexpected error"))
}
}()
host := r.Host
if idx := strings.IndexByte(host, ':'); idx >= 0 { // strip port
host = host[:idx]
}
SetRequestHost(host)
// ensure per-host SQLite DB has schema
EnsureSchemaCurrent()
defer ClearRequestHost()
mux.ServeHTTP(w, r)
})
if err := http.ListenAndServe(":8083", root); err != nil {
log.Printf("server stopped: %v", err)
}
}
// indexHandler shows the home page
func indexHandler(w http.ResponseWriter, r *http.Request) {
users := getUsers()
activities := getActivities()
// current user status (if we can resolve a DB user)
type cur struct{ Status, Since string }
var current *cur
if u, ok := currentDBUserFromSession(r); ok {
if st, at, ok2 := getCurrentStatusForUserID(u.ID); ok2 {
current = &cur{Status: st, Since: humanizeDuration(time.Since(at))}
}
}
data := struct {
Users []User
Activities []Activity
Current *cur
}{users, activities, current}
renderTemplate(w, r, "index", data)
}
func loginHandler(users map[string]AuthUser) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
renderTemplate(w, r, "login", nil)
return
}
// POST
username := r.FormValue("username")
password := r.FormValue("password")
user, ok := users[username]
if ok && user.Password == password {
session, _ := store.Get(r, "session")
session.Values["username"] = user.Username
session.Values["role"] = user.Role
session.Options = &sessions.Options{Path: "/", MaxAge: sessionDuration * 60, HttpOnly: true}
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
return
}
// Try DB users: treat username as email and set a normal session
if u, exists := getUserByEmail(username); exists && u.Password != "" {
if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password)); err == nil {
session, _ := store.Get(r, "session")
// prefer displaying the DB user's name
session.Values["username"] = u.Name
session.Values["role"] = u.Role
session.Values["db_user_id"] = u.ID
session.Values["db_user_email"] = u.Email
session.Options = &sessions.Options{Path: "/", MaxAge: sessionDuration * 60, HttpOnly: true}
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
return
}
}
renderTemplate(w, r, "login", map[string]any{"Error": "Benutzername oder Passwort falsch."})
}
}
func logoutHandler(w http.ResponseWriter, r *http.Request) {
// Clear session for both CSV and DB users and redirect to login
session, _ := store.Get(r, "session")
// reset values and set delete cookie explicitly
session.Values = map[interface{}]interface{}{}
session.Options = &sessions.Options{Path: "/", MaxAge: -1, HttpOnly: true}
_ = session.Save(r, w)
// additionally ensure cookie deletion
http.SetCookie(w, &http.Cookie{Name: "session", Path: "/", MaxAge: -1})
http.Redirect(w, r, "/login", http.StatusFound)
}
// adminOnly middleware: requires logged-in CSV user with role=admin
func adminOnly(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session")
role, _ := session.Values["role"].(string)
if role != "admin" && role != "Admin" && role != "ADMIN" {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
// Entry-Struktur anpassen je nach deiner DB
type Entry struct {
ID int
UserID int
UserName string
ActivityID string
Date string
Start string
End string
}
// clockInOutForm shows the manual clock in/out form
func clockInOutForm(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
users := getUsers()
activities := getActivities()
type cur struct{ Status, Since string }
var current *cur
if u, ok := currentDBUserFromSession(r); ok {
if st, at, ok2 := getCurrentStatusForUserID(u.ID); ok2 {
current = &cur{Status: st, Since: humanizeDuration(time.Since(at))}
}
}
data := struct {
Users []User
Activities []Activity
Current *cur
}{users, activities, current}
renderTemplate(w, r, "clockInOutForm", data)
}
}
// addUserHandler shows the add-user page
func addUserHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
depts := getDepartments()
users := getUsers()
renderTemplate(w, r, "addUser", struct {
Departments []Department
Users []User
}{depts, users})
}
}
// editUserHandler shows or processes the edit-user page
func editUserHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
id := r.FormValue("id")
u := getUser(id)
depts := getDepartments()
renderTemplate(w, r, "editUser", struct {
User User
Departments []Department
}{u, depts})
return
} else if r.Method == http.MethodPost {
id := r.FormValue("id")
updateUser(id,
r.FormValue("name"),
r.FormValue("stampkey"),
r.FormValue("email"),
r.FormValue("password"),
r.FormValue("role"),
r.FormValue("position"),
r.FormValue("department_id"),
)
// update auto-checkout flag
setUserAutoCheckout(id, r.FormValue("auto_checkout_midnight") == "on")
}
http.Redirect(w, r, "/addUser", http.StatusSeeOther)
}
// addActivityHandler shows the add-activity page
func addActivityHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
activities := getActivities()
renderTemplate(w, r, "addActivity", struct {
Activities []Activity
}{activities})
}
}
// addDepartmentHandler shows the add-department page
func addDepartmentHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
depts := getDepartments()
renderTemplate(w, r, "addDepartment", struct {
Departments []Department
}{depts})
}
}
// createUserHandler processes adding a new user
func createUserHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
createUser(
r.FormValue("name"),
r.FormValue("stampkey"),
r.FormValue("email"),
r.FormValue("password"),
r.FormValue("role"),
r.FormValue("position"),
r.FormValue("department_id"),
)
// Set auto-checkout flag if provided
// Need the created user id; simplest: lookup by email+name (could be non-unique on name; email is unique)
if email := r.FormValue("email"); email != "" {
if u, ok := getUserByEmail(email); ok {
setUserAutoCheckout(strconv.Itoa(u.ID), r.FormValue("auto_checkout_midnight") == "on")
}
}
}
http.Redirect(w, r, "/addUser", http.StatusSeeOther)
}
func barcodesHandler(w http.ResponseWriter, r *http.Request) {
data := struct {
Users []User
Activities []Activity
}{
Users: getUsers(),
Activities: getActivities(),
}
renderTemplate(w, r, "barcodes", data)
}
// calendarHandler shows the calendar view with working times
func calendarHandler(w http.ResponseWriter, r *http.Request) {
// Get filter parameters
selectedUserID := r.URL.Query().Get("user")
selectedActivityID := r.URL.Query().Get("activity")
monthParam := r.URL.Query().Get("month")
// Parse month parameter or default to current month
var targetDate time.Time
if monthParam != "" {
if parsed, err := time.Parse("2006-01", monthParam); err == nil {
targetDate = parsed
} else {
targetDate = time.Now()
}
} else {
targetDate = time.Now()
}
// Get calendar data
calendarData := getCalendarData(targetDate, selectedUserID, selectedActivityID)
data := struct {
Users []User
Activities []Activity
CalendarData CalendarMonth
SelectedUser string
SelectedActivity string
CurrentMonth string
PrevMonth string
NextMonth string
}{
Users: getUsers(),
Activities: getActivities(),
CalendarData: calendarData,
SelectedUser: selectedUserID,
SelectedActivity: selectedActivityID,
CurrentMonth: targetDate.Format("2006-01"),
PrevMonth: targetDate.AddDate(0, -1, 0).Format("2006-01"),
NextMonth: targetDate.AddDate(0, 1, 0).Format("2006-01"),
}
renderTemplate(w, r, "calendar", data)
}
// weekHandler shows a 7-day week timeline with bars for work/break
func weekHandler(w http.ResponseWriter, r *http.Request) {
// Inputs: week (any date within week or YYYY-01-02), user, activity
selectedUserID := r.URL.Query().Get("user")
selectedActivityID := r.URL.Query().Get("activity")
weekParam := r.URL.Query().Get("week")
// Determine target date
target := time.Now()
if weekParam != "" {
// try multiple formats
if t, err := time.Parse("2006-01-02", weekParam); err == nil {
target = t
} else if t2, err2 := time.Parse("2006-01", weekParam); err2 == nil {
target = t2
}
}
// normalize to Monday of the week
startOfWeek := target
for startOfWeek.Weekday() != time.Monday {
startOfWeek = startOfWeek.AddDate(0, 0, -1)
}
endOfWeek := startOfWeek.AddDate(0, 0, 6)
// Get raw entries spanning week
entries := getCalendarEntries(startOfWeek, endOfWeek, selectedUserID, selectedActivityID)
days := buildWeekDays(startOfWeek, entries)
// tenant-aware date-only formatting for label
host := r.Host
if idx := strings.IndexByte(host, ':'); idx >= 0 {
host = host[:idx]
}
cfg := loadTenantConfig(host)
dLayout := dateOnlyLayoutFromTenant(cfg.DateTimeFormat)
data := struct {
Users []User
Activities []Activity
Days []WeekViewDay
SelectedUser string
SelectedActivity string
WeekLabel string
PrevWeek string
NextWeek string
WeekParam string
MonthParam string
}{
Users: getUsers(),
Activities: getActivities(),
Days: days,
SelectedUser: selectedUserID,
SelectedActivity: selectedActivityID,
WeekLabel: fmt.Sprintf("%s – %s", startOfWeek.Format(dLayout), endOfWeek.Format(dLayout)),
PrevWeek: startOfWeek.AddDate(0, 0, -7).Format("2006-01-02"),
NextWeek: startOfWeek.AddDate(0, 0, 7).Format("2006-01-02"),
WeekParam: startOfWeek.Format("2006-01-02"),
MonthParam: startOfWeek.Format("2006-01"),
}
renderTemplate(w, r, "week", data)
}
// buildWeekDays converts raw CalendarEntry events (point-in-time markers) into per-day segments
func buildWeekDays(weekStart time.Time, entries []CalendarEntry) []WeekViewDay {
loc := weekStart.Location()
// group entries per day per user in chronological order
type key struct {
date string
user string
}
groups := map[key][]CalendarEntry{}
for _, e := range entries {
dateKey := e.Date[:10]
k := key{date: dateKey, user: e.UserName}
groups[k] = append(groups[k], e)
}
// Build 7 days
days := make([]WeekViewDay, 0, 7)
todayStr := time.Now().Format("2006-01-02")
for i := 0; i < 7; i++ {
d := weekStart.AddDate(0, 0, i)
dateKey := d.Format("2006-01-02")
day := WeekViewDay{Date: dateKey, Weekday: d.Weekday().String(), Day: d.Day(), IsToday: dateKey == todayStr}
// For each user group that matches this date, translate events into segments
// We concatenate across users within the day (stack visually via multiple rows if needed by CSS)
// Here we just merge sequentially; overlapping handled by separate segments
var daySegs []WeekSegment
var workHours, breakHours float64
for k, list := range groups {
if k.date != dateKey {
continue
}
// entries are already ordered by time in query; if not, we would sort by Date
// Build segments between successive events for this user
for idx, ev := range list {
startTs := parseDBTimeInLoc(ev.Date, loc)
// end is next event or end of day if last and open; but our SQL already computed hours, not explicit end
var endTs time.Time
if idx+1 < len(list) {
endTs = parseDBTimeInLoc(list[idx+1].Date, loc)
} else {
// cap at 24:00 of same day
endTs = time.Date(d.Year(), d.Month(), d.Day(), 24, 0, 0, 0, loc)
}
// clamp to day bounds
dayStart := time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, loc)
dayEnd := time.Date(d.Year(), d.Month(), d.Day(), 24, 0, 0, 0, loc)
if endTs.Before(dayStart) || startTs.After(dayEnd) {
continue
}
if startTs.Before(dayStart) {
startTs = dayStart
}
if endTs.After(dayEnd) {
endTs = dayEnd
}
seg := WeekSegment{
StartHour: startTs.Sub(dayStart).Hours(),
EndHour: endTs.Sub(dayStart).Hours(),
IsWork: ev.IsWork,
}
if seg.EndHour > seg.StartHour {
seg.LeftPct = (seg.StartHour / 24.0) * 100.0
seg.WidthPct = ((seg.EndHour - seg.StartHour) / 24.0) * 100.0
daySegs = append(daySegs, seg)
dur := seg.EndHour - seg.StartHour
if seg.IsWork {
workHours += dur
} else {
breakHours += dur
}
}
}
_ = k // avoid unused if compiled differently
}
day.Segments = daySegs
day.WorkHours = workHours
day.BreakHours = breakHours
days = append(days, day)
}
return days
}
// parseDBTimeInLoc parses timestamps from DB that might be in RFC3339 or '2006-01-02 15:04:05' format
func parseDBTimeInLoc(s string, loc *time.Location) time.Time {
if s == "" {
return time.Now().In(loc)
}
// 1) RFC3339 with timezone info -> parse as given, then convert to loc
if t, err := time.Parse(time.RFC3339, s); err == nil {
return t.In(loc)
}
// 2) HTML datetime-local (no zone) -> interpret in provided loc
if strings.Contains(s, "T") {
if t, err := time.ParseInLocation("2006-01-02T15:04:05", s, loc); err == nil {
return t
}
if t, err := time.ParseInLocation("2006-01-02T15:04", s, loc); err == nil {
return t
}
}
// 3) Plain "YYYY-MM-DD HH:MM:SS" from SQLite DATETIME('unixepoch') is UTC text -> parse in UTC then convert
if len(s) >= 19 && s[4] == '-' && s[7] == '-' && s[10] == ' ' {
if t, err := time.Parse("2006-01-02 15:04:05", s); err == nil {
return t.In(loc)
}
}
// 4) Date-only -> treat as UTC midnight and convert
if len(s) == 10 && s[4] == '-' && s[7] == '-' {
if t, err := time.Parse("2006-01-02", s); err == nil {
return t.In(loc)
}
if t, err := time.ParseInLocation("2006-01-02", s, loc); err == nil {
return t
}
}
// Fallbacks
if t, err := time.Parse("2006-01-02 15:04:05", s); err == nil {
return t.In(loc)
}
if t, err := time.ParseInLocation("2006-01-02 15:04:05", s, loc); err == nil {
return t
}
if t, err := time.Parse("2006-01-02T15:04", s); err == nil {
return t.In(loc)
}
if t, err := time.ParseInLocation("2006-01-02T15:04", s, loc); err == nil {
return t
}
if t, err := time.Parse("2006-01-02", s); err == nil {
return t.In(loc)
}
if t, err := time.ParseInLocation("2006-01-02", s, loc); err == nil {
return t
}
return time.Now().In(loc)
}
// getCalendarData generates calendar data for a specific month with optional filters
func getCalendarData(targetDate time.Time, userFilter, activityFilter string) CalendarMonth {
year := targetDate.Year()
month := targetDate.Month()
// Get first day of month
firstDay := time.Date(year, month, 1, 0, 0, 0, 0, targetDate.Location())
// Get last day of month
lastDay := firstDay.AddDate(0, 1, -1)
// Get first day of calendar (may be in previous month)
// Start from Monday (1) to Sunday (0)
calendarStart := firstDay
for calendarStart.Weekday() != time.Monday {
calendarStart = calendarStart.AddDate(0, 0, -1)
}
// Get last day of calendar (may be in next month)
calendarEnd := lastDay
for calendarEnd.Weekday() != time.Sunday {
calendarEnd = calendarEnd.AddDate(0, 0, 1)
}
// Get entries for the calendar period
entries := getCalendarEntries(calendarStart, calendarEnd, userFilter, activityFilter)
// Group entries by date
entriesByDate := make(map[string][]CalendarEntry)
for _, entry := range entries {
dateKey := entry.Date[:10] // Extract YYYY-MM-DD part
if entry.IsWork {
entriesByDate[dateKey] = append(entriesByDate[dateKey], entry)
}
}
// Build calendar structure
var weeks []CalendarWeek
current := calendarStart
for current.Before(calendarEnd.AddDate(0, 0, 1)) {
week := CalendarWeek{}
// Build 7 days for this week
for i := 0; i < 7; i++ {
dateKey := current.Format("2006-01-02")
dayEntries := entriesByDate[dateKey]
totalHours := 0.0
for _, entry := range dayEntries {
if entry.IsWork {
totalHours += entry.Hours
}
}
day := CalendarDay{
Day: current.Day(),
Date: dateKey,
IsToday: current.Format("2006-01-02") == time.Now().Format("2006-01-02"),
IsOtherMonth: current.Month() != month,
Entries: dayEntries,
TotalHours: totalHours,
}
week.Days = append(week.Days, day)
current = current.AddDate(0, 0, 1)
}
weeks = append(weeks, week)
}
return CalendarMonth{
Year: year,
Month: month,
MonthName: month.String(),
Weeks: weeks,
}
}
// createActivityHandler processes adding a new activity
func createActivityHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
createActivity(
r.FormValue("status"),
r.FormValue("work"),
r.FormValue("comment"),
)
}
http.Redirect(w, r, "/addActivity", http.StatusSeeOther)
}
// createDepartmentHandler processes adding a new department
func createDepartmentHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
createDepartment(r.FormValue("name"))
}
http.Redirect(w, r, "/addDepartment", http.StatusSeeOther)
}
// clockInOut handles manual clock in/out submissions
func clockInOut(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
userID := r.FormValue("user_id")
stampKey := r.FormValue("stampkey")
activityID := r.FormValue("activity_id")
if userID == "" && stampKey != "" {
userID = getUserIDFromStampKey(stampKey)
}
if userID == "" || activityID == "" {
http.Error(w, "Invalid input", http.StatusBadRequest)
return
}
createEntry(userID, activityID, time.Now())
// Redirect back to the referring page
http.Redirect(w, r, r.Header.Get("Referer"), http.StatusSeeOther)
}
// passwordStampHandler allows stamping by email+password, then choosing activity buttons
func passwordStampHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session")
if idVal, ok := session.Values["db_user_id"]; ok {
// Logged-in DB user: no password needed
uid := 0
switch v := idVal.(type) {
case int:
uid = v
case int64:
uid = int(v)
case string:
uid, _ = strconv.Atoi(v)
}
u := getUser(strconv.Itoa(uid))
switch r.Method {
case http.MethodGet:
activities := getActivities()
var current any
if st, at, ok2 := getCurrentStatusForUserID(u.ID); ok2 {
current = map[string]string{"Status": st, "Since": humanizeDuration(time.Since(at))}
}
renderTemplate(w, r, "passwordStamp", map[string]any{
"User": u,
"Activities": activities,
"Current": current,
})
return
case http.MethodPost:
activityID := r.FormValue("activity_id")
if activityID == "" {
activities := getActivities()
var current any
if st, at, ok2 := getCurrentStatusForUserID(u.ID); ok2 {
current = map[string]string{"Status": st, "Since": humanizeDuration(time.Since(at))}
}
renderTemplate(w, r, "passwordStamp", map[string]any{
"User": u,
"Activities": activities,
"Current": current,
})
return
}
createEntry(strconv.Itoa(u.ID), activityID, time.Now())
var current any
if st, at, ok2 := getCurrentStatusForUserID(u.ID); ok2 {
current = map[string]string{"Status": st, "Since": humanizeDuration(time.Since(at))}
}
renderTemplate(w, r, "passwordStamp", map[string]any{"User": u, "Success": true, "Current": current})
return
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
}
// Fallback: email + password flow
switch r.Method {
case http.MethodGet:
renderTemplate(w, r, "passwordStamp", nil)
return
case http.MethodPost:
email := r.FormValue("email")
pwd := r.FormValue("pwd")
activityID := r.FormValue("activity_id")
u, ok := getUserByEmail(email)
if !ok || u.Password == "" {
renderTemplate(w, r, "passwordStamp", map[string]any{"Error": "Unbekannte E-Mail oder kein Passwort gesetzt."})
return
}
if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(pwd)); err != nil {
renderTemplate(w, r, "passwordStamp", map[string]any{"Error": "Falsches Passwort."})
return
}
if activityID == "" {
activities := getActivities()
var current any
if st, at, ok2 := getCurrentStatusForUserID(u.ID); ok2 {
current = map[string]string{"Status": st, "Since": humanizeDuration(time.Since(at))}
}
renderTemplate(w, r, "passwordStamp", map[string]any{
"User": u,
"Activities": activities,
"Pwd": pwd,
"Current": current,
})
return
}
createEntry(strconv.Itoa(u.ID), activityID, time.Now())
var current any
if st, at, ok2 := getCurrentStatusForUserID(u.ID); ok2 {
current = map[string]string{"Status": st, "Since": humanizeDuration(time.Since(at))}
}
renderTemplate(w, r, "passwordStamp", map[string]any{"User": u, "Success": true, "Current": current})
return
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
}
type PageData struct {
WorkHoursTable TableData
CurrentStatusTable TableData
}
func workStatusHandler(w http.ResponseWriter, r *http.Request) {
workData := getWorkHoursData()
statusData := getCurrentStatusData()
workRows := make([][]interface{}, len(workData))
for i, d := range workData {
workRows[i] = []interface{}{d.UserName, d.WorkDate, d.WorkHours}
}
statusRows := make([][]interface{}, len(statusData))
for i, d := range statusData {