50 lines
1.4 KiB
Python
50 lines
1.4 KiB
Python
# This file is for database functions
|
|
from db.db import get_db
|
|
|
|
conn = get_db()
|
|
|
|
def get_users(search):
|
|
# Get search param
|
|
search_param = f"%{search}%"
|
|
|
|
# Generate cursor
|
|
cursor = conn.cursor()
|
|
|
|
# Search if needed
|
|
if search:
|
|
cursor.execute("SELECT * FROM Employees WHERE username LIKE ?", (search_param,))
|
|
else:
|
|
cursor.execute("SELECT * FROM Employees")
|
|
|
|
# Fetch users from database
|
|
users = cursor.fetchall()
|
|
return users
|
|
|
|
def get_attendance(id):
|
|
# Set up query for worked hours, group by and ordered by date
|
|
cursor = conn.cursor()
|
|
cursor.execute("""
|
|
SELECT date, sum(hours_worked) as hours_worked
|
|
FROM Attendance
|
|
WHERE employee_id = ?
|
|
GROUP BY date
|
|
ORDER BY date DESC
|
|
""", (id,))
|
|
attendance = cursor.fetchall()
|
|
|
|
# Fetch username from database
|
|
# I am not using table JOIN because when theres no attendance, the query returns no rows (and shows user doesnt exist)
|
|
cursor.execute("SELECT username FROM Employees WHERE id = ?", (id,))
|
|
username = cursor.fetchone()
|
|
|
|
# Check if user exists
|
|
if not username:
|
|
return {"username": None, "attendance": []}
|
|
|
|
# Return clean api response
|
|
return {
|
|
"username": username[0],
|
|
"attendance": attendance
|
|
}
|
|
|