from datetime import datetime class ScheduleRepository: def __init__(self, connection): self.connection = connection def create(self, user_id: int, enter_time: datetime, day_of_week: str, out_time: datetime | None): with self.connection.cursor() as cursor: cursor.execute( """ INSERT INTO schedules (user_id, enter_time, day_of_week, out_time) VALUES (%s, %s, %s, %s) RETURNING id, user_id, enter_time, day_of_week, out_time """, (user_id, enter_time, day_of_week, out_time), ) schedule = cursor.fetchone() self.connection.commit() return schedule def list_weekly(self, company_id: int | None = None): params = () where = "" if company_id is not None: where = "WHERE company_users.company_id = %s" params = (company_id,) with self.connection.cursor() as cursor: cursor.execute( f""" SELECT schedules.id, schedules.user_id, schedules.enter_time, schedules.day_of_week, schedules.out_time FROM schedules INNER JOIN company_users ON company_users.user_id = schedules.user_id {where} ORDER BY schedules.day_of_week, schedules.enter_time, schedules.id """, params, ) return cursor.fetchall() def update_clock_out(self, user_id: int, day_of_week: str, out_time: datetime): with self.connection.cursor() as cursor: cursor.execute( """ UPDATE schedules SET out_time = %s, date_updated = NOW() WHERE id = ( SELECT id FROM schedules WHERE user_id = %s AND day_of_week = %s ORDER BY date_created DESC LIMIT 1 ) RETURNING id, user_id, enter_time, day_of_week, out_time """, (out_time, user_id, day_of_week), ) schedule = cursor.fetchone() self.connection.commit() return schedule