### Install Python Dependencies Source: https://github.com/junnel10001/alphasyshr/blob/main/README.md Installs all necessary Python packages required for the AlphaSys HR Payroll System to run, as listed in the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Run AlphaSys Application Source: https://github.com/junnel10001/alphasyshr/blob/main/README.md Launches the AlphaSys HR Payroll System using the Streamlit framework. This command starts the web application. ```bash streamlit run app.py ``` -------------------------------- ### Clone AlphaSys Repository Source: https://github.com/junnel10001/alphasyshr/blob/main/README.md Clones the AlphaSys HR Payroll System repository from a given URL. This is the first step in setting up the project locally. ```bash git clone [repository_url] cd AlphaSys ``` -------------------------------- ### Create Dashboard Components (Streamlit) Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md Defines frontend components for a dashboard using Streamlit. Includes functions to display key performance indicator (KPI) cards for metrics like present employees and pending requests, and a placeholder for attendance visualization. ```Python # frontend/dashboard.py def kpi_cards(): st.metric("Employees Present Today", 25) st.metric("Pending Leave Requests", 3) st.metric("Pending Overtime Requests", 2) def attendance_chart(): # Create attendance visualization pass ``` -------------------------------- ### Frontend Payroll Page Integration (Streamlit) Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md Illustrates the frontend structure for the payroll management page using Streamlit. It includes logic to display different dashboards based on user roles (Admin, HR, Employee) and sections for payroll operations. ```Python # frontend/app.py payroll sections def payroll_page(): st.header("Payroll Management") # Payroll dashboard if st.session_state.role in ["Admin", "HR"]: show_admin_payroll_dashboard() elif st.session_state.role == "Employee": show_employee_payroll_dashboard() # Payroll management forms st.subheader("Payroll Operations") # Add payroll generation, payslip download, etc. ``` -------------------------------- ### Create Logging Middleware Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md This Python snippet defines a middleware for logging system activities in FastAPI. It captures request details and logs them, aiding in audit and debugging. ```Python import time import logging from fastapi import Request # Configure logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') async def logging_middleware(request: Request, call_next): start_time = time.time() response = await call_next(request) process_time = time.time() - start_time # Log request details logging.info( f"Method={request.method} " f"URL={request.url.path} " f"Client={request.client.host}:{request.client.port} " f"Status={response.status_code} " f"ProcessTime={process_time:.4f}s" ) return response # To use this middleware, add it to your FastAPI app: # from fastapi import FastAPI # app = FastAPI() # app.middleware('http')(logging_middleware) ``` -------------------------------- ### Implement Payroll Service (Python) Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md Provides a service class for payroll calculations. It includes methods to calculate basic pay, overtime pay, deductions, and generate payslips, interacting with user data and attendance records. ```Python from sqlalchemy.orm import Session from datetime import date, datetime from decimal import Decimal from typing import List, Optional from ..models import Payroll, Attendance, LeaveRequest, User class PayrollService: def calculate_basic_pay(self, employee: User, start_date: date, end_date: date) -> Decimal: # Calculate based on hourly rate and working days pass def calculate_overtime_pay(self, employee: User, start_date: date, end_date: date) -> Decimal: # Calculate overtime based on attendance records pass def calculate_deductions(self, employee: User, start_date: date, end_date: date) -> Decimal: # Calculate taxes and other deductions pass def generate_payslip(self, payroll: Payroll) -> str: # Generate PDF payslip document pass ``` -------------------------------- ### Create Payroll Router (FastAPI) Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md Defines the API router for payroll-related endpoints using FastAPI. It includes Pydantic models for creating and outputting payroll and payslip data, specifying fields like user ID, dates, pay components, and file paths. ```Python from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from typing import List from ..models import Payroll, Payslip from ..database import get_db from pydantic import BaseModel, Field router = APIRouter(prefix="/payroll", tags=["payroll"]) class PayrollCreate(BaseModel): user_id: int cutoff_start: date cutoff_end: date class PayrollOut(BaseModel): payroll_id: int user_id: int cutoff_start: date cutoff_end: date basic_pay: decimal.Decimal overtime_pay: decimal.Decimal deductions: decimal.Decimal net_pay: decimal.Decimal generated_at: datetime class PayslipCreate(BaseModel): payroll_id: int file_format: str = "pdf" class PayslipOut(BaseModel): payslip_id: int payroll_id: int file_path: str generated_at: datetime ``` -------------------------------- ### Create Role Management Router (FastAPI) Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md Defines the API router for role management endpoints using FastAPI. It includes Pydantic models for creating and outputting role data, specifying role names, descriptions, and associated permissions. ```Python # backend/routers/roles.py from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from typing import List from ..models import Role, Permission, User router = APIRouter(prefix="/roles", tags=["roles"]) class RoleCreate(BaseModel): role_name: str description: str permissions: List[int] class RoleOut(BaseModel): role_id: int role_name: str description: str permissions: List[dict] ``` -------------------------------- ### Implement Backend Payroll Router Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md This snippet focuses on creating the backend router for payroll management in Python. It includes setting up CRUD operations and payslip generation endpoints within the FastAPI framework. ```Python from fastapi import APIRouter, HTTPException from pydantic import BaseModel router = APIRouter() class PayrollRecord(BaseModel): employee_id: int month: int year: int gross_salary: float deductions: float net_salary: float # Placeholder for database operations payroll_db = [] @router.post("/payroll/") def create_payroll_record(record: PayrollRecord): payroll_db.append(record) return {"message": "Payroll record created successfully"} @router.get("/payroll/{employee_id}") def get_payroll_records(employee_id: int): records = [r for r in payroll_db if r.employee_id == employee_id] if not records: raise HTTPException(status_code=404, detail="Payroll records not found") return records # Placeholder for payslip generation endpoint @router.get("/payroll/payslip/{record_id}") def generate_payslip(record_id: int): # Logic to generate payslip (e.g., PDF) return {"message": f"Payslip for record {record_id} generated"} ``` -------------------------------- ### Create Export Functionality Utilities (Python) Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md Provides utility functions for exporting data and generating documents. Includes functions to export payroll data to CSV format and generate payslips in PDF format. ```Python # backend/utils/export.py def export_payroll_csv(payroll_data: List[dict]) -> str: # Generate CSV file from payroll data pass def generate_payslip_pdf(payroll: Payroll) -> str: # Generate PDF payslip pass ``` -------------------------------- ### Create Database Operations for Payroll (Python) Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md Contains functions for interacting with the database for payroll records. It includes operations to create new payroll entries, retrieve payroll by ID, and fetch payroll records for a specific user and period. ```Python # backend/database.py payroll operations def create_payroll(db: Session, payroll_data: dict) -> Payroll: # Create new payroll record pass def get_payroll_by_id(db: Session, payroll_id: int) -> Optional[Payroll]: # Get payroll by ID pass def get_payroll_by_period(db: Session, user_id: int, start_date: date, end_date: date) -> List[Payroll]: # Get payroll records for specific period pass ``` -------------------------------- ### Implement Permission Checking Middleware Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md This Python snippet demonstrates how to implement middleware for checking user permissions in a FastAPI application. It ensures that users can only access resources they are authorized for. ```Python from fastapi import Request, Depends, HTTPException, status from functools import wraps # Assume you have a function to get the current user's roles and permissions def get_current_user_permissions(request: Request) -> list[str]: # In a real app, this would involve decoding JWT, checking DB, etc. # For demonstration, returning hardcoded permissions user_roles = request.state.user.get("roles", []) all_permissions = set() # Assume a mapping of roles to permissions exists role_permission_map = { "admin": ["read:users", "write:users", "read:payroll", "write:payroll"], "hr": ["read:users", "read:payroll"], "employee": ["read:self"] } for role in user_roles: all_permissions.update(role_permission_map.get(role, [])) return list(all_permissions) def require_permission(required_permission: str): def decorator(func): @wraps(func) async def wrapper(request: Request, *args, **kwargs): user_permissions = get_current_user_permissions(request) if required_permission not in user_permissions: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Insufficient permissions" ) return await func(request, *args, **kwargs) return wrapper return decorator # Example Usage in a FastAPI endpoint: # @app.get("/payroll/all") # @require_permission("read:payroll") # async def get_all_payroll_data(request: Request): # # Access user_permissions if needed: request.state.user_permissions # return {"message": "Payroll data accessed successfully"} ``` -------------------------------- ### Create Role Management Endpoints Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md This Python snippet defines FastAPI endpoints for managing roles within the HR system. It includes functionalities for creating, retrieving, updating, and deleting roles. ```Python from fastapi import APIRouter, HTTPException from pydantic import BaseModel router = APIRouter() class Role(BaseModel): role_id: int role_name: str permissions: list[str] # Placeholder for role database operations roles_db = [] next_role_id = 1 @router.post("/roles/", response_model=Role) def create_role(role: Role): global next_role_id role.role_id = next_role_id roles_db.append(role) next_role_id += 1 return role @router.get("/roles/", response_model=list[Role]) def get_roles(): return roles_db @router.get("/roles/{role_id}", response_model=Role) def get_role(role_id: int): for role in roles_db: if role.role_id == role_id: return role raise HTTPException(status_code=404, detail="Role not found") @router.post("/roles/{role_id}", response_model=Role) def update_role(role_id: int, updated_role: Role): for i, role in enumerate(roles_db): if role.role_id == role_id: roles_db[i] = updated_role roles_db[i].role_id = role_id # Ensure ID remains the same return roles_db[i] raise HTTPException(status_code=404, detail="Role not found") @router.delete("/roles/{role_id}") def delete_role(role_id: int): global roles_db initial_length = len(roles_db) roles_db = [role for role in roles_db if role.role_id != role_id] if len(roles_db) == initial_length: raise HTTPException(status_code=404, detail="Role not found") return {"message": "Role deleted successfully"} ``` -------------------------------- ### Implement Permission System Middleware (FastAPI) Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md A middleware decorator for FastAPI applications to check user permissions. It takes a required permission string and wraps the decorated function, performing the permission check before execution. ```Python # backend/middleware/permissions.py from fastapi import Request, HTTPException from typing import Callable def check_permission(required_permission: str): def decorator(func: Callable): async def wrapper(request: Request, *args, **kwargs): # Check if user has required permission pass return wrapper return decorator ``` -------------------------------- ### Implement Payroll Service Layer Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md This Python snippet outlines the service layer for payroll calculations, including salary, deductions, and overtime. It's designed to be integrated with the backend API. ```Python from typing import Dict, Any class PayrollService: def calculate_gross_salary(self, base_salary: float, allowances: float) -> float: return base_salary + allowances def calculate_deductions(self, gross_salary: float, tax_rate: float, other_deductions: float) -> float: tax_amount = gross_salary * tax_rate return tax_amount + other_deductions def calculate_net_salary(self, gross_salary: float, deductions: float) -> float: return gross_salary - deductions def calculate_overtime_pay(self, hourly_rate: float, hours_worked: float, overtime_multiplier: float) -> float: return hourly_rate * hours_worked * overtime_multiplier # Example Usage: # payroll_service = PayrollService() # gross = payroll_service.calculate_gross_salary(5000.0, 500.0) # deductions = payroll_service.calculate_deductions(gross, 0.1, 200.0) # net = payroll_service.calculate_net_salary(gross, deductions) # overtime_pay = payroll_service.calculate_overtime_pay(25.0, 10.0, 1.5) ``` -------------------------------- ### Create Activity Logs Table SQL Source: https://github.com/junnel10001/alphasyshr/blob/main/db_schema.md Defines the 'activity_logs' table for recording user actions within the system, including the action performed and the timestamp. ```SQL CREATE TABLE activity_logs ( log_id SERIAL PRIMARY KEY, user_id INT NOT NULL REFERENCES users(user_id), action TEXT NOT NULL, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); ``` -------------------------------- ### Create Permissions Table SQL Source: https://github.com/junnel10001/alphasyshr/blob/main/db_schema.md Defines the 'permissions' table for managing system permissions. Each permission has a unique name and an optional description. ```SQL CREATE TABLE permissions ( permission_id SERIAL PRIMARY KEY, permission_name VARCHAR(50) UNIQUE NOT NULL, description TEXT ); ``` -------------------------------- ### Create Users Table SQL Source: https://github.com/junnel10001/alphasyshr/blob/main/db_schema.md Defines the 'users' table for storing employee information, including personal details, department, role, and employment status. It includes constraints for uniqueness and non-null values. ```SQL CREATE TABLE users ( user_id SERIAL PRIMARY KEY, username VARCHAR(50) UNIQUE NOT NULL, password_hash VARCHAR(255) NOT NULL, first_name VARCHAR(100) NOT NULL, last_name VARCHAR(100) NOT NULL, email VARCHAR(150) UNIQUE NOT NULL, phone_number VARCHAR(20), department_id INT REFERENCES departments(department_id), role_id INT REFERENCES roles(role_id), hourly_rate NUMERIC(10,2) NOT NULL, date_hired DATE NOT NULL, status VARCHAR(20) DEFAULT 'active' ); ``` -------------------------------- ### Create Payslips Table SQL Source: https://github.com/junnel10001/alphasyshr/blob/main/db_schema.md Defines the 'payslips' table to store the file paths for generated payslips, linking them to specific payroll records. ```SQL CREATE TABLE payslips ( payslip_id SERIAL PRIMARY KEY, payroll_id INT NOT NULL REFERENCES payroll(payroll_id), file_path VARCHAR(255) NOT NULL ); ``` -------------------------------- ### Create Roles Table SQL Source: https://github.com/junnel10001/alphasyshr/blob/main/db_schema.md Defines the 'roles' table for managing user roles within the system. Each role has a unique name and an optional description. ```SQL CREATE TABLE roles ( role_id SERIAL PRIMARY KEY, role_name VARCHAR(50) UNIQUE NOT NULL, description TEXT ); ``` -------------------------------- ### Implement Payroll Database Operations Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md This SQL snippet defines the database schema for payroll records, including essential fields for salary calculation and payslip management. It supports CRUD operations. ```SQL CREATE TABLE IF NOT EXISTS payroll_records ( record_id SERIAL PRIMARY KEY, employee_id INT NOT NULL, month INT NOT NULL, year INT NOT NULL, gross_salary DECIMAL(10, 2) NOT NULL, deductions DECIMAL(10, 2) DEFAULT 0.00, net_salary DECIMAL(10, 2) NOT NULL, payslip_path VARCHAR(255), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (employee_id) REFERENCES employees(employee_id) ); CREATE TABLE IF NOT EXISTS payslips ( payslip_id SERIAL PRIMARY KEY, record_id INT UNIQUE NOT NULL, file_path VARCHAR(255) NOT NULL, generated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (record_id) REFERENCES payroll_records(record_id) ); -- Example of seeding data (assuming employees table exists) -- INSERT INTO payroll_records (employee_id, month, year, gross_salary, deductions, net_salary) -- VALUES (1, 10, 2023, 5000.00, 500.00, 4500.00); ``` -------------------------------- ### Create Overtime Requests Table SQL Source: https://github.com/junnel10001/alphasyshr/blob/main/db_schema.md Defines the 'overtime_requests' table for managing employee overtime requests, including hours, reason, status, and approval details. ```SQL CREATE TABLE overtime_requests ( ot_id SERIAL PRIMARY KEY, user_id INT NOT NULL REFERENCES users(user_id), date DATE NOT NULL, hours_requested NUMERIC(4,2) NOT NULL, reason TEXT, status VARCHAR(20) CHECK (status IN ('Pending','Approved','Rejected')), approver_id INT REFERENCES users(user_id), approved_at TIMESTAMP ); ``` -------------------------------- ### Create Payroll Table SQL Source: https://github.com/junnel10001/alphasyshr/blob/main/db_schema.md Defines the 'payroll' table for storing payroll records, including basic pay, overtime, deductions, and net pay for each pay period. ```SQL CREATE TABLE payroll ( payroll_id SERIAL PRIMARY KEY, user_id INT NOT NULL REFERENCES users(user_id), cutoff_start DATE NOT NULL, cutoff_end DATE NOT NULL, basic_pay NUMERIC(10,2) NOT NULL, overtime_pay NUMERIC(10,2) DEFAULT 0, deductions NUMERIC(10,2) DEFAULT 0, net_pay NUMERIC(10,2) NOT NULL, generated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); ``` -------------------------------- ### Create Leave Requests Table SQL Source: https://github.com/junnel10001/alphasyshr/blob/main/db_schema.md Defines the 'leave_requests' table for managing employee leave requests, including dates, reason, status, and approver information. ```SQL CREATE TABLE leave_requests ( leave_id SERIAL PRIMARY KEY, user_id INT NOT NULL REFERENCES users(user_id), leave_type_id INT NOT NULL REFERENCES leave_types(leave_type_id), date_from DATE NOT NULL, date_to DATE NOT NULL, reason TEXT, status VARCHAR(20) CHECK (status IN ('Pending','Approved','Rejected','Cancelled')), approver_id INT REFERENCES users(user_id), approved_at TIMESTAMP ); ``` -------------------------------- ### Create Role Permissions Table SQL Source: https://github.com/junnel10001/alphasyshr/blob/main/db_schema.md Creates a many-to-many relationship between roles and permissions, allowing specific permissions to be assigned to different roles. ```SQL CREATE TABLE role_permissions ( role_id INT REFERENCES roles(role_id), permission_id INT REFERENCES permissions(permission_id), PRIMARY KEY (role_id, permission_id) ); ``` -------------------------------- ### Implement Overtime Calculation Logic Source: https://github.com/junnel10001/alphasyshr/blob/main/comprehensive_implementation_plan.md This Python snippet provides the core logic for calculating overtime pay based on hourly rates, hours worked, and a multiplier. It's a key component for the overtime management feature. ```Python class OvertimeCalculator: def __init__(self, base_hourly_rate: float, overtime_multiplier: float = 1.5): if base_hourly_rate <= 0: raise ValueError("Base hourly rate must be positive.") if overtime_multiplier <= 1: raise ValueError("Overtime multiplier must be greater than 1.") self.base_hourly_rate = base_hourly_rate self.overtime_multiplier = overtime_multiplier def calculate_regular_pay(self, regular_hours: float) -> float: if regular_hours < 0: raise ValueError("Regular hours cannot be negative.") return regular_hours * self.base_hourly_rate def calculate_overtime_pay(self, overtime_hours: float) -> float: if overtime_hours < 0: raise ValueError("Overtime hours cannot be negative.") return overtime_hours * self.base_hourly_rate * self.overtime_multiplier def calculate_total_pay(self, regular_hours: float, overtime_hours: float) -> float: regular_pay = self.calculate_regular_pay(regular_hours) overtime_pay = self.calculate_overtime_pay(overtime_hours) return regular_pay + overtime_pay # Example Usage: # calculator = OvertimeCalculator(base_hourly_rate=20.0, overtime_multiplier=2.0) # regular_pay = calculator.calculate_regular_pay(160) # overtime_pay = calculator.calculate_overtime_pay(10) # total_pay = calculator.calculate_total_pay(160, 10) # print(f"Regular Pay: {regular_pay}") # print(f"Overtime Pay: {overtime_pay}") # print(f"Total Pay: {total_pay}") ``` -------------------------------- ### Create Attendance Table SQL Source: https://github.com/junnel10001/alphasyshr/blob/main/db_schema.md Defines the 'attendance' table for tracking employee work hours, including time-in and time-out. It supports computed hours worked and status tracking. ```SQL CREATE TABLE attendance ( attendance_id SERIAL PRIMARY KEY, user_id INT NOT NULL REFERENCES users(user_id), date DATE NOT NULL, time_in TIMESTAMP, time_out TIMESTAMP, hours_worked NUMERIC(5,2) GENERATED ALWAYS AS (EXTRACT(EPOCH FROM (time_out - time_in)) / 3600) STORED, status VARCHAR(20) CHECK (status IN ('Present','Late','Absent','On Leave','Overtime')) ); ``` -------------------------------- ### Create Departments Table SQL Source: https://github.com/junnel10001/alphasyshr/blob/main/db_schema.md Defines the 'departments' table for storing department information, with each department having a unique name. ```SQL CREATE TABLE departments ( department_id SERIAL PRIMARY KEY, department_name VARCHAR(100) UNIQUE NOT NULL ); ``` -------------------------------- ### Create Leave Types Table SQL Source: https://github.com/junnel10001/alphasyshr/blob/main/db_schema.md Defines the 'leave_types' table for categorizing different types of leave, including their default allocation. ```SQL CREATE TABLE leave_types ( leave_type_id SERIAL PRIMARY KEY, leave_name VARCHAR(50) UNIQUE NOT NULL, default_allocation INT NOT NULL ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.