-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
827 lines (787 loc) · 30.9 KB
/
app.js
File metadata and controls
827 lines (787 loc) · 30.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
/* ========= Storage & Utilities ========= */
const SESS_KEY='tt.sessions'; // project sessions
const PROJ_KEY='tt.projects';
const ACTIVE_KEY='tt.active';
const DONE_KEY='tt.done'; // array of done project names
const DAY_ACTIVE_KEY='tt.dayActive'; // day timer active
const DAY_SESS_KEY='tt.daySessions'; // day sessions [{start,end}]
const AUTO_CHECKIN_KEY='tt.autoCheckinEnabled';
const AUTO_CHECKOUT_KEY='tt.autoCheckoutEnabled';
const LAST_EXPORT_KEY='tt.lastExportWeekStart';
const LAST_ACTIVITY_KEY='tt.lastActivityMs';
const LAST_AUTO_CHECKOUT_KEY='tt.lastAutoCheckoutMs';
const LAST_AUTO_ACTION_KEY='tt.lastAutoAction';
const LAST_MANUAL_DAY_OUT_KEY='tt.lastManualDayOutMs';
const OFF_DAYS_KEY='tt.offDays';
const LAST_OFF_CHECK_KEY='tt.lastOffCheckDay';
const CORR_KEY='tt.corrections'; // manual corrections [{project,day,deltaMs,at}]
const DAY_MS=24*60*60*1000;
const EIGHT_HOURS_MS=8*60*60*1000;
const BUSINESS_START_HOUR=9;
const BUSINESS_END_HOUR=19;
const $=(id)=>document.getElementById(id);
const el={
projectSelect:$('projectSelect'), newProject:$('newProject'),
addProjectBtn:$('addProjectBtn'), renameProjectBtn:$('renameProjectBtn'),
adjustMinutes:$('adjustMinutes'), adjustMinus:$('adjustMinus'), adjustPlus:$('adjustPlus'),
startBtn:$('startBtn'), stopBtn:$('stopBtn'),
resetActiveBtn:$('resetActiveBtn'), exportWeekBtn:$('exportWeekBtn'),
projectList:$('projectList'), status:$('status'), weekRange:$('weekRange'),
nowTimer:$('nowTimer'), nowProject:$('nowProject'), todayTotal:$('todayTotal'),
todayDate:$('todayDate'), weekTotal:$('weekTotal'), resetAll:$('resetAll'),
bannerText:$('bannerText'),
dayTimer:$('dayTimer'), dayInBtn:$('dayInBtn'), dayOutBtn:$('dayOutBtn'),
autoCheckinBtn:$('autoCheckinBtn'), autoCheckinState:$('autoCheckinState'),
autoCheckoutBtn:$('autoCheckoutBtn'), autoCheckoutState:$('autoCheckoutState'),
dayStatus:$('dayStatus')
};
function load(k,d){ try{ return JSON.parse(localStorage.getItem(k)) ?? d }catch{ return d } }
function save(k,v){ localStorage.setItem(k, JSON.stringify(v)) }
function loadBool(k,d){
const v=load(k,d);
return typeof v === 'boolean' ? v : d;
}
function fmtDuration(ms){
const safe=Math.max(0, ms);
const s=Math.floor(safe/1000);
const hh=String(Math.floor(s/3600)).padStart(2,'0');
const mm=String(Math.floor((s%3600)/60)).padStart(2,'0');
const ss=String(s%60).padStart(2,'0');
return `${hh}:${mm}:${ss}`;
}
function fmtSignedDuration(ms){
const sign=ms<0?'-':'';
return `${sign}${fmtDuration(Math.abs(ms))}`;
}
function startOfToday(){ const d=new Date(); d.setHours(0,0,0,0); return d.getTime(); }
function startOfDay(ms){ const d=new Date(ms); d.setHours(0,0,0,0); return d.getTime(); }
function endOfToday(){ const d=new Date(); d.setHours(23,59,59,999); return d.getTime(); }
function endOfDay(ms){ return startOfDay(ms) + DAY_MS - 1; }
function startOfWeekMonday(){ const d=new Date(); const day=(d.getDay()+6)%7; d.setHours(0,0,0,0); d.setDate(d.getDate()-day); return d.getTime(); }
function endOfWeekMonday(){ const s=startOfWeekMonday(); return s + 7*24*3600*1000 - 1; }
function formatDateRange(ms1,ms2){
const f=(ms)=>new Date(ms).toLocaleDateString(undefined,{weekday:'short',month:'short',day:'numeric'});
return `${f(ms1)} - ${f(ms2)}`;
}
function formatDateShort(ms){ return new Date(ms).toLocaleDateString(undefined,{year:'numeric',month:'2-digit',day:'2-digit'}); }
function formatTime(ms){ return new Date(ms).toLocaleTimeString(); }
function isoWeekInfo(ms){
const d=new Date(ms); d.setHours(0,0,0,0);
d.setDate(d.getDate() + 3 - ((d.getDay()+6)%7)); // shift to Thursday
const week1=new Date(d.getFullYear(),0,4);
const week=1 + Math.round(((d - week1)/DAY_MS - 3 + ((week1.getDay()+6)%7))/7);
return {week, year:d.getFullYear()};
}
function getData(){ return {
projects: load(PROJ_KEY,['General']),
sessions: load(SESS_KEY,[]),
active: load(ACTIVE_KEY,null),
done: new Set(load(DONE_KEY,[])),
dayActive:load(DAY_ACTIVE_KEY,null),
daySess: load(DAY_SESS_KEY,[]),
corrections: load(CORR_KEY,[])
};}
/* ========= Activity & time helpers ========= */
function getLastActivityMs(){
const v=load(LAST_ACTIVITY_KEY,null);
return (typeof v==='number' && !Number.isNaN(v)) ? v : Date.now();
}
let lastActivityCache=getLastActivityMs();
function touchActivity(ms){
const t=ms ?? Date.now();
if(t - lastActivityCache >= 5000){ save(LAST_ACTIVITY_KEY,t); }
lastActivityCache=t;
return t;
}
function isAutoCheckinEnabled(){
return loadBool(AUTO_CHECKIN_KEY,true);
}
function isAutoCheckoutEnabled(){
return loadBool(AUTO_CHECKOUT_KEY,true);
}
function setAutoCheckinEnabled(enabled){
save(AUTO_CHECKIN_KEY, !!enabled);
}
function setAutoCheckoutEnabled(enabled){
save(AUTO_CHECKOUT_KEY, !!enabled);
}
function autoCheckinTooltip(enabled){
return enabled
? 'Automatically checks you in when you first interact during work hours.'
: 'Automatic day check-in is off. Use Check In or start a project to begin the day.';
}
function autoCheckoutTooltip(enabled){
return enabled
? 'Automatically checks you out and stops all timers at the end of the workday.'
: 'Automatic day check-out is off. You will need to check out manually.';
}
function isBusinessHours(ms){
return ms >= workdayStartMs(ms) && ms < workdayEndMs(ms);
}
function workdayStartMs(ms){
return startOfDay(ms) + BUSINESS_START_HOUR*60*60*1000;
}
function workdayEndMs(ms){
return startOfDay(ms) + BUSINESS_END_HOUR*60*60*1000;
}
function autoCheckoutDeadlineMs(startMs){
const workEnd = workdayEndMs(startMs);
return startMs < workEnd ? workEnd : endOfDay(startMs);
}
function getAutoStopTarget(startMs, now=Date.now()){
if(typeof startMs !== 'number' || Number.isNaN(startMs)) return null;
const deadline = autoCheckoutDeadlineMs(startMs);
if(now < deadline) return null;
return {
effectiveAt: deadline,
reason: startOfDay(startMs) < startOfDay(now) ? 'previous-day' : 'workday-end'
};
}
function getLastAutoAction(){
const action = load(LAST_AUTO_ACTION_KEY,null);
if(!action || typeof action.type!=='string' || typeof action.effectiveAt!=='number') return null;
return action;
}
function saveAutoAction(type, reason, effectiveAt, recordedAt=Date.now()){
save(LAST_AUTO_ACTION_KEY,{type, reason, effectiveAt, recordedAt});
}
function clearAutoAction(){
localStorage.removeItem(LAST_AUTO_ACTION_KEY);
}
function getLastManualDayOutMs(){
const v=load(LAST_MANUAL_DAY_OUT_KEY,null);
return (typeof v==='number' && !Number.isNaN(v)) ? v : null;
}
function markDayOffIfNoSessions(dayStart){
const arr = load(DAY_SESS_KEY,[]);
const dayEnd = dayStart + DAY_MS - 1;
const hadSession = arr.some(s=> !(s.end<dayStart || s.start>dayEnd));
if(hadSession) return false;
const offDays = load(OFF_DAYS_KEY,[]);
if(!offDays.includes(dayStart)){
offDays.push(dayStart);
save(OFF_DAYS_KEY, offDays);
}
return true;
}
function maybeMarkPreviousDayOff(){
const today = startOfToday();
const lastChecked = load(LAST_OFF_CHECK_KEY,null);
if(lastChecked === today) return;
const yesterday = today - DAY_MS;
if(yesterday >= 0){
markDayOffIfNoSessions(yesterday);
}
save(LAST_OFF_CHECK_KEY, today);
}
/* ========= Project-level helpers ========= */
function setActive(a){ if(a) save(ACTIVE_KEY,a); else localStorage.removeItem(ACTIVE_KEY); }
function ensureProject(name){
if(!name) return;
const list=load(PROJ_KEY,['General']);
if(!list.includes(name)){ list.push(name); save(PROJ_KEY,list); }
}
function addProject(name){
const d=getData(); if(!name) return;
if(!d.projects.includes(name)){ d.projects.push(name); save(PROJ_KEY,d.projects); }
render(); el.projectSelect.value=name;
}
function getProjectForAdjustment(){
const typed=el.newProject.value.trim();
if(typed){
addProject(typed);
el.newProject.value='';
return typed;
}
const selected=el.projectSelect.value;
if(selected){
ensureProject(selected);
return selected;
}
ensureProject('General');
return 'General';
}
function addCorrection(project,deltaMs,dayOverride){
const name=String(project ?? '').trim();
if(!name || !deltaMs) return;
ensureProject(name);
const day=typeof dayOverride==='number' ? dayOverride : startOfToday();
const arr=load(CORR_KEY,[]);
arr.push({project:name, day, deltaMs, at:Date.now()});
save(CORR_KEY,arr);
render();
}
function correctionsInRange(from,to){
const arr=load(CORR_KEY,[]);
return arr.filter(c=>c.day>=from && c.day<=to);
}
function applyCorrectionsToTotals(totals, corrections){
for(const c of corrections){
totals.set(c.project,(totals.get(c.project)||0)+c.deltaMs);
}
return totals;
}
function applyCorrectionsToPerDay(perDay, corrections){
for(const c of corrections){
const m=perDay.get(c.day) || new Map();
m.set(c.project,(m.get(c.project)||0)+c.deltaMs);
perDay.set(c.day,m);
}
return perDay;
}
function renameProject(oldName,newName){
const from = String(oldName ?? '').trim();
const to = String(newName ?? '').trim();
if(!from || !to || from===to) return;
const projects = load(PROJ_KEY,['General']);
const exists = projects.includes(to);
if(exists && !confirm(`"${to}" already exists. Merge "${from}" into "${to}"?`)) return;
const nextProjects = projects.filter(p=>p!==from);
if(!nextProjects.includes(to)) nextProjects.push(to);
save(PROJ_KEY, nextProjects);
const sessions = load(SESS_KEY,[]).map(s=> s.project===from ? {...s, project: to} : s);
save(SESS_KEY, sessions);
const corrections = load(CORR_KEY,[]).map(c=> c.project===from ? {...c, project: to} : c);
save(CORR_KEY, corrections);
const active = load(ACTIVE_KEY,null);
if(active?.project===from){
save(ACTIVE_KEY,{...active, project: to});
}
const done = load(DONE_KEY,[]);
const isDone = done.includes(from) || done.includes(to);
const nextDone = done.filter(p=>p!==from);
if(isDone && !nextDone.includes(to)) nextDone.push(to);
save(DONE_KEY, nextDone);
render();
el.projectSelect.value = to;
}
function startTimer(project){
const d=getData();
if(d.active){ if(d.active.project===project) return; stopTimer(); }
if(!normalizeDayActive()) dayCheckIn({atMs:Date.now(), source:'auto', reason:'project-start'});
ensureProject(project);
touchActivity();
setActive({project, startEpochMs:Date.now()}); render();
}
function stopTimer(){
stopActiveAt(Date.now());
}
function stopActiveAt(endMs,{skipRender=false}={}){
const d=getData(); if(!d.active) return;
const safeEnd=Math.max(endMs, d.active.startEpochMs);
const sess={project:d.active.project,start:d.active.startEpochMs,end:safeEnd};
const arr=load(SESS_KEY,[]); arr.push(sess); save(SESS_KEY,arr);
setActive(null);
if(!skipRender) render();
}
function stopDayAt(endMs,{skipRender=false}={}){
const dayActive = normalizeDayActive();
if(!dayActive) return;
const safeEnd=Math.max(endMs, dayActive.startEpochMs);
const arr = load(DAY_SESS_KEY,[]);
arr.push({start: dayActive.startEpochMs, end: safeEnd});
save(DAY_SESS_KEY, arr);
localStorage.removeItem(DAY_ACTIVE_KEY);
if(!skipRender) render();
}
function stopAllAt(endMs){
stopActiveAt(endMs,{skipRender:true});
stopDayAt(endMs,{skipRender:true});
render();
}
function markDone(project){
const d=getData();
if(d.active?.project===project) stopTimer();
const arr=load(DONE_KEY,[]);
if(!arr.includes(project)) arr.push(project);
save(DONE_KEY,arr); render();
}
function markUndone(project){
const arr=load(DONE_KEY,[]).filter(p=>p!==project);
save(DONE_KEY,arr); render();
}
function sessionsInRange(from,to){
const arr=load(SESS_KEY,[]);
return arr.flatMap(s=>{
const s1=Math.max(s.start,from); const e1=Math.min(s.end,to);
return (e1>=s1)?[{...s,start:s1,end:e1}]:[];
});
}
function sumByProject(s){
const m=new Map(); for(const x of s){ m.set(x.project,(m.get(x.project)||0)+(x.end-x.start)); } return m;
}
function splitSessionByDay(sess){
const parts=[];
let start=sess.start;
const end=sess.end;
while(start<=end){
const day=startOfDay(start);
const dayEnd=day+DAY_MS-1;
const segEnd=Math.min(end,dayEnd);
parts.push({...sess,start,end:segEnd,day});
start=segEnd+1;
}
return parts;
}
function dailyTotals(segments, corrections=[]){
const map=new Map();
for(const seg of segments){
const day=seg.day ?? startOfDay(seg.start);
map.set(day,(map.get(day)||0)+(seg.end-seg.start));
}
for(const c of corrections){
map.set(c.day,(map.get(c.day)||0)+c.deltaMs);
}
return map;
}
function projectTotalsWithOvertime(segments, corrections=[]){
// Break down normal vs overtime per project, allocating overtime proportionally per day.
const perDay=new Map(); // day -> Map(project, ms)
for(const seg of segments){
const day=seg.day ?? startOfDay(seg.start);
const m=perDay.get(day) || new Map();
m.set(seg.project,(m.get(seg.project)||0)+(seg.end-seg.start));
perDay.set(day,m);
}
applyCorrectionsToPerDay(perDay, corrections);
const totals=new Map(); // project -> {normal, overtime}
for(const [day,map] of perDay.entries()){
const dayTotal=[...map.values()].reduce((a,b)=>a+b,0);
const safeDayTotal=Math.max(0, dayTotal);
const dayOver=Math.max(0, safeDayTotal - EIGHT_HOURS_MS);
const factor=safeDayTotal>0 ? dayOver/safeDayTotal : 0;
for(const [project,ms] of map.entries()){
const overtime=ms*factor;
const normal=ms-overtime;
const agg=totals.get(project)||{normal:0,overtime:0};
agg.normal+=normal; agg.overtime+=overtime;
totals.set(project, agg);
}
}
return totals;
}
function dailyProjectTotalsWithOvertime(segments, corrections=[]){
const perDay=new Map(); // day -> Map(project, ms)
for(const seg of segments){
const day=seg.day ?? startOfDay(seg.start);
const m=perDay.get(day) || new Map();
m.set(seg.project,(m.get(seg.project)||0)+(seg.end-seg.start));
perDay.set(day,m);
}
applyCorrectionsToPerDay(perDay, corrections);
const rows=[];
for(const [day,map] of perDay.entries()){
const dayTotal=[...map.values()].reduce((a,b)=>a+b,0);
const safeDayTotal=Math.max(0, dayTotal);
const dayOver=Math.max(0, safeDayTotal - EIGHT_HOURS_MS);
const factor=safeDayTotal>0 ? dayOver/safeDayTotal : 0;
for(const [project,ms] of map.entries()){
const overtime=ms*factor;
const normal=ms-overtime;
rows.push({day, project, normal, overtime});
}
}
return rows;
}
/* ========= Day timer helpers ========= */
function normalizeDayActive(){
const dayActive = load(DAY_ACTIVE_KEY,null);
if(!dayActive || typeof dayActive.startEpochMs !== 'number'){
localStorage.removeItem(DAY_ACTIVE_KEY);
return null;
}
return dayActive;
}
function getOpenStartMs(){
const dayActive = normalizeDayActive();
const active = load(ACTIVE_KEY,null);
const starts = [];
if(dayActive?.startEpochMs) starts.push(dayActive.startEpochMs);
if(active?.startEpochMs) starts.push(active.startEpochMs);
return starts.length ? Math.min(...starts) : null;
}
function reconcileOpenSessions(now=Date.now()){
if(!isAutoCheckoutEnabled()) return false;
const openStartMs = getOpenStartMs();
const target = getAutoStopTarget(openStartMs, now);
if(!target) return false;
stopAllAt(target.effectiveAt);
save(LAST_AUTO_CHECKOUT_KEY, target.effectiveAt);
saveAutoAction('checkout', target.reason, target.effectiveAt, now);
return true;
}
function dayCheckIn({atMs=Date.now(), source='manual', reason='manual'}={}){
const dayActive = normalizeDayActive();
if(dayActive) return dayActive;
save(DAY_ACTIVE_KEY,{startEpochMs: atMs, source, reason});
localStorage.removeItem(LAST_MANUAL_DAY_OUT_KEY);
touchActivity(atMs);
if(source!=='auto') clearAutoAction();
render();
return normalizeDayActive();
}
function maybeAutoCheckIn(now=Date.now(), reason='activity'){
const lastManualDayOutMs = getLastManualDayOutMs();
if(!isAutoCheckinEnabled() || !isBusinessHours(now) || normalizeDayActive()) return false;
if(lastManualDayOutMs !== null && startOfDay(lastManualDayOutMs) === startOfDay(now)) return false;
dayCheckIn({atMs: now, source:'auto', reason});
saveAutoAction('checkin', reason, now, now);
return true;
}
function dayCheckOut(endOverrideMs, source='manual'){
const endMs = typeof endOverrideMs==='number' ? endOverrideMs : Date.now();
stopAllAt(endMs);
if(source === 'manual'){
save(LAST_MANUAL_DAY_OUT_KEY,endMs);
clearAutoAction();
}
touchActivity(endMs);
}
function daySessionsToday(){
const from = startOfToday(), to = endOfToday();
const arr = load(DAY_SESS_KEY,[]);
return arr.flatMap(s=>{
const s1=Math.max(s.start,from); const e1=Math.min(s.end,to);
return (e1>=s1)?[{start:s1,end:e1}]:[];
});
}
function dayTotalMsNow(activeOverride){
const todayStart = startOfToday();
const sessions = daySessionsToday();
let ms = sessions.reduce((a,s)=>a+(s.end-s.start),0);
const active = activeOverride ?? normalizeDayActive();
if(active){
const activeStart = Math.max(active.startEpochMs, todayStart);
ms += (Date.now() - activeStart);
}
return ms;
}
function buildDayStatus(dayAct){
if(dayAct){
return dayAct.source === 'auto'
? `Checked in automatically at ${formatTime(dayAct.startEpochMs)}`
: 'Checked in';
}
const action = getLastAutoAction();
if(action?.type === 'checkout' && startOfDay(action.effectiveAt) === startOfToday()){
return `Auto checked out at ${formatTime(action.effectiveAt)}`;
}
return 'Not checked in';
}
/* ========= Export ========= */
function exportCSVForRange(from,to, filename){
const sessions=sessionsInRange(from,to);
const segments=sessions.flatMap(splitSessionByDay).sort((a,b)=>a.start-b.start);
const corrections=correctionsInRange(from,to);
const dayTotalsMap=dailyTotals(segments, corrections);
const projectTotals=sumByProject(sessions);
applyCorrectionsToTotals(projectTotals, corrections);
const projectTotalsOT=projectTotalsWithOvertime(segments, corrections);
const dailyProjectTotals=dailyProjectTotalsWithOvertime(segments, corrections);
const rows=[['Date','Project','Start','End','Duration (hh:mm:ss)','Day total','Overtime?','Overtime (hh:mm:ss)']];
for(const seg of segments){
const dayTotal=dayTotalsMap.get(seg.day)||0;
const overtimeMs=Math.max(0, dayTotal - EIGHT_HOURS_MS);
rows.push([
formatDateShort(seg.day),
seg.project,
formatTime(seg.start),
formatTime(seg.end),
fmtDuration(seg.end - seg.start),
fmtDuration(dayTotal),
overtimeMs>0?'Yes':'No',
fmtDuration(overtimeMs)
]);
}
for(const c of corrections){
const dayTotal=dayTotalsMap.get(c.day)||0;
const overtimeMs=Math.max(0, dayTotal - EIGHT_HOURS_MS);
rows.push([
formatDateShort(c.day),
c.project,
'Correction',
'',
fmtSignedDuration(c.deltaMs),
fmtDuration(dayTotal),
overtimeMs>0?'Yes':'No',
fmtDuration(overtimeMs)
]);
}
rows.push([]);
rows.push(['Daily totals T/O']);
rows.push(['Date','Project','Time (hh:mm:ss)','Overtime (hh:mm:ss)']);
for(const item of dailyProjectTotals.sort((a,b)=> a.day===b.day ? a.project.localeCompare(b.project) : a.day-b.day)){
const total=item.normal + item.overtime;
rows.push([
formatDateShort(item.day),
item.project,
fmtDuration(total),
fmtDuration(item.overtime)
]);
}
rows.push([]);
rows.push(['Project totals T/O']);
rows.push(['Project','Time (hh:mm:ss)','Overtime (hh:mm:ss)']);
for(const p of [...projectTotals.keys()].sort((a,b)=>a.localeCompare(b))){
const totals = projectTotalsOT.get(p) || {normal:0,overtime:0};
rows.push([p, fmtDuration(totals.normal), fmtDuration(totals.overtime)]);
}
rows.push([]);
rows.push(['Project totals (sum)']);
rows.push(['Project','Total (hh:mm:ss)']);
for(const p of [...projectTotals.keys()].sort((a,b)=>a.localeCompare(b))){
rows.push([p, fmtDuration(projectTotals.get(p)||0)]);
}
const csv=rows.map(r=>r.map(v=>`"${String(v).replace(/"/g,'""')}"`).join(',')).join('\n');
const blob=new Blob([csv],{type:'text/csv'}); const url=URL.createObjectURL(blob);
const a=document.createElement('a'); a.href=url; a.download=filename; a.click(); URL.revokeObjectURL(url);
}
function maybeAutoExport(){
const currentWeekStart=startOfWeekMonday();
const lastExportWeekStart=load(LAST_EXPORT_KEY,null);
if(lastExportWeekStart===null){ save(LAST_EXPORT_KEY,currentWeekStart); return; }
if(currentWeekStart>lastExportWeekStart){
const from=lastExportWeekStart, to=lastExportWeekStart+7*24*3600*1000-1;
exportCSVForRange(from,to, `times_${formatDateShort(from)}_to_${formatDateShort(to)}.csv`);
save(LAST_EXPORT_KEY,currentWeekStart);
}
}
/* ========= Banner text (multi-project, colored by status) ========= */
function escapeHtml(s){ return String(s).replace(/[&<>"']/g,m=>({ '&':'&','<':'<','>':'>','"':'"',"'":''' }[m])); }
function buildBannerHTML(){
const {projects, sessions, active, done} = getData();
const now=Date.now();
const weekStart=startOfWeekMonday();
const weekEnd=endOfWeekMonday();
const weekSessions=sessionsInRange(weekStart, weekEnd);
const weekCorrections=correctionsInRange(weekStart, weekEnd);
const totals=sumByProject(weekSessions);
applyCorrectionsToTotals(totals, weekCorrections);
if(active){
const extraFrom=Math.max(active.startEpochMs,weekStart);
if(now>=extraFrom) totals.set(active.project,(totals.get(active.project)||0)+(now-extraFrom));
}
const names=[...new Set([...projects, ...totals.keys()])].sort((a,b)=>a.localeCompare(b));
const parts=[];
for(const name of names){
const isRunning = active?.project === name;
const isDone = done.has(name);
const runField = isRunning ? fmtDuration(now - active.startEpochMs)
: isDone ? '' // done: "Name | total"
: '00:00:00'; // stopped: "Name 00:00:00 | total"
const totalField = fmtDuration(totals.get(name)||0);
const cls = isRunning ? 'running' : (isDone ? 'done' : 'notrunning');
const left = isDone ? `${escapeHtml(name)} | ${totalField}`
: `${escapeHtml(name)} ${runField} | ${totalField}`;
parts.push(`<span class="proj ${cls}">${left}</span>`);
}
// No ALL total; use diamond separators with spacing.
return parts.join(`<span class="sep">◆</span>`);
}
/* ========= UI Render ========= */
function render(){
const {projects, sessions, active, done} = getData();
// Picker
const prevSelection = el.projectSelect.value;
el.projectSelect.innerHTML = projects.map(p=>`<option value="${p}">${p}</option>`).join('');
if(prevSelection && projects.includes(prevSelection)){
el.projectSelect.value = prevSelection;
} else if(projects.length){
el.projectSelect.value=projects[0];
}
// Week label
const weekInfo = isoWeekInfo(startOfWeekMonday());
el.weekRange.textContent = `Week ${weekInfo.week} (${weekInfo.year}): ${formatDateRange(startOfWeekMonday(), endOfWeekMonday())}`;
// Per-project list (this week)
const weekStart=startOfWeekMonday();
const weekEnd=endOfWeekMonday();
const weekSessions=sessionsInRange(weekStart, weekEnd);
const weekCorrections=correctionsInRange(weekStart, weekEnd);
const totals=sumByProject(weekSessions);
applyCorrectionsToTotals(totals, weekCorrections);
if(active){
const now=Date.now(), extraFrom=Math.max(active.startEpochMs,weekStart);
if(now>=extraFrom) totals.set(active.project,(totals.get(active.project)||0)+(now-extraFrom));
}
const names=[...new Set([...projects, ...totals.keys()])].sort((a,b)=>a.localeCompare(b));
el.projectList.innerHTML=names.map(name=>{
const isActive=active?.project===name;
const isDone=done.has(name);
const ms=totals.get(name)||0;
const esc=escapeHtml(name);
return `
<div class="project">
<div class="project-meta">
<div class="pname">${esc} ${isActive?'<span class="muted">(running)</span>':''} ${isDone?'<span class="muted">(done)</span>':''}</div>
<div class="muted">This week: ${fmtDuration(ms)}</div>
</div>
<div class="row" style="gap:8px">
${isActive?`<button data-act="stop" data-p="${esc}">Stop</button>`:`<button class="btn-ok" data-act="start" data-p="${esc}">Start</button>`}
${isDone?`<button class="btn-undone" data-act="undone" data-p="${esc}">Undone</button>`
:`<button class="btn-done" data-act="done" data-p="${esc}">Done</button>`}
<button class="btn-danger" data-act="resetOne" data-p="${esc}">Reset</button>
</div>
</div>
`;
}).join('');
// Panels
if(active){ el.status.textContent=`Running: ${active.project}`; el.nowProject.textContent=active.project; }
else { el.status.textContent='Idle'; el.nowProject.textContent='—'; }
// Today + week (projects)
const todayStart=startOfToday();
const todayEnd=endOfToday();
const todaySessions=sessionsInRange(todayStart, todayEnd);
const todayCorrections=correctionsInRange(todayStart, todayEnd);
const todayCorrectionMs=todayCorrections.reduce((a,c)=>a+c.deltaMs,0);
let todayMs=todaySessions.reduce((a,s)=>a+(s.end-s.start),0);
if(active && active.startEpochMs>=todayStart){ todayMs += (Date.now()-active.startEpochMs); }
todayMs += todayCorrectionMs;
el.todayTotal.textContent=fmtDuration(todayMs);
el.todayDate.textContent=new Date().toLocaleDateString(undefined,{weekday:'long',month:'short',day:'numeric'});
const weekMs=Array.from(totals.values()).reduce((a,b)=>a+b,0);
el.weekTotal.textContent=fmtDuration(weekMs);
// Day timer panel
const dayAct = normalizeDayActive();
const dayMs = dayTotalMsNow(dayAct);
el.dayTimer.textContent = fmtDuration(dayMs);
el.dayStatus.textContent = buildDayStatus(dayAct);
const autoCheckinEnabled = isAutoCheckinEnabled();
el.autoCheckinState.textContent = autoCheckinEnabled ? 'On' : 'Off';
el.autoCheckinBtn.classList.toggle('is-on', autoCheckinEnabled);
el.autoCheckinBtn.classList.toggle('is-off', !autoCheckinEnabled);
el.autoCheckinBtn.setAttribute('aria-checked', String(autoCheckinEnabled));
el.autoCheckinBtn.setAttribute('data-tooltip', autoCheckinTooltip(autoCheckinEnabled));
const autoCheckoutEnabled = isAutoCheckoutEnabled();
el.autoCheckoutState.textContent = autoCheckoutEnabled ? 'On' : 'Off';
el.autoCheckoutBtn.classList.toggle('is-on', autoCheckoutEnabled);
el.autoCheckoutBtn.classList.toggle('is-off', !autoCheckoutEnabled);
el.autoCheckoutBtn.setAttribute('aria-checked', String(autoCheckoutEnabled));
el.autoCheckoutBtn.setAttribute('data-tooltip', autoCheckoutTooltip(autoCheckoutEnabled));
// Banner HTML (colored per project)
el.bannerText.innerHTML = buildBannerHTML();
}
/* ========= Timers & events ========= */
setInterval(()=>{
const a=load(ACTIVE_KEY,null);
el.nowTimer.textContent = a ? fmtDuration(Date.now()-a.startEpochMs) : '00:00:00';
// day timer tick
const dayAct = normalizeDayActive();
el.dayTimer.textContent = fmtDuration(dayTotalMsNow(dayAct));
render();
},1000);
function resetProjectWeek(p){
const from=startOfWeekMonday(), to=endOfWeekMonday();
const arr=load(SESS_KEY,[]);
const kept=arr.filter(s=>{
const overlap=!(s.end<from||s.start>to);
if(!overlap) return true;
return s.project!==p;
});
save(SESS_KEY,kept);
const corr=load(CORR_KEY,[]).filter(c=> !(c.project===p && c.day>=from && c.day<=to));
save(CORR_KEY,corr);
render();
}
/* Buttons & delegation */
el.exportWeekBtn.addEventListener('click', ()=>{
const from=startOfWeekMonday(), to=endOfWeekMonday();
exportCSVForRange(from,to, `times_${formatDateShort(from)}_to_${formatDateShort(to)}.csv`);
});
el.addProjectBtn.addEventListener('click', ()=>{
const txt=el.newProject.value.trim();
if(txt){ addProject(txt); el.newProject.value=''; } else if(el.projectSelect.value){ render(); }
});
el.renameProjectBtn.addEventListener('click', ()=>{
const from = el.projectSelect.value;
const to = el.newProject.value.trim();
if(!from || !to) return;
renameProject(from, to);
el.newProject.value='';
});
el.adjustMinus.addEventListener('click', ()=>{
const mins=Number(el.adjustMinutes.value)||0;
if(mins<=0) return;
const p=getProjectForAdjustment();
addCorrection(p, -mins*60*1000);
});
el.adjustPlus.addEventListener('click', ()=>{
const mins=Number(el.adjustMinutes.value)||0;
if(mins<=0) return;
const p=getProjectForAdjustment();
addCorrection(p, mins*60*1000);
});
el.startBtn.addEventListener('click', ()=>{
const p=el.projectSelect.value || el.newProject.value.trim() || 'General';
addProject(p); startTimer(p);
});
el.stopBtn.addEventListener('click', ()=> stopTimer());
el.resetActiveBtn.addEventListener('click', ()=>{
const p=el.projectSelect.value; if(!p) return;
if(confirm(`Reset THIS WEEK for "${p}"?`)) resetProjectWeek(p);
});
el.resetAll.addEventListener('click', ()=>{
if(confirm('Delete ALL data?')){
localStorage.removeItem(SESS_KEY); localStorage.removeItem(PROJ_KEY);
localStorage.removeItem(ACTIVE_KEY); localStorage.removeItem(DONE_KEY);
localStorage.removeItem(DAY_ACTIVE_KEY); localStorage.removeItem(DAY_SESS_KEY);
localStorage.removeItem(AUTO_CHECKIN_KEY); localStorage.removeItem(AUTO_CHECKOUT_KEY);
localStorage.removeItem(LAST_EXPORT_KEY); localStorage.removeItem(LAST_ACTIVITY_KEY);
localStorage.removeItem(LAST_AUTO_CHECKOUT_KEY); localStorage.removeItem(LAST_AUTO_ACTION_KEY);
localStorage.removeItem(LAST_MANUAL_DAY_OUT_KEY);
localStorage.removeItem(OFF_DAYS_KEY); localStorage.removeItem(LAST_OFF_CHECK_KEY);
localStorage.removeItem(CORR_KEY);
render();
}
});
el.projectList.addEventListener('click',(e)=>{
const btn=e.target.closest('button'); if(!btn) return;
const act=btn.dataset.act; const p=btn.dataset.p;
if(act==='start'){ addProject(p); startTimer(p); }
if(act==='stop'){ stopTimer(); }
if(act==='done'){ markDone(p); }
if(act==='undone'){ markUndone(p); }
if(act==='resetOne'){
if(confirm(`Reset THIS WEEK for "${p}"?`)) resetProjectWeek(p);
}
});
el.dayInBtn.addEventListener('click', ()=>dayCheckIn());
el.dayOutBtn.addEventListener('click', ()=>dayCheckOut());
el.autoCheckinBtn.addEventListener('click', (e)=>{
e.stopPropagation();
setAutoCheckinEnabled(!isAutoCheckinEnabled());
render();
});
el.autoCheckoutBtn.addEventListener('click', (e)=>{
e.stopPropagation();
setAutoCheckoutEnabled(!isAutoCheckoutEnabled());
render();
});
/* Activity tracking */
function handleWorkActivity(reason='activity'){
const now = Date.now();
maybeAutoCheckIn(now, reason);
touchActivity(now);
}
function handleResume(reason='resume'){
const now = Date.now();
reconcileOpenSessions(now);
maybeAutoCheckIn(now, reason);
touchActivity(now);
}
['mousemove','keydown','click'].forEach(evt=>{
document.addEventListener(evt, ()=>handleWorkActivity(evt));
});
document.addEventListener('visibilitychange', ()=>{
if(!document.hidden) handleResume('visibility');
});
window.addEventListener('focus', ()=>handleResume('focus'));
touchActivity(getLastActivityMs()); // seed cached activity
maybeMarkPreviousDayOff();
/* Auto-export weekly rollover */
setInterval(maybeAutoExport, 60*1000);
setInterval(()=>reconcileOpenSessions(Date.now()), 60*1000);
setInterval(maybeMarkPreviousDayOff, 60*60*1000);
maybeAutoExport();
/* Initial render */
if(!document.hidden && document.hasFocus()) handleResume('load');
render();