from .database import DatabaseController from models.users.user import User from models.users.customer import Customer from models.users.seller import Seller from models.users.admin import Admin class UserController(DatabaseController): FIELDS = ['id', 'username', 'password', 'firstName', 'lastName', 'email', 'phone', 'role'] TYPE = User def __init__(self): super().__init__() def convert_type(self, user: User | None ) -> User | Customer | Seller | Admin | None: """ Function to convert a given user to their correct subtype """ if user is None: return None # Set the object to the correct type type = Customer if user.role == "Seller": type = Seller if user.role == "Admin": type = Admin obj = self.new_instance(type, user.__dict__) return obj def create(self, user: User): params = [ user.username, user.password, user.firstName, user.lastName, user.email, user.phone, user.role ] query = """ INSERT INTO Users (username, password, first_name, last_name, email, phone, role) VALUES (?, ?, ?, ?, ?, ?, ?) """ self.do(query, params) def read(self, username: str) -> User | None: params = [ username ] query = "SELECT * FROM Users WHERE Username = ?" return self.convert_type(self.get_one(query, params)) def read_id(self, id: int) -> User | None: params = [ id ] query = "SELECT * FROM Users WHERE id = ?" return self.convert_type(self.get_one(query, params)) def read_all(self, username: str = "") -> list[User] | None: params = [ "%" + username + "%" ] query = """ SELECT * FROM Users WHERE Username like ? """ return self.get_many(query, params) def update(self, user: User): params = [ user.username, user.firstName, user.lastName, user.email, user.phone, user.role, user.id ] query = """ UPDATE Users SET username = ?, first_name = ?, last_name = ?, email = ?, phone = ?, role = ? WHERE id = ? """ return self.do(query, params) def delete(self, id: int): params = [ id ] query = """ DELETE FROM Users WHERE id = ? """ return self.do(query, params)