-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2507 lines (2153 loc) · 104 KB
/
Copy pathmain.py
File metadata and controls
2507 lines (2153 loc) · 104 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
#!/usr/bin/env python3
"""TimeTrackr - Personal time tracker with Windows system tray"""
import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
import threading
from datetime import datetime, date, timedelta
from pathlib import Path
import sys
import math
import platform_support as plat
from PIL import Image, ImageDraw
try:
import reportlab # noqa: F401
_REPORTLAB = True
except ImportError:
_REPORTLAB = False
# ── Config ───────────────────────────────────────────────────────────────────
APP_NAME = "TimeTrackr"
DATA_DIR = Path.home() / ".timetrackr"
DB_PATH = DATA_DIR / "data.db"
JOB_COLORS = [
"#2196F3", "#4CAF50", "#F44336", "#FF9800",
"#9C27B0", "#00BCD4", "#795548", "#607D8B",
]
# ── Country / dialling-code reference ─────────────────────────────────────────
# (name, dial_code). Curated common set; the country combobox is editable so
# anything not listed can still be typed. Plain text only — flag emoji do not
# render in Tkinter comboboxes on Windows.
COUNTRIES = [
("United Kingdom", "+44"), ("United States", "+1"), ("Ireland", "+353"),
("Canada", "+1"), ("Australia", "+61"), ("New Zealand", "+64"),
("Germany", "+49"), ("France", "+33"), ("Spain", "+34"), ("Italy", "+39"),
("Netherlands", "+31"), ("Belgium", "+32"), ("Switzerland", "+41"),
("Austria", "+43"), ("Sweden", "+46"), ("Norway", "+47"), ("Denmark", "+45"),
("Finland", "+358"), ("Portugal", "+351"), ("Poland", "+48"),
("Czech Republic", "+420"), ("India", "+91"), ("Singapore", "+65"),
("Hong Kong", "+852"), ("Japan", "+81"), ("South Africa", "+27"),
("United Arab Emirates", "+971"), ("Brazil", "+55"), ("Mexico", "+52"),
]
def country_names():
return [name for name, _ in COUNTRIES]
def dial_labels():
return [f"{name} ({code})" for name, code in COUNTRIES]
def label_for_code(code):
for name, c in COUNTRIES:
if c == code:
return f"{name} ({c})"
return code
def code_from_label(label):
label = (label or "").strip()
if label.endswith(")") and "(" in label:
return label[label.rindex("(") + 1:-1].strip()
return label
def compose_address(parts, sep=", "):
"""Join non-empty address parts (line1, line2, city, county, postcode, country)."""
return sep.join(p.strip() for p in parts if p and p.strip())
def compose_phone(code, number):
number = (number or "").strip()
if not number:
return ""
return f"{(code or '').strip()} {number}".strip()
def compose_business_address(line_parts, country, legacy):
"""Business address for the PDF.
Use the structured lines (plus country) only when at least one address
line/locality field is set; otherwise fall back to the legacy single-blob
address. A defaulted country alone must NOT mask an empty address.
line_parts: [line1, line2, city, county, postcode] (country excluded).
"""
if compose_address(line_parts):
return compose_address(list(line_parts) + [country])
return (legacy or "").strip()
def resolve_project_job(selected_job_id, job_ids):
"""Decide which job a new project attaches to when + Project is pressed.
Returns ("use", job_id) to proceed, ("choose", None) to prompt the user,
or ("empty", None) when no jobs exist.
"""
if selected_job_id is not None:
return ("use", selected_job_id)
if not job_ids:
return ("empty", None)
if len(job_ids) == 1:
return ("use", job_ids[0])
return ("choose", None)
TAX_FREE_ALLOWANCE = 12_570
BASIC_RATE_LIMIT = 50_270
HIGHER_RATE_LIMIT = 125_140
# ── Database ──────────────────────────────────────────────────────────────────
class Database:
def __init__(self):
DATA_DIR.mkdir(exist_ok=True)
self.conn = sqlite3.connect(str(DB_PATH), check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self.conn.execute("PRAGMA foreign_keys = ON")
self._lock = threading.Lock()
self._init()
def _init(self):
self.conn.executescript("""
CREATE TABLE IF NOT EXISTS jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
color TEXT NOT NULL DEFAULT '#2196F3',
active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
);
CREATE TABLE IF NOT EXISTS projects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
job_id INTEGER NOT NULL REFERENCES jobs(id),
name TEXT NOT NULL,
active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
);
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
job_id INTEGER NOT NULL REFERENCES jobs(id),
project_id INTEGER REFERENCES projects(id),
start_time TEXT NOT NULL,
end_time TEXT,
notes TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
);
CREATE TABLE IF NOT EXISTS invoice_settings (
key TEXT PRIMARY KEY,
value TEXT
);
CREATE TABLE IF NOT EXISTS invoices (
id INTEGER PRIMARY KEY AUTOINCREMENT,
number TEXT NOT NULL,
client_name TEXT,
period_start TEXT,
period_end TEXT,
total REAL,
pdf_path TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))
);
CREATE TABLE IF NOT EXISTS invoice_jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
invoice_id INTEGER NOT NULL REFERENCES invoices(id),
job_name TEXT NOT NULL,
hours REAL NOT NULL DEFAULT 0,
rate REAL NOT NULL DEFAULT 0,
amount REAL NOT NULL DEFAULT 0
);
""")
self.conn.commit()
# Migrate: add columns introduced after initial release
for stmt in (
"ALTER TABLE jobs ADD COLUMN hourly_rate REAL",
"ALTER TABLE entries ADD COLUMN invoiced INTEGER NOT NULL DEFAULT 0",
):
try:
self.conn.execute(stmt)
self.conn.commit()
except sqlite3.OperationalError:
pass
# Backfill: ensure any rows that stored NULL get set to 0
self.conn.execute("UPDATE entries SET invoiced = 0 WHERE invoiced IS NULL")
self.conn.commit()
def _q(self, sql, params=()):
with self._lock:
return self.conn.execute(sql, params)
def _w(self, sql, params=()):
with self._lock:
with self.conn:
cur = self.conn.execute(sql, params)
return cur.lastrowid
# Jobs
def jobs(self):
return self._q("SELECT * FROM jobs WHERE active=1 ORDER BY name").fetchall()
def add_job(self, name, color):
return self._w("INSERT INTO jobs (name,color) VALUES (?,?)", (name, color))
def update_job(self, jid, name, color):
self._w("UPDATE jobs SET name=?,color=? WHERE id=?", (name, color, jid))
def archive_job(self, jid):
self._w("UPDATE jobs SET active=0 WHERE id=?", (jid,))
# Projects
def projects(self, job_id):
return self._q(
"SELECT * FROM projects WHERE job_id=? AND active=1 ORDER BY name",
(job_id,)
).fetchall()
def add_project(self, job_id, name):
return self._w("INSERT INTO projects (job_id,name) VALUES (?,?)", (job_id, name))
def update_project(self, pid, name):
self._w("UPDATE projects SET name=? WHERE id=?", (name, pid))
def archive_project(self, pid):
self._w("UPDATE projects SET active=0 WHERE id=?", (pid,))
# Entries
def start_entry(self, job_id, project_id, notes):
now = datetime.now().isoformat(timespec="seconds")
return self._w(
"INSERT INTO entries (job_id,project_id,start_time,notes) VALUES (?,?,?,?)",
(job_id, project_id or None, now, notes or None),
)
def stop_entry(self, eid):
now = datetime.now().isoformat(timespec="seconds")
self._w("UPDATE entries SET end_time=? WHERE id=?", (now, eid))
def log_entry(self, job_id, project_id, start_dt, end_dt, notes):
self._w(
"INSERT INTO entries (job_id,project_id,start_time,end_time,notes) VALUES (?,?,?,?,?)",
(job_id, project_id or None,
start_dt.isoformat(timespec="seconds"),
end_dt.isoformat(timespec="seconds"),
notes or None),
)
def open_entry(self):
return self._q("""
SELECT e.*, j.name AS job_name, j.color, p.name AS project_name
FROM entries e
JOIN jobs j ON e.job_id = j.id
LEFT JOIN projects p ON e.project_id = p.id
WHERE e.end_time IS NULL
LIMIT 1
""").fetchone()
def recent_entries(self, limit=30):
return self._q("""
SELECT e.*,
j.name AS job_name, j.color,
p.name AS project_name,
ROUND(
(julianday(COALESCE(e.end_time, datetime('now','localtime')))
- julianday(e.start_time)) * 86400
) AS duration_sec
FROM entries e
JOIN jobs j ON e.job_id = j.id
LEFT JOIN projects p ON e.project_id = p.id
ORDER BY e.start_time DESC
LIMIT ?
""", (limit,)).fetchall()
def summary(self, start, end):
return self._q("""
SELECT j.name AS job_name, j.color,
p.name AS project_name,
SUM(ROUND(
(julianday(e.end_time) - julianday(e.start_time)) * 86400
)) AS seconds
FROM entries e
JOIN jobs j ON e.job_id = j.id
LEFT JOIN projects p ON e.project_id = p.id
WHERE e.end_time IS NOT NULL
AND e.start_time >= ? AND e.start_time < ?
GROUP BY e.job_id, e.project_id
ORDER BY seconds DESC
""", (start, end)).fetchall()
def week_entries(self, start, end):
return self._q("""
SELECT e.*,
j.name AS job_name, j.color,
p.name AS project_name
FROM entries e
JOIN jobs j ON e.job_id = j.id
LEFT JOIN projects p ON e.project_id = p.id
WHERE e.start_time >= ? AND e.start_time < ?
ORDER BY e.start_time
""", (start, end)).fetchall()
def entry_by_id(self, eid):
return self._q("""
SELECT e.*, j.name AS job_name, p.name AS project_name
FROM entries e
JOIN jobs j ON e.job_id = j.id
LEFT JOIN projects p ON e.project_id = p.id
WHERE e.id = ?
""", (eid,)).fetchone()
def update_entry(self, eid, job_id, project_id, start_dt, end_dt, notes):
self._w(
"UPDATE entries SET job_id=?, project_id=?, start_time=?, end_time=?, notes=? WHERE id=?",
(job_id, project_id or None,
start_dt.isoformat(timespec="seconds"),
end_dt.isoformat(timespec="seconds") if end_dt else None,
notes or None, eid),
)
def delete_entry(self, eid):
self._w("DELETE FROM entries WHERE id=?", (eid,))
# Invoice settings
def get_setting(self, key, default=""):
row = self._q("SELECT value FROM invoice_settings WHERE key=?", (key,)).fetchone()
return row["value"] if row else default
def set_setting(self, key, value):
self._w("INSERT OR REPLACE INTO invoice_settings (key,value) VALUES (?,?)", (key, value))
def invoice_line_items(self, start, end):
return self._q("""
SELECT j.id AS job_id, j.name AS job_name, j.hourly_rate,
p.id AS project_id, p.name AS project_name,
ROUND(SUM(
(julianday(e.end_time) - julianday(e.start_time)) * 24
), 2) AS hours
FROM entries e
JOIN jobs j ON e.job_id = j.id
LEFT JOIN projects p ON e.project_id = p.id
WHERE e.end_time IS NOT NULL
AND COALESCE(e.invoiced, 0) = 0
AND e.start_time >= ? AND e.start_time < ?
GROUP BY j.id, p.id
ORDER BY j.name, p.name
""", (start, end)).fetchall()
def next_invoice_number(self, prefix="INV-"):
row = self._q("SELECT COUNT(*) AS n FROM invoices").fetchone()
return f"{prefix}{row['n'] + 1:03d}"
def save_invoice(self, number, client_name, period_start, period_end, total, pdf_path,
line_items=None):
with self._lock:
with self.conn:
cur = self.conn.execute(
"INSERT INTO invoices"
" (number,client_name,period_start,period_end,total,pdf_path)"
" VALUES (?,?,?,?,?,?)",
(number, client_name, period_start, period_end, total, str(pdf_path)),
)
invoice_id = cur.lastrowid
if line_items:
for item in line_items:
self.conn.execute(
"INSERT INTO invoice_jobs (invoice_id,job_name,hours,rate,amount)"
" VALUES (?,?,?,?,?)",
(invoice_id, item["job"], item["hours"],
item.get("rate", 0), item["amount"]),
)
self.conn.execute(
"UPDATE entries SET invoiced=1"
" WHERE end_time IS NOT NULL AND start_time >= ? AND start_time < ?",
(period_start, period_end),
)
def tax_overview(self, period_start=None, period_end=None):
"""Return (total_invoiced, [(job_name, amount), ...]) for the given date window.
period_start/period_end filter by invoice.period_start (ISO date strings).
Pass None to query all time.
"""
where = ""
p = []
if period_start:
where += " AND i.period_start >= ?"
p.append(period_start)
if period_end:
where += " AND i.period_start < ?"
p.append(period_end)
total = self._q(
f"SELECT COALESCE(SUM(total),0) AS t FROM invoices i WHERE 1=1{where}", p
).fetchone()["t"]
by_job = self._q(
f"""SELECT ij.job_name, SUM(ij.amount) AS amount
FROM invoice_jobs ij
JOIN invoices i ON ij.invoice_id = i.id
WHERE 1=1{where}
GROUP BY ij.job_name
ORDER BY amount DESC""",
p,
).fetchall()
return total, by_job
# ── Helpers ───────────────────────────────────────────────────────────────────
def fmt_hm(seconds):
if not seconds:
return "0h 0m"
return f"{int(seconds // 3600)}h {int(seconds % 3600 // 60)}m"
def fmt_hms(seconds):
if not seconds:
return "0:00:00"
h, r = divmod(int(seconds), 3600)
m, s = divmod(r, 60)
return f"{h}:{m:02d}:{s:02d}"
def week_bounds(d=None):
d = d or date.today()
start = d - timedelta(days=d.weekday())
return start.isoformat(), (start + timedelta(days=7)).isoformat()
def month_bounds(d=None):
d = d or date.today()
start = date(d.year, d.month, 1)
end = date(d.year + (d.month == 12), d.month % 12 + 1, 1)
return start.isoformat(), end.isoformat()
# A known past invoicing Thursday. Only its phase (mod 14 days) matters — it fixes
# which Thursdays are biweekly anchors, since the cycle is out of phase with ISO weeks.
BIWEEKLY_ANCHOR = date(2026, 6, 18)
def biweekly_bounds(offset=0):
"""Return (start_iso, end_iso) for a biweekly billing period. End is EXCLUSIVE
(SQL uses start_time < end). Periods are anchored to invoicing Thursdays every
14 days from BIWEEKLY_ANCHOR; each completed period covers the 14 days ending on
(and including) its anchor Thursday.
offset=0 → current in-progress period: the day AFTER the most recent anchor,
up to and including today. (On an anchor Thursday this is empty —
that day's work belongs to the period that just closed.)
offset=-1 → most recently completed period (closes on the most recent anchor on
or before today, and includes that Thursday's work).
offset=-2 → the period before that, and so on.
Consecutive periods abut exactly: an anchor Thursday is the last billed day of
its period and is never shared with the next.
"""
today = date.today()
# Most recent anchor Thursday on or before today (phase-aware, 14-day steps).
days_since_anchor = (today - BIWEEKLY_ANCHOR).days % 14
last_anchor = today - timedelta(days=days_since_anchor)
if offset == 0:
# In-progress: day after the last anchor → today (inclusive via exclusive +1).
start = last_anchor + timedelta(days=1)
return start.isoformat(), (today + timedelta(days=1)).isoformat()
# Completed period(s): the anchor that closes the period, stepping back 14 days.
anchor = last_anchor + timedelta(weeks=2 * (offset + 1)) # last_anchor when offset=-1
start = anchor - timedelta(days=13) # 14-day window ending on the anchor
end = anchor + timedelta(days=1) # exclusive → includes the anchor Thursday
return start.isoformat(), end.isoformat()
def uk_tax_year_bounds(offset=0):
"""Return (start_iso, end_iso) for a UK tax year (Apr 6 → Apr 5).
offset=0 → current tax year; offset=-1 → previous.
"""
today = date.today()
start_year = today.year if today >= date(today.year, 4, 6) else today.year - 1
start_year += offset
return date(start_year, 4, 6).isoformat(), date(start_year + 1, 4, 6).isoformat()
def calc_uk_tax(income):
"""Break down income across UK tax bands and return estimated liability dict."""
allowance_used = min(income, TAX_FREE_ALLOWANCE)
basic_taxable = max(0.0, min(income, BASIC_RATE_LIMIT) - TAX_FREE_ALLOWANCE)
higher_taxable = max(0.0, min(income, HIGHER_RATE_LIMIT) - BASIC_RATE_LIMIT)
basic_tax = basic_taxable * 0.20
higher_tax = higher_taxable * 0.40
return {
"allowance_used": allowance_used,
"basic_taxable": basic_taxable,
"higher_taxable": higher_taxable,
"basic_tax": basic_tax,
"higher_tax": higher_tax,
"total_tax": basic_tax + higher_tax,
}
def make_tray_icon(tracking=False):
img = Image.new("RGBA", (64, 64), (0, 0, 0, 0))
d = ImageDraw.Draw(img)
fill = "#43A047" if tracking else "#9E9E9E"
border = "#1B5E20" if tracking else "#424242"
d.ellipse([2, 2, 62, 62], fill=fill, outline=border, width=3)
d.ellipse([12, 12, 52, 52], fill="white", outline=border, width=2)
# clock hands
d.line([32, 32, 32, 18], fill=border, width=3)
d.line([32, 32, 43, 38], fill=border, width=2)
d.ellipse([29, 29, 35, 35], fill=border)
return img
class PlaceholderEntry(tk.Entry):
"""Entry that shows greyed example text when empty and unfocused.
get_value() returns "" while the placeholder is displayed so placeholder
text never leaks into saved settings or a generated PDF.
"""
def __init__(self, master, placeholder="", color="#9AA0A6", **kw):
super().__init__(master, **kw)
self._placeholder = placeholder
self._ph_color = color
self._default_fg = self.cget("fg")
self._is_placeholder = False
self.bind("<FocusIn>", self._on_focus_in)
self.bind("<FocusOut>", self._on_focus_out)
self._show_placeholder()
def _show_placeholder(self):
self.delete(0, tk.END)
self.insert(0, self._placeholder)
self.config(fg=self._ph_color)
self._is_placeholder = True
def _on_focus_in(self, _=None):
if self._is_placeholder:
self.delete(0, tk.END)
self.config(fg=self._default_fg)
self._is_placeholder = False
def _on_focus_out(self, _=None):
if not self.get():
self._show_placeholder()
def get_value(self):
return "" if self._is_placeholder else self.get()
def set_value(self, text):
if text:
self.config(fg=self._default_fg)
self._is_placeholder = False
self.delete(0, tk.END)
self.insert(0, text)
else:
self._show_placeholder()
def ask_string(parent, title, prompt, initial=""):
dlg = tk.Toplevel(parent)
dlg.title(title)
dlg.resizable(False, False)
dlg.grab_set()
result = [None]
tk.Label(dlg, text=prompt, padx=12, pady=8).pack()
var = tk.StringVar(value=initial)
ent = tk.Entry(dlg, textvariable=var, width=32)
ent.pack(padx=12, pady=(0, 8))
ent.focus_set()
ent.select_range(0, tk.END)
def ok(_=None):
result[0] = var.get().strip()
dlg.destroy()
ent.bind("<Return>", ok)
ent.bind("<Escape>", lambda _: dlg.destroy())
bf = tk.Frame(dlg)
bf.pack(pady=(0, 8))
ttk.Button(bf, text="OK", command=ok).pack(side="left", padx=4)
ttk.Button(bf, text="Cancel", command=dlg.destroy).pack(side="left", padx=4)
dlg.geometry("+%d+%d" % (parent.winfo_rootx() + 60, parent.winfo_rooty() + 60))
parent.wait_window(dlg)
return result[0]
def ask_choice(parent, title, prompt, options):
"""Modal single-choice picker. Returns the selected index, or None if cancelled."""
dlg = tk.Toplevel(parent)
dlg.title(title)
dlg.resizable(False, False)
dlg.grab_set()
result = {"idx": None}
f = tk.Frame(dlg, padx=16, pady=12)
f.pack()
tk.Label(f, text=prompt, anchor="w").pack(fill="x", pady=(0, 6))
var = tk.StringVar(value=options[0] if options else "")
cb = ttk.Combobox(f, textvariable=var, values=list(options),
state="readonly", width=28)
cb.pack()
if options:
cb.current(0)
def ok(_=None):
result["idx"] = cb.current()
dlg.destroy()
bf = tk.Frame(f)
bf.pack(pady=(10, 0))
ttk.Button(bf, text="OK", command=ok).pack(side="left", padx=5)
ttk.Button(bf, text="Cancel", command=dlg.destroy).pack(side="left", padx=5)
cx = parent.winfo_screenwidth() // 2 - 160
cy = parent.winfo_screenheight() // 2 - 80
dlg.geometry(f"+{cx}+{cy}")
dlg.focus_force()
parent.wait_window(dlg)
return result["idx"]
# ── Invoice PDF generator ─────────────────────────────────────────────────────
def generate_invoice_pdf(data, out_path):
from reportlab.platypus import (SimpleDocTemplate, Table, TableStyle,
Paragraph, Spacer, HRFlowable)
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from reportlab.lib import colors
from reportlab.lib.enums import TA_RIGHT
doc = SimpleDocTemplate(str(out_path), pagesize=A4,
leftMargin=2*cm, rightMargin=2*cm,
topMargin=2*cm, bottomMargin=2*cm)
ss = getSampleStyleSheet()
blue = colors.HexColor("#1565C0")
cur = data.get("currency", "£")
pw = A4[0] - 4*cm
def ps(name, **kw):
return ParagraphStyle(name, parent=ss["Normal"], **kw)
normal = ss["Normal"]
s_r = ps("_r", alignment=TA_RIGHT)
s_h2 = ps("_h2", fontSize=11, fontName="Helvetica-Bold", spaceAfter=4)
s_sm = ps("_sm", fontSize=9, textColor=colors.grey)
story = []
# Header: business name (left) | INVOICE (right)
hdr = Table(
[[Paragraph(f"<font size=20><b>{data.get('biz_name','')}</b></font>", normal),
Paragraph(f'<font size=26 color="#1565C0"><b>INVOICE</b></font>', s_r)]],
colWidths=[pw*0.6, pw*0.4],
)
hdr.setStyle(TableStyle([("VALIGN", (0,0), (-1,-1), "TOP")]))
story.append(hdr)
story.append(Spacer(1, 0.6*cm))
# Biz contact line + invoice meta
biz_parts = [data.get(k,"").strip()
for k in ("biz_address","biz_email","biz_phone")
if data.get(k,"").strip()]
biz_text = " · ".join(biz_parts) or " "
def fmt_date(iso, inclusive_end=False):
try:
d = datetime.strptime(iso, "%Y-%m-%d")
# Stored period_end is exclusive (SQL uses start_time < end); show the
# actual last billed day (the invoicing Thursday) by stepping back one day.
if inclusive_end:
d = d - timedelta(days=1)
return f"{d.day} {d.strftime('%B %Y')}"
except Exception:
return iso
period_start = fmt_date(data.get("period_start", ""))
period_end = fmt_date(data.get("period_end", ""), inclusive_end=True)
period_str = f"{period_start} – {period_end}" if period_start and period_end else ""
meta_html = (f"<b>Invoice #:</b> {data.get('invoice_number','')}<br/>"
f"<b>Date:</b> {data.get('issue_date','')}<br/>"
f"<b>Due:</b> {data.get('due_date','')}<br/>"
f"<b>Period:</b> {period_str}")
meta_tbl = Table([[Paragraph(biz_text, normal), Paragraph(meta_html, s_r)]],
colWidths=[pw*0.6, pw*0.4])
story += [meta_tbl, Spacer(1,0.3*cm),
HRFlowable(width="100%", thickness=2, color=blue),
Spacer(1,0.4*cm)]
# Bill To
story.append(Paragraph("Bill To", s_h2))
story.append(Paragraph(f"<b>{data.get('client_name','')}</b>", normal))
for line in data.get("client_address","").splitlines():
if line.strip():
story.append(Paragraph(line.strip(), normal))
story.append(Spacer(1, 0.5*cm))
# Line items table
rows = [["Job", "Project", "Hours", f"Rate ({cur}/hr)", "Amount"]]
for it in data.get("line_items", []):
rows.append([it["job"], it["project"] or "—",
f"{it['hours']:.2f}",
f"{cur}{it['rate']:.2f}",
f"{cur}{it['amount']:.2f}"])
cw = [pw*p for p in (0.28, 0.24, 0.12, 0.18, 0.18)]
it_tbl = Table(rows, colWidths=cw, repeatRows=1)
it_ts = TableStyle([
("BACKGROUND", (0,0), (-1,0), blue),
("TEXTCOLOR", (0,0), (-1,0), colors.white),
("FONTNAME", (0,0), (-1,0), "Helvetica-Bold"),
("FONTSIZE", (0,0), (-1,-1), 9),
("ALIGN", (2,0), (-1,-1), "RIGHT"),
("VALIGN", (0,0), (-1,-1), "MIDDLE"),
("TOPPADDING", (0,0), (-1,-1), 5),
("BOTTOMPADDING", (0,0), (-1,-1), 5),
("GRID", (0,0), (-1,-1), 0.5, colors.HexColor("#DDDDDD")),
])
for i in range(1, len(rows)):
if i % 2 == 0:
it_ts.add("BACKGROUND", (0,i), (-1,i), colors.HexColor("#F0F4FF"))
it_tbl.setStyle(it_ts)
story += [it_tbl, Spacer(1, 0.4*cm)]
# Totals
subtotal = data.get("subtotal", 0.0)
tax_rate = data.get("tax_rate", 0.0)
tax_amount = data.get("tax_amount", 0.0)
total = data.get("total", 0.0)
tot_data = [["", "Subtotal", f"{cur}{subtotal:.2f}"]]
if tax_rate:
tot_data.append(["", f"Tax ({tax_rate:.1f}%)", f"{cur}{tax_amount:.2f}"])
tot_data.append(["",
Paragraph("<b>Total Due</b>", normal),
Paragraph(f"<b>{cur}{total:.2f}</b>", s_r)])
tot_tbl = Table(tot_data, colWidths=[pw*0.55, pw*0.25, pw*0.20])
tot_tbl.setStyle(TableStyle([
("ALIGN", (1,0), (-1,-1), "RIGHT"),
("FONTSIZE", (0,0), (-1,-1), 10),
("TOPPADDING", (0,0), (-1,-1), 4),
("BOTTOMPADDING", (0,0), (-1,-1), 4),
("LINEABOVE", (0,-1), (-1,-1), 1, colors.black),
]))
story += [tot_tbl, Spacer(1,0.8*cm),
HRFlowable(width="100%", thickness=0.5, color=colors.grey),
Spacer(1,0.3*cm)]
# Payment details
bank_keys = [("Account Name","bank_account_name"),("Bank","bank_name"),
("Account No.","bank_account_number"),("Sort Code","bank_sort_code"),
("IBAN","bank_iban"),("BIC/SWIFT","bank_bic")]
bank_parts = [f"<b>{lbl}:</b> {data.get(k,'')}"
for lbl, k in bank_keys if data.get(k,"").strip()]
if bank_parts:
story.append(Paragraph("Payment Details", s_h2))
story.append(Paragraph("Please make payment by bank transfer to:", normal))
story.append(Spacer(1, 0.15*cm))
story.append(Paragraph(" · ".join(bank_parts), normal))
story.append(Spacer(1, 0.3*cm))
if data.get("notes","").strip():
story.append(Paragraph("Notes", s_h2))
story.append(Paragraph(data["notes"].strip(), s_sm))
doc.build(story)
# ── Start Tracking Dialog ─────────────────────────────────────────────────────
class StartDialog(tk.Toplevel):
def __init__(self, parent, db, on_start):
super().__init__(parent)
self.db = db
self.on_start = on_start
self.title("Start Tracking")
self.resizable(False, False)
self.grab_set()
self._jobs = db.jobs()
self._projs_data = []
self._build()
cx = parent.winfo_screenwidth() // 2 - 165
cy = parent.winfo_screenheight() // 2 - 100
self.geometry(f"+{cx}+{cy}")
self.focus_force()
def _build(self):
f = tk.Frame(self, padx=16, pady=12)
f.pack()
tk.Label(f, text="Job", anchor="w", width=8).grid(row=0, column=0, sticky="w", pady=4)
self._job_var = tk.StringVar()
self._job_cb = ttk.Combobox(f, textvariable=self._job_var,
values=[j["name"] for j in self._jobs],
state="readonly", width=26)
self._job_cb.grid(row=0, column=1, pady=4)
if self._jobs:
self._job_cb.current(0)
self._job_cb.bind("<<ComboboxSelected>>", lambda _: self._load_projects())
tk.Label(f, text="Project", anchor="w", width=8).grid(row=1, column=0, sticky="w", pady=4)
self._proj_var = tk.StringVar()
self._proj_cb = ttk.Combobox(f, textvariable=self._proj_var,
state="readonly", width=26)
self._proj_cb.grid(row=1, column=1, pady=4)
self._load_projects()
tk.Label(f, text="Notes", anchor="w", width=8).grid(row=2, column=0, sticky="w", pady=4)
self._notes_var = tk.StringVar()
tk.Entry(f, textvariable=self._notes_var, width=28).grid(row=2, column=1, pady=4)
bf = tk.Frame(f)
bf.grid(row=3, column=0, columnspan=2, pady=(10, 0))
ttk.Button(bf, text="Start", command=self._start).pack(side="left", padx=5)
ttk.Button(bf, text="Cancel", command=self.destroy).pack(side="left", padx=5)
def _load_projects(self):
job = self._sel_job()
if job:
projs = self.db.projects(job["id"])
self._projs_data = [None] + list(projs)
self._proj_cb["values"] = ["(none)"] + [p["name"] for p in projs]
else:
self._projs_data = [None]
self._proj_cb["values"] = ["(none)"]
self._proj_cb.current(0)
def _sel_job(self):
n = self._job_var.get()
return next((j for j in self._jobs if j["name"] == n), None)
def _start(self):
job = self._sel_job()
if not job:
messagebox.showwarning("No Job", "Please select a job first.", parent=self)
return
idx = self._proj_cb.current()
proj = self._projs_data[idx] if idx >= 0 else None
proj_id = proj["id"] if proj else None
notes = self._notes_var.get().strip() or None
eid = self.db.start_entry(job["id"], proj_id, notes)
self.on_start(eid)
self.destroy()
# ── Log Past Time Dialog ──────────────────────────────────────────────────────
class LogTimeDialog(tk.Toplevel):
"""Log a completed block of time that has already happened."""
def __init__(self, parent, db, on_logged):
super().__init__(parent)
self.db = db
self.on_logged = on_logged
self.title("Log Past Time")
self.resizable(False, False)
self.grab_set()
self._jobs = db.jobs()
self._projs_data = []
self._build()
cx = parent.winfo_screenwidth() // 2 - 170
cy = parent.winfo_screenheight() // 2 - 140
self.geometry(f"+{cx}+{cy}")
self.focus_force()
def _build(self):
f = tk.Frame(self, padx=16, pady=12)
f.pack()
now = datetime.now()
def lbl_row(r, text, widget):
tk.Label(f, text=text, anchor="w", width=9).grid(row=r, column=0, sticky="w", pady=4)
widget.grid(row=r, column=1, pady=4, sticky="w")
# Job
self._job_var = tk.StringVar()
self._job_cb = ttk.Combobox(f, textvariable=self._job_var,
values=[j["name"] for j in self._jobs],
state="readonly", width=24)
lbl_row(0, "Job", self._job_cb)
if self._jobs:
self._job_cb.current(0)
self._job_cb.bind("<<ComboboxSelected>>", lambda _: self._load_projects())
# Project
self._proj_var = tk.StringVar()
self._proj_cb = ttk.Combobox(f, textvariable=self._proj_var, state="readonly", width=24)
lbl_row(1, "Project", self._proj_cb)
self._load_projects()
# Date
self._date_var = tk.StringVar(value=now.strftime("%Y-%m-%d"))
lbl_row(2, "Date", tk.Entry(f, textvariable=self._date_var, width=14))
tk.Label(f, text="YYYY-MM-DD", fg="#888", font=("Segoe UI", 8)).grid(
row=2, column=2, padx=(4, 0), sticky="w")
# Start / End times
self._start_var = tk.StringVar(value=(now - timedelta(hours=1)).strftime("%H:%M"))
self._end_var = tk.StringVar(value=now.strftime("%H:%M"))
lbl_row(3, "Start", tk.Entry(f, textvariable=self._start_var, width=8))
lbl_row(4, "End", tk.Entry(f, textvariable=self._end_var, width=8))
tk.Label(f, text="HH:MM", fg="#888", font=("Segoe UI", 8)).grid(
row=3, column=2, padx=(4, 0), sticky="w")
# Live duration display
tk.Label(f, text="Duration", anchor="w", width=9).grid(row=5, column=0, sticky="w", pady=4)
self._dur_lbl = tk.Label(f, text="", font=("Segoe UI", 9, "bold"), fg="#1565C0")
self._dur_lbl.grid(row=5, column=1, sticky="w", pady=4)
# Notes
self._notes_var = tk.StringVar()
lbl_row(6, "Notes", tk.Entry(f, textvariable=self._notes_var, width=26))
# Buttons
bf = tk.Frame(f)
bf.grid(row=7, column=0, columnspan=3, pady=(12, 0))
ttk.Button(bf, text="Log Time", command=self._log).pack(side="left", padx=5)
ttk.Button(bf, text="Cancel", command=self.destroy).pack(side="left", padx=5)
# Update duration whenever times change
for var in (self._date_var, self._start_var, self._end_var):
var.trace_add("write", lambda *_: self._update_dur())
self._update_dur()
def _load_projects(self):
job = self._sel_job()
if job:
projs = self.db.projects(job["id"])
self._projs_data = [None] + list(projs)
self._proj_cb["values"] = ["(none)"] + [p["name"] for p in projs]
else:
self._projs_data = [None]
self._proj_cb["values"] = ["(none)"]
self._proj_cb.current(0)
def _sel_job(self):
n = self._job_var.get()
return next((j for j in self._jobs if j["name"] == n), None)
def _parse_times(self):
try:
d = self._date_var.get().strip()
s = self._start_var.get().strip()
e = self._end_var.get().strip()
start = datetime.strptime(f"{d} {s}", "%Y-%m-%d %H:%M")
end = datetime.strptime(f"{d} {e}", "%Y-%m-%d %H:%M")
return start, end
except ValueError:
return None, None
def _update_dur(self):
start, end = self._parse_times()
if start is None:
self._dur_lbl.config(text="—", fg="#888")
elif end <= start:
self._dur_lbl.config(text="end must be after start", fg="#c62828")
else:
secs = (end - start).total_seconds()
self._dur_lbl.config(text=fmt_hm(secs), fg="#1565C0")
def _log(self):
job = self._sel_job()
if not job:
messagebox.showwarning("No Job", "Please select a job.", parent=self)
return
start, end = self._parse_times()
if start is None:
messagebox.showwarning("Invalid time",
"Use YYYY-MM-DD for the date and HH:MM for start/end.", parent=self)
return
if end <= start:
messagebox.showwarning("Invalid time", "End must be after start.", parent=self)
return
if end > datetime.now() + timedelta(minutes=5):
messagebox.showwarning("Invalid time", "End time can't be in the future.", parent=self)
return
idx = self._proj_cb.current()
proj = self._projs_data[idx] if idx >= 0 else None
proj_id = proj["id"] if proj else None
notes = self._notes_var.get().strip() or None
self.db.log_entry(job["id"], proj_id, start, end, notes)
self.on_logged()
self.destroy()
# ── Edit Entry Dialog ─────────────────────────────────────────────────────────
class EditEntryDialog(tk.Toplevel):
"""Edit or delete an existing time entry."""
def __init__(self, parent, db, entry_id, on_change):
super().__init__(parent)
self.db = db