Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
For license information, please see license.txt
timesheet_tool.py
import frappe
from frappe.model.document import Document
from frappe import _
import datetime
from time_sheet_tool.time_sheet_tool.utils.timesheet_tool import check_missing_records
class TimesheetTool(Document):
@frappe.whitelist()
def clear_timesheet_tool_details_table(self):
# Clear the Timesheet Tool Details table
self.set("timesheet_tool_details", [])
code
Assistant
User
Assistant
User
"Submit Timesheet","تقديم جدول الزمان"
"Fetch to Timesheet Tool","جلب إلى أداة جدول الزمان"
"Timesheets Created",""
"Timesheets Submited",""
Assistant
It looks like you're working on translating some labels or phrases used in your application into Arabic. Below are translations or suggested translations for the phrases you've provided. I've filled in the last two phrases that were left empty based on common terms used in timesheet contexts:
plaintext
"Submit Timesheet", "تقديم جدول الزمان"
"Fetch to Timesheet Tool", "جلب إلى أداة جدول الزمان"
"Timesheets Created", "جدول الزمان تم إنشاؤه"
"Timesheets Submitted", "جدول الزمان تم تقديمه"
Translations Explained:
"Submit Timesheet" (تقديم جدول الزمان): This phrase indicates the action of submitting a timesheet.
"Fetch to Timesheet Tool" (جلب إلى أداة جدول الزمان): This phrase suggests retrieving or pulling data into the timesheet tool.
@frappe.whitelist()
def get_all_employees(self, project=None):
settings = get_settings()
default_activity = settings.dufault_activity
ratio_attendance = settings.ratio_attendance
dufault_working_hours = settings.dufault_working_hours
self.clear_timesheet_tool_details_table()
# Fetch employees depending on the project
if project:
# Fetch employees from Project Team, ensure all conditions are met
employees = frappe.db.sql("""
SELECT DISTINCT
pt.employee AS name,
pt.employee_name,
ss.hour_rate AS hourly_rate,
ssa.salary_structure
FROM
`tabProject Team` pt
INNER JOIN
`tabSalary Structure Assignment` ssa ON pt.employee = ssa.employee
INNER JOIN
`tabSalary Structure` ss ON ssa.salary_structure = ss.name
WHERE
pt.parent = %s
AND pt.fetch_to_timesheet_tool = 1
AND ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
AND ss.docstatus = 1 -- Ensure only approved Salary Structure
AND ss.salary_slip_based_on_timesheet = 1 -- Ensure timesheet-based salary is required
""", (project,), as_dict=True)
if not employees:
frappe.throw(_("No employees found in the Project Team with a valid Salary Structure Assignment and salary slip based on timesheet for the selected project."))
else:
# Fetch active employees directly when no project is selected
employees = frappe.db.sql("""
SELECT DISTINCT
emp.name AS name,
emp.employee_name AS employee_name,
ss.hour_rate AS hourly_rate,
ssa.salary_structure
FROM
`tabEmployee` emp
INNER JOIN
`tabSalary Structure Assignment` ssa ON emp.name = ssa.employee
INNER JOIN
`tabSalary Structure` ss ON ssa.salary_structure = ss.name
WHERE
emp.status = 'Active'
AND ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
AND ss.docstatus = 1 -- Ensure only approved Salary Structure
AND ss.salary_slip_based_on_timesheet = 1 -- Ensure timesheet-based salary is required
""", as_dict=True)
# Append employees to the child table
for emp in employees:
self.append("timesheet_tool_details", {
"employee": emp.get('name'),
"employee_name": emp.get('employee_name'),
"hourly_rate": emp.get('hourly_rate'),
"attendance": default_activity,
"ratio_attendance": ratio_attendance,
"salary_structure":emp.get('salary_structure'),
"hour":dufault_working_hours,
})
# Return employees after fetching
return employees
@frappe.whitelist()
def create_attendance(self):
"""
A function to implement all accounts and create the required records.
"""
timesheet_count = 0
additional_salary_count = 0
settings = get_settings()
print("*"*50,self.timesheets_created)
# Preparation of Fields of Settings
salary_component_overtime_h = settings.salary_component_overtime_h
salary_component_overtime_n = settings.salary_component_overtime_n
salary_component_deduction = settings.salary_component_deduction
from_time = f"{self.day} {settings.from_time}"
# Check for values
if not all([salary_component_overtime_h, salary_component_overtime_n, salary_component_deduction]):
frappe.throw(_("Please configure the Salary Components in Timesheet Tool Settings."))
for detail in self.timesheet_tool_details:
try:
if detail.hour:
# total_working_hours
totalhours = detail.hour * detail.ratio_attendance
create_timesheet(self, detail, totalhours, from_time)
timesheet_count += 1
# Additional Salary (Overtime H, Overtime N, Deduction)
if detail.over_time_h:
total_over_time_h = detail.over_time_h * settings.h_over_time
detail.total_payment = total_over_time_h * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_h, detail.total_payment)
additional_salary_count += 1
if detail.over_time_n:
total_over_time_n = detail.over_time_n * settings.n_over_time
detail.total_payment = total_over_time_n * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_n, detail.total_payment)
additional_salary_count += 1
if detail.deduction:
detail.total_payment = detail.deduction * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_deduction, detail.total_payment)
additional_salary_count += 1
except Exception as e:
frappe.log_error(f"Error processing detail for employee {detail.employee}: {str(e)}")
frappe.msgprint(_("Error processing detail for employee {}: {}").format(detail.employee, str(e)))
# Update timesheets_created to True after successfully creating the records
self.db_set("timesheets_created", 1)
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count)) @frappe.whitelist()
def approval_attendance(self):
"""Approves all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets()
self.approval_additional_salaries()
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been approved successfully."))
except Exception as e:
frappe.throw(_("An error occurred during approval: {0}").format(str(e)))
def approval_timesheets(self, cancel=False):
"""Shared logic for approving or canceling Timesheets."""
timesheet_list = frappe.get_all("Timesheet",
filters={
"timesheet_tool": self.name
},
)
record_num = 0
for timesheet in timesheet_list:
document = frappe.get_doc("Timesheet", timesheet.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
record_num += 1
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Timesheet {0} has been cancelled.").format(document.name))
frappe.msgprint(_("Timesheet {0} has been approved.").format(record_num))
def approval_additional_salaries(self, cancel=False):
"""Shared logic for approving or canceling Additional Salaries."""
additional_salary_list = frappe.get_all("Additional Salary",
filters={
"timesheet_tool": self.name
},
)
record_num = 0
for additional_salary in additional_salary_list:
document = frappe.get_doc("Additional Salary", additional_salary.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
record_num +=1
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Additional Salary {0} has been approved.").format(record_num))
def cancel_attendance(self):
"""Cancels all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets(cancel=True)
self.approval_additional_salaries(cancel=True)
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been cancelled successfully."))
except Exception as e:
frappe.throw(_("An error occurred during cancellation: {0}").format(str(e)))
def on_cancel(self):
# Cancel Timesheets and Additional Salaries when Timesheet Tool is cancelled.
self.cancel_attendance()
def on_submit(self):
self.check_future_day()
self.check_values_in_timesheet_tool_details()
self.check_zero_values_in_timesheet_tool_details()
self.check_over_time_values()
def before_save(self):
pass
def validate(self):
self.ensure_unique_employee()
self.check_limits_in_timesheet_tool_details()
def check_future_day(self):
settings = get_settings()
future_day = settings.future_day
today = datetime.date.today()
# Turn self.day from text to date object
try:
day_date = datetime.datetime.strptime(self.day, "%Y-%m-%d").date()
except ValueError:
frappe.throw(_("Invalid date format for day. Please use YYYY-MM-DD."))
# See if the settings allow future dates.
if not future_day and day_date > today:
frappe.throw(_("Company settings do not allow the establishment of a future date schedule."))
def check_zero_values_in_timesheet_tool_details(self):
"""Check for zero values in timesheet_tool_details and raise an error if found."""
error_rows = []
for idx, detail in enumerate(self.timesheet_tool_details):
# Check if hourly_rate, over_time_n, over_time_h and deduction are all zero
if detail.ratio_attendance != 0:
if detail.hour == 0 and detail.over_time_n == 0 and detail.over_time_h == 0 and detail.deduction == 0:
error_rows.append(idx + 1) # Save the row number (1-based index)
if error_rows:
error_message = _("The following rows have Hour, Over Time N, and Over Time H all equal to 0 in rows: {rows}").format(rows=" , ".join(map(str, error_rows)))
frappe.throw(error_message)
def check_values_in_timesheet_tool_details(self):
if not self.timesheet_tool_details:
frappe.throw(_("Cannot proceed: No records found in Timesheet Tool Details."))
def check_over_time_values(self):
"""Check that values over_time_n,over_time_h cannot be entered for the staff member on the same date."""
for idx, row in enumerate(self.timesheet_tool_details):
if row.over_time_n > 0 and row.over_time_h > 0:
employee_name = row.employee
frappe.throw(
_("Neither of the values Over Time N, Over Time H can be entered for employee {0} at row {1}.").format(employee_name, idx + 1)
)
def check_limits_in_timesheet_tool_details(self):
settings = get_settings()
max_n_over_time = settings.maximum_n_over_time
max_h_over_time = settings.maximum_h_over_time
max_deduction = settings.maximum_deduction
max_standard_working_hours = settings.maximum_standard_working_hours
for idx, detail in enumerate(self.timesheet_tool_details):
if detail.hour is not None and detail.hour > max_standard_working_hours:
frappe.throw(_(f"Row {idx + 1}: The value of 'Hour' cannot exceed the maximum standard working hours ({max_standard_working_hours})."))
if detail.over_time_n is not None and detail.over_time_n > max_n_over_time:
frappe.throw(_(f"Row {idx + 1}: The value of 'Over Time N' cannot exceed the maximum allowed overtime hours (normal) ({max_n_over_time})."))
if detail.over_time_h is not None and detail.over_time_h > max_h_over_time:
frappe.throw(_(f"Row {idx + 1}: The value of 'Over Time H' cannot exceed the maximum allowed overtime hours (holiday) ({max_h_over_time})."))
if detail.deduction is not None and detail.deduction > max_deduction:
frappe.throw(_(f"Row {idx + 1}: The value of 'Deduction' cannot exceed the maximum deduction allowed ({max_deduction})."))
def ensure_unique_employee(self):
"""
Check not to repeat the selection of the same employee in Timesheet Tool Details.
"""
timesheet_tool_details = [os.employee for os in self.timesheet_tool_details if os.employee]
if len(timesheet_tool_details) != len(set(timesheet_tool_details)):
frappe.throw(_("The same employee cannot be selected more than once."))
The provided code is a Python script that defines the TimesheetTool class, a custom document for managing timesheets and employee salary calculations within a Frappe framework application, typically used along with ERPNext for business management. Here's an overview of its key functionalities and methods:
Key Functions and Methods:
Document Initialization and Methods:
The TimesheetTool class extends the base document class provided by Frappe, allowing it to manage specific business logic related to timesheet handling.
Clearing Timesheet Details:
clear_timesheet_tool_details_table(): This method clears the child table that holds details of timesheet entries.
Employee Retrieval:
get_all_employees(project=None): This method fetches employees either from a specific project or directly from the active employee list, ensuring that they have valid salary structures and are marked for timesheet processing.
Creating Attendance Records:
create_attendance(): This method processes the entries in the timesheet tool details, calculating and creating corresponding Timesheet and Additional Salary records in ERPNext.
Approval and Cancellation:
approval_attendance(): Approves all associated timesheets and additional salaries.
cancel_attendance(): Cancels all associated timesheets and additional salaries.
Data Validation:
The class contains several validation methods:
check_future_day(): Checks if the specified day in the timesheet tool is a future date, according to settings.
check_zero_values_in_timesheet_tool_details(): Ensures that not all hours and compensation values are zero.
check_values_in_timesheet_tool_details(): Ensures that the timesheet detail records are populated.
check_over_time_values(): Validates that overtime values aren't double-registered for an employee.
check_limits_in_timesheet_tool_details(): Ensures that the various hour and deduction values are within permissible limits.
ensure_unique_employee(): Validates that each employee is only listed once in the timesheet details.
Utility Methods:
get_settings(): Fetches the latest configurations settings related to the Timesheet Tool.
create_timesheet(): Responsible for creating a new Timesheet entry.
create_additional_salary(): Responsible for creating records for additional salary calculations like overtime and deductions.
Notes:
The code is equipped with error handling, logging, and user messaging through Frappe's frappe.throw(), frappe.msgprint(), and frappe.log_error(), which aids in debugging and user interaction during operations.
The structure follows a standard pattern of querying the database, processing data, and returning appropriate responses, which is commonly used in applications that require handling complex business logic.
The use of decorators (e.g., @frappe.whitelist()) indicates that these methods are available for remote procedure calls, which is crucial for front-end integrations or API calls.
Potential Improvements:
Code Documentation: While there is some inline documentation, further comments explaining the intention of major blocks of code would enhance maintainability.
Testing: Automated tests could be written to ensure the correctness and reliability of critical functionalities.
Performance Optimization: Depending on the volume of employees and records processed, performance optimization may be warranted, particularly in SQL queries and loops over large datasets.
Error Handling: Enhance error handling to give more context about the failures, particularly in batch processing loops, to aid in diagnosing issues.
This structured approach allows businesses to maintain thorough records of employee hours worked, manage payroll seamlessly, and ensures data integrity throughout the timesheet processing workflow.
Traceback (most recent call last):
File "apps/frappe/frappe/app.py", line 114, in application
response = frappe.api.handle(request)
File "apps/frappe/frappe/api/__init__.py", line 49, in handle
data = endpoint(**arguments)
File "apps/frappe/frappe/api/v1.py", line 36, in handle_rpc_call
return frappe.handler.handle()
File "apps/frappe/frappe/handler.py", line 49, in handle
data = execute_cmd(cmd)
File "apps/frappe/frappe/handler.py", line 85, in execute_cmd
return frappe.call(method, **frappe.form_dict)
File "apps/frappe/frappe/__init__.py", line 1725, in call
return fn(*args, **newargs)
File "apps/frappe/frappe/handler.py", line 331, in run_doc_method
response = doc.run_method(method)
File "apps/frappe/frappe/model/document.py", line 966, in run_method
out = Document.hook(fn)(self, *args, **kwargs)
File "apps/frappe/frappe/model/document.py", line 1326, in composer
return composed(self, method, *args, **kwargs)
File "apps/frappe/frappe/model/document.py", line 1308, in runner
add_to_return_value(self, fn(self, *args, **kwargs))
File "apps/frappe/frappe/model/document.py", line 963, in fn
return method_object(*args, **kwargs)
File "apps/frappe/frappe/utils/typing_validations.py", line 31, in wrapper
return func(*args, **kwargs)
File "apps/time_sheet_tool/time_sheet_tool/time_sheet_tool/doctype/timesheet_tool/timesheet_tool.py", line 137, in create_attendance
self.db_set("timesheets_processed", 1)
File "apps/frappe/frappe/model/document.py", line 1230, in db_set
frappe.db.set_value(
File "apps/frappe/frappe/database/database.py", line 989, in set_value
query.run(debug=debug)
File "apps/frappe/frappe/query_builder/utils.py", line 87, in execute_query
result = frappe.db.sql(query, params, *args, **kwargs) # nosemgrep
File "apps/frappe/frappe/database/database.py", line 229, in sql
self._cursor.execute(query, values)
File "env/lib/python3.10/site-packages/pymysql/cursors.py", line 153, in execute
result = self._query(query)
File "env/lib/python3.10/site-packages/pymysql/cursors.py", line 322, in _query
conn.query(q)
File "env/lib/python3.10/site-packages/pymysql/connections.py", line 563, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "env/lib/python3.10/site-packages/pymysql/connections.py", line 825, in _read_query_result
result.read()
File "env/lib/python3.10/site-packages/pymysql/connections.py", line 1199, in read
first_packet = self.connection._read_packet()
File "env/lib/python3.10/site-packages/pymysql/connections.py", line 775, in _read_packet
packet.raise_for_error()
File "env/lib/python3.10/site-packages/pymysql/protocol.py", line 219, in raise_for_error
err.raise_mysql_exception(self._data)
File "env/lib/python3.10/site-packages/pymysql/err.py", line 150, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.OperationalError: (1054, "Unknown column 'timesheets_processed' in 'field list'")
The error traceback you've provided indicates a failure in your code when trying to execute a SQL update query involving the column timesheets_processed. The specific error you encountered is:
code
pymysql.err.OperationalError: (1054, "Unknown column 'timesheets_processed' in 'field list'")
This error occurs because the specified column timesheets_processed does not exist in the database table corresponding to the Timesheet Tool doctype when you attempt to set or update it.
Possible Causes
Missing Database Column:
The column timesheets_processed might not have been added to your database schema. It could be that when the doctype was modified, an appropriate database migration was not performed.
Typo in Field Name:
Ensure that there are no typographical errors in the field name. The field in code must exactly match the field in the database.
Database Migrations:
If you have recently made changes to the Timesheet Tool doctype (like adding a new field), you need to apply those changes to the database schema.
Steps to Fix
Check the Doctype:
Go to your ERPNext/Frappe application and locate the Timesheet Tool doctype. Verify whether the timesheets_processed field exists in the doctype fields.
Add Missing Field:
If the field does not exist, you can add it via the Frappe UI under the doctype settings. Make sure to specify the appropriate data type (likely a Check or Int if you're counting).
Run Database Migrations:
If you have made changes to the doctype definitions, run the command to update the database schema. You might do this from the terminal with:
bash
bench migrate
This command applies any changes made to your doctype definitions to the underlying database and ensures all fields exist.
Update Your Code:
Ensure that when you are trying to set timesheets_processed, it is done correctly in the code. For instance:
python
self.db_set("timesheets_processed", 1)
Check for Relational Integrity:
If your application is directly altering database structures or if this column is reliant on other application changes, ensure that there are no prior states with unfinished migrations that might impact this column.
Additional Considerations
Backup Data: Always ensure you back up your database before making schema changes, especially in production environments.
Logs and Debugging: Check the logs for any other issues that may not have been captured. There might be other related errors leading to this condition.
Consult ERPNext/Frappe Documentation: If you're unsure of how to make schema updates or handling the migrations, consult the official ERPNext or Frappe documentation or community forums for further guidance.
Following these steps should help you resolve the error and allow your application to successfully create attendance records. After adjusting your database schema, verify the functionality by attempting to rerun the operation that previously caused the error.
"Timesheets Created" (جدول الزمان تم إنشاؤه): Indicates that timesheets have been generated and is often used in contexts to show success messages.
"Timesheets Submitted" (جدول الزمان تم تقديمه): This indicates that the timesheets have been submitted for approval or processing.
Usage:
Make sure that wherever these phrases are used in your application, they accurately reflect the actions or statuses they are meant to represent, especially in the context of user interactions and feedback. Furthermore, consistency in terminology helps maintain clarity for users operating in both languages.