-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.py
More file actions
237 lines (189 loc) · 7.36 KB
/
Copy pathsetup.py
File metadata and controls
237 lines (189 loc) · 7.36 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
# setup.py
# First-time setup script for the Data Plan Tracker.
#
# Run this once to:
# 1. Install required Python packages
# 2. Create config.json if it does not exist
# 3. Register a Windows Task Scheduler task to run the daily check at 9am
#
# Usage: python setup.py
import subprocess
import sys
import os
import json
# All paths are relative to this script's location so nothing breaks
# if you move the project folder
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_PATH = os.path.join(SCRIPT_DIR, "config.json")
TRACKER_PATH = os.path.join(SCRIPT_DIR, "tracker.py")
# The Task Scheduler task name - must be unique on this PC
TASK_NAME = "DataPlanTrackerDailyCheck"
def step(msg: str):
"""Print a step header so progress is easy to read."""
print(f"\n[*] {msg}")
def ok(msg: str):
print(f" OK: {msg}")
def warn(msg: str):
print(f" [!] {msg}")
# ---------------------------------------------------------------------------
# Step 1 - Install packages
# ---------------------------------------------------------------------------
def install_packages():
step("Installing required Python packages...")
requirements = os.path.join(SCRIPT_DIR, "requirements.txt")
if not os.path.exists(requirements):
warn("requirements.txt not found - skipping package install")
return
result = subprocess.run(
[sys.executable, "-m", "pip", "install", "-r", requirements],
capture_output=True,
text=True
)
if result.returncode == 0:
ok("All packages installed successfully")
else:
warn("pip install had errors. Output:")
for line in result.stdout.splitlines()[-10:]: # Show last 10 lines
print(f" {line}")
for line in result.stderr.splitlines()[-5:]:
print(f" {line}")
# ---------------------------------------------------------------------------
# Step 2 - Create config.json if missing
# ---------------------------------------------------------------------------
def create_config():
step("Checking config.json...")
if os.path.exists(CONFIG_PATH):
ok("config.json already exists - not overwriting")
return
default_config = {
"alert_days_warning": 14,
"email": {
"enabled": False,
"smtp_server": "smtp.gmail.com",
"smtp_port": 587,
"sender_email": "",
"sender_password": "",
"recipient_email": ""
},
"desktop_notification": {
"enabled": True
}
}
try:
with open(CONFIG_PATH, "w") as f:
json.dump(default_config, f, indent=2)
ok(f"config.json created at: {CONFIG_PATH}")
except Exception as e:
warn(f"Could not create config.json: {e}")
# ---------------------------------------------------------------------------
# Step 3 - Create Windows Task Scheduler task
# ---------------------------------------------------------------------------
def create_scheduled_task():
"""
Register a Windows Task Scheduler task that runs 'python tracker.py check'
every day at 9:00 AM.
Uses schtasks.exe which is available on all Windows versions.
Requires the script to be run with administrator privileges to create tasks.
"""
step("Creating Windows Task Scheduler task...")
python_exe = sys.executable # Full path to python.exe currently running
tracker_script = TRACKER_PATH
# Build the schtasks command
# /SC DAILY = run every day
# /ST 09:00 = start time 9am
# /F = force (overwrite if task already exists)
# /RL HIGHEST = run with highest available privileges
command = [
"schtasks", "/Create",
"/TN", TASK_NAME,
"/TR", f'"{python_exe}" "{tracker_script}" check',
"/SC", "DAILY",
"/ST", "09:00",
"/F", # Overwrite existing task with same name
"/RL", "HIGHEST"
]
try:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode == 0:
ok(f"Task '{TASK_NAME}' created - will run daily at 9:00 AM")
ok(f"Python: {python_exe}")
ok(f"Script: {tracker_script}")
else:
warn(f"schtasks returned error code {result.returncode}")
warn(result.stderr.strip() or result.stdout.strip())
print()
print(" To create the task manually:")
print(f" 1. Open Task Scheduler (search in Start menu)")
print(f" 2. Create Basic Task -> name it '{TASK_NAME}'")
print(f" 3. Trigger: Daily at 9:00 AM")
print(f" 4. Action: Start a program")
print(f" Program: {python_exe}")
print(f" Arguments: \"{tracker_script}\" check")
except FileNotFoundError:
warn("schtasks.exe not found - are you on Windows?")
# ---------------------------------------------------------------------------
# Step 4 - Print email setup instructions
# ---------------------------------------------------------------------------
def print_email_instructions():
step("Email alert setup (optional)")
print("""
Email alerts are disabled by default. To enable them:
1. Open config.json in this folder
2. Set "enabled": true under the "email" section
3. Fill in:
"sender_email" - your Gmail address (e.g. you@gmail.com)
"sender_password" - an App Password (NOT your regular Gmail password)
"recipient_email" - where to send alerts (can be same as sender)
To create a Gmail App Password:
a. Go to: https://myaccount.google.com/security
b. Enable 2-Step Verification if not already on
c. Search for "App passwords"
d. Create a new app password -> copy the 16-character code
e. Paste it into "sender_password" in config.json
Note: App Passwords only work with 2-Step Verification enabled.
""")
# ---------------------------------------------------------------------------
# Step 5 - Initialise the database
# ---------------------------------------------------------------------------
def init_database():
step("Initialising database...")
try:
# Import here so setup.py works even before packages are installed
# (the db module only uses built-in sqlite3)
sys.path.insert(0, SCRIPT_DIR)
import database
database.init_db()
ok(f"Database ready: {database.DB_PATH}")
except Exception as e:
warn(f"Database init failed: {e}")
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main():
print("=" * 60)
print(" Data Plan Tracker - First-Time Setup")
print("=" * 60)
install_packages()
create_config()
init_database()
create_scheduled_task()
print_email_instructions()
print("\n" + "=" * 60)
print(" Setup complete!")
print("=" * 60)
print("""
Next steps:
1. Add your first plan:
python tracker.py add
2. Or load sample data to see how it looks:
python tracker.py seed
python tracker.py list
3. See spending summary:
python tracker.py summary
4. Run the daily check manually to test alerts:
python tracker.py check
5. (Optional) Configure email alerts in config.json
See instructions above.
""")
if __name__ == "__main__":
main()