I have the following code to create bulk time off data it gets employee name and info of time off period and type of time off and it writes to an excel file. it gets employee list from the file hr.employee.xlsx which also contains another column called contract_name it has data in form of e.g. 8-8-8-8-8 (start 08:00 - vzw) as you see there are 5 numbers address each day from monday to friday no work, at weekend. it also says start 08:00 which means emploeyee starts at 08 am and his shift ends at 08:00 + 8 = 16:00. i want to implement a feature to my existing code. when an employee is selected it should read this contract_name and should show only the working hours as available hours with 30 min interval for that employee. here is the code: import os
from pathlib import Path
import tkinter as tk
import customtkinter as ctk
from CTkScrollableDropdown import *
from tkinter import ttk
from PIL import ImageTk, Image
from ttkwidgets import CheckboxTreeview
from tkinter import messagebox
from tkcalendar import DateEntry
import random
import string
from datetime import datetime, timedelta
import pandas as pd
def create_excel(data):
# New Dataframe for Fresh Created Time-Off Data
df_new = pd.DataFrame(data, columns=["id", "employee_id", "holiday_status_id", "date_from", "date_to"])
# Use Destination Path to Check Whether Previously Created Excel File Exist
file_path = F"{downloads_path}\time_off_data.xlsx"
# Merge Old and New Dataframes by Dropping Duplicates to Avoid Conflict
if os.path.exists(file_path):
df_ex = pd.read_excel(file_path)
df_merge = pd.concat([df_ex, df_new]).drop_duplicates(["employee_id", "holiday_status_id", "date_from", "date_to"])
df_merge.to_excel(file_path, index=False)
else:
df_new.to_excel(file_path, index=False)
messagebox.showinfo("Success", "Time-Off Data Created!")
Function to Check Weekend Days
def check_weekend(datetime):
week_days = datetime.strftime("%A")
if week_days == "Saturday":
return False
if week_days == "Sunday":
return False
else:
return True
Function to Handle the Submission Process
def submit_data():
# Pass the values from user's inputs
name = entry.get()
if not name:
messagebox.showerror("Error", "Please select an employee!")
return
Assistant
User
thanks a lot it worked well but i got 2 issues, there are some contract_name values that doesnt contain any numbers and for those i want to make exception and dont update the available_hours. 2nd part is the difficult one: there are 3 pauses in the whole operation scedule - 10:00(15min), 12:30(30min), 14:30(15min). so if an employee reaches these time thresholds while working he will take a break and therefore this extra time should be added on top of the available_hours. please let me know if any part of my problem is unclear and needs further explanation.
Assistant
User
great. it works as it should, thanks! i have one more request; i want to bind this feature to a checkbox as "apply contract" if it is not checked then this feature will be ignored else it will be active and default should be checked
Assistant
User
again, it is solved with best way possible. thanks alot
Assistant
You're welcome! I'm glad the solution worked well for you. If you have any more questions or need further assistance in the future, feel free to ask. Happy coding!
code
time_off_type = time_off_option.get()
start_date = f"{cal_start.get()} {start_hour_option.get()}"
end_date = f"{cal_end.get()} {end_hour_option.get()}"
# Set error messageboxes for faulty inputs
if not name or not time_off_type or not start_date or not end_date:
messagebox.showerror("Error", "All fields must be filled!")
return
if end_date<start_date:
messagebox.showerror("Error", "End Date can't be set earlier than Start Date")
return
try:
start_dt = datetime.strptime(start_date, "%Y-%m-%d %H:%M")
end_dt = datetime.strptime(end_date, "%Y-%m-%d %H:%M")
except ValueError:
messagebox.showerror("Error", "Please enter valid dates in YYYY-MM-DD HH:MM format!")
return
# Apply weekly option
if radio_var.get()==2:
end_recurring_date = cal_recurring.get()
if not end_recurring_date:
messagebox.showerror("Error", "Please provide the recurring end date!")
return
try:
recurring_end_dt = datetime.strptime(end_recurring_date, "%Y-%m-%d")
except ValueError:
messagebox.showerror("Error", "Please enter a valid recurring end date in YYYY-MM-DD format!")
return
data = []
current_start = start_dt
current_end = end_dt
while current_start.date()<= recurring_end_dt.date():#current_start <= recurring_end_dt:
random_id = generate_random_id()
data.append([random_id, name, time_off_type, current_start, current_end])
current_start += timedelta(weeks=1)
current_end += timedelta(weeks=1)
show_confirmation_window(data, root)
# Apply daily option
if radio_var.get()==3:
end_recurring_date = cal_recurring.get()
if not end_recurring_date:
messagebox.showerror("Error", "Please provide the recurring end date!")
return
try:
recurring_end_dt = datetime.strptime(end_recurring_date, "%Y-%m-%d")
except ValueError:
messagebox.showerror("Error", "Please enter a valid recurring end date in YYYY-MM-DD format!")
return
data = []
current_start = start_dt
current_end = end_dt
while current_start.date()<= recurring_end_dt.date():
random_id = generate_random_id()
if check_weekend(current_start):
data.append([random_id, name, time_off_type, current_start, current_end])
current_start += timedelta(days=1)
current_end += timedelta(days=1)
show_confirmation_window(data, root)
# Apply once option
if radio_var.get()==1:
random_id = generate_random_id()
data = [[random_id, name, time_off_type, start_dt, end_dt]]
show_confirmation_window(data, root)
def show_confirmation_window(data, root, existing_top=None, existing_table=None, existing_check_vars=None):
# Function to add another employee
def add_another_employee():
# Reset the live search bar
new_employee = entry.get()
if not new_employee:
messagebox.showerror("Error", "Please select an employee!")
return
code
checked_data = [row for i, row in enumerate(data) if check_vars[i].get()]
# Copy the selections and add new employee data
new_data = []
for row in checked_data:
random_id = generate_random_id()
new_data.append([random_id, new_employee, row[2], row[3], row[4]])
combined_data = checked_data + new_data
# combined_data = pd.concat([checked_data, new_data]).drop_duplicates(["employee_id", "holiday_status_id", "date_from", "date_to"])
# Remove duplicates based on Name, Type, Start, and End (excluding ID)
unique_combined_data = {}
for item in combined_data:
key = (item[1], item[2], item[3], item[4]) # Tuple of Name, Type, Start, End
unique_combined_data[key] = item
# Dict.values() extracts unique rows
unique_combined_data = list(unique_combined_data.values())
# Destroy the existing confirmation window
top.destroy()
# Create a new window with updated data
show_confirmation_window(unique_combined_data, root)
# Check if we are updating an existing window
if existing_top and existing_table and existing_check_vars:
top = existing_top
table = existing_table
check_vars = existing_check_vars
else:
# Get master window position
root_x = root.winfo_rootx()
root_y = root.winfo_rooty()
# Add offset
win_x = root_x + 568
win_y = root_y - 31
# Toplevel Window to Display Time off Data List
top = ctk.CTkToplevel(root)
top.wm_iconbitmap()
top.after(300, lambda: top.iconphoto(False, root.iconpath))
top.geometry("950x500" + f'+{win_x}+{win_y}')
top.title("Confirm Time-Off Entries")
# Frame to Contain Treeview Widget
frame = ctk.CTkFrame(top)
frame.pack(fill="both", expand=True, padx=20) #, pady=15
# Style for Column Headings
style = ttk.Style(top)
style.theme_use("alt")
style.configure("Treeview", foreground=p_green_d, background=p_cream, fieldbackground=p_cream, font=("Bahnschrift", 11))
style.configure("Treeview.Heading", background=p_green, foreground=p_cream, font=("Bahnschrift", 13), hover=False)
# Table to display rows (without ID in columns but still accessible in the data)
table = CheckboxTreeview(frame, columns=("Name", "Type", "Start", "End"))
# Set the headings without showing the "ID"
table.heading("Name", text="Employer Name")
table.heading("Type", text="Type of Time Off")
table.heading("Start", text="Start Date & Time")
table.heading("End", text="End Date & Time")
check_vars = []
# Label to host widgets for adding new employee
label_add_entry = ctk.CTkLabel(top)
# label_add_entry.pack(padx=15, pady=15)
label_add_entry.pack(padx=20, pady=15, side="top") #, side="bottom"
# Entry Box Widget Combined with Scrollable Dropdown Widget
entry = ctk.CTkEntry(master=label_add_entry, width=290, fg_color=p_cream, text_color=p_green_d, font=("Bahnschrift", 15))
entry.grid(row=0, column=0, padx=2) #, padx=10
CTkScrollableDropdown(entry, values=name_list, command=lambda e: (entry.delete(0, 'end'), entry.insert(0, e)),
fg_color=p_cream, text_color=p_cream, hover_color=p_green, autocomplete=True, font=("Bahnschrift", 12, "bold"))
# Add Another Employee button
add_employee_button = ctk.CTkButton(master=label_add_entry, text="Apply to an Another Employee", command=add_another_employee, width=290, fg_color=p_green,
hover_color=p_red, text_color=p_cream)
add_employee_button.configure(font=("Bahnschrift", 15, "bold"))
add_employee_button.grid(row=0, column=1, padx=2) #, padx=10
# Confirmation button
confirm_button = ctk.CTkButton(master=label_add_entry, text="Confirm & Save", command=lambda: [save_confirmed_rows(data, check_vars), top.destroy()], fg_color=p_green,
hover_color=p_red, text_color=p_cream, width=290)
confirm_button.configure(font=("Bahnschrift", 15, "bold"))
# confirm_button.pack(pady=15)
confirm_button.grid(row=0, column=2, padx=2)
# Add data to the table without displaying the "ID" column
for i, row in enumerate(data):
check_var = tk.BooleanVar(value=True)
check_vars.append(check_var)
table.insert("", "end", values=(row[1], row[2], row[3], row[4]), tags=(f"row{i}",))
table.tag_bind(f"row{i}", "<<TreeviewSelect>>", lambda e, var=check_var: var.set(not var.get()))
table.check_all()
if (i % 2) == 0:
table.tag_configure(f"row{i}", background=p_yellow_l)
else:
table.tag_configure(f"row{i}", background=p_yellow_d)
table.column("# 0", width=50)
table.pack(expand=True, fill='both', padx=10, pady=10)
This function saves only the confirmed rows
def save_confirmed_rows(data, check_vars):
# Filter rows based on checked boxes
confirmed_rows = [row for i, row in enumerate(data) if check_vars[i].get()]
create_excel(confirmed_rows)
Main GUI creation
if name == "main":
# Initialize the GUI
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("dark-blue")
root = ctk.CTk()
root.iconpath = ImageTk.PhotoImage(file=os.path.abspath("")+"\image2nd.ico")
root.wm_iconbitmap()
root.iconphoto(False, root.iconpath)
root.title("Bulk Time-Off by M.Cetin")
root.geometry("575x350")
root.resizable(False, False)
To implement a feature that updates the available working hours based on the selected employee's contract information, you can modify the function in the code that manages the selection of the employee. The goal is to update the available times in the start and end hour menu based on the contract hours (e.g., 8-8-8-8-8 (start 08:00 - vzw)), only allowing selections within the specified working hours. Here's a step-by-step integration of this feature into your existing code:
Modifications and Additions:
Extract Contract Information: Obtain the contract_name of the selected employee when they are chosen from the dropdown. Use this information to filter available working hours.
Parse Contract Hours: Interpret the contract_name string to extract start and end times.
Update Hour Menus: Dynamically change the hour_values for the start and end hour options according to the employee's contract hours.
Here's how you can implement these steps in the code:
python
# Function to Parse Working Hours from Contract Name
def parse_contract_hours(contract_name):
# Example: "8-8-8-8-8 (start 08:00 - vzw)"
days_hours = contract_name.split(' ')[0].split('-') # Get hours only e.g. ['8', '8', '8', '8', '8']
start_time = contract_name.split(' ')[2] # '08:00'
# Assume that the format is consistent
start_hour, start_minute = map(int, start_time.split(':'))
working_hours = int(days_hours[0]) # Hours per day
start_dt = datetime(2023, 1, 1, start_hour, start_minute) # Fixed date, only time is important
end_dt = start_dt + timedelta(hours=working_hours)
return start_dt.time(), end_dt.time()
# Function to Filter Available Hours based on Contract
def set_available_hours(employee_name):
employee_data = df_name[df_name['name'] == employee_name]
if not employee_data.empty:
contract_name = employee_data['contract_name'].values[0]
start_time, end_time = parse_contract_hours(contract_name)
available_hours = []
current_time = datetime.combine(datetime.today(), start_time)
last_time = datetime.combine(datetime.today(), end_time)
# Create half-hour intervals within working hours
while current_time <= last_time:
available_hours.append(current_time.strftime("%H:%M"))
current_time += timedelta(minutes=30)
# Update Option Menus
start_hour_menu.configure(values=available_hours)
end_hour_menu.configure(values=available_hours)
start_hour_option.set(available_hours[0]) # Set default start
end_hour_option.set(available_hours[-1]) # Set default end
# Modify your Employee Search setup to include the dynamic hour updating
entry = ctk.CTkEntry(root,textvariable=entry_name, width=240, fg_color=p_cream, text_color=p_green_d, font=("Bahnschrift", 15))
entry.grid(row = 0, column = 1, padx=10, pady=10)
CTkScrollableDropdown(
entry,
values=name_list,
command=lambda e: (
entry.delete(0, 'end'),
entry.insert(0, e),
set_available_hours(e) # New line to set available hours when Employee is selected
),
fg_color=p_cream,
text_color=p_cream,
hover_color=p_green,
autocomplete=True,
font=("Bahnschrift", 12, "bold")
)
Explanation:
parse_contract_hours: This function extracts the starting time and daily hours from the contract_name string. It calculates the end_time based on the given start time and working hours.
set_available_hours: When an employee is selected, this function retrieves their contract information and calculates available working half-hour slots, updating the time dropdowns accordingly.
This modification to your application will ensure that the time selection is aligned with the employee's contract hours. Make sure to test for various contract scenarios to verify that available time slots are correctly interpreted and displayed.
To address your two issues, we can modify the functions to handle cases where the contract_name doesn't contain numbers and adjust the working hours calculation to account for scheduled breaks. Here's how you can implement these changes:
1. Handling Missing Contract Information:
For cases where there is no numerical working hours in the contract_name, you can add a check to skip updating the available_hours.
2. Incorporating Breaks into Working Hours:
We need to add extra time for scheduled breaks. The logic will involve checking if breaks occur within the work schedule and adjusting the end time accordingly.
Here's how you can update the code to handle these cases:
python
import re
def parse_contract_hours(contract_name):
# Extract the numerical part and start time from the contract_name
numbers = re.findall(r'\d+', contract_name)
if not numbers:
return None, None # No valid hours found, return None to indicate exception
days_hours = numbers[:5] # Get first 5 numbers as hours for weekdays
start_time_match = re.search(r'start (\d{2}:\d{2})', contract_name)
if start_time_match:
start_time_str = start_time_match.group(1)
start_hour, start_minute = map(int, start_time_str.split(':'))
working_hours = int(days_hours[0]) # Assuming same hours for all weekdays
start_dt = datetime(2023, 1, 1, start_hour, start_minute)
# Calculate end time considering breaks
end_dt = calculate_end_time_with_breaks(start_dt, working_hours)
return start_dt.time(), end_dt.time()
return None, None # If no start time is found
def calculate_end_time_with_breaks(start_dt, working_hours):
# Initiate the current work duration
current_end_dt = start_dt + timedelta(hours=working_hours)
# Define break times and durations
breaks = [
(datetime(2023, 1, 1, 10, 0), timedelta(minutes=15)), # 10:00 AM break
(datetime(2023, 1, 1, 12, 30), timedelta(minutes=30)), # 12:30 PM break
(datetime(2023, 1, 1, 14, 30), timedelta(minutes=15)) # 2:30 PM break
]
# Check if a break happens within the schedule and adjust end time
for break_start, break_duration in breaks:
break_start, break_end = (break_start.time(), (break_start + break_duration).time())
if start_dt.time() <= break_start and break_start < current_end_dt.time():
# The break is within the working hours, add its duration to the end time
current_end_dt += break_duration
return current_end_dt
def set_available_hours(employee_name):
employee_data = df_name[df_name['name'] == employee_name]
if not employee_data.empty:
contract_name = employee_data['contract_name'].values[0]
start_time, end_time = parse_contract_hours(contract_name)
if start_time is None or end_time is None:
return # Do nothing if contract hours can't be parsed
available_hours = []
current_time = datetime.combine(datetime.today(), start_time)
last_time = datetime.combine(datetime.today(), end_time)
# Create half-hour intervals within working hours
while current_time <= last_time:
available_hours.append(current_time.strftime("%H:%M"))
current_time += timedelta(minutes=30)
# Update Option Menus
start_hour_menu.configure(values=available_hours)
end_hour_menu.configure(values=available_hours)
start_hour_option.set(available_hours[0]) # Set default start
end_hour_option.set(available_hours[-1]) # Set default end
Key Changes:
Regex for Parsing: I used regular expressions (re) to find numerical values and the start time in the contract_name.
Check for Exceptions: If no numbers or start time is found, the function returns None, indicating an exception where available hours should not be updated.
Break Handling: The calculate_end_time_with_breaks function checks if a scheduled break occurs within the working hours and extends the end time accordingly.
This implementation considers breaks only if they occur during the scheduled work hours. This assumes that employees should not work during these breaks and should extend their workday to compensate for this non-working time. Make sure to adjust the dates in calculate_end_time_with_breaks as needed if specific conditions or customizations for different employees are required.
To implement a feature that allows enabling or disabling the "apply contract" functionality through a checkbox, you'll need to add a CheckButton widget and modify the logic to check whether the feature is enabled when setting available hours.
Here’s how to integrate this feature into your existing GUI:
Steps:
Add a Checkbox Widget: Create a checkbox that allows the user to toggle the "apply contract" feature on or off.
Modify Logic to Check the Checkbox State: When setting available hours, consider the state of the checkbox to decide whether to apply the contract hours.
Here's the updated code snippet including these changes:
python
# Functionality to determine if contract should be applied
apply_contract_var = tk.BooleanVar(value=True) # Default to checked
def set_available_hours(employee_name):
# Only apply contract if checkbox is checked
if apply_contract_var.get():
employee_data = df_name[df_name['name'] == employee_name]
if not employee_data.empty:
contract_name = employee_data['contract_name'].values[0]
start_time, end_time = parse_contract_hours(contract_name)
if start_time is None or end_time is None:
return # Do nothing if contract hours can't be parsed
available_hours = []
current_time = datetime.combine(datetime.today(), start_time)
last_time = datetime.combine(datetime.today(), end_time)
# Create half-hour intervals within working hours
while current_time <= last_time:
available_hours.append(current_time.strftime("%H:%M"))
current_time += timedelta(minutes=30)
# Update Option Menus
start_hour_menu.configure(values=available_hours)
end_hour_menu.configure(values=available_hours)
start_hour_option.set(available_hours[0]) # Set default start
end_hour_option.set(available_hours[-1]) # Set default end
else:
# If not applying contract, follow standard setup
start_hour_menu.configure(values=hour_values)
end_hour_menu.configure(values=hour_values)
start_hour_option.set(hour_values[0])
end_hour_option.set(hour_values[-1])
# GUI setup to include the checkbox
apply_contract_checkbox = ctk.CTkCheckBox(
root,
text="Apply Contract",
variable=apply_contract_var,
onvalue=True,
offvalue=False,
text_color=p_cream
)
apply_contract_checkbox.configure(font=("Bahnschrift", 15, "bold"))
apply_contract_checkbox.grid(row=6, column=2, sticky="w", padx=10, pady=10)
Explanation:
apply_contract_var: A Boolean variable tied to the state of the checkbox, with a default value of True indicating that the feature should be applied by default.
apply_contract_checkbox: This checkbox, when checked, means that the contract hours should be applied when selecting the available hours. If unchecked, the standard hour values (hour_values) are used.
Logic Check: The set_available_hours function checks the value of apply_contract_var. If it is True, it executes the logic to apply the contract hours. Otherwise, it uses the standard set of available hours.
This setup provides flexibility to the user allowing them to choose whether to utilize the employee contract hours or to ignore them, giving full control over the scheduling interface.