Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
3137 lines (2744 loc) · 113 KB
/
Copy pathapp.js
File metadata and controls
3137 lines (2744 loc) · 113 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
/* ===========================================================
Diensten Dashboard — app.js
State management, localStorage-migraties, bewonerszoekbalk,
agenda, taken, noodcontacten, stadsteams en sancties.
=========================================================== */
(function(){
var errorToastShown = false;
function showErrorToast(){
if(errorToastShown) return;
errorToastShown = true;
function place(){
if(!document.body){
document.addEventListener("DOMContentLoaded", place, { once: true });
return;
}
var toast = document.createElement("div");
toast.setAttribute("role", "alert");
toast.style.cssText =
"position:fixed;left:50%;bottom:20px;transform:translateX(-50%);z-index:99999;" +
"max-width:calc(100% - 32px);background:#23272c;color:#e9ebee;" +
"border:1px solid #363b41;border-left:3px solid #db7a6b;border-radius:12px;" +
"padding:12px 16px;font:13px/1.45 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;" +
"box-shadow:0 8px 24px rgba(0,0,0,0.4);";
toast.textContent = "Er is een onverwachte fout opgetreden. Herlaad de app.";
document.body.appendChild(toast);
setTimeout(function(){
if(toast.parentNode) toast.parentNode.removeChild(toast);
errorToastShown = false;
}, 8000);
}
place();
}
window.addEventListener("error", function(e){
console.error(
"JS-fout:", e.message,
"\nBestand: " + (e.filename || "onbekend") + ":" + e.lineno + ":" + e.colno,
e.error && e.error.stack ? "\n" + e.error.stack : ""
);
showErrorToast();
});
window.addEventListener("unhandledrejection", function(e){
console.error("Onafgehandelde promise-afwijzing:", e.reason);
showErrorToast();
});
})();
(function(){
"use strict";
var STORAGE_KEY = "wb_diensten_dashboard";
var LEGACY_KEYS = ["wb_diensten_dashboard_v4", "wb_diensten_dashboard_v3", "wb_diensten_dashboard_v2", "wb_diensten_dashboard_v1"];
// ---------- Beveiliging: versleutelde opslag (AES-GCM + PBKDF2) ----------
var VAULT_DB_NAME = "onshift_vault_db";
var VAULT_STORE = "vault";
var VAULT_RECORD_KEY = "state";
var SALT_LS_KEY = "onshift_vault_salt";
var INIT_FLAG_LS_KEY = "onshift_vault_initialized";
var PBKDF2_ITERATIONS = 310000;
var STATUS_ORDER = ["unseen", "seen", "absent"];
var STATUS_META = {
unseen: { label: "Nog niet gezien", cls: "st-unseen" },
seen: { label: "Gezien", cls: "st-seen" },
absent: { label: "Afwezig / verlof", cls: "st-absent" }
};
var DEFAULT_TASKS = [
{ id: "t1", text: "Medicatieronde ochtend afgetekend", done: false },
{ id: "t2", text: "Medicatieronde avond afgetekend", done: false },
{ id: "t3", text: "Rapportages bijgewerkt in dossier", done: false },
{ id: "t4", text: "Maaltijdbegeleiding / koken begeleid", done: false },
{ id: "t5", text: "Avondronde & veiligheidscheck gedaan", done: false },
{ id: "t6", text: "Huishoudelijke ondersteuning gecontroleerd", done: false }
];
var DEFAULT_RESIDENTS = [
{ id: "r1", name: "J. de Vries", room: "101", status: "unseen", note: "", clientnr: "", locker: "", isAttention: false, attentionNote: "" },
{ id: "r2", name: "M. El Amrani", room: "102", status: "unseen", note: "", clientnr: "", locker: "", isAttention: false, attentionNote: "" },
{ id: "r3", name: "R. Boersema", room: "103", status: "unseen", note: "", clientnr: "", locker: "", isAttention: false, attentionNote: "" },
{ id: "r4", name: "S. Kowalski", room: "104", status: "unseen", note: "", clientnr: "", locker: "", isAttention: false, attentionNote: "" },
{ id: "r5", name: "T. Hendriks", room: "105", status: "unseen", note: "", clientnr: "", locker: "", isAttention: false, attentionNote: "" },
{ id: "r6", name: "L. van Dijk", room: "106", status: "unseen", note: "", clientnr: "", locker: "", isAttention: false, attentionNote: "" }
];
var DEFAULT_CONTACTS = [
{ id: "c1", name: "Alarm (levensbedreigend)", number: "112" },
{ id: "c2", name: "Bereikbaarheidsdienst", number: "06 - 00 00 00 00" },
{ id: "c3", name: "Beveiliging pand", number: "06 - 11 11 11 11" },
{ id: "c4", name: "Huisartsenpost", number: "0900 - 000 000" },
{ id: "c5", name: "Crisisdienst GGZ", number: "0800 - 000 000" },
{ id: "c6", name: "Politie (geen spoed)", number: "0900 - 8844" }
];
var TEAM_KEYS = ["volwassenen", "jongvolwassenen", "veldwerkers"];
var TEAM_LABELS = { volwassenen: "Volwassenen", jongvolwassenen: "Jongvolwassenen", veldwerkers: "Veldwerkers" };
var DEFAULT_STADSTEAM = [
{ id: "s1", name: "P. Willemsen", team: "volwassenen", phone: "06 - 22 33 44 55", email: "[email protected]" },
{ id: "s2", name: "F. Yilmaz", team: "jongvolwassenen", phone: "06 - 33 44 55 66", email: "[email protected]" },
{ id: "s3", name: "K. Bakker", team: "veldwerkers", phone: "06 - 44 55 66 77", email: "[email protected]" }
];
var DEFAULT_PANELS_OPEN = {
overdracht: true,
aandacht: true,
taken: true,
bewoners: true,
agendaVandaag: true,
contacten: true,
stadsteam: true,
beheerBewoners: true,
beheerContacten: true,
beheerStadsteam: true,
beheerBeveiliging: true,
beheerData: true,
beheerTour: true,
sanctiesWarnings: true,
sanctiesBans: true
};
function uid(prefix){
return prefix + "-" + Date.now() + "-" + Math.random().toString(36).slice(2, 7);
}
function openZorgNedLink(url){
var isStandalone = window.navigator.standalone === true ||
(window.matchMedia && window.matchMedia("(display-mode: standalone)").matches);
var isIOS = /iP(hone|od|ad)/.test(navigator.userAgent) ||
(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
if (isStandalone && isIOS) {
// Forceert openen in de native Safari-app i.p.v. de WebSheet-overlay,
// zodat de 2FA/Authenticator-sessie bewaard blijft.
window.location.href = url.replace(/^https:\/\//, "x-safari-https://");
} else {
window.open(url, "_blank", "noopener,noreferrer");
}
}
function todayISO(){
var d = new Date();
var m = ("0" + (d.getMonth() + 1)).slice(-2);
var day = ("0" + d.getDate()).slice(-2);
return d.getFullYear() + "-" + m + "-" + day;
}
function defaultState(){
var t = todayISO();
var parts = t.split("-");
return {
handoverNote: "",
tasks: JSON.parse(JSON.stringify(DEFAULT_TASKS)),
residents: JSON.parse(JSON.stringify(DEFAULT_RESIDENTS)),
contacts: JSON.parse(JSON.stringify(DEFAULT_CONTACTS)),
stadsteam: JSON.parse(JSON.stringify(DEFAULT_STADSTEAM)),
events: [],
warnings: [],
bans: [],
panelsOpen: JSON.parse(JSON.stringify(DEFAULT_PANELS_OPEN)),
agendaView: "month",
agendaSelectedDate: t,
calYear: parseInt(parts[0], 10),
calMonth: parseInt(parts[1], 10) - 1,
dashboardSort: "naam",
dashboardSelectedResidentId: null,
autoLockMinutes: 5
};
}
// ---------- Normalisatie / migratie ----------
function normalizeResident(r, i){
r = r || {};
var status = "unseen";
if(r.status === "seen" || r.status === "absent" || r.status === "unseen"){
status = r.status;
}else if(typeof r.seen === "boolean"){
status = r.seen ? "seen" : "unseen"; // migratie van oude boolean 'seen'
}
return {
id: r.id || uid("res"),
name: typeof r.name === "string" ? r.name : ("Bewoner " + (i + 1)),
room: typeof r.room === "string" ? r.room : "",
status: status,
note: typeof r.note === "string" ? r.note : "",
clientnr: typeof r.clientnr === "string" ? r.clientnr : "",
locker: typeof r.locker === "string" ? r.locker : "",
isAttention: !!r.isAttention,
attentionNote: typeof r.attentionNote === "string" ? r.attentionNote : ""
};
}
function normalizeWarning(w){
w = w || {};
return {
id: w.id || uid("warn"),
residentId: typeof w.residentId === "string" ? w.residentId : "",
date: typeof w.date === "string" ? w.date : todayISO(),
level: typeof w.level === "string" ? w.level : "1e waarschuwing",
note: typeof w.note === "string" ? w.note : ""
};
}
function normalizeBan(b){
b = b || {};
return {
id: b.id || uid("ban"),
name: typeof b.name === "string" ? b.name : "",
clientnr: typeof b.clientnr === "string" ? b.clientnr : "",
reason: typeof b.reason === "string" ? b.reason : "",
untilDate: typeof b.untilDate === "string" ? b.untilDate : "",
untilTime: typeof b.untilTime === "string" ? b.untilTime : ""
};
}
function normalizeTask(t){
t = t || {};
return { id: t.id || uid("task"), text: typeof t.text === "string" ? t.text : "", done: !!t.done };
}
function normalizeContact(c){
c = c || {};
return { id: c.id || uid("contact"), name: typeof c.name === "string" ? c.name : "", number: typeof c.number === "string" ? c.number : "" };
}
function normalizeStadsteamContact(s){
s = s || {};
return {
id: s.id || uid("stads"),
name: typeof s.name === "string" ? s.name : "",
team: TEAM_KEYS.indexOf(s.team) !== -1 ? s.team : "volwassenen",
phone: typeof s.phone === "string" ? s.phone : "",
email: typeof s.email === "string" ? s.email : ""
};
}
function normalizePanelsOpen(parsed, legacyAccordionOpen){
var base = JSON.parse(JSON.stringify(DEFAULT_PANELS_OPEN));
if(parsed && typeof parsed === "object"){
Object.keys(base).forEach(function(key){
if(typeof parsed[key] === "boolean") base[key] = parsed[key];
});
}
if(typeof parsed !== "object" || parsed === null || typeof parsed.contacten !== "boolean"){
if(typeof legacyAccordionOpen === "boolean") base.contacten = legacyAccordionOpen;
}
return base;
}
function normalizeEvent(e){
e = e || {};
return {
id: e.id || uid("ev"),
date: typeof e.date === "string" ? e.date : todayISO(),
time: typeof e.time === "string" ? e.time : "",
title: typeof e.title === "string" ? e.title : "",
residentId: typeof e.residentId === "string" ? e.residentId : null
};
}
function normalizeLoadedData(parsed){
var base = defaultState();
if(!parsed || typeof parsed !== "object") return base;
return {
handoverNote: typeof parsed.handoverNote === "string" ? parsed.handoverNote : base.handoverNote,
tasks: Array.isArray(parsed.tasks) ? parsed.tasks.map(normalizeTask) : base.tasks,
residents: Array.isArray(parsed.residents) ? parsed.residents.map(normalizeResident) : base.residents,
contacts: Array.isArray(parsed.contacts) ? parsed.contacts.map(normalizeContact) : base.contacts,
stadsteam: Array.isArray(parsed.stadsteam) ? parsed.stadsteam.map(normalizeStadsteamContact) : base.stadsteam,
events: Array.isArray(parsed.events) ? parsed.events.map(normalizeEvent) : base.events,
warnings: Array.isArray(parsed.warnings) ? parsed.warnings.map(normalizeWarning) : base.warnings,
bans: Array.isArray(parsed.bans) ? parsed.bans.map(normalizeBan) : base.bans,
panelsOpen: normalizePanelsOpen(parsed.panelsOpen, parsed.accordionOpen),
agendaView: (parsed.agendaView === "day" ? "day" : "month"),
agendaSelectedDate: typeof parsed.agendaSelectedDate === "string" ? parsed.agendaSelectedDate : base.agendaSelectedDate,
calYear: typeof parsed.calYear === "number" ? parsed.calYear : base.calYear,
calMonth: typeof parsed.calMonth === "number" ? parsed.calMonth : base.calMonth,
dashboardSort: (parsed.dashboardSort === "kamer" ? "kamer" : "naam"),
dashboardSelectedResidentId: typeof parsed.dashboardSelectedResidentId === "string" ? parsed.dashboardSelectedResidentId : null,
autoLockMinutes: [2, 5, 10].indexOf(parsed.autoLockMinutes) !== -1 ? parsed.autoLockMinutes : base.autoLockMinutes
};
}
function readRawFromAnyKey(){
try{
var raw = localStorage.getItem(STORAGE_KEY);
if(raw) return raw;
for(var i = 0; i < LEGACY_KEYS.length; i++){
raw = localStorage.getItem(LEGACY_KEYS[i]);
if(raw) return raw;
}
}catch(e){ /* localStorage niet beschikbaar */ }
return null;
}
// Alleen gebruikt tijdens de eenmalige migratie van oude, onversleutelde
// localStorage-data naar de versleutelde IndexedDB-vault (zie boot-logica
// onderaan dit bestand). Wordt daarna niet meer aangeroepen.
function loadLegacyPlaintextState(){
try{
var raw = readRawFromAnyKey();
if(!raw) return null;
return normalizeLoadedData(JSON.parse(raw));
}catch(e){
return null;
}
}
// ---------- Crypto-helpers (Web Crypto API: PBKDF2 + AES-GCM) ----------
function bufToB64(buf){
var bytes = new Uint8Array(buf);
var binary = "";
for(var i = 0; i < bytes.byteLength; i++){ binary += String.fromCharCode(bytes[i]); }
return btoa(binary);
}
function b64ToBuf(b64){
var binary = atob(b64);
var bytes = new Uint8Array(binary.length);
for(var i = 0; i < binary.length; i++){ bytes[i] = binary.charCodeAt(i); }
return bytes;
}
function deriveKey(pin, saltBytes){
var enc = new TextEncoder();
return crypto.subtle.importKey("raw", enc.encode(pin), "PBKDF2", false, ["deriveKey"]).then(function(keyMaterial){
return crypto.subtle.deriveKey(
{ name: "PBKDF2", salt: saltBytes, iterations: PBKDF2_ITERATIONS, hash: "SHA-256" },
keyMaterial,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
});
}
function decryptBlob(key, ivB64, ctB64){
var iv = b64ToBuf(ivB64);
var ct = b64ToBuf(ctB64);
return crypto.subtle.decrypt({ name: "AES-GCM", iv: iv }, key, ct).then(function(plainBuf){
var dec = new TextDecoder();
return JSON.parse(dec.decode(plainBuf));
});
}
// ---------- IndexedDB-vault (versleutelde blob, één record) ----------
function openVaultDB(){
return new Promise(function(resolve, reject){
var req = indexedDB.open(VAULT_DB_NAME, 1);
req.onupgradeneeded = function(){
var db = req.result;
if(!db.objectStoreNames.contains(VAULT_STORE)) db.createObjectStore(VAULT_STORE);
};
req.onsuccess = function(){ resolve(req.result); };
req.onerror = function(){ reject(req.error); };
});
}
function vaultGet(){
return openVaultDB().then(function(db){
return new Promise(function(resolve, reject){
var tx = db.transaction(VAULT_STORE, "readonly");
var req = tx.objectStore(VAULT_STORE).get(VAULT_RECORD_KEY);
req.onsuccess = function(){ resolve(req.result || null); };
req.onerror = function(){ reject(req.error); };
});
});
}
function vaultPut(record){
return openVaultDB().then(function(db){
return new Promise(function(resolve, reject){
var tx = db.transaction(VAULT_STORE, "readwrite");
var req = tx.objectStore(VAULT_STORE).put(record, VAULT_RECORD_KEY);
req.onsuccess = function(){ resolve(); };
req.onerror = function(){ reject(req.error); };
});
});
}
// ---------- Sessiesleutel (alleen in geheugen, nooit opgeslagen) ----------
var cryptoKey = null; // niet-exporteerbare AES-GCM CryptoKey, alleen tijdens ontgrendelde sessie
var currentPin = null; // huidige pincode in geheugen (nodig voor export-standaardwachtwoord en pincode wijzigen)
var state = null; // pas gevuld na succesvolle setup/ontgrendeling
function persistEncrypted(){
if(!cryptoKey || !state) return Promise.resolve();
var iv = crypto.getRandomValues(new Uint8Array(12));
var enc = new TextEncoder();
var data = enc.encode(JSON.stringify(state));
return crypto.subtle.encrypt({ name: "AES-GCM", iv: iv }, cryptoKey, data).then(function(ctBuf){
return vaultPut({ iv: bufToB64(iv), ciphertext: bufToB64(ctBuf) });
});
}
function saveState(){
persistEncrypted().then(function(){
flashSaveHint();
}).catch(function(e){
console.warn("Opslaan (versleuteld) mislukt:", e);
});
}
// ---------- Save hint ----------
var saveHintEl = document.getElementById("saveHint");
var saveHintTimer = null;
function flashSaveHint(){
if(!saveHintEl) return;
saveHintEl.textContent = "Opgeslagen";
if(saveHintTimer) clearTimeout(saveHintTimer);
saveHintTimer = setTimeout(function(){ saveHintEl.textContent = ""; }, 1400);
}
// ---------- Datum helpers ----------
var days = ["zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"];
var months = ["januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","november","december"];
function pad2(n){ return ("0" + n).slice(-2); }
function isoOf(year, month, day){ return year + "-" + pad2(month + 1) + "-" + pad2(day); }
// ---------- Tijdselector helpers (uur-dropdown + kwartier-minuten) ----------
function buildHourOptions(selectEl){
selectEl.innerHTML = "";
var noneOpt = document.createElement("option");
noneOpt.value = "";
noneOpt.textContent = "Hele dag";
selectEl.appendChild(noneOpt);
for(var h = 0; h < 24; h++){
var hh = pad2(h);
var opt = document.createElement("option");
opt.value = hh;
opt.textContent = hh;
selectEl.appendChild(opt);
}
}
function syncMinuteDisabled(hourSel, minuteSel){
minuteSel.disabled = (hourSel.value === "");
}
function readTimeFromSelects(hourSel, minuteSel){
if(hourSel.value === "") return "";
return hourSel.value + ":" + minuteSel.value;
}
function resetTimeSelects(hourSel, minuteSel){
hourSel.value = "";
minuteSel.value = "00";
syncMinuteDisabled(hourSel, minuteSel);
}
function formatDateLabel(iso){
var parts = iso.split("-");
var d = new Date(parseInt(parts[0],10), parseInt(parts[1],10) - 1, parseInt(parts[2],10));
return days[d.getDay()] + " " + d.getDate() + " " + months[d.getMonth()] + " " + d.getFullYear();
}
function shiftDateISO(iso, deltaDays){
var parts = iso.split("-");
var d = new Date(parseInt(parts[0],10), parseInt(parts[1],10) - 1, parseInt(parts[2],10));
d.setDate(d.getDate() + deltaDays);
return isoOf(d.getFullYear(), d.getMonth(), d.getDate());
}
var now = new Date();
document.getElementById("shiftDate").textContent =
days[now.getDay()] + " " + now.getDate() + " " + months[now.getMonth()] + " " + now.getFullYear();
function getResidentById(id){
return state.residents.filter(function(r){ return r.id === id; })[0];
}
// ---------- Tabs ----------
var tabButtons = document.querySelectorAll(".tab-btn[data-tab]");
var TAB_PANEL_IDS = {
dashboard: "panelDashboard",
agenda: "panelAgenda",
bewoners: "panelBewoners",
sancties: "panelSancties",
contacten: "panelContacten",
beheer: "panelBeheer"
};
function activateTab(tab){
tabButtons.forEach(function(btn){
var isActive = btn.getAttribute("data-tab") === tab;
btn.classList.toggle("active", isActive);
if(isActive && typeof btn.scrollIntoView === "function"){
btn.scrollIntoView({ behavior: "smooth", inline: "center", block: "nearest" });
}
});
Object.keys(TAB_PANEL_IDS).forEach(function(key){
var panel = document.getElementById(TAB_PANEL_IDS[key]);
if(panel) panel.classList.toggle("active", key === tab);
});
if(tab === "bewoners") renderResidentsFullList();
if(tab === "contacten"){ renderStadsteamListTab(); renderContactsTab(); }
if(tab === "sancties"){ renderWarningsList(); renderBansList(); }
}
tabButtons.forEach(function(btn){
btn.addEventListener("click", function(){ activateTab(btn.getAttribute("data-tab")); });
});
// ---------- Overdracht ----------
var handoverEl = document.getElementById("handoverNote");
var handoverDebounce = null;
handoverEl.addEventListener("input", function(){
state.handoverNote = handoverEl.value;
if(handoverDebounce) clearTimeout(handoverDebounce);
handoverDebounce = setTimeout(saveState, 350);
});
// ---------- Checklist ----------
var taskListEl = document.getElementById("taskList");
var taskCountEl = document.getElementById("taskCount");
function renderTasks(){
taskListEl.innerHTML = "";
var doneCount = 0;
state.tasks.forEach(function(task){
if(task.done) doneCount++;
var li = document.createElement("li");
li.className = "task-row" + (task.done ? " done" : "");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = task.done;
checkbox.id = "chk-" + task.id;
checkbox.addEventListener("change", function(){
task.done = checkbox.checked;
saveState();
renderTasks();
});
var label = document.createElement("label");
label.className = "task-label";
label.setAttribute("for", "chk-" + task.id);
label.textContent = task.text;
var removeBtn = document.createElement("button");
removeBtn.className = "remove-btn";
removeBtn.type = "button";
removeBtn.setAttribute("aria-label", "Taak verwijderen");
removeBtn.textContent = "✕";
removeBtn.addEventListener("click", function(){
state.tasks = state.tasks.filter(function(t){ return t.id !== task.id; });
saveState();
renderTasks();
});
li.appendChild(checkbox);
li.appendChild(label);
li.appendChild(removeBtn);
taskListEl.appendChild(li);
});
taskCountEl.textContent = doneCount + "/" + state.tasks.length;
}
var newTaskInput = document.getElementById("newTaskInput");
var addTaskBtn = document.getElementById("addTaskBtn");
function addTask(){
var val = newTaskInput.value.trim();
if(!val) return;
state.tasks.push({ id: uid("task"), text: val, done: false });
newTaskInput.value = "";
saveState();
renderTasks();
}
addTaskBtn.addEventListener("click", addTask);
newTaskInput.addEventListener("keydown", function(e){
if(e.key === "Enter"){ e.preventDefault(); addTask(); }
});
// ======================================================
// ---------- Bewoners: Dashboard (compact combobox) -----
// ======================================================
var residentSummary = document.getElementById("residentSummary");
var residentSearch = document.getElementById("residentSearch");
var residentSearchWrap = document.getElementById("residentSearchWrap");
var clearResidentSearchBtn = document.getElementById("clearResidentSearch");
var residentDropdown = document.getElementById("residentDropdown");
var residentDetailWrap = document.getElementById("residentDetailWrap");
var sortDropdownWrap = document.getElementById("sortDropdownWrap");
var sortDropdownBtn = document.getElementById("sortDropdownBtn");
var sortDropdownMenu = document.getElementById("sortDropdownMenu");
var sortDropdownLabel = document.getElementById("sortDropdownLabel");
var sortDropdownOptions = sortDropdownMenu.querySelectorAll(".sort-dropdown-option");
function sortedResidents(){
var list = state.residents.slice();
if(state.dashboardSort === "kamer"){
list.sort(function(a, b){
var ra = (a.room || "").trim();
var rb = (b.room || "").trim();
if(ra === "" && rb === "") return a.name.localeCompare(b.name, "nl");
if(ra === "") return 1;
if(rb === "") return -1;
return ra.localeCompare(rb, "nl", { numeric: true, sensitivity: "base" });
});
}else{
list.sort(function(a, b){ return a.name.localeCompare(b.name, "nl"); });
}
return list;
}
function filteredResidents(query){
var q = (query || "").trim().toLowerCase();
var list = sortedResidents();
if(!q) return list;
return list.filter(function(r){ return r.name.toLowerCase().indexOf(q) !== -1; });
}
function renderResidentSummary(){
var seen = 0, absent = 0, unseen = 0;
state.residents.forEach(function(r){
if(r.status === "seen") seen++;
else if(r.status === "absent") absent++;
else unseen++;
});
function tile(num, label, mod){
return '<div class="stat-tile ' + mod + '">' +
'<span class="stat-num">' + num + '</span>' +
'<span class="stat-label">' + label + '</span>' +
'</div>';
}
residentSummary.innerHTML =
tile(seen, "Gezien", "st-seen") +
tile(absent, "Afwezig", "st-absent") +
tile(unseen, "Nog niet gezien", "st-unseen") +
'<div class="stat-total">' + state.residents.length + ' bewoners totaal</div>';
}
function renderResidentDropdown(){
var query = residentSearch.value;
var list = filteredResidents(query);
residentDropdown.innerHTML = "";
var activeBan = query.trim() ? activeBanForName(query) : null;
if(activeBan){
var banWarning = document.createElement("div");
banWarning.className = "resident-dropdown-ban-warning";
var untilText = activeBan.untilDate
? (activeBan.untilDate + (activeBan.untilTime ? " " + activeBan.untilTime : ""))
: "onbekende datum";
banWarning.textContent = "⚠️ LET OP: ACTIEF PANDVERBOD voor " + activeBan.name + " tot " + untilText +
(activeBan.reason ? " (" + activeBan.reason + ")" : "");
residentDropdown.appendChild(banWarning);
}
if(list.length === 0){
var empty = document.createElement("div");
empty.className = "resident-dropdown-empty";
empty.textContent = "Geen bewoners gevonden.";
residentDropdown.appendChild(empty);
return;
}
list.forEach(function(resident){
var row = document.createElement("div");
row.className = "resident-option" + (resident.id === state.dashboardSelectedResidentId ? " selected" : "");
var dot = document.createElement("span");
dot.className = "rdot " + STATUS_META[resident.status].cls;
row.appendChild(dot);
var nameEl = document.createElement("span");
nameEl.className = "roname";
nameEl.textContent = resident.name;
row.appendChild(nameEl);
if(resident.room){
var roomEl = document.createElement("span");
roomEl.className = "roroom";
roomEl.textContent = "Kamer " + resident.room;
row.appendChild(roomEl);
}
row.addEventListener("click", function(){ selectResident(resident.id); });
residentDropdown.appendChild(row);
});
}
function openDropdown(){ renderResidentDropdown(); residentDropdown.classList.add("open"); }
function closeDropdown(){ residentDropdown.classList.remove("open"); }
function updateClearButtonVisibility(){
clearResidentSearchBtn.classList.toggle("visible", residentSearch.value.length > 0);
}
residentSearch.addEventListener("focus", openDropdown);
residentSearch.addEventListener("input", function(){
openDropdown();
updateClearButtonVisibility();
});
residentSearch.addEventListener("keydown", function(e){
if(e.key === "Enter"){
e.preventDefault();
var list = filteredResidents(residentSearch.value);
if(list.length > 0) selectResident(list[0].id);
}else if(e.key === "Escape"){
closeDropdown();
}
});
clearResidentSearchBtn.addEventListener("click", function(){
residentSearch.value = "";
updateClearButtonVisibility();
openDropdown();
residentSearch.focus();
});
document.addEventListener("click", function(e){
if(!residentSearchWrap.contains(e.target)) closeDropdown();
});
function selectResident(id){
state.dashboardSelectedResidentId = id;
var resident = getResidentById(id);
residentSearch.value = resident ? resident.name : "";
updateClearButtonVisibility();
saveState();
closeDropdown();
renderResidentDetail();
}
function buildStatusIndicator(resident){
var wrap = document.createElement("div");
wrap.className = "status-indicator-wrap";
var mainBtn = document.createElement("button");
mainBtn.type = "button";
mainBtn.className = "status-dot-btn";
mainBtn.setAttribute("aria-label", "Status wisselen (huidig: " + STATUS_META[resident.status].label + ")");
var dotSpan = document.createElement("span");
dotSpan.className = "status-dot-visual " + STATUS_META[resident.status].cls;
mainBtn.appendChild(dotSpan);
mainBtn.addEventListener("click", function(){
var idx = STATUS_ORDER.indexOf(resident.status);
resident.status = STATUS_ORDER[(idx + 1) % STATUS_ORDER.length];
afterResidentStatusChange();
});
wrap.appendChild(mainBtn);
var popover = document.createElement("div");
popover.className = "status-popover";
STATUS_ORDER.forEach(function(key){
var opt = document.createElement("button");
opt.type = "button";
opt.className = "status-popover-option";
var d = document.createElement("span");
d.className = "status-dot-visual " + STATUS_META[key].cls;
var t = document.createElement("span");
t.textContent = STATUS_META[key].label;
opt.appendChild(d);
opt.appendChild(t);
opt.addEventListener("click", function(e){
e.stopPropagation();
resident.status = key;
afterResidentStatusChange();
});
popover.appendChild(opt);
});
wrap.appendChild(popover);
function afterResidentStatusChange(){
saveState();
renderResidentDetail();
renderResidentSummary();
if(residentDropdown.classList.contains("open")) renderResidentDropdown();
renderResidentsFullList();
}
return wrap;
}
function buildResidentDetailCard(resident, opts){
opts = opts || {};
var inList = !!opts.inList;
var card = document.createElement("div");
card.className = "resident-detail-card " + STATUS_META[resident.status].cls + (inList ? " in-list" : "");
function makeZorgnedBtn(){
var zorgnedUrl = "https://utrecht.zorgned.nl/prod/applicatie/Regie?lcclientnr=" + encodeURIComponent(resident.clientnr) + "§ion=1";
var btn = document.createElement("button");
btn.type = "button";
btn.className = "zorgned-badge";
var ic = document.createElement("img");
ic.src = "zorgned-icon.png";
ic.alt = "";
ic.className = "zorgned-badge-icon";
btn.appendChild(ic);
btn.appendChild(document.createTextNode("ZorgNed ↗"));
btn.setAttribute("aria-label", "Open cliëntdossier in ZorgNed");
btn.addEventListener("click", function(){ openZorgNedLink(zorgnedUrl); });
return btn;
}
if(!inList){
// Dashboard: de kop toont naam/kamer/status + vorige/volgende-navigatie.
var head = document.createElement("div");
head.className = "resident-detail-head";
var nameWrap = document.createElement("div");
nameWrap.className = "resident-detail-name-wrap";
nameWrap.appendChild(buildStatusIndicator(resident));
var nameEl = document.createElement("span");
nameEl.className = "resident-detail-name";
nameEl.textContent = resident.name;
nameWrap.appendChild(nameEl);
if(resident.room){
var roomBadge = document.createElement("span");
roomBadge.className = "resident-detail-room";
roomBadge.textContent = "Kamer " + resident.room;
nameWrap.appendChild(roomBadge);
}
if(resident.locker){
var lockerBadge = document.createElement("span");
lockerBadge.className = "resident-detail-room";
lockerBadge.textContent = "Kluis " + resident.locker;
nameWrap.appendChild(lockerBadge);
}
if(resident.isAttention){
var attentionBadge = document.createElement("span");
attentionBadge.className = "attention-flag-badge";
attentionBadge.textContent = "🚩 Aandacht";
nameWrap.appendChild(attentionBadge);
}
if(resident.clientnr) nameWrap.appendChild(makeZorgnedBtn());
head.appendChild(nameWrap);
var nav = document.createElement("div");
nav.className = "resident-nav";
var prevBtn = document.createElement("button");
prevBtn.type = "button";
prevBtn.className = "resident-nav-btn";
prevBtn.setAttribute("aria-label", "Vorige bewoner");
prevBtn.textContent = "‹";
prevBtn.addEventListener("click", function(){ navigateResident(-1); });
var nextBtn = document.createElement("button");
nextBtn.type = "button";
nextBtn.className = "resident-nav-btn";
nextBtn.setAttribute("aria-label", "Volgende bewoner");
nextBtn.textContent = "›";
nextBtn.addEventListener("click", function(){ navigateResident(1); });
nav.appendChild(prevBtn);
nav.appendChild(nextBtn);
head.appendChild(nav);
card.appendChild(head);
} else if(resident.clientnr){
// Bewonerslijst: naam/kamer/status staan al in de rij erboven — alleen
// de ZorgNed-actie is hier nog relevant.
var actionRow = document.createElement("div");
actionRow.className = "resident-detail-actions";
actionRow.appendChild(makeZorgnedBtn());
card.appendChild(actionRow);
}
var noteInput = document.createElement("input");
noteInput.type = "text";
noteInput.className = "resident-note";
noteInput.placeholder = "Dienstnotitie, bijv. gesprek 14:00...";
noteInput.value = resident.note || "";
var noteDebounce = null;
noteInput.addEventListener("input", function(){
resident.note = noteInput.value;
if(noteDebounce) clearTimeout(noteDebounce);
noteDebounce = setTimeout(saveState, 350);
});
card.appendChild(noteInput);
var attentionWrap = document.createElement("div");
attentionWrap.className = "attention-toggle-wrap";
var attentionLabel = document.createElement("label");
attentionLabel.className = "attention-toggle-label";
var attentionCheckbox = document.createElement("input");
attentionCheckbox.type = "checkbox";
attentionCheckbox.checked = !!resident.isAttention;
var attentionLabelText = document.createElement("span");
attentionLabelText.textContent = "Op aandachtslijst zetten";
attentionLabel.appendChild(attentionCheckbox);
attentionLabel.appendChild(attentionLabelText);
attentionWrap.appendChild(attentionLabel);
var attentionNoteInput = document.createElement("input");
attentionNoteInput.type = "text";
attentionNoteInput.className = "resident-note attention-note-input";
attentionNoteInput.placeholder = "Waarom aandacht nodig is...";
attentionNoteInput.value = resident.attentionNote || "";
attentionNoteInput.style.display = resident.isAttention ? "block" : "none";
var attentionNoteDebounce = null;
attentionNoteInput.addEventListener("input", function(){
resident.attentionNote = attentionNoteInput.value;
if(attentionNoteDebounce) clearTimeout(attentionNoteDebounce);
attentionNoteDebounce = setTimeout(function(){
saveState();
renderAandachtCard();
}, 350);
});
attentionCheckbox.addEventListener("change", function(){
resident.isAttention = attentionCheckbox.checked;
attentionNoteInput.style.display = resident.isAttention ? "block" : "none";
saveState();
renderResidentDetail();
renderAandachtCard();
renderResidentsFullList();
});
attentionWrap.appendChild(attentionNoteInput);
card.appendChild(attentionWrap);
return card;
}
function renderResidentDetail(){
residentDetailWrap.innerHTML = "";
var resident = getResidentById(state.dashboardSelectedResidentId);
if(!resident){
var empty = document.createElement("div");
empty.className = "resident-detail-empty";
empty.textContent = "Zoek of kies hierboven een bewoner om de status en notitie te bekijken of aan te passen.";
residentDetailWrap.appendChild(empty);
return;
}
residentDetailWrap.appendChild(buildResidentDetailCard(resident));
}
function navigateResident(delta){
var list = sortedResidents();
if(list.length === 0) return;
var idx = list.findIndex(function(r){ return r.id === state.dashboardSelectedResidentId; });
if(idx === -1) idx = 0;
else idx = (idx + delta + list.length) % list.length;
selectResident(list[idx].id);
}
// ======================================================
// ---------- Aandachtsdossiers & Alertheid (Dashboard) --
// ======================================================
var attentionList = document.getElementById("attentionList");
var attentionCountEl = document.getElementById("attentionCount");
function renderAandachtCard(){
var flagged = sortedResidents().filter(function(r){ return r.isAttention; });
attentionCountEl.textContent = flagged.length + (flagged.length === 1 ? " dossier" : " dossiers");
attentionList.innerHTML = "";
if(flagged.length === 0){
var empty = document.createElement("li");
empty.className = "empty-note";
empty.textContent = "Geen actieve aandachtsdossiers.";
attentionList.appendChild(empty);
return;
}
flagged.forEach(function(resident){
var li = document.createElement("li");
li.className = "attention-row";
var main = document.createElement("div");
main.className = "attention-row-main";
var nameEl = document.createElement("span");
nameEl.className = "attention-row-name";
nameEl.textContent = "🚩 " + resident.name;
main.appendChild(nameEl);
if(resident.attentionNote){
var noteEl = document.createElement("div");