-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
740 lines (679 loc) · 27.9 KB
/
Copy pathcontent.js
File metadata and controls
740 lines (679 loc) · 27.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
// Content script: runs on *.timr.com and performs UI automation in the timeline page.
// Strategy: open the global "+ Arbeitszeit" / "+ Projektzeit nachtragen" dialogs and
// fill them via label-based field lookup. CSS class names are avoided (Angular/Material
// often hashes them); we use visible text + aria-labels + label associations instead.
(() => {
if (window.__timrAutoInserterLoaded) return;
window.__timrAutoInserterLoaded = true;
/* ============================================================
* Selector configuration — tweak here if timr's UI changes.
* Each entry is a list of strategies tried in order.
* ============================================================ */
const SELECTORS = {
addArbeitszeit: [
{ byText: '+ Arbeitszeit' },
{ byText: 'Arbeitszeit', containsOnly: true, exclude: ['nachtragen', 'hinzufügen'] },
{ aria: 'Arbeitszeit hinzufügen' },
],
addProjektzeit: [
{ byText: '+ Projektzeit nachtragen' },
{ byText: 'Projektzeit nachtragen' },
{ aria: 'Projektzeit nachtragen' },
],
// Specific dialogs (so we can pick "our" modal even if an error popup is on top).
arbeitszeitDialog: '.modal-content.border-ATTENDANCE_TIME',
projektzeitDialog: '.modal-content.border-PROJECT_TIME',
modalContainer: [
'.modal-content.border-ATTENDANCE_TIME',
'.modal-content.border-PROJECT_TIME',
'mat-dialog-container',
'[role="dialog"]',
'.modal-dialog',
'.cdk-overlay-pane',
],
saveButton: [
{ byText: 'Speichern' },
{ byText: 'Hinzufügen' },
{ byText: 'Übernehmen' },
{ byText: 'Save' },
],
cancelButton: [
{ byText: 'Abbrechen' },
{ byText: 'Schließen' },
{ byText: 'Cancel' },
],
};
/* ============================================================
* Logging — sends progress messages back to the popup.
* ============================================================ */
function log(text) {
console.log('[TimrAutoInserter]', text);
try {
chrome.runtime.sendMessage({ type: 'TIMR_PROGRESS', text });
} catch (_) {}
}
/* ============================================================
* Utilities
* ============================================================ */
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function isVisible(el) {
if (!el) return false;
const rect = el.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return false;
const style = window.getComputedStyle(el);
return style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0';
}
function textOf(el) {
return (el.innerText || el.textContent || '').trim();
}
/** Find clickable element (button/a/[role=button]) whose visible text matches. */
function findClickableByText(text, root = document) {
const norm = (s) => s.replace(/\s+/g, ' ').trim().toLowerCase();
const target = norm(text);
const candidates = root.querySelectorAll('button, a, [role="button"], mat-button, [mat-button], [mat-raised-button], [mat-flat-button], [mat-stroked-button]');
for (const el of candidates) {
if (!isVisible(el)) continue;
if (norm(textOf(el)) === target) return el;
}
for (const el of candidates) {
if (!isVisible(el)) continue;
if (norm(textOf(el)).includes(target)) return el;
}
return null;
}
function findClickableByAria(aria, root = document) {
const sels = [`[aria-label="${aria}"]`, `[aria-label*="${aria}"]`, `[title="${aria}"]`, `[title*="${aria}"]`];
for (const sel of sels) {
const els = root.querySelectorAll(sel);
for (const el of els) if (isVisible(el)) return el;
}
return null;
}
function findClickable(strategies, root = document) {
for (const s of strategies) {
if (s.byText) {
const el = findClickableByText(s.byText, root);
if (el) return el;
}
if (s.aria) {
const el = findClickableByAria(s.aria, root);
if (el) return el;
}
}
return null;
}
async function waitFor(fn, timeoutMs = 6000, intervalMs = 100) {
const t0 = Date.now();
while (Date.now() - t0 < timeoutMs) {
const v = fn();
if (v) return v;
await sleep(intervalMs);
}
return null;
}
function findModal() {
for (const sel of SELECTORS.modalContainer) {
const els = document.querySelectorAll(sel);
for (const el of els) if (isVisible(el)) return el;
}
return null;
}
/* ============================================================
* Framework-safe value setter — works across React/Angular/Vue.
* Sets the value bypassing the framework's property descriptor,
* then dispatches the input/change events the framework listens to.
* ============================================================ */
function setNativeValue(el, value) {
const tag = el.tagName;
const proto = tag === 'TEXTAREA' ? HTMLTextAreaElement.prototype
: tag === 'SELECT' ? HTMLSelectElement.prototype
: HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, 'value').set;
setter.call(el, value);
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
el.dispatchEvent(new Event('blur', { bubbles: true }));
}
/** Find an input by an associated label text within a root. */
function findFieldByLabel(labelText, root = document) {
const norm = (s) => s.replace(/\s+/g, ' ').trim().toLowerCase();
const target = norm(labelText);
const labels = root.querySelectorAll('label, mat-label, .mat-form-field-label, .field-label');
for (const lab of labels) {
if (norm(textOf(lab)) !== target && !norm(textOf(lab)).startsWith(target)) continue;
const forId = lab.getAttribute('for');
if (forId) {
const f = document.getElementById(forId);
if (f) return f;
}
const wrap = lab.closest('mat-form-field, .form-field, .field, .input-wrapper, div, td, tr');
if (wrap) {
const inp = wrap.querySelector('input, textarea, select, [contenteditable="true"]');
if (inp) return inp;
}
let sib = lab.nextElementSibling;
while (sib) {
const inp = sib.matches?.('input, textarea, select') ? sib : sib.querySelector?.('input, textarea, select');
if (inp) return inp;
sib = sib.nextElementSibling;
}
}
return null;
}
/** Type into a field that may be a native input or a custom autocomplete. */
async function fillField(labelText, value, root = document) {
const field = findFieldByLabel(labelText, root);
if (!field) {
log(` ⚠ Feld "${labelText}" nicht gefunden`);
return false;
}
field.focus();
if (field.tagName === 'SELECT') {
const opt = [...field.options].find((o) => o.text.trim().toLowerCase() === value.toLowerCase()
|| o.text.trim().toLowerCase().includes(value.toLowerCase()));
if (opt) {
field.value = opt.value;
field.dispatchEvent(new Event('change', { bubbles: true }));
return true;
}
return false;
}
setNativeValue(field, value);
return true;
}
/**
* Pick an option from a custom autocomplete/dropdown:
* focus + type the value, wait for an option to appear, click it.
*/
async function selectAutocomplete(labelText, value, root = document) {
const field = findFieldByLabel(labelText, root);
if (!field) {
log(` ⚠ Auswahl "${labelText}" nicht gefunden`);
return false;
}
field.focus();
setNativeValue(field, value);
// Wait for option list
const option = await waitFor(() => {
const lists = document.querySelectorAll('mat-option, [role="option"], .dropdown-item, li');
for (const o of lists) {
if (!isVisible(o)) continue;
const t = textOf(o).toLowerCase();
if (t && t.includes(value.toLowerCase())) return o;
}
return null;
}, 3000);
if (option) {
option.click();
return true;
}
// Fallback: just leave the typed value and hope the form accepts it
field.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
return true;
}
/* ============================================================
* jQuery-aware setter — timr uses Bootstrap + jQuery daterangepicker/timepicker.
* Sets the value and triggers both native + jQuery events.
* ============================================================ */
function $$() { return window.jQuery || window.$; }
function setInputValue(el, value) {
if (!el) return false;
setNativeValue(el, value);
const jq = $$();
if (jq) {
try { jq(el).val(value).trigger('change').trigger('keyup').trigger('blur'); } catch (_) {}
}
return true;
}
function setByName(modal, name, value) {
const el = modal.querySelector(`[name="${CSS.escape(name)}"]`);
if (!el) { log(` ⚠ Feld name="${name}" nicht gefunden`); return false; }
return setInputValue(el, value);
}
function setById(root, id, value) {
const el = root.querySelector(`#${CSS.escape(id)}`) || document.getElementById(id);
if (!el) { log(` ⚠ Feld id="${id}" nicht gefunden`); return false; }
return setInputValue(el, value);
}
function selectOptionByText(select, text) {
if (!select) return false;
const opt = [...select.options].find((o) =>
o.text.trim().toLowerCase() === text.toLowerCase()
|| o.text.trim().toLowerCase().includes(text.toLowerCase()));
if (!opt) { log(` ⚠ Select-Option "${text}" nicht gefunden`); return false; }
select.value = opt.value;
select.dispatchEvent(new Event('change', { bubbles: true }));
const jq = $$();
if (jq) { try { jq(select).val(opt.value).trigger('change'); } catch (_) {} }
return true;
}
function setCheckbox(el, checked) {
if (!el) return false;
if (el.checked === checked) return true;
el.click();
return true;
}
/* ============================================================
* High-level actions
* ============================================================ */
function formatDateDE(iso) {
// iso: YYYY-MM-DD -> DD.MM.YYYY
const [y, m, d] = iso.split('-');
return `${d}.${m}.${y}`;
}
/**
* Open one of our target dialogs and return the *.modal-content* element so we can
* scope all further queries to it (avoids confusion when a "Fehler" popup appears on top).
*/
async function openModalVia(strategies, label, dialogSelector) {
log(`Öffne Dialog: ${label}`);
const btn = findClickable(strategies);
if (!btn) throw new Error(`Button "${label}" nicht gefunden`);
btn.click();
const modal = await waitFor(() => {
if (dialogSelector) {
const m = document.querySelector(dialogSelector);
if (m && isVisible(m)) return m;
}
return findModal();
}, 4000);
if (!modal) throw new Error(`Dialog "${label}" wurde nicht geöffnet`);
await sleep(400);
dumpModalStructure(modal, label);
return modal;
}
/** Find a "Fehler" error popup (red bootstrap modal with an Ok button) sitting on top. */
function findErrorModal() {
const titles = document.querySelectorAll('.modal-title, .modal-header h4, .modal-header h3');
for (const t of titles) {
if (!isVisible(t)) continue;
if (/^fehler/i.test(textOf(t))) {
return t.closest('.modal-content, .modal-dialog, [role="dialog"]') || t.parentElement;
}
}
return null;
}
async function dismissErrorModal(errModal) {
const text = textOf(errModal.querySelector('.modal-body') || errModal).replace(/\s+/g, ' ').trim().slice(0, 200);
const ok = findClickableByText('Ok', errModal) || findClickableByText('OK', errModal);
if (ok) ok.click();
await sleep(250);
return text;
}
/**
* Diagnostic: log every input/select/textarea/checkbox inside the modal with its
* best-guess label. Run this once with Trockenlauf to discover the real field names.
*/
function dumpModalStructure(modal, dialogLabel) {
const items = [];
const fields = modal.querySelectorAll('input, select, textarea, mat-select, [role="combobox"], [role="textbox"], [contenteditable="true"]');
fields.forEach((f, i) => {
items.push({
'#': i,
tag: f.tagName.toLowerCase(),
type: f.getAttribute('type') || '',
name: f.getAttribute('name') || '',
id: f.id || '',
placeholder: f.getAttribute('placeholder') || '',
ariaLabel: f.getAttribute('aria-label') || '',
label: labelTextFor(f, modal),
value: ('value' in f ? f.value : '') || f.textContent?.trim().slice(0, 30) || '',
});
});
console.groupCollapsed(`[TimrAutoInserter] Modal-Struktur: "${dialogLabel}" (${items.length} Felder)`);
console.table(items);
console.log('outerHTML-Auszug:', modal.outerHTML.slice(0, 4000));
console.groupEnd();
log(` ⓘ Modal-Struktur in DevTools-Konsole geloggt (${items.length} Felder)`);
}
/** Best-effort label text for a field: <label for>, ancestor label, sibling label, aria-label, placeholder. */
function labelTextFor(field, root) {
if (field.id) {
const lab = root.querySelector(`label[for="${CSS.escape(field.id)}"]`);
if (lab) return textOf(lab);
}
let p = field.parentElement;
for (let i = 0; i < 6 && p; i++, p = p.parentElement) {
const lab = p.querySelector(':scope > label, :scope > mat-label, :scope > .label, :scope > .field-label');
if (lab && lab !== field) return textOf(lab);
}
p = field.parentElement;
for (let i = 0; i < 4 && p; i++, p = p.parentElement) {
const prevLab = p.previousElementSibling;
if (prevLab && /label/i.test(prevLab.tagName)) return textOf(prevLab);
}
return field.getAttribute('aria-label') || field.getAttribute('placeholder') || '';
}
async function closeModal(modal) {
const btn = findClickable(SELECTORS.cancelButton, modal) || findClickableByAria('Schließen', modal) || findClickableByAria('schließen', modal);
if (btn) btn.click();
await sleep(200);
}
async function saveModal(modal) {
const btn = findClickable(SELECTORS.saveButton, modal);
if (!btn) throw new Error('Speichern-Button nicht gefunden');
if (btn.disabled || btn.classList.contains('disabled') || btn.getAttribute('aria-disabled') === 'true') {
throw new Error('Speichern-Button ist deaktiviert (Formularvalidierung fehlgeschlagen)');
}
btn.click();
// Wait for either: success (modal closes) OR Fehler popup appears
const outcome = await waitFor(() => {
const err = findErrorModal();
if (err) return { kind: 'error', el: err };
if (!document.contains(modal) || !isVisible(modal)) return { kind: 'closed' };
return null;
}, 6000);
if (!outcome) throw new Error('Dialog wurde nach Speichern nicht geschlossen (Timeout)');
if (outcome.kind === 'error') {
const msg = await dismissErrorModal(outcome.el);
// Also close our underlying modal so the next iteration can proceed
try { await closeModal(modal); } catch (_) {}
throw new Error(`Validierungsfehler: ${msg}`);
}
await sleep(150);
}
/**
* Fill the working-time ("Arbeitszeit") dialog for one day.
* Uses the discovered `name=` attributes from the actual timr DOM.
*/
async function insertArbeitszeit(modal, { iso, settings }) {
const dateStr = formatDateDE(iso);
// Art (select). Usually pre-set to Anwesenheitszeit, but enforce it.
const typeSelect = modal.querySelector('select[name="workingTimeType.id"]');
if (typeSelect) {
const okType = selectOptionByText(typeSelect, 'Anwesenheitszeit');
if (!okType) log(' ⚠ Option "Anwesenheitszeit" nicht im Art-Select gefunden');
}
setByName(modal, 'startDate', dateStr);
setByName(modal, 'startTime', settings.startTime);
setByName(modal, 'endDate', dateStr);
setByName(modal, 'endTime', settings.endTime);
setByName(modal, 'breakTime', String(settings.includeBreak === false ? 0 : settings.breakMin));
await sleep(150); // let validators run
}
/**
* Fill the project-time ("Projektzeit nachtragen") dialog for one day.
* Field names are largely shared with the working-time dialog; the task picker
* is the new piece — it's likely a typeahead input (twitter-typeahead).
*/
async function insertProjektzeit(modal, { iso, settings }) {
const dateStr = formatDateDE(iso);
// Task / Aufgabe — twitter-typeahead style autocomplete.
await pickTask(modal, settings.taskName);
setByName(modal, 'startDate', dateStr);
setByName(modal, 'startTime', settings.startTime);
setByName(modal, 'endDate', dateStr);
setByName(modal, 'endTime', settings.endTime);
setByName(modal, 'breakTime', String(settings.includeBreak === false ? 0 : settings.breakMin));
// Verrechenbar checkbox (try a few common names/markers).
const billable = modal.querySelector('input[name="billable"], input[name="chargeable"], input[name="invoiceable"], input[type="checkbox"].billable, input[type="checkbox"].chargeable');
if (billable) {
setCheckbox(billable, !!settings.verrechenbar);
} else {
// Fallback: label text "Verrechenbar"
const lab = [...modal.querySelectorAll('label')].find((l) => /verrechenbar/i.test(textOf(l)));
if (lab) {
const cb = lab.querySelector('input[type="checkbox"]')
|| document.getElementById(lab.getAttribute('for') || '')
|| lab.parentElement?.querySelector('input[type="checkbox"]');
if (cb) setCheckbox(cb, !!settings.verrechenbar);
}
}
await sleep(150);
}
/**
* Pick a task in the typeahead. Strategy: find the typeahead input (the visible one,
* not the hint), focus, type the value, wait for a menu option matching the value, click it.
*/
async function pickTask(modal, taskName) {
// Visible typeahead input is usually the second tt-input, or just tt-input not tt-hint.
const candidates = [
...modal.querySelectorAll('input.tt-input:not(.tt-hint)'),
...modal.querySelectorAll('input[data-task-combobox-filter]'),
...modal.querySelectorAll('input[data-toggle="autocomplete"]'),
];
const input = candidates.find((el) => isVisible(el));
if (!input) {
log(' ⚠ Aufgabe-Eingabefeld (Typeahead) nicht gefunden — bitte Projektzeit-Dialog-HTML prüfen');
return false;
}
input.focus();
setInputValue(input, taskName);
// Trigger keyup so the typeahead queries
input.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, key: 'g' }));
const jq = $$();
if (jq) { try { jq(input).trigger('input').trigger('keyup'); } catch (_) {} }
const option = await waitFor(() => {
const suggestions = document.querySelectorAll('.tt-suggestion, .tt-selectable, [role="option"], li.dropdown-item');
for (const s of suggestions) {
if (!isVisible(s)) continue;
if (textOf(s).toLowerCase().includes(taskName.toLowerCase())) return s;
}
return null;
}, 3000);
if (option) {
option.click();
// Some typeaheads need a mousedown to commit
option.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
await sleep(150);
return true;
}
log(` ⚠ Keine Vorschläge für Aufgabe "${taskName}" gefunden`);
return false;
}
/* ============================================================
* Timeline navigation — switch to Day mode and jump to a specific date.
* Uses #timelineModeDailyButton + #timelineNavigationDailyDate.
* ============================================================ */
async function ensureDailyMode() {
const dailyBtn = document.querySelector('#timelineModeDailyButton');
if (!dailyBtn) return false;
// The active mode button has class btn-primary
if (dailyBtn.classList.contains('btn-primary')) return true;
dailyBtn.click();
await sleep(400);
return dailyBtn.classList.contains('btn-primary');
}
/** Navigate the timeline to a specific ISO day. Returns true if the day is now visible. */
async function navigateToDay(iso) {
await ensureDailyMode();
const dateStr = formatDateDE(iso);
const input = document.querySelector('#timelineNavigationDailyDate');
if (!input) {
log(' ⚠ Tages-Navigationsfeld (#timelineNavigationDailyDate) nicht gefunden');
return false;
}
if (input.value === dateStr && findDayColumn(iso)) return true;
setInputValue(input, dateStr);
const jq = $$();
if (jq) {
try { jq(input).val(dateStr).trigger('change').trigger('apply.daterangepicker'); } catch (_) {}
}
const ok = await waitFor(() => findDayColumn(iso), 5000);
if (!ok) {
log(` ⚠ Tag ${dateStr} ist nach Navigation nicht sichtbar geworden`);
return false;
}
return true;
}
/* ============================================================
* Duplicate detection — look at the visible timeline day-column
* ============================================================ */
/**
* Find the day column element for a given ISO date.
* Heuristic: locate the element whose text is exactly "DD.MM." or "DD.MM" and
* walk up to the nearest "column-shaped" container (taller than wide, reasonable width).
* Returns the container element or null if the day isn't currently visible.
*/
function findDayColumn(iso) {
const [y, m, d] = iso.split('-');
const target1 = `${d}.${m}.`;
const target2 = `${d}.${m}`;
const candidates = document.querySelectorAll('div, span, p, h1, h2, h3, h4, h5, td, th');
for (const el of candidates) {
if (!isVisible(el)) continue;
const t = textOf(el);
if (t !== target1 && t !== target2) continue;
// Walk up looking for a container that is taller than wide and reasonably sized
let p = el.parentElement;
for (let i = 0; i < 12 && p; i++, p = p.parentElement) {
const r = p.getBoundingClientRect();
if (r.width >= 90 && r.width <= 500 && r.height >= 150 && r.height > r.width * 0.5) {
// Sanity: container's text should contain the full date label or entries / empty marker
const pt = textOf(p);
if (pt.includes('Keine Arbeitszeit erfasst')
|| /\b\d{1,2}:\d{2}\b/.test(pt)
|| /Anwesenheitszeit|Pause|Projektzeit/i.test(pt)
|| pt.includes('Arbeitszeit hinzufügen')) {
return p;
}
}
}
}
return null;
}
/**
* Check whether the day already contains entries.
* Returns:
* { visible: true, anwesenheit: bool, projekt: bool }
* { visible: false } if the day's column isn't in the DOM right now
*/
function dayExistingEntries(iso, taskName) {
const col = findDayColumn(iso);
if (!col) return { visible: false };
const txt = textOf(col);
if (txt.includes('Keine Arbeitszeit erfasst')) {
return { visible: true, anwesenheit: false, projekt: false };
}
const lower = txt.toLowerCase();
return {
visible: true,
anwesenheit: lower.includes('anwesenheitszeit'),
projekt: taskName ? lower.includes(taskName.toLowerCase()) : /projektzeit/i.test(txt),
};
}
/* ============================================================
* Orchestration
* ============================================================ */
async function processDay(iso, settings, opts, counters, result) {
log(`— ${iso} —`);
// Bring the day into view so the duplicate check and any per-day buttons work.
const navigated = await navigateToDay(iso);
if (navigated) await sleep(250);
// Determine what's already there (per-type)
let existing = { visible: false };
if (settings.skipExisting) {
existing = dayExistingEntries(iso, settings.taskName);
result.visible = existing.visible;
if (!existing.visible) {
log(' ⓘ Tag nicht in Sicht — kann Duplikate nicht prüfen, fahre vorsichtig fort');
} else {
result.anwesenheit = existing.anwesenheit;
result.projekt = existing.projekt;
log(` Status: Anwesenheit=${existing.anwesenheit ? 'JA' : 'nein'}, Projekt=${existing.projekt ? 'JA' : 'nein'}`);
}
}
const doAnwesenheit = settings.includeAnwesenheit && !(settings.skipExisting && existing.anwesenheit);
const doProjekt = settings.includeProjekt && !(settings.skipExisting && existing.projekt);
if (settings.includeAnwesenheit && !doAnwesenheit) {
log(' ⊘ Anwesenheitszeit übersprungen (bereits vorhanden)');
counters.skipped++;
}
if (settings.includeProjekt && !doProjekt) {
log(' ⊘ Projektzeit übersprungen (bereits vorhanden)');
counters.skipped++;
}
if (doAnwesenheit) {
const modal = await openModalVia(SELECTORS.addArbeitszeit, '+ Arbeitszeit', SELECTORS.arbeitszeitDialog);
await insertArbeitszeit(modal, { iso, settings });
if (opts.dryRun) {
log(' Trockenlauf: nicht gespeichert, schließe Dialog');
await closeModal(modal);
} else {
await saveModal(modal);
result.anwesenheit = true;
log(' ✓ Anwesenheitszeit gespeichert');
counters.ok++;
}
await sleep(300);
}
if (doProjekt) {
const modal = await openModalVia(SELECTORS.addProjektzeit, '+ Projektzeit nachtragen', SELECTORS.projektzeitDialog);
await insertProjektzeit(modal, { iso, settings });
if (opts.dryRun) {
log(' Trockenlauf: nicht gespeichert, schließe Dialog');
await closeModal(modal);
} else {
await saveModal(modal);
result.projekt = true;
log(' ✓ Projektzeit gespeichert');
counters.ok++;
}
await sleep(300);
}
}
async function rememberEntry(entry, taskName) {
const stored = await chrome.storage.local.get('dayStates');
const dayStates = stored.dayStates || {};
mergeTimrEntries(dayStates, [entry], taskName);
await chrome.storage.local.set({ dayStates });
}
async function syncMonth({ days, taskName }) {
const entries = [];
for (const iso of days) {
log(`Prüfe ${iso} …`);
if (!await navigateToDay(iso)) {
entries.push({ iso, visible: false });
continue;
}
await sleep(250);
const entry = { iso, ...dayExistingEntries(iso, taskName) };
entries.push(entry);
await rememberEntry(entry, taskName);
}
return { ok: true, entries };
}
async function run({ days, settings }) {
const opts = { dryRun: !!settings.dryRun };
const counters = { ok: 0, skipped: 0, fail: 0 };
const entries = [];
for (const iso of days) {
const result = { iso };
try {
await processDay(iso, settings, opts, counters, result);
} catch (e) {
counters.fail++;
log(` ✗ Fehler an ${iso}: ${e.message || e}`);
// Try to close any leftover modal so subsequent days still work
const modal = findModal();
if (modal) {
try { await closeModal(modal); } catch (_) {}
}
}
entries.push(result);
if (!opts.dryRun) await rememberEntry(result, settings.taskName);
}
return {
ok: counters.fail === 0,
entries,
summary: `${counters.ok} Einträge gespeichert, ${counters.skipped} übersprungen, ${counters.fail} Fehler.`,
};
}
/* ============================================================
* Messaging entrypoint
* ============================================================ */
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (msg?.type === 'TIMR_PING') {
sendResponse({ ok: true });
return false;
}
if (msg?.type === 'TIMR_SYNC_MONTH') {
syncMonth(msg.payload).then(sendResponse).catch((e) => sendResponse({ ok: false, error: e.message || String(e) }));
return true;
}
if (msg?.type !== 'TIMR_AUTO_INSERT') return;
run(msg.payload).then(sendResponse).catch((e) => sendResponse({ ok: false, error: e.message || String(e) }));
return true; // async
});
log('Timr Auto Inserter content script geladen.');
})();