-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker.py
More file actions
2821 lines (2336 loc) · 99.1 KB
/
Copy pathtracker.py
File metadata and controls
2821 lines (2336 loc) · 99.1 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
# tracker.py
# Main CLI tool for the Data Plan Tracker.
#
# Usage:
# python tracker.py add - Add a new plan interactively
# python tracker.py list - Show all active plans in a table
# python tracker.py renew <id> - Update renewal date for a plan
# python tracker.py edit <id> - Edit any field of a plan
# python tracker.py deactivate <id> - Mark a plan as inactive
# python tracker.py summary - Spending summary + upcoming renewals
# python tracker.py check - Daily check (used by Task Scheduler)
# python tracker.py seed - Add sample data to see how it looks
import sys
import os
from datetime import datetime, date
# --- Third-party library imports with friendly error messages ---
try:
from colorama import Fore, Style, init as colorama_init
colorama_init(autoreset=True) # Reset colour after each print automatically
except ImportError:
print("[!] colorama not installed. Run: pip install colorama")
sys.exit(1)
try:
from tabulate import tabulate
except ImportError:
print("[!] tabulate not installed. Run: pip install tabulate")
sys.exit(1)
# Our own modules
import database
import alerts
# --- Constants ---
VALID_TYPES = ["sim", "proxy", "vpn", "phone", "other"]
VALID_CYCLES = ["monthly", "28-day", "annual", "one-off"]
VALID_EXPENSE_CATEGORIES = ["software", "hosting", "tools", "entertainment", "utilities", "services", "other"]
# Colour thresholds for "days left" column
RED_DAYS = 7
YELLOW_DAYS = 14
# Monthly cost multiplier by billing cycle
MONTHLY_EQUIV = {
"monthly": 1.0,
"28-day": 1.0,
"annual": 1.0 / 12.0,
"one-off": 0.0,
}
# Phone number validation regex (Australian mobile format)
import re
PHONE_REGEX = re.compile(r'^(\+?61|0)4[0-9]{8}$')
# Global state for CLI flags (--quiet, --format, etc.)
GLOBAL_STATE = {
"quiet": False,
"silent": False,
"format": "table",
}
def is_quiet() -> bool:
"""Check if quiet mode is enabled."""
return GLOBAL_STATE.get("quiet", False)
def is_silent() -> bool:
"""Check if silent mode is enabled."""
return GLOBAL_STATE.get("silent", False)
def output_format() -> str:
"""Get current output format."""
return GLOBAL_STATE.get("format", "table")
def qprint(*args, **kwargs):
"""Print only if not in quiet/silent mode."""
if not is_quiet():
print(*args, **kwargs)
def eprint(*args, **kwargs):
"""Print to stderr (always, even in quiet mode)."""
print(*args, file=sys.stderr, **kwargs)
def validate_phone_number(phone: str) -> tuple:
"""
Validate and normalize an Australian mobile phone number.
Returns (is_valid: bool, normalized: str, error_msg: str)
"""
if not phone or not phone.strip():
return True, "", "" # Empty is valid (optional field)
# Remove all whitespace and common separators
cleaned = re.sub(r'[\s\-\.\(\)]', '', phone.strip())
# Check for valid Australian mobile format
# Formats accepted: 0412345678, 61412345678, +61412345678
if not PHONE_REGEX.match(cleaned):
return False, phone, "Invalid Australian mobile format. Use 04xx xxx xxx or +614xx xxx xxx"
# Normalize to local format (04xx xxx xxx)
if cleaned.startswith('+61'):
normalized = '0' + cleaned[3:]
elif cleaned.startswith('61'):
normalized = '0' + cleaned[2:]
else:
normalized = cleaned
# Format with spaces: 04xx xxx xxx
formatted = f"{normalized[:4]} {normalized[4:7]} {normalized[7:]}"
return True, formatted, ""
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def colour_days(days: int) -> str:
"""Return the days-left number wrapped in the appropriate colour code."""
text = str(days)
if days <= RED_DAYS:
return Fore.RED + text + Style.RESET_ALL
elif days <= YELLOW_DAYS:
return Fore.YELLOW + text + Style.RESET_ALL
else:
return Fore.GREEN + text + Style.RESET_ALL
def days_until(date_str: str) -> int:
"""Return number of days from today until date_str (YYYY-MM-DD). Negative = overdue."""
try:
renewal = datetime.strptime(date_str, "%Y-%m-%d").date()
return (renewal - date.today()).days
except Exception:
return 9999 # No date set - treat as far away
def format_date_display(date_str: str) -> str:
"""Convert YYYY-MM-DD to DD/MM/YYYY for display. Returns original if invalid."""
try:
return datetime.strptime(date_str, "%Y-%m-%d").strftime("%d/%m/%Y")
except Exception:
return date_str or "-"
def parse_date_input(raw: str) -> str:
"""
Accept dates in DD/MM/YYYY or YYYY-MM-DD format.
Returns YYYY-MM-DD (ISO format) for storage, or raises ValueError.
"""
raw = raw.strip()
for fmt in ("%d/%m/%Y", "%Y-%m-%d"):
try:
return datetime.strptime(raw, fmt).strftime("%Y-%m-%d")
except ValueError:
continue
raise ValueError(f"Date '{raw}' not recognised. Use DD/MM/YYYY or YYYY-MM-DD.")
def prompt(label: str, default: str = "", required: bool = False) -> str:
"""
Show a prompt and return the user's input.
If a default is provided it is shown in brackets and used when user presses Enter.
"""
hint = f" [{default}]" if default else ""
while True:
value = input(f" {label}{hint}: ").strip()
if not value and default:
return default
if value:
return value
if required:
print(" [!] This field is required.")
else:
return ""
def prompt_choice(label: str, choices: list, default: str = "") -> str:
"""Prompt user to pick from a list of valid choices."""
choices_str = "/".join(choices)
hint = f" [{default}]" if default else f" ({choices_str})"
while True:
value = input(f" {label}{hint}: ").strip().lower()
if not value and default:
return default
if value in choices:
return value
print(f" [!] Must be one of: {choices_str}")
def prompt_yn(label: str, default: bool = False) -> bool:
"""Prompt for a yes/no answer. Returns True for yes."""
hint = "[Y/n]" if default else "[y/N]"
value = input(f" {label} {hint}: ").strip().lower()
if not value:
return default
return value in ("y", "yes")
def prompt_float(label: str, default: float = 0.0) -> float:
"""Prompt for a decimal number (cost). Returns default on blank/invalid."""
hint = f" [{default:.2f}]" if default else ""
while True:
raw = input(f" {label}{hint}: ").strip()
if not raw:
return default
try:
return float(raw)
except ValueError:
print(" [!] Enter a number, e.g. 29.90")
# ---------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------
def cmd_add():
"""Interactively collect details for a new plan and save it to the database."""
print("\n--- Add New Plan ---")
print("Press Enter to skip optional fields.\n")
data = {}
data["name"] = prompt("Plan name (e.g. Boost SIM #3)", required=True)
data["type"] = prompt_choice("Type", VALID_TYPES)
data["provider"] = prompt("Provider (e.g. Boost, Oxylabs)")
data["assigned_vm"] = prompt("Assigned VM (e.g. VM-01)")
data["cost"] = prompt_float("Cost per cycle (AUD)", default=0.0)
data["billing_cycle"] = prompt_choice("Billing cycle", VALID_CYCLES, default="monthly")
# Calculate smart default based on billing cycle
from datetime import datetime, timedelta
cycle_days = {
"monthly": 30,
"28-day": 28,
"annual": 365,
"one-off": 0
}
default_days = cycle_days.get(data["billing_cycle"], 30)
default_date = ""
if default_days > 0:
default_date_obj = datetime.now() + timedelta(days=default_days)
default_date = default_date_obj.strftime("%d/%m/%Y")
raw_date = prompt(f"Next renewal date (DD/MM/YYYY) [{default_date}]")
if raw_date:
try:
data["next_renewal"] = parse_date_input(raw_date)
except ValueError as e:
print(f" [!] {e} - renewal date not saved. Edit later with: python tracker.py edit <id>")
data["next_renewal"] = ""
elif default_date:
# User pressed Enter - use the default
data["next_renewal"] = parse_date_input(default_date)
else:
data["next_renewal"] = ""
# Suggest auto-renew based on billing cycle
default_auto = data["billing_cycle"] != "one-off"
data["auto_renew"] = 1 if prompt_yn("Auto-renews?", default=default_auto) else 0
data["notes"] = prompt("Notes (optional)")
# Validate before saving
is_valid, validation_issues = validate_plan_consistency(data, is_new=True)
if validation_issues:
print("\n[*] Validation notes:")
for issue in validation_issues:
print(f" - {issue}")
if not is_valid:
print("\n[!] Please fix the above issues before saving.")
return
plan_id = database.add_plan(data)
print(f"\n[*] Plan saved with ID {plan_id}: {data['name']}")
def cmd_list(show_all: bool = False):
"""Display plans in a colour-coded table, grouped by type."""
plans = database.get_all_plans(active_only=not show_all)
if not plans:
if show_all:
print("\nNo plans in the database. Add one with: python tracker.py add")
else:
print("\nNo active plans found. Add one with: python tracker.py add")
return
if show_all:
active_count = sum(1 for p in plans if p.get("active"))
inactive_count = len(plans) - active_count
print(f"\n Showing all plans ({active_count} active, {inactive_count} inactive)")
# Group plans by type for cleaner display
by_type = {}
for plan in plans:
t = plan.get("type", "other")
by_type.setdefault(t, []).append(plan)
for plan_type, group in sorted(by_type.items()):
print(f"\n --- {plan_type.upper()} ---")
rows = []
for p in group:
renewal = p.get("next_renewal", "")
is_active = bool(p.get("active", 1))
if renewal and is_active:
days = days_until(renewal)
days_str = colour_days(days)
renewal_display = format_date_display(renewal)
elif renewal:
days_str = "-"
renewal_display = format_date_display(renewal)
else:
days_str = "-"
renewal_display = "-"
auto = "Yes" if p.get("auto_renew") else "No"
cost = f"${p.get('cost', 0.0):.2f}"
status = "active" if is_active else Fore.RED + "inactive" + Style.RESET_ALL
row = [
p["id"],
p.get("name", ""),
p.get("provider", "") or "-",
p.get("assigned_vm", "") or "-",
cost,
p.get("billing_cycle", "") or "-",
renewal_display,
days_str,
auto,
]
if show_all:
row.append(status)
rows.append(row)
headers = ["ID", "Name", "Provider", "VM", "Cost", "Cycle",
"Next Renewal", "Days Left", "Auto-renew"]
if show_all:
headers.append("Status")
print(tabulate(rows, headers=headers, tablefmt="simple"))
label = "plans (all)" if show_all else "active plans"
print(f"\n Total {label}: {len(plans)}")
def calculate_next_renewal(current_date: str, billing_cycle: str) -> str:
"""Calculate the next renewal date based on billing cycle."""
from datetime import datetime, timedelta
try:
current = datetime.strptime(current_date, "%Y-%m-%d")
except (ValueError, TypeError):
return None
if billing_cycle == "one-off":
return None
if billing_cycle == "monthly":
try:
from dateutil.relativedelta import relativedelta
next_date = current + relativedelta(months=+1)
except ImportError:
next_date = current + timedelta(days=30)
elif billing_cycle == "28-day":
next_date = current + timedelta(days=28)
elif billing_cycle == "annual":
try:
from dateutil.relativedelta import relativedelta
next_date = current + relativedelta(months=+12)
except ImportError:
next_date = current + timedelta(days=365)
else:
# Default to monthly for unknown cycles
try:
from dateutil.relativedelta import relativedelta
next_date = current + relativedelta(months=+1)
except ImportError:
next_date = current + timedelta(days=30)
return next_date.strftime("%Y-%m-%d")
def cmd_renew(plan_id: int, auto_advance: bool = False):
"""Update the next_renewal date for a single plan."""
plan = database.get_plan_by_id(plan_id)
if not plan:
print(f"[!] No plan found with ID {plan_id}")
# Suggest similar IDs
all_plans = database.get_all_plans(active_only=False)
existing_ids = [p['id'] for p in all_plans]
if existing_ids:
closest = min(existing_ids, key=lambda x: abs(x - plan_id))
print(f" Did you mean ID {closest}? Run 'python tracker.py list' to see all plans")
return
current_renewal = plan.get("next_renewal", "")
billing_cycle = plan.get("billing_cycle", "monthly")
print(f"\n Plan: {plan['name']} (current renewal: {format_date_display(current_renewal)})")
# Offer auto-calculation based on billing cycle
if current_renewal and billing_cycle:
calculated = calculate_next_renewal(current_renewal, billing_cycle)
if calculated and not auto_advance:
use_auto = prompt_yn(f"Auto-calculate next renewal ({format_date_display(calculated)})?", default=True)
if use_auto:
database.update_plan(plan_id, {"next_renewal": calculated})
# Log the renewal for history tracking
_log_plan_change(plan_id, "renewal", f"Renewed from {current_renewal} to {calculated}")
print(f"[*] Renewal date auto-updated to {format_date_display(calculated)}")
return
# Manual date entry
raw_date = prompt("New renewal date (DD/MM/YYYY)", required=True)
try:
new_date = parse_date_input(raw_date)
except ValueError as e:
print(f"[!] {e}")
return
database.update_plan(plan_id, {"next_renewal": new_date})
_log_plan_change(plan_id, "renewal", f"Manually updated to {new_date}")
print(f"[*] Renewal date updated to {format_date_display(new_date)}")
def cmd_edit(plan_id: int):
"""Edit any field of a plan interactively."""
plan = database.get_plan_by_id(plan_id)
if not plan:
print(f"[!] No plan found with ID {plan_id}")
# Suggest similar IDs
all_plans = database.get_all_plans(active_only=False)
existing_ids = [p['id'] for p in all_plans]
if existing_ids:
closest = min(existing_ids, key=lambda x: abs(x - plan_id))
print(f" Did you mean ID {closest}? Run 'python tracker.py list' to see all plans")
return
print(f"\n--- Edit Plan: {plan['name']} ---")
print("Press Enter to keep current value.\n")
updates = {}
history_logs = [] # Track changes for history
# Go through each editable field and offer to update it
new_name = prompt("Plan name", default=plan.get("name", ""))
if new_name != plan.get("name", ""):
updates["name"] = new_name
history_logs.append(("name", plan.get("name", ""), new_name))
new_type = prompt_choice("Type", VALID_TYPES, default=plan.get("type", "other"))
if new_type != plan.get("type"):
updates["type"] = new_type
history_logs.append(("type", plan.get("type", ""), new_type))
new_provider = prompt("Provider", default=plan.get("provider", "") or "")
if new_provider != (plan.get("provider") or ""):
updates["provider"] = new_provider
history_logs.append(("provider", plan.get("provider", ""), new_provider))
new_vm = prompt("Assigned VM", default=plan.get("assigned_vm", "") or "")
if new_vm != (plan.get("assigned_vm") or ""):
updates["assigned_vm"] = new_vm
history_logs.append(("assigned_vm", plan.get("assigned_vm", ""), new_vm))
current_cost = plan.get("cost", 0.0) or 0.0
new_cost = prompt_float("Cost (AUD)", default=current_cost)
if new_cost != current_cost:
updates["cost"] = new_cost
history_logs.append(("cost", str(current_cost), str(new_cost)))
# Special logging for cost changes
change_pct = ((new_cost - current_cost) / current_cost * 100) if current_cost else 0
change_dir = "increased" if new_cost > current_cost else "decreased" if new_cost < current_cost else "changed"
print(f" [!] Cost {change_dir} by {abs(change_pct):.1f}% (${current_cost:.2f} → ${new_cost:.2f})")
new_cycle = prompt_choice("Billing cycle", VALID_CYCLES, default=plan.get("billing_cycle", "monthly"))
if new_cycle != plan.get("billing_cycle"):
updates["billing_cycle"] = new_cycle
history_logs.append(("billing_cycle", plan.get("billing_cycle", ""), new_cycle))
current_renewal = format_date_display(plan.get("next_renewal", ""))
raw_date = prompt("Next renewal date (DD/MM/YYYY)", default=current_renewal)
if raw_date and raw_date != current_renewal:
try:
new_renewal = parse_date_input(raw_date)
updates["next_renewal"] = new_renewal
history_logs.append(("next_renewal", plan.get("next_renewal", ""), new_renewal))
except ValueError as e:
print(f" [!] {e} - renewal date not changed")
current_auto = bool(plan.get("auto_renew", 0))
new_auto = prompt_yn("Auto-renews?", default=current_auto)
if new_auto != current_auto:
updates["auto_renew"] = 1 if new_auto else 0
history_logs.append(("auto_renew", str(current_auto), str(new_auto)))
new_notes = prompt("Notes", default=plan.get("notes", "") or "")
if new_notes != (plan.get("notes") or ""):
updates["notes"] = new_notes
history_logs.append(("notes", "updated", "updated")) # Don't log full notes content
if updates:
database.update_plan(plan_id, updates)
# Log changes to history
for field, old_val, new_val in history_logs:
database.log_plan_change(plan_id, field, str(old_val), str(new_val))
# Log to audit log
_log_plan_change(plan_id, "edit", f"Updated {len(updates)} field(s): {', '.join(updates.keys())}")
print(f"\n[*] Plan {plan_id} updated ({len(updates)} field(s) changed)")
else:
print("\n[*] No changes made")
def cmd_provider_report():
"""Show spending breakdown by provider."""
plans = database.get_all_plans(active_only=True)
if not plans:
print("\nNo active plans found.")
return
# Group by provider
by_provider = {}
for p in plans:
prov = (p.get("provider") or "Unknown").strip()
if not prov:
prov = "Unknown"
cost = p.get("cost", 0.0) or 0.0
cycle = p.get("billing_cycle", "monthly") or "monthly"
monthly_cost = cost * MONTHLY_EQUIV.get(cycle, 1.0)
by_provider.setdefault(prov, {"count": 0, "monthly": 0.0, "annual": 0.0, "plans": []})
by_provider[prov]["count"] += 1
by_provider[prov]["monthly"] += monthly_cost
by_provider[prov]["annual"] += monthly_cost * 12
by_provider[prov]["plans"].append(p)
print("\n=== Provider Spend Report ===\n")
# Sort by monthly spend descending
sorted_providers = sorted(by_provider.items(), key=lambda x: x[1]["monthly"], reverse=True)
rows = []
total_monthly = 0.0
for prov, stats in sorted_providers:
rows.append([
prov,
stats["count"],
f"${stats['monthly']:.2f}",
f"${stats['annual']:.2f}",
])
total_monthly += stats["monthly"]
headers = ["Provider", "Plans", "Monthly", "Annual"]
print(tabulate(rows, headers=headers, tablefmt="simple"))
print(f"\n Total monthly spend: AUD ${total_monthly:.2f}")
print(f" Total annual spend: AUD ${total_monthly * 12:.2f}")
print(f" Providers tracked: {len(by_provider)}")
# Show top provider's plans
if sorted_providers:
top_provider = sorted_providers[0]
print(f"\n Top provider: {top_provider[0]} ({top_provider[1]['count']} plans)")
def cmd_budget_report():
"""Show budget variance report comparing actual spend vs budget."""
from datetime import datetime
# Load budget config
config = alerts.load_config()
monthly_budget = config.get("monthly_budget")
annual_budget = config.get("annual_budget")
plans = database.get_all_plans(active_only=True)
expenses = database.get_all_expenses(active_only=True)
# Calculate actual monthly spend
actual_monthly = 0.0
for p in plans:
cost = p.get("cost", 0.0) or 0.0
cycle = p.get("billing_cycle", "monthly") or "monthly"
actual_monthly += cost * MONTHLY_EQUIV.get(cycle, 1.0)
for e in expenses:
cost = e.get("cost", 0.0) or 0.0
cycle = e.get("billing_cycle", "monthly") or "monthly"
actual_monthly += cost * MONTHLY_EQUIV.get(cycle, 1.0)
actual_annual = actual_monthly * 12
print("\n=== Budget Variance Report ===\n")
# Monthly budget analysis
if monthly_budget and monthly_budget > 0:
variance = actual_monthly - monthly_budget
variance_pct = (variance / monthly_budget) * 100
remaining = monthly_budget - actual_monthly
print(f" Monthly Budget: ${monthly_budget:,.2f}")
print(f" Actual Monthly: ${actual_monthly:,.2f}")
print(f" Variance: ${variance:+,.2f} ({variance_pct:+.1f}%)")
print(f" Remaining: ${remaining:,.2f}")
if variance_pct > 10:
print(f" [!] OVER BUDGET by {variance_pct:.1f}%")
elif variance_pct > 0:
print(f" [*] Near budget limit (+{variance_pct:.1f}%)")
else:
print(f" [OK] Under budget ({abs(variance_pct):.1f}% remaining)")
print()
# Annual budget analysis
if annual_budget and annual_budget > 0:
variance = actual_annual - annual_budget
variance_pct = (variance / annual_budget) * 100
remaining = annual_budget - actual_annual
print(f" Annual Budget: ${annual_budget:,.2f}")
print(f" Projected Annual: ${actual_annual:,.2f}")
print(f" Variance: ${variance:+,.2f} ({variance_pct:+.1f}%)")
print(f" Remaining: ${remaining:,.2f}")
if variance_pct > 10:
print(f" [!] OVER ANNUAL BUDGET by {variance_pct:.1f}%")
elif variance_pct > 0:
print(f" [*] Near annual budget limit (+{variance_pct:.1f}%)")
else:
print(f" [OK] Under annual budget ({abs(variance_pct):.1f}% remaining)")
print()
# Spend breakdown by category
print(" Spend by Category:")
by_type = {}
for p in plans:
t = p.get("type", "other")
cost = p.get("cost", 0.0) or 0.0
cycle = p.get("billing_cycle", "monthly") or "monthly"
monthly = cost * MONTHLY_EQUIV.get(cycle, 1.0)
by_type[t] = by_type.get(t, 0.0) + monthly
for e in expenses:
cat = e.get("category") or "other"
cost = e.get("cost", 0.0) or 0.0
cycle = e.get("billing_cycle", "monthly") or "monthly"
monthly = cost * MONTHLY_EQUIV.get(cycle, 1.0)
by_type[cat] = by_type.get(cat, 0.0) + monthly
total = sum(by_type.values())
for cat, amount in sorted(by_type.items(), key=lambda x: x[1], reverse=True):
pct = (amount / total * 100) if total else 0
print(f" {cat:12} ${amount:>8.2f} ({pct:>5.1f}%)")
print(f"\n Total Monthly: ${actual_monthly:,.2f}")
print()
if not monthly_budget and not annual_budget:
print(" [!] No budget configured. Set monthly_budget or annual_budget in config.json")
print()
def cmd_date_range_report(from_date: str = None, to_date: str = None):
"""Show plans with renewals within a date range."""
from datetime import datetime, timedelta
# Parse dates
if not from_date:
# Default to today
from_dt = datetime.now()
else:
try:
from_dt = datetime.strptime(from_date, "%Y-%m-%d")
except ValueError:
try:
from_dt = datetime.strptime(from_date, "%d/%m/%Y")
except ValueError:
print(f"[!] Invalid from_date format. Use YYYY-MM-DD or DD/MM/YYYY")
return
if not to_date:
# Default to 30 days from from_date
to_dt = from_dt + timedelta(days=30)
else:
try:
to_dt = datetime.strptime(to_date, "%Y-%m-%d")
except ValueError:
try:
to_dt = datetime.strptime(to_date, "%d/%m/%Y")
except ValueError:
print(f"[!] Invalid to_date format. Use YYYY-MM-DD or DD/MM/YYYY")
return
plans = database.get_all_plans(active_only=True)
# Filter plans with renewals in range
matching = []
for p in plans:
renewal = p.get("next_renewal")
if renewal:
try:
renewal_dt = datetime.strptime(renewal, "%Y-%m-%d")
if from_dt <= renewal_dt <= to_dt:
matching.append(p)
except ValueError:
pass
# Sort by renewal date
matching.sort(key=lambda p: p.get("next_renewal", ""))
print(f"\n=== Renewals from {from_dt.strftime('%d/%m/%Y')} to {to_dt.strftime('%d/%m/%Y')} ===\n")
if not matching:
print(" No renewals found in this date range.")
return
total_cost = sum(p.get("cost", 0) or 0 for p in matching)
rows = []
for p in matching:
days = days_until(p.get("next_renewal", ""))
rows.append([
p['id'],
p.get('name', '')[:25],
p.get('provider', '-')[:15],
format_date_display(p.get('next_renewal', '')),
colour_days(days) if days < 9999 else '-',
f"${p.get('cost', 0):.2f}",
])
headers = ["ID", "Name", "Provider", "Renewal", "Days", "Cost"]
print(tabulate(rows, headers=headers, tablefmt="simple"))
print(f"\n Total: {len(matching)} renewal(s), ${total_cost:.2f}")
# Group by month
by_month = {}
for p in matching:
renewal = p.get("next_renewal", "")
if renewal:
month_key = renewal[:7] # YYYY-MM
month_label = datetime.strptime(month_key, "%Y-%m").strftime("%B %Y")
by_month.setdefault(month_label, []).append(p)
if len(by_month) > 1:
print("\n By Month:")
for month, plans in sorted(by_month.items()):
month_cost = sum(p.get("cost", 0) or 0 for p in plans)
print(f" {month}: {len(plans)} plan(s), ${month_cost:.2f}")
print()
def cmd_forecast(months: int = 6):
"""Forecast cash flow for upcoming months based on renewal dates."""
from datetime import datetime, timedelta
from collections import defaultdict
plans = database.get_all_plans(active_only=True)
# Group renewals by month
monthly_renewals = defaultdict(list)
for p in plans:
renewal = p.get("next_renewal")
if renewal:
try:
renewal_dt = datetime.strptime(renewal, "%Y-%m-%d")
month_key = renewal_dt.strftime("%Y-%m")
monthly_renewals[month_key].append(p)
except ValueError:
pass
print(f"\n=== Cash Flow Forecast (Next {months} Months) ===\n")
today = datetime.now()
forecast_data = []
for i in range(months):
month_dt = today + timedelta(days=30*i)
month_key = month_dt.strftime("%Y-%m")
month_label = month_dt.strftime("%B %Y")
renewals = monthly_renewals.get(month_key, [])
total_cost = sum(p.get("cost", 0) or 0 for p in renewals)
forecast_data.append({
"month": month_label,
"count": len(renewals),
"cost": total_cost,
})
# Display forecast
max_cost = max(f["cost"] for f in forecast_data) if forecast_data else 1
for f in forecast_data:
bar_length = int((f["cost"] / max_cost) * 20) if max_cost > 0 else 0
bar = "#" * bar_length
warning = " [!]" if f["cost"] > 200 else ""
print(f" {f['month']:12} {bar:<20} ${f['cost']:>7.2f} ({f['count']} plans){warning}")
# Identify expensive months
expensive = [f for f in forecast_data if f["cost"] > 200]
if expensive:
print(f"\n [!] Expensive months (> $200): {len(expensive)}")
for e in expensive:
print(f" {e['month']}: ${e['cost']:.2f}")
total_forecast = sum(f["cost"] for f in forecast_data)
print(f"\n Total forecasted spend: ${total_forecast:.2f}")
print(f" Average per month: ${total_forecast/months:.2f}" if months > 0 else "")
print()
def cmd_stats():
"""Show detailed statistics about plans and expenses."""
plans = database.get_all_plans(active_only=False)
active_plans = [p for p in plans if p.get("active", 1)]
inactive_plans = [p for p in plans if not p.get("active", 1)]
expenses = database.get_all_expenses(active_only=False)
active_expenses = [e for e in expenses if e.get("active", 1)]
print("\n=== Data Plan Tracker Statistics ===\n")
# Overview
print(" OVERVIEW")
print(f" Total plans (all time): {len(plans)}")
print(f" Active plans: {len(active_plans)}")
print(f" Inactive plans: {len(inactive_plans)}")
print(f" Active expenses: {len(active_expenses)}")
print()
# Plan types breakdown
if active_plans:
print(" PLANS BY TYPE")
by_type = {}
for p in active_plans:
t = p.get("type", "other")
by_type[t] = by_type.get(t, 0) + 1
for t, count in sorted(by_type.items()):
print(f" {t:12} {count} plan(s)")
print()
# Financials
if active_plans:
print(" FINANCIALS (active plans)")
monthly = 0.0
for p in active_plans:
cost = p.get("cost", 0.0) or 0.0
cycle = p.get("billing_cycle", "monthly") or "monthly"
monthly += cost * MONTHLY_EQUIV.get(cycle, 1.0)
for e in active_expenses:
cost = e.get("cost", 0.0) or 0.0
cycle = e.get("billing_cycle", "monthly") or "monthly"
monthly += cost * MONTHLY_EQUIV.get(cycle, 1.0)
print(f" Monthly spend: AUD ${monthly:.2f}")
print(f" Annual spend: AUD ${monthly * 12:.2f}")
print()
# Renewals analysis
if active_plans:
print(" UPCOMING RENEWALS")
expiring_7 = sum(1 for p in active_plans if 0 <= days_until(p.get("next_renewal", "")) <= 7)
expiring_14 = sum(1 for p in active_plans if 0 <= days_until(p.get("next_renewal", "")) <= 14)
expiring_30 = sum(1 for p in active_plans if 0 <= days_until(p.get("next_renewal", "")) <= 30)
overdue = sum(1 for p in active_plans if days_until(p.get("next_renewal", "")) < 0)
no_date = sum(1 for p in active_plans if not p.get("next_renewal"))
print(f" Next 7 days: {expiring_7}")
print(f" Next 14 days: {expiring_14}")
print(f" Next 30 days: {expiring_30}")
if overdue:
print(f" OVERDUE: {overdue} ⚠️")
if no_date:
print(f" No date set: {no_date}")
print()
# Phone numbers
with_numbers = [p for p in active_plans if p.get("phone_number")]
with_num_expiry = [p for p in active_plans if p.get("number_expiry")]
if with_numbers:
print(" PHONE NUMBERS")
print(f" Plans with numbers: {len(with_numbers)}")
print(f" With expiry tracking: {len(with_num_expiry)}")
nums_expiring = sum(1 for p in with_num_expiry
if 0 <= days_until(p.get("number_expiry", "")) <= 30)
nums_overdue = sum(1 for p in with_num_expiry
if days_until(p.get("number_expiry", "")) < 0)
if nums_expiring:
print(f" Expiring soon: {nums_expiring} 📞")
if nums_overdue:
print(f" OVERDUE: {nums_overdue} ⚠️")
print()
# Auto-renew analysis
auto_renew_count = sum(1 for p in active_plans if p.get("auto_renew"))
manual_count = len(active_plans) - auto_renew_count
if active_plans:
print(" AUTO-RENEW STATUS")
print(f" Auto-renew: {auto_renew_count}")
print(f" Manual renew: {manual_count}")
print()
# VM assignments
vms_used = set(p.get("assigned_vm", "").strip() for p in active_plans if p.get("assigned_vm"))
unassigned = sum(1 for p in active_plans if not p.get("assigned_vm"))
print(" VM ASSIGNMENTS")
print(f" Unique VMs: {len(vms_used)}")
print(f" Unassigned: {unassigned} plan(s)")
print()
def cmd_duplicates():
"""Detect and report potential duplicate plans."""
plans = database.get_all_plans(active_only=False)
print("\n=== Duplicate Detection ===\n")
duplicates_found = []
# Check 1: Exact phone number duplicates
phone_map = {}
for p in plans:
phone = (p.get("phone_number") or "").strip()
if phone:
if phone in phone_map:
duplicates_found.append({
"type": "Same phone number",
"plans": [phone_map[phone], p],
"detail": phone
})
else:
phone_map[phone] = p
# Check 2: Same name + provider (case insensitive)
name_provider_map = {}
for p in plans:
name = (p.get("name") or "").lower().strip()
provider = (p.get("provider") or "").lower().strip()
key = f"{name}|{provider}"
if name and provider:
if key in name_provider_map:
duplicates_found.append({
"type": "Same name + provider",
"plans": [name_provider_map[key], p],
"detail": f"{p.get('name')} ({p.get('provider')})"
})
else:
name_provider_map[key] = p
# Check 3: Same provider + VM + cost (likely duplicate entry)
provider_vm_cost_map = {}
for p in plans:
provider = (p.get("provider") or "").lower().strip()
vm = (p.get("assigned_vm") or "").lower().strip()
cost = p.get("cost", 0)
key = f"{provider}|{vm}|{cost}"
if provider and vm:
if key in provider_vm_cost_map:
# Only flag if names are also similar
other = provider_vm_cost_map[key]
other_name = (other.get("name") or "").lower()
this_name = (p.get("name") or "").lower()
# Simple similarity: first 5 chars match
if other_name[:5] == this_name[:5]:
duplicates_found.append({
"type": "Similar plan (same provider/VM/cost)",
"plans": [other, p],
"detail": f"${cost} at {p.get('provider')} on {p.get('assigned_vm')}"
})
else:
provider_vm_cost_map[key] = p
# Report results
if duplicates_found:
print(f"[!] Found {len(duplicates_found)} potential duplicate(s):\n")
for dup in duplicates_found:
print(f" {dup['type']}: {dup['detail']}")
for p in dup['plans']:
status = " (inactive)" if not p.get("active", 1) else ""
print(f" - [{p['id']}] {p.get('name')}{status}")
print()
print(" Tip: Review these plans and consider merging or deactivating duplicates.")
else:
print("[OK] No potential duplicates found.")