62 lines
1.9 KiB
Python
62 lines
1.9 KiB
Python
import sqlite3
|
|
|
|
|
|
class Database:
|
|
def __init__(self):
|
|
self._con = sqlite3.connect("shifts.db")
|
|
self._setup_tables()
|
|
pass
|
|
|
|
|
|
def _setup_tables(self):
|
|
# create the shifts table.
|
|
cur = self._con.cursor()
|
|
cur.execute('''
|
|
CREATE TABLE IF NOT EXISTS shifts (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
shift_start DATETIME NOT NULL,
|
|
shift_end DATETIME NOT NULL,
|
|
department TEXT NOT NULL,
|
|
duration TEXT NOT NULL,
|
|
description TEXT,
|
|
fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
|
|
UNIQUE(shift_start, department) -- No duplicates
|
|
);
|
|
''')
|
|
self._con.commit()
|
|
|
|
|
|
def insert_shifts(self, shifts):
|
|
# start db connection
|
|
cur = self._con.cursor()
|
|
inserted = 0
|
|
|
|
for shift in shifts:
|
|
# parse all information from the shift
|
|
start = shift.get('start_datetime', 'N/A')
|
|
end = shift.get('end_datetime', 'N/A')
|
|
|
|
department = shift.get('department_name', 'N/A')
|
|
duration = shift.get('duration', 'N/A')
|
|
description = shift.get('shift_remark', shift.get('description', 'N/A'))
|
|
|
|
# insert it into the db.
|
|
cur.execute("""
|
|
INSERT OR IGNORE INTO shifts
|
|
(shift_start, shift_end, department, duration, description)
|
|
VALUES (?, ?, ?, ?, ?)
|
|
""", (start, end, department, duration, description))
|
|
|
|
if cur.rowcount > 0:
|
|
inserted += 1
|
|
|
|
self._con.commit()
|
|
print(f"✅ Inserted {inserted}/{len(shifts)} new shifts")
|
|
|
|
def delete_future_shifts(self):
|
|
cur = self._con.cursor()
|
|
cur.execute("DELETE FROM shifts WHERE shift_start > current_timestamp")
|
|
self._con.commit()
|
|
print(f"✅ Deleted all future shifts")
|