added comments

This commit is contained in:
Valentijn
2026-03-18 19:57:30 +01:00
parent c271656f51
commit 47bb6585d1
4 changed files with 29 additions and 7 deletions

1
API.py
View File

@@ -0,0 +1 @@
# TODO

4
DB.py
View File

@@ -9,6 +9,7 @@ class Database:
def _setup_tables(self): def _setup_tables(self):
# create the shifts table.
cur = self._con.cursor() cur = self._con.cursor()
cur.execute(''' cur.execute('''
CREATE TABLE IF NOT EXISTS shifts ( CREATE TABLE IF NOT EXISTS shifts (
@@ -27,10 +28,12 @@ class Database:
def insert_shifts(self, shifts): def insert_shifts(self, shifts):
# start db connection
cur = self._con.cursor() cur = self._con.cursor()
inserted = 0 inserted = 0
for shift in shifts: for shift in shifts:
# parse all information from the shift
start = shift.get('start_datetime', 'N/A') start = shift.get('start_datetime', 'N/A')
end = shift.get('end_datetime', 'N/A') end = shift.get('end_datetime', 'N/A')
@@ -38,6 +41,7 @@ class Database:
duration = shift.get('duration', 'N/A') duration = shift.get('duration', 'N/A')
description = shift.get('shift_remark', shift.get('description', 'N/A')) description = shift.get('shift_remark', shift.get('description', 'N/A'))
# insert it into the db.
cur.execute(""" cur.execute("""
INSERT OR IGNORE INTO shifts INSERT OR IGNORE INTO shifts
(shift_start, shift_end, department, duration, description) (shift_start, shift_end, department, duration, description)

18
PMT.py
View File

@@ -22,12 +22,13 @@ class PMT:
return target_monday.strftime("%Y-%m-%d") return target_monday.strftime("%Y-%m-%d")
def login(self): def login(self):
self.session = requests.Session() self.session = requests.Session()
login_url = f"{self.base_url}/login" login_url = f"{self.base_url}/login"
resp = self.session.get(login_url) resp = self.session.get(login_url)
# Step 2: SSO login POST # SSO login POST
sso_data = { sso_data = {
"username": self._username, "username": self._username,
"password": self._password, "password": self._password,
@@ -43,22 +44,29 @@ class PMT:
json=sso_data, json=sso_data,
headers={'Content-Type': 'application/json'}) headers={'Content-Type': 'application/json'})
# Check if it succeeded.
if sso_resp.status_code != 200 or not sso_resp.json().get('result', {}).get('authenticated'): if sso_resp.status_code != 200 or not sso_resp.json().get('result', {}).get('authenticated'):
print("Login failed!") print("Login failed!")
print(sso_resp.text) print(sso_resp.text)
sys.exit(1) sys.exit(1)
# Store the useful information in some class fields
login_data = sso_resp.json()['result'] login_data = sso_resp.json()['result']
self.context_token = login_data['context_token'] self.context_token = login_data['context_token']
self.user_token = login_data['user_token'] self.user_token = login_data['user_token']
print(f"✅ Logged in as {self._username} (store AH 8541 Rhoon)") # return session info
print(f"✅ Logged in as {self._username}")
return self.session, self.context_token, self.user_token return self.session, self.context_token, self.user_token
def get_shifts(self, days_ahead=14): def get_shifts(self, days_ahead=14):
# raise if not logged in.
if not self.session or not self.context_token or not self.user_token: if not self.session or not self.context_token or not self.user_token:
raise ValueError("Must call login() first!") raise ValueError("Must call login() first!")
# define date ranges
shifts = [] shifts = []
from_date = datetime.now().strftime("%Y-%m-%d") from_date = datetime.now().strftime("%Y-%m-%d")
@@ -66,6 +74,7 @@ class PMT:
print(f"Fetching shifts from {from_date} to {to_date}...") print(f"Fetching shifts from {from_date} to {to_date}...")
# send request for shifts
headers = { headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:148.0) Gecko/20100101 Firefox/148.0', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:148.0) Gecko/20100101 Firefox/148.0',
'Accept': 'application/json, text/plain, */*', 'Accept': 'application/json, text/plain, */*',
@@ -89,6 +98,8 @@ class PMT:
resp = self.session.get(shifts_url, headers=headers, params=params) resp = self.session.get(shifts_url, headers=headers, params=params)
# check if request succeeded
if resp.status_code == 200: if resp.status_code == 200:
data = resp.json() data = resp.json()
week_shifts = data.get('result', {}).get('shift_instances', []) week_shifts = data.get('result', {}).get('shift_instances', [])
@@ -98,6 +109,7 @@ class PMT:
print(f"❌ Failed: {resp.status_code}") print(f"❌ Failed: {resp.status_code}")
print(resp.text[:500]) print(resp.text[:500])
# return all shifts fetched
return shifts return shifts
@classmethod @classmethod
@@ -106,7 +118,7 @@ class PMT:
print("No upcoming shifts found.") print("No upcoming shifts found.")
return return
print("\n📅 UPCOMING SHIFTS:\n") print("\nUPCOMING SHIFTS:\n")
print("Date | Time | Dept | Duration | Description") print("Date | Time | Dept | Duration | Description")
print("-" * 80) print("-" * 80)

View File

@@ -4,21 +4,26 @@ from dotenv import load_dotenv
import os import os
def main(): def main():
# Load the environment
load_dotenv(override=True) load_dotenv(override=True)
# Set up database, webserver and PMT connection
db = Database() db = Database()
pmt = PMT() pmt = PMT()
# fetch PMT shifts
pmt.login() pmt.login()
days_ahead = int(os.environ.get("DAYS_TO_FETCH")) days_ahead = int(os.environ.get("DAYS_TO_FETCH"))
shifts = pmt.get_shifts(days_ahead) shifts = pmt.get_shifts(days_ahead)
PMT.print_shifts(shifts) PMT.print_shifts(shifts)
# Insert those shifts into the database
db.insert_shifts(shifts) db.insert_shifts(shifts)
print(f"\nFound {len(shifts)} shifts total.")
if __name__ == "__main__": if __name__ == "__main__":
main() main()