def create_attendance(self):
"""
A function to implement all accounts and create the required records.
"""
"""
Calculation of fields required in the timesheet_tool_details
"""
timesheet_count = 0
additional_salary_count = 0
settings = get_settings()
code
# 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 salary_component_overtime_h or not salary_component_overtime_n or not salary_component_deduction:
frappe.throw(_("Please configure the Salary Components in Timesheet Tool Settings."))
for detail in self.timesheet_tool_details:
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
self.set("timesheets_created", True)
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count,additional_salary_count))
Assistant
The code you've posted is a method named create_attendance, likely part of a larger class within a framework like Frappe or ERPNext. This method is responsible for processing attendance records and creating timesheets and additional salary records based on the hours worked and any overtime or deductions.
Here's a breakdown of how this function works, along with some potential points for improvement or considerations:
Breakdown of the Function:
Initialization:
The function initializes counters for timesheets and additional salary records (timesheet_count and additional_salary_count).
It retrieves configuration settings related to salary components and time calculations using get_settings().
Settings Validation:
The function validates whether necessary salary components for overtime and deductions are configured. If they are not set, it raises an error message.
Processing Timesheet Details:
The method then iterates through each detail in self.timesheet_tool_details.
For each detail, if hour (the hours worked) is provided, it calculates the total working hours (considering a potential ratio of attendance) and invokes create_timesheet.
The function also checks and processes additional salary entries for:
Overtime hours during "H" (normal hours).
Overtime hours during "N" (night hours).
Any deductions.
Creating Salary Records:
For each of the above cases, if applicable, it calculates the total payment and calls the create_additional_salary function to create the corresponding records.
Final Steps:
After processing all details, it sets a flag (timesheets_created) to True and shows a message indicating how many timesheets and additional salaries were created.
Considerations for Improvement:
Error Handling:
While there is basic error handling for missing configuration values, consider adding more robust error handling for potential issues, such as missing fields in detail or failed database operations during timesheet or salary creation.
User
اريد تسحسين الدالة من حيث التعامل مع الاخطاء
Assistant
تحسين التعامل مع الأخطاء في الدالة يمكن أن يتم عن طريق استخدام معالجة استثنائية (Exception Handling) لإدارة الأخطاء المحتملة بدلاً من الاعتماد فقط على رفع الاستثناءات. دعنا نعيد كتابة الدالة create_attendance مع تحسين طريقة التعامل مع الأخطاء:
تحسين دالة create_attendance:
python
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()
# 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)))
self.set("timesheets_created", True)
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
User
// Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
// For license information, please see license.txt
// timesheet_tool.js
let settings = {};
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
code
attachHideEventHandlers(frm);
hideGridButtons(frm);
preventCtrlDownKey(frm);
// Amendment of the filter for the staff field to bring only active staff with Salary Structure Assignment
frm.fields_dict['timesheet_tool_details'].grid.get_field('employee').get_query = function(doc, cdt, cdn) {
return {
query: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.get_active_employees_with_salary"
};
};
if (frm.doc.docstatus === 1) {
if (hasRole("Create Timesheet")) {
handleCreateTimesheetButton(frm);
}
if (hasRole("Submit Timesheet")) {
handleSubmitTimesheetButton(frm);
}
}
frm.set_query('project', () => {
let filters = {
company : frm.doc.company,
};
return {filters: filters};
})
},
// "Get Employmentee" button to get employees based on the project
get_employee(frm) {
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
frappe.call({
method: "get_all_employees",
doc: frm.doc,
args: { project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
}
}
});
},
project(frm) {
frappe.call({
method: "clear_timesheet_tool_details_table",
doc: frm.doc,
callback: function(response) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
}
});
},
Assistant
لتعزيز وتحسين التعامل مع الأخطاء في كود JavaScript الخاص بك لـ "Timesheet Tool" في إطار فِرَاق (Frappe)، يمكنك اتباع بعض الممارسات الجيدة مثل إضافة معالجة للأخطاء في المكالمات البرمجية (API calls) وتوفير تغذية مرتدة أفضل للمستخدم.
ستركز التحسينات على ضمان أن تتلقى واجهة المستخدم ردود أفعال كافية عند حدوث أخطاء، مما يجعلها أكثر أمانًا وسهولة للمستخدمين. إليك بعض الاقتراحات والتعديلات:
تحسين كود JavaScript:
javascript
User
اريد ان لايظهر الزر Create Timesheet ال اذا كانت قيمة الحقل timesheets_created تساوي 0
Assistant
لإخفاء زر "Create Timesheet" وعدم إظهاره إلا عندما تكون قيمة الحقل timesheets_created تساوي 0، يمكنك تعديل الدالة handleCreateTimesheetButton بحيث تتحقق أولاً من قيمة timesheets_created قبل إضافة الزر.
إليك كيفية تعديل الكود لتحقيق ذلك:
تعديل الدالة handleCreateTimesheetButton:
javascript
function handleCreateTimesheetButton(frm) {
// تحقق مما إذا كانت قيمة الحقل timesheets_created تساوي 0
if (frm.doc.timesheets_created === 0) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records",
"create_attendance",
"Create Timesheet",
"Timesheet records have been created successfully.",
"All records have already been created."
);
}
}
الكود الكامل مع التعديل:
إليك الكود لديك بعد التعديل:
javascript
User
اريد ان يكون الشرط هنا
if (frm.doc.docstatus === 1) {
if (hasRole("Create Timesheet")) {
handleCreateTimesheetButton(frm);
}
if (hasRole("Submit Timesheet")) {
handleSubmitTimesheetButton(frm);
}
}
Assistant
لتلبية طلبك، يمكنك تعديل الشرط الذي يتحقق من حالة الوثيقة (docstatus) بحيث يتم التحقق من قيمة timesheets_created داخل هذا الشرط.
الكود المعدل:
javascript
User
def
"""
A function to implement all accounts and create the required records.
"""
timesheet_count = 0
additional_salary_count = 0
settings = get_settings()
# 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
self.timesheets_created = True
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)))
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
```` اريد بعد ان يتم انشاء السجلات يتم تغيير قيمة الحقل timesheets_created الى 1
Assistant
لتحديث قيمة الحقل timesheets_created إلى 1 بعد إنشاء السجلات، يجب عليك التأكد من أن التحديث يتم بعد إتمام عملية إنشاء جميع السجلات، وليس داخل الحلقة.
يمكنك تحديث قيمة timesheets_created في نهاية الدالة بعد عرض الرسالة التي تخبر عدد السجلات التي تم إنشاؤها. إليك كيفية تعديل الدالة:
python
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()
# 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 1 after successfully creating the records
self.timesheets_created = 1
self.save() # Make sure to save the changes in the database
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
User
22:16:29 web.1 | ************************************************** 0
22:16:29 web.1 | ************************************************** True
22:16:29 web.1 | Traceback (most recent call last):
22:16:29 web.1 | File "apps/frappe/frappe/app.py", line 114, in application
22:16:29 web.1 | response = frappe.api.handle(request)
22:16:29 web.1 | File "apps/frappe/frappe/api/init.py", line 49, in handle
22:16:29 web.1 | data = endpoint(**arguments)
22:16:29 web.1 | File "apps/frappe/frappe/api/v1.py", line 36, in handle_rpc_call
22:16:29 web.1 | return frappe.handler.handle()
22:16:29 web.1 | File "apps/frappe/frappe/handler.py", line 49, in handle
22:16:29 web.1 | data = execute_cmd(cmd)
22:16:29 web.1 | File "apps/frappe/frappe/handler.py", line 85, in execute_cmd
22:16:29 web.1 | return frappe.call(method, **frappe.form_dict)
22:16:29 web.1 | File "apps/frappe/frappe/init.py", line 1725, in call
22:16:29 web.1 | return fn(*args, **newargs)
22:16:29 web.1 | File "apps/frappe/frappe/handler.py", line 331, in run_doc_method
22:16:29 web.1 | response = doc.run_method(method)
22:16:29 web.1 | File "apps/frappe/frappe/model/document.py", line 966, in run_method
22:16:29 web.1 | out = Document.hook(fn)(self, *args, **kwargs)
22:16:29 web.1 | File "apps/frappe/frappe/model/document.py", line 1326, in composer
22:16:29 web.1 | return composed(self, method, *args, **kwargs)
22:16:29 web.1 | File "apps/frappe/frappe/model/document.py", line 1308, in runner
22:16:29 web.1 | add_to_return_value(self, fn(self, *args, **kwargs))
22:16:29 web.1 | File "apps/frappe/frappe/model/document.py", line 963, in fn
22:16:29 web.1 | return method_object(*args, **kwargs)
22:16:29 web.1 | File "apps/frappe/frappe/utils/typing_validations.py", line 31, in wrapper
22:16:29 web.1 | return func(*args, **kwargs)
22:16:29 web.1 | File "apps/time_sheet_tool/time_sheet_tool/time_sheet_tool/doctype/timesheet_tool/timesheet_tool.py", line 139, in create_attendance
22:16:29 web.1 | self.save() # Make sure to save the changes in the database
22:16:29 web.1 | File "apps/frappe/frappe/model/document.py", line 341, in save
22:16:29 web.1 | return self._save(*args, **kwargs)
22:16:29 web.1 | File "apps/frappe/frappe/model/document.py", line 383, in _save
22:16:29 web.1 | self.validate_update_after_submit()
22:16:29 web.1 | File "apps/frappe/frappe/model/document.py", line 894, in validate_update_after_submit
22:16:29 web.1 | d._validate_update_after_submit()
22:16:29 web.1 | File "apps/frappe/frappe/model/base_document.py", line 1047, in _validate_update_after_submit
22:16:29 web.1 | frappe.throw(
22:16:29 web.1 | File "apps/frappe/frappe/init.py", line 602, in throw
22:16:29 web.1 | msgprint(
22:16:29 web.1 | File "apps/frappe/frappe/.py", line 567, in msgprint
22:16:29 web.1 | _raise_exception()
22:16:29 web.1 | File "apps/frappe/frappe/.py", line 518, in _raise_exception
22:16:29 web.1 | raise exc
22:16:29 web.1 | frappe.exceptions.UpdateAfterSubmitError: Row #1: Not allowed to change Total Payment after submission from 0.0 to 100000.0
Assistant
الخطأ الذي تواجهه هو UpdateAfterSubmitError والذي يشير إلى أنه لا يُسمح بتغيير قيمة لم يتم السماح بتعديلها بعد تقديم المستند. في هذه الحالة، يبدو أنك تحاول تغيير القيمة لـ total_payment (أو أي حقل آخر مُقيد) بعد أن تم تقديم سجل بالفعل.
الحلول الممكنة
تغيير الحقل بعد التقديم:
إذا كنت تريد تغيير قيمة timesheets_created إلى 1 فقط بعد التأكد من انتهاء جميع العمليات، ولكن يجب أن يتم ذلك قبل تقديم السجل. لذلك تأكد من تنفيذ هذا قبل أي submit في المستند.
تحقق من الحالة قبل حفظ القيمة:
قبل تعيين self.timesheets_created = 1، تحقق من حالة الوثيقة (docstatus). يجب أن تكون 0 (أي: المسودة) إذا كنت ترغب في تعديل الحقول. إليك كيفية تنفيذ ذلك:
python
User
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}"
code
# 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 1 after successfully creating the records
self.timesheets_created = True
print("*"*50,self.timesheets_created)
self.save() # Make sure to save the changes in the database
frappe.db.commit()
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count)) @frappe.whitelist()
Assistant
لتحديث قيمة الحقل timesheets_created إلى 1 (أو True) بعد إنشاء السجلات، وضمان أن العملية تتم بشكل صحيح دون حدوث أي أخطاء، من المهم مراعاة بعض النقاط.
النقاط التي يجب مراجعتها:
التحقق من حالة الوثيقة: تأكد من أنه يتم تحديث timesheets_created بطريقة صحيحة، وأن المستند لا يزال قابلاً للتعديل (أي لم يتم تقديمه بعد).
حفظ التغييرات: استخدم self.save() لحفظ التغييرات على المستند بعد إجراء جميع العمليات. تأكد من أن البيانات في حالة صالحة للحفظ.
إضافة نقطة التحقق في الإخراج (اللوج): لديك بالفعل print لعرض القيمة قبل وبعد التحديث، وهو أمر جيد للترتيب المحلي.
الكود المعدل:
إليك الكود المعدل الذي يتضمن هذه النقاط:
python
User
مع العلم ان المستند معتمد
Assistant
إذا كان المستند معتمدًا (submitted)، فإن محاولة تعديل أي حقل من الحقول (مثل timesheets_created) ستؤدي إلى حدوث خطأ UpdateAfterSubmitError، مما يعني أنه لا يُسمح بتعديل تلك القيم بعد تقديم المستند. في حالة تقديم المستندات، يجب استخدام طرق أخرى للإشارة إلى الحالات.
كيفية التعامل مع هذه المشكلة:
استخدام حالات جديدة:
إذا كان المستند قد تم تقديمه، فكر في استخدام حقل جديد أو طريقة أخرى لتتبع الميزات المطلوبة. بدلاً من تعديل timesheets_created بعد الاعتماد، يمكنك إضافة حقل جديد مثل timesheets_processed.
تحديث الحقل قبل تقديم المستند:
إذا كانت العمليات المرتبطة بتحديث timesheets_created ينبغي أن تتم بعد تقديم المستند، يمكن أن تجري هذه العمليات في حدث يعتمد على الزر أو حدث آخر خاص بالعملية، ولكن ينبغي أن يتم ذلك قبل تقديم المستند.
اقتراح الكود:
إذا كنت ترغب في الاحتفاظ بالتحكم في الحقل timesheets_created بعد تقديم المستند، أقترح استخدام الطريقة التالية:
1. إنشاء حقل جديد:
قم بإضافة حقل جديد يسمى timesheets_processed، والذي سيتم استخدامه لتحديد ما إذا كانت السجلات قد تمت معالجتها.
2. تغيير الدالة create_attendance:
python
User
22:20:31 web.1 | ************************************************** 0
22:20:32 web.1 | ************************************************** True
22:20:32 web.1 | Traceback (most recent call last):
22:20:32 web.1 | File "apps/frappe/frappe/app.py", line 114, in application
22:20:32 web.1 | response = frappe.api.handle(request)
22:20:32 web.1 | File "apps/frappe/frappe/api/init.py", line 49, in handle
22:20:32 web.1 | data = endpoint(**arguments)
22:20:32 web.1 | File "apps/frappe/frappe/api/v1.py", line 36, in handle_rpc_call
22:20:32 web.1 | return frappe.handler.handle()
22:20:32 web.1 | File "apps/frappe/frappe/handler.py", line 49, in handle
22:20:32 web.1 | data = execute_cmd(cmd)
22:20:32 web.1 | File "apps/frappe/frappe/handler.py", line 85, in execute_cmd
22:20:32 web.1 | return frappe.call(method, **frappe.form_dict)
22:20:32 web.1 | File "apps/frappe/frappe/init.py", line 1725, in call
22:20:32 web.1 | return fn(*args, **newargs)
22:20:32 web.1 | File "apps/frappe/frappe/handler.py", line 331, in run_doc_method
22:20:32 web.1 | response = doc.run_method(method)
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 966, in run_method
22:20:32 web.1 | out = Document.hook(fn)(self, *args, **kwargs)
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 1326, in composer
22:20:32 web.1 | return composed(self, method, *args, **kwargs)
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 1308, in runner
22:20:32 web.1 | add_to_return_value(self, fn(self, *args, **kwargs))
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 963, in fn
22:20:32 web.1 | return method_object(*args, **kwargs)
22:20:32 web.1 | File "apps/frappe/frappe/utils/typing_validations.py", line 31, in wrapper
22:20:32 web.1 | return func(*args, **kwargs)
22:20:32 web.1 | File "apps/time_sheet_tool/time_sheet_tool/time_sheet_tool/doctype/timesheet_tool/timesheet_tool.py", line 139, in create_attendance
22:20:32 web.1 | self.save() # Make sure to save the changes in the database
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 341, in save
22:20:32 web.1 | return self._save(*args, **kwargs)
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 383, in _save
22:20:32 web.1 | self.validate_update_after_submit()
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 894, in validate_update_after_submit
22:20:32 web.1 | d._validate_update_after_submit()
22:20:32 web.1 | File "apps/frappe/frappe/model/base_document.py", line 1047, in _validate_update_after_submit
22:20:32 web.1 | frappe.throw(
22:20:32 web.1 | File "apps/frappe/frappe/init.py", line 602, in throw
22:20:32 web.1 | msgprint(
22:20:32 web.1 | File "apps/frappe/frappe/.py", line 567, in msgprint
22:20:32 web.1 | _raise_exception()
22:20:32 web.1 | File "apps/frappe/frappe/.py", line 518, in _raise_exception
22:20:32 web.1 | raise exc
22:20:32 web.1 | frappe.exceptions.UpdateAfterSubmitError: Row #1: Not allowed to change Total Payment after submission from 0.0 to 100000.0
Assistant
الخطأ الذي تواجهه هو UpdateAfterSubmitError، وهو يعني أنك تحاول تعديل حقل (في هذه الحالة، Total Payment) بعد تقديم المستند. السجلات المعتمدة (submitted) لا يمكن تغييرها إلا وفق شروط صارمة.
استراتيجيات للتعامل مع هذا الخطأ:
التأكد من عدم تحديث الحقول المحظورة:
إذا كانت عملية المعالجة تتضمن تعديلًا لبعض الحقول، تأكد من أنك لا تحاول تعديل تلك الحقول بعد تقديم المستند. بمجرد تقديم المستند، يمكنك فقط إضافة سجلات جديدة أو إنشاء معدلات جديدة، وليس تعديل السجلات الحالية.
إضافة حقول جديدة:
إذا كنت بحاجة إلى الاحتفاظ بمعلومات إضافية عن عدة مدفوعات أو أوقات إضافية، يمكنك استخدام حقول جديدة بدلاً من تعديل الحقول الحالية. على سبيل المثال، يمكنك إنشاء حقل جديد لتتبع المدفوعات المباشرة.
التأكد من الحالة:
إذا كانت الدالة create_attendance متكررة على مستند تم تقديمه سابقًا، تأكد من أنها تُستدعى فقط على مستندات غير معتمدة.
تعديل الكود ليكون أكثر قوة:
لجعل عملية create_attendance غير قابلة للتنفيذ على المستندات المعتمدة، يمكننا استخدام شرط للتحقق من حالة المستند (إذا كان في حالة مسودة) قبل محاولة تحديث الحقول. إليك كيف يمكنك القيام بذلك:
python
User
ستدعى فقط على مستندات معتمدة
Assistant
إذا كانت الدالة create_attendance ستستدعى فقط على مستندات معتمدة (أي أن docstatus ستكون دائمًا 1)، فسيتعين عليك تعديل منطق المعالجة بطريقة تخدم هذه المتطلبات.
خيارات للتحكم في معالجة البيانات:
تجاهل تعديل الحقول الموجودة: يجب أن تحاول أن تكون العمليات التي تنطوي على تعديل الحقول (مثل total_payment) على مستندات معتمدة. يمكن أن يتضمن ذلك استخلاص معلومات إضافية أو إنشاء سجلات جديدة بدلاً من تعديل المعتمد.
إنشاء سجلات جديدة: إذا كنت ترغب في معالجة الأرقام المالية (مثل total_payment) على مستوى المستند المعتمد، قد يتعين عليك فقط إنشاء سجلات إضافية تعكس التغييرات بدلاً من تعديل القيم الأصلية.
تعديل الدالة:
إضافة سجلات بدلاً من تعديل الحقول:
يمكنك استخدام دالة جديدة تتعامل مع مدفوعات إضافية بعد تقديم السجلات في create_attendance؛ وبالتالي، كل ما تحتاجه هو تجميع المعلومات وليس تحديث الحقول الجوهرية.
الكود المعدل:
إليك كيف يمكنك تنفيذ ذلك:
python
User
22:20:31 web.1 | method = get_attr(cmd)
22:20:31 web.1 | ************************************************** 0
22:20:32 web.1 | ************************************************** True
22:20:32 web.1 | Traceback (most recent call last):
22:20:32 web.1 | File "apps/frappe/frappe/app.py", line 114, in application
22:20:32 web.1 | response = frappe.api.handle(request)
22:20:32 web.1 | File "apps/frappe/frappe/api/init.py", line 49, in handle
22:20:32 web.1 | data = endpoint(**arguments)
22:20:32 web.1 | File "apps/frappe/frappe/api/v1.py", line 36, in handle_rpc_call
22:20:32 web.1 | return frappe.handler.handle()
22:20:32 web.1 | File "apps/frappe/frappe/handler.py", line 49, in handle
22:20:32 web.1 | data = execute_cmd(cmd)
22:20:32 web.1 | File "apps/frappe/frappe/handler.py", line 85, in execute_cmd
22:20:32 web.1 | return frappe.call(method, **frappe.form_dict)
22:20:32 web.1 | File "apps/frappe/frappe/init.py", line 1725, in call
22:20:32 web.1 | return fn(*args, **newargs)
22:20:32 web.1 | File "apps/frappe/frappe/handler.py", line 331, in run_doc_method
22:20:32 web.1 | response = doc.run_method(method)
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 966, in run_method
22:20:32 web.1 | out = Document.hook(fn)(self, *args, **kwargs)
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 1326, in composer
22:20:32 web.1 | return composed(self, method, *args, **kwargs)
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 1308, in runner
22:20:32 web.1 | add_to_return_value(self, fn(self, *args, **kwargs))
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 963, in fn
22:20:32 web.1 | return method_object(*args, **kwargs)
22:20:32 web.1 | File "apps/frappe/frappe/utils/typing_validations.py", line 31, in wrapper
22:20:32 web.1 | return func(*args, **kwargs)
22:20:32 web.1 | File "apps/time_sheet_tool/time_sheet_tool/time_sheet_tool/doctype/timesheet_tool/timesheet_tool.py", line 139, in create_attendance
22:20:32 web.1 | self.save() # Make sure to save the changes in the database
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 341, in save
22:20:32 web.1 | return self._save(*args, **kwargs)
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 383, in _save
22:20:32 web.1 | self.validate_update_after_submit()
22:20:32 web.1 | File "apps/frappe/frappe/model/document.py", line 894, in validate_update_after_submit
22:20:32 web.1 | d._validate_update_after_submit()
22:20:32 web.1 | File "apps/frappe/frappe/model/base_document.py", line 1047, in _validate_update_after_submit
22:20:32 web.1 | frappe.throw(
22:20:32 web.1 | File "apps/frappe/frappe/.py", line 602, in throw
22:20:32 web.1 | msgprint(
22:20:32 web.1 | File "apps/frappe/frappe/.py", line 567, in msgprint
22:20:32 web.1 | _raise_exception()
22:20:32 web.1 | File "apps/frappe/frappe/.py", line 518, in _raise_exception
22:20:32 web.1 | raise exc
22:20:32 web.1 | frappe.exceptions.UpdateAfterSubmitError: Row #1: Not allowed to change Total Payment after submission from 0.0 to 100000.0
Assistant
يبدو أنك تواجه مشكلة متعلقة بمحاولتك لتعديل قيمة حقل Total Payment بعد تقديم المستند (docstatus = 1). كما قلت سابقًا، لا يُسمح بتغيير القيم في الحقول المعتمدة في Frappe/ERPNext بعد تقديم المستند.
أسباب الخطأ:
التعديل بعد الاعتماد: الخطأ يحدث لأنك تحاول تعديل Total Payment لأحد التفاصيل (row) في المستند بعد أن تم تقديمه.
الحلول الممكنة:
عدم تعديل الحقول التي تم تقديمها:
إذا كنت بحاجة إلى معالجة الحقول الخاصة بالمستندات المعتمدة، يجب أن تفكر في كيفية تحقيق ذلك دون تعديل أي منها. يجب أن تقوم بحفظ أي مدفوعات جديدة أو إضافات كمدفوعات جديدة بدلاً من تعديل القيم الموجودة.
إضافة سجلات جديدة:
يمكنك دائمًا إنشاء سجل جديد لأي مدفوعات (ساعات عمل إضافية، خصومات، وما إلى ذلك) بدلاً من تحديث القيم الموجودة. عندها ستحافظ على المعلومات كاملة دون المساس بالبيانات المعتمدة.
تعديل الكود:
إليك كودًا يمكنه التعامل مع المدفوعات الإضافية دون محاولة تعديل الحقول المعتمدة:
python
User
لا يتم تغيير قيمة الحقل 
Timesheets Created
Assistant
إذا كانت قيمة الحقل timesheets_created لا تتغير كما هو متوقع في دالة create_attendance، فمن المحتمل أن المشكلة تكمن في المنطق أو الترتيب الذي يتم فيه تغيير القيمة. إليك نظرة خطوة بخطوة على كيفية ضمان تحديث هذا الحقل بشكل صحيح:
الخطوات لتحديث الحقل timesheets_created:
التحقق من الدالة واستدعاءها:
تأكد من أن الدالة create_attendance يتم استدعاؤها بشكل صحيح في سياق صحيح (يجب أن يتم استدعاؤها من مكان يسمح بتعديل الحقول).
تغيير القيمة بعد إنشاء السجلات:
تأكد من أن القيمة self.timesheets_created يتم تغييرها بعد الانتهاء من جميع عمليات إنشاء السجلات.
حفظ المستند:
بعد تغيير القيمة، تأكد من حفظ المستند باستخدام self.save().
الكود المعدل:
إليك التعديلات الممكنة على دالة create_attendance:
Validate input data types to ensure that the calculations performed (like multiplications) receive the correct type (e.g., integers or floats).
Logging:
Consider adding logging functionality to record details of the process, especially if there are errors or unusual results.
Refactoring Long Blocks:
The code processes multiple salary components in a single block. Refactoring the creation of additional salary entries into a helper method could improve readability.
Documentation:
The docstrings for the function should be expanded to give context about the parameters and returns. This is especially helpful for maintenance and future developers.
Performance:
If the process is expected to handle a large number of timesheet entries, consider profiling the performance and optimizing as necessary.
By considering the above points, you could enhance the function's reliability, maintainability, and performance while keeping its core functionality intact.
نقاط التحسين:
استخدام try-except:
تُستخدم الكتلة try-except لتقليل تأثير الأخطاء المحتملة على العملية الكاملة.
تسجيل الأخطاء:
يتم تسجيل الأخطاء باستخدام frappe.log_error، مما يساعد في تتبع الأخطاء ومعرفة التفاصيل الخاصة بكل خطأ حصل أثناء معالجة بيانات الحضور.
عرض رسالة للمستخدم:
بعد حدوث خطأ في معالجة أحد التفاصيل، يتم إعلام المستخدم بالخطأ المحدد.
تحقق من القيم:
تم تبسيط عملية التحقق من إعدادات الراتب المفقودة باستخدام all(), مما يجعل الكود أكثر وضوحًا.
نصائح إضافية:
إذا كان بالإمكان، على سبيل المثال، تحديد أنواع الأخطاء التي يتم التعامل معها (مثل الأخطاء المتعلقة بالمدخلات، أو الأخطاء في عمليات قاعدة البيانات)، يمكن استخدام أكثر من كتلة except للتحكم في معالجة الأخطاء بشكل أفضل.
تأكد من أن أي استثناءات يمكن أن تؤثر على العمليات الحيوية (مثل إخفاقات القاعدة البيانات) يتم التعامل معها بطريقة تسمح بإعادة المحاولة أو إلغاء العمليات بشكل آمن إذا لزم الأمر.
});
// A function to handle the "Create Timesheet" button
function handleCreateTimesheetButton(frm) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records",
"create_attendance",
"Create Timesheet",
"Timesheet records have been created successfully.",
"All records have already been created."
);
}
// A function to handle the "Submit Timesheet" button
function handleSubmitTimesheetButton(frm) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
"approval_attendance",
"Submit Timesheet",
"Timesheet records have been approved successfully.",
"All records have already been approved."
);
}
// A function to handle buttons
function handle_button(frm, method, def, btn_label, success_msg, fail_msg) {
let button_visible = false;
frappe.call({
method: method,
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
frm.add_custom_button((btn_label), function() {
if (frm.is_dirty()) {
frappe.throw(("You have unsaved changes in this form. Please save before you continue."));
}
frappe.call({
method: def,
doc: frm.doc,
callback: function() {
frm.reload_doc();
frappe.msgprint(__(success_msg));
}
});
});
button_visible = true; // Mark button as visible
}
}
});
return button_visible; // Return whether the button is visible
}
// Function to check if the user has a specific role
function hasRole(roleName) {
return frappe.user.has_role(roleName);
}
// Hide specified DVD using jQuery
function hideTargetDiv(selector) {
const targetDiv = $(selector);
if (targetDiv.length) {
targetDiv.hide();
}
}
// Add processors to buttons
function attachHideEventHandlers(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.find('.btn-open-row').on('click', function() {
hideTargetDiv('span.row-actions');
hideTargetDiv('div.grid-footer-toolbar');
});
// A function to hide buttons in the table.
function hideGridButtons(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.find('.grid-add-row').hide();
gridWrapper.find('.grid-remove-rows').hide();
gridWrapper.find('.grid-row-check').closest('.row-check').hide();
}
// A function for general treatment
function processAll(frm) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
}
});
}
// A function to prevent "Ctrl + Down" in the table
function preventCtrlDownKey(frm) {
// Listening to the keydown event in the table
frm.fields_dict['timesheet_tool_details'].grid.wrapper.on('keydown', function(event) {
// Check if the user presses "Ctrl + Down"
if (event.ctrlKey && event.key === "ArrowDown") {
return false; // Preventing further treatment of the event
}
});
}
let settings = {};
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
attachHideEventHandlers(frm);
hideGridButtons(frm);
preventCtrlDownKey(frm);
frm.fields_dict['timesheet_tool_details'].grid.get_field('employee').get_query = function(doc, cdt, cdn) {
return {
query: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.get_active_employees_with_salary"
};
};
if (frm.doc.docstatus === 1) {
if (hasRole("Create Timesheet")) {
handleCreateTimesheetButton(frm);
}
if (hasRole("Submit Timesheet")) {
handleSubmitTimesheetButton(frm);
}
}
frm.set_query('project', () => {
let filters = { company: frm.doc.company };
return { filters: filters };
});
},
// Improved error handling in the "Get Employee" button
get_employee(frm) {
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
frappe.call({
method: "get_all_employees",
doc: frm.doc,
args: { project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
} else {
// Handle errors if they occur
frappe.msgprint(__('Error fetching employees: {0}', response.exc));
}
},
// Handle network errors or other cases
error: function(error) {
frappe.msgprint(__('An error occurred while fetching employees: {0}', error.message));
}
});
},
project(frm) {
frappe.call({
method: "clear_timesheet_tool_details_table",
doc: frm.doc,
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
} else {
frappe.msgprint(__('Error clearing timesheet details: {0}', response.exc));
}
},
error: function(error) {
frappe.msgprint(__('An error occurred while clearing timesheet details: {0}', error.message));
}
});
},
});
// Improved error handling in button handlers
function handleCreateTimesheetButton(frm) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records",
"create_attendance",
"Create Timesheet",
"Timesheet records have been created successfully.",
"All records have already been created."
);
}
function handleSubmitTimesheetButton(frm) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
"approval_attendance",
"Submit Timesheet",
"Timesheet records have been approved successfully.",
"All records have already been approved."
);
}
function handle_button(frm, method, def, btn_label, success_msg, fail_msg) {
let button_visible = false;
frappe.call({
method: method,
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
frm.add_custom_button(__(btn_label), function() {
if (frm.is_dirty()) {
frappe.throw(__("You have unsaved changes in this form. Please save before you continue."));
}
frappe.call({
method: def,
doc: frm.doc,
callback: function() {
frm.reload_doc();
frappe.msgprint(__(success_msg));
},
error: function(error) {
frappe.msgprint(__('Error during the process: {0}', error.message));
}
});
});
button_visible = true; // Mark button as visible
}
},
error: function(error) {
frappe.msgprint(__('Error checking missing records: {0}', error.message));
}
});
return button_visible; // Return whether the button is visible
}
// Function to check if the user has a specific role
function hasRole(roleName) {
return frappe.user.has_role(roleName);
}
// Hide specified DVD using jQuery
function hideTargetDiv(selector) {
const targetDiv = $(selector);
if (targetDiv.length) {
targetDiv.hide();
}
}
// Add processors to buttons
function attachHideEventHandlers(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.find('.btn-open-row').on('click', function() {
hideTargetDiv('span.row-actions');
hideTargetDiv('div.grid-footer-toolbar');
});
gridWrapper.find('.row-index').on('click', function() {
hideTargetDiv('span.row-actions');
hideTargetDiv('div.grid-footer-toolbar');
});
}
// A function to hide buttons in the table.
function hideGridButtons(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.find('.grid-add-row').hide();
gridWrapper.find('.grid-remove-rows').hide();
gridWrapper.find('.grid-row-check').closest('.row-check').hide();
}
// A function for general treatment
function processAll(frm) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function () {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
},
error: function (error) {
frappe.msgprint(__('Error processing all: {0}', error.message));
}
});
}
// A function to prevent "Ctrl + Down" in the table
function preventCtrlDownKey(frm) {
// Listening to the keydown event in the table
frm.fields_dict['timesheet_tool_details'].grid.wrapper.on('keydown', function(event) {
// Check if the user presses "Ctrl + Down"
if (event.ctrlKey && event.key === "ArrowDown") {
return false; // Preventing further treatment of the event
}
});
}
التحسينات التي تم تنفيذها:
معالجة الأخطاء: تم إضافة معالجة للخطأ لكل مكالمة frappe.call()، مما يوفر إشعارات للمستخدم في حال حدوث خطأ أثناء تنفيذ العمليات.
تغذية مرتدة أفضل: كلما حدث خطأ، يتم عرض رسالة توضيحية توضح طبيعة الخطأ، مما يسهل على المستخدمين فهم ما يجري.
التحقق من حالات الاستجابة: تم التحقق مما إذا كانت استجابة response تحتوي على أي أخطاء ومعالجتها بشكل صحيح.
نصائح إضافية:
حافظ على تنسيق الكود والنمط المستخدم في التعليقات لضمان وضوح الكود بالنسبة لك أو للآخرين الذين قد يعملون عليه لاحقًا.
تأكد من اختبار التطبيق بشكل كامل بعد إدخال هذه التعديلات للتأكد من أن كل شيء يعمل كما هو متوقع.
يمكن أن تكون الرسائل التي تظهر للمستخدم أكثر تحديدًا بناءً على أنواع الأخطاء المختلفة، مما يساعد على تسريع حل المشكلات.
let settings = {};
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
attachHideEventHandlers(frm);
hideGridButtons(frm);
preventCtrlDownKey(frm);
frm.fields_dict['timesheet_tool_details'].grid.get_field('employee').get_query = function(doc, cdt, cdn) {
return {
query: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.get_active_employees_with_salary"
};
};
if (frm.doc.docstatus === 1) {
if (hasRole("Create Timesheet")) {
handleCreateTimesheetButton(frm);
}
if (hasRole("Submit Timesheet")) {
handleSubmitTimesheetButton(frm);
}
}
frm.set_query('project', () => {
let filters = { company: frm.doc.company };
return { filters: filters };
});
},
get_employee(frm) {
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
frappe.call({
method: "get_all_employees",
doc: frm.doc,
args: { project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
} else {
frappe.msgprint(__('Error fetching employees: {0}', response.exc));
}
},
error: function(error) {
frappe.msgprint(__('An error occurred while fetching employees: {0}', error.message));
}
});
},
project(frm) {
frappe.call({
method: "clear_timesheet_tool_details_table",
doc: frm.doc,
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
} else {
frappe.msgprint(__('Error clearing timesheet details: {0}', response.exc));
}
},
error: function(error) {
frappe.msgprint(__('An error occurred while clearing timesheet details: {0}', error.message));
}
});
},
});
// احتفظ بالتعديل هنا
function handleCreateTimesheetButton(frm) {
// تحقق مما إذا كانت قيمة timesheets_created تساوي 0
if (frm.doc.timesheets_created === 0) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records",
"create_attendance",
"Create Timesheet",
"Timesheet records have been created successfully.",
"All records have already been created."
);
}
}
function handleSubmitTimesheetButton(frm) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
"approval_attendance",
"Submit Timesheet",
"Timesheet records have been approved successfully.",
"All records have already been approved."
);
}
function handle_button(frm, method, def, btn_label, success_msg, fail_msg) {
let button_visible = false;
frappe.call({
method: method,
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
frm.add_custom_button(__(btn_label), function() {
if (frm.is_dirty()) {
frappe.throw(__("You have unsaved changes in this form. Please save before you continue."));
}
frappe.call({
method: def,
doc: frm.doc,
callback: function() {
frm.reload_doc();
frappe.msgprint(__(success_msg));
},
error: function(error) {
frappe.msgprint(__('Error during the process: {0}', error.message));
}
});
});
button_visible = true; // Mark button as visible
}
},
error: function(error) {
frappe.msgprint(__('Error checking missing records: {0}', error.message));
}
});
return button_visible; // Return whether the button is visible
}
function hasRole(roleName) {
return frappe.user.has_role(roleName);
}
function hideTargetDiv(selector) {
const targetDiv = $(selector);
if (targetDiv.length) {
targetDiv.hide();
}
}
function attachHideEventHandlers(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.find('.btn-open-row').on('click', function() {
hideTargetDiv('span.row-actions');
hideTargetDiv('div.grid-footer-toolbar');
});
gridWrapper.find('.row-index').on('click', function() {
hideTargetDiv('span.row-actions');
hideTargetDiv('div.grid-footer-toolbar');
});
}
function hideGridButtons(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.find('.grid-add-row').hide();
gridWrapper.find('.grid-remove-rows').hide();
gridWrapper.find('.grid-row-check').closest('.row-check').hide();
}
function processAll(frm) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
},
error: function(error) {
frappe.msgprint(__('Error processing all: {0}', error.message));
}
});
}
function preventCtrlDownKey(frm) {
frm.fields_dict['timesheet_tool_details'].grid.wrapper.on('keydown', function(event) {
if (event.ctrlKey && event.key === "ArrowDown") {
return false; // Preventing further treatment of the event
}
});
}
ما تم تعديله:
في الدالة handleCreateTimesheetButton، تم إضافة شرط يتحقق من قيمة timesheets_created في frm.doc، وأصبح الزر "Create Timesheet" يُضاف فقط إذا كانت هذه القيمة تساوي 0.
بهذا الشكل، سيتأكد المستخدم من أنه يرى زر "Create Timesheet" فقط عندما تكون القيمة في الحقل المقابل تساوي 0.
let settings = {};
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
attachHideEventHandlers(frm);
hideGridButtons(frm);
preventCtrlDownKey(frm);
frm.fields_dict['timesheet_tool_details'].grid.get_field('employee').get_query = function(doc, cdt, cdn) {
return {
query: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.get_active_employees_with_salary"
};
};
// تحقق من حالة الوثيقة وإن كانت القيمة timesheets_created تساوي 0
if (frm.doc.docstatus === 1) {
if (hasRole("Create Timesheet") && frm.doc.timesheets_created === 0) {
handleCreateTimesheetButton(frm);
}
if (hasRole("Submit Timesheet")) {
handleSubmitTimesheetButton(frm);
}
}
frm.set_query('project', () => {
let filters = { company: frm.doc.company };
return { filters: filters };
});
},
get_employee(frm) {
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
frappe.call({
method: "get_all_employees",
doc: frm.doc,
args: { project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
} else {
frappe.msgprint(__('Error fetching employees: {0}', response.exc));
}
},
error: function(error) {
frappe.msgprint(__('An error occurred while fetching employees: {0}', error.message));
}
});
},
project(frm) {
frappe.call({
method: "clear_timesheet_tool_details_table",
doc: frm.doc,
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
} else {
frappe.msgprint(__('Error clearing timesheet details: {0}', response.exc));
}
},
error: function(error) {
frappe.msgprint(__('An error occurred while clearing timesheet details: {0}', error.message));
}
});
},
});
// احتفظ بالتعديل هنا
function handleCreateTimesheetButton(frm) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records",
"create_attendance",
"Create Timesheet",
"Timesheet records have been created successfully.",
"All records have already been created."
);
}
function handleSubmitTimesheetButton(frm) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
"approval_attendance",
"Submit Timesheet",
"Timesheet records have been approved successfully.",
"All records have already been approved."
);
}
function handle_button(frm, method, def, btn_label, success_msg, fail_msg) {
let button_visible = false;
frappe.call({
method: method,
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
frm.add_custom_button(__(btn_label), function() {
if (frm.is_dirty()) {
frappe.throw(__("You have unsaved changes in this form. Please save before you continue."));
}
frappe.call({
method: def,
doc: frm.doc,
callback: function() {
frm.reload_doc();
frappe.msgprint(__(success_msg));
},
error: function(error) {
frappe.msgprint(__('Error during the process: {0}', error.message));
}
});
});
button_visible = true;
}
},
error: function(error) {
frappe.msgprint(__('Error checking missing records: {0}', error.message));
}
});
return button_visible;
}
function hasRole(roleName) {
return frappe.user.has_role(roleName);
}
function hideTargetDiv(selector) {
const targetDiv = $(selector);
if (targetDiv.length) {
targetDiv.hide();
}
}
function attachHideEventHandlers(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.find('.btn-open-row').on('click', function() {
hideTargetDiv('span.row-actions');
hideTargetDiv('div.grid-footer-toolbar');
});
gridWrapper.find('.row-index').on('click', function() {
hideTargetDiv('span.row-actions');
hideTargetDiv('div.grid-footer-toolbar');
});
}
function hideGridButtons(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.find('.grid-add-row').hide();
gridWrapper.find('.grid-remove-rows').hide();
gridWrapper.find('.grid-row-check').closest('.row-check').hide();
}
function processAll(frm) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
},
error: function(error) {
frappe.msgprint(__('Error processing all: {0}', error.message));
}
});
}
function preventCtrlDownKey(frm) {
frm.fields_dict['timesheet_tool_details'].grid.wrapper.on('keydown', function(event) {
if (event.ctrlKey && event.key === "ArrowDown") {
return false; // Preventing further treatment of the event
}
});
}
ما تم تعديله:
تم إضافة شرط frm.doc.timesheets_created === 0 ضمن كتلة الشرط الخاصة بالزر "Create Timesheet"، مما يعني أن الزر لن يظهر إلا إذا كانت قيمة timesheets_created تساوي 0.
بهذا الشكل، يجب أن يظهر زر "Create Timesheet" فقط عندما تكون الحالة .docstatus تساوي 1 وقيمة timesheets_created تساوي 0.
ما تم تغييره:
تحديث قيمة timesheets_created:
بعد الانتهاء من معالجة السجلات، يتم تعيين self.timesheets_created إلى 1.
حفظ التغييرات:
تم إضافة self.save() لحفظ التغييرات في قاعدة البيانات بعد تغيير قيمة timesheets_created.
ملاحظات:
تأكد من أن هناك طريقة مناسبة لمزامنة القيم قبل الحفظ لضمان عدم فقدان البيانات أو حدوث تداخل.
قد تحتاج إلى معالجة السيناريوهات التي قد يحدث فيها خطأ بعد البدء في إنشاء السجلات، وهذا يعتمد على كيفية هيكلة الدالة ومكان استخدامها.
init
init
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()
# 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)))
if self.docstatus == 0: # Only update if document is in draft state
self.timesheets_created = 1
self.save() # Save the changes only if the doc is still draft
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
التغييرات التي تم إجراؤها:
التحقق من docstatus:
تم إضافة شرط يتحقق من وضع الوثيقة (إذا كانت في المسودة 0)، وبالتالي يمكن تعديل القيم فقط إذا كانت الوثيقة لم يتم تقديمها بعد.
تأجيل عملية الحفظ:
يتم الحفظ فقط في حالة كون الوثيقة لا تزال في حالة المسودة، مما يسمح بتجنب الأخطاء المتعلقة بتحديث الحقول المحظور.
التأكد من أن الكود يعمل:
تأكد من أن get_settings() و create_timesheet() و create_additional_salary() تعمل بشكل أعتيادي ولا تسبب تغييرات غير مرغوب فيها في الحقول التي تم تقديمها مسبقاً.
اختبر الكود بعد إجراء هذه التعديلات. إذا حدثت أي أخطاء جديدة، سيكون من الضروري مراجعة المكدس (stack trace) للحصول على معلومات إضافية حول التحليل.
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) # Debugging output
# 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
if self.docstatus == 0: # Only if the document is in draft state
self.timesheets_created = True
print("*" * 50, self.timesheets_created) # Debugging output
self.save() # Save the changes in the database
frappe.db.commit()
# Show message indicating completion
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
التعديلات المضافة:
التحقق من docstatus: يسمح بتغيير timesheets_created فقط إذا كانت الوثيقة في حالة المسودة (0).
حفظ التغييرات: يتم استخدام self.save() لحفظ التغييرات في قاعدة البيانات.
لقطات الأخطاء: تم الحفاظ على التعامل مع الأخطاء كما هو لضمان الحفاظ على الاستقرار.
خطوة تالية:
بعد هذه التعديلات، يجب عليكم اختبار الدالة في بيئة تطوير للتحقق من أنها تعمل كما هو متوقع وأنها ليست هناك أي أخطاء. كما يجب أن تأخذ في الاعتبار أي تغييرات أخرى قد تلزم بناءً على السياق العام للتطبيق.
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_processed) # تغيير الأسماء بناءً على الحقل الجديد
# 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_processed to True after successfully creating the records
self.timesheets_processed = True
print("*" * 50, self.timesheets_processed) # Debugging output
self.save() # Make sure to save the changes in the database
frappe.db.commit()
# Show message indicating completion
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
ما تم تغييره:
استخدام حقل جديد: استخدم timesheets_processed بدلاً من timesheets_created.
تعديل الطباعة: تمت طباعة قيمة timesheets_processed في حالتها الجديدة.
الخلاصة:
إذا كانت العمليات تتطلب تعديلات على المستندات التي تم تقديمها، ستحتاج إلى إعادة التفكير في كيفية إدارة تلك العمليات.
استخدم حقول إضافية لتتبع حالة المعالجة الخاصة بالسجلات دون تغيير السجلات المعتمدة.
تأكد من اختبار الكود الجديد بشكل جيد بعد إجراء هذه التعديلات.
init
init
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_processed) # Debugging output
# 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
if self.docstatus == 0: # Only in draft state
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
if self.docstatus == 0: # Only in draft state
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
if self.docstatus == 0: # Only in draft state
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_processed to True after successfully creating the records
if self.docstatus == 0: # Ensure the document is in draft state
self.timesheets_processed = True
print("*" * 50, self.timesheets_processed) # Debugging output
self.save() # Save the changes in the database
frappe.db.commit()
# Show message indicating completion
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
ما تم تغييره:
تعديل المدفوعات فقط في حالة المسودة:
استخدم شرط للتحقق من أن self.docstatus == 0 (المستند في حالة المسودة) قبل تنفيذ عمليات تعديل تلك الحقول.
عدم تعديل الحقول المعتمدة:
لا يمكنك ببساطة تغيير total_payment أو أي حقل آخر محظور بمجرد أن تم تقديم المستند.
نصائح إضافية:
تأكد من مراجعة تصاريح الوصول للأدوار وتحديد ما إذا كانت هناك صفقات إضافية يجب إضافتها لمستخدمين محددين.
ابدأ الاختبار على مستندات جديدة أو غير معتمدة للتحقق من أن الحل يعمل كما هو متوقع.
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_processed) # Debugging output
# 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
# Assuming we can create a new record without modifying the existing approved one
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_processed to True after successfully creating the records
self.timesheets_processed = True
print("*" * 50, self.timesheets_processed) # Debugging output
self.save() # Make sure to save the changes in the database
frappe.db.commit()
# Show message indicating completion
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
التعديلات:
الحفاظ على إنشاء سجلات جديدة:
تأكد من أن كل عملية لإنشاء دخول جديد يتم بشكل صحيح دون محاولة تعديل الحقول المعتمدة.
الاعتماد على الدوال المساعدة:
استخدم دوال مفيدة مثل create_additional_salary بشكل صحيح للتأكد من أن جميع المدفوعات الإضافية تتم معالجتها دون تعديل الحقول الموجودة بالفعل.
حفظ التغييرات:
إذا كنت تقوم بتحديث حالة timesheets_processed لإظهار أن السجلات تمت معالجتها، تأكد من أنها مفيدة في سياق جميع عمليات الدفع الحالية.
ملاحظات إضافية:
من المهم فهم كيف تعمل العمليات بداخل ERPNEXT و FRAPPE. عند التعامل مع المستندات المعتمدة، يجب أن يكون هناك تركيز على إنشاء سجلات جديدة بدلاً من التعديل المباشر على السجلات التي أصبحت غير قابلة للتعديل.
تأكد من اختبار هذه الوظيفة جيداً في بيئة تطوير قبل نشرها لبيئة الإنتاج.
init
init
init
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_processed) # Debugging output
# 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 the document is approved, we can't change the Total Payment
# Therefore, we will create additional salary record without modifying the original detail
if detail.over_time_h:
total_over_time_h = detail.over_time_h * settings.h_over_time
total_payment = total_over_time_h * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_h, total_payment)
additional_salary_count += 1
if detail.over_time_n:
total_over_time_n = detail.over_time_n * settings.n_over_time
total_payment = total_over_time_n * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_n, total_payment)
additional_salary_count += 1
if detail.deduction:
total_payment = detail.deduction * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_deduction, 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_processed to True after successfully creating the records
self.timesheets_processed = True
print("*" * 50, self.timesheets_processed) # Debugging output
self.save() # Make sure to save the changes in the database
frappe.db.commit()
# Show message indicating completion
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
ما تم تغييره في الكود:
عدم استخدام تعديل detail.total_payment:
بعد أن تم تقديم الوثيقة، يتم تخزين نتائج المدفوعات الإضافية كقيمة مؤقتة (مثل total_payment) بدلاً من استخدامها لتعديل detail.total_payment.
إنشاء سجلات جديدة:
باستخدام create_additional_salary لإنشاء السجلات الجديدة دون تعديل السجلات السابقة.
خلاصة:
تأكد من أن لديك مفاهيم واضحة عن كيفية إنشاء سجلات جديدة لتمثيل المدفوعات، دون الحاجة إلى تعديل الحقول الموجودة في المستندات التي تم تقديمها.
يجب دائمًا التحقق من أنه لا يتم تعديل الحقول المحظورة لعدم الحصول على أخطاء من نوع UpdateAfterSubmitError.
اختبر الكود في بيئة تطوير بعد إجراء التعديلات لضمان الوظائف المتوقعة دون مشاكل.
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) # Debugging output
# 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
if timesheet_count > 0 or additional_salary_count > 0: # Check if any records were created
self.timesheets_created = True
print("*" * 50, self.timesheets_created) # Debugging output
self.save() # Save the changes in the database
frappe.db.commit()
# Show message indicating completion
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
النقاط الرئيسية:
التحقق من عدد السجلات المُعالجة:
قبل تحديث self.timesheets_created، تحقق من أنه تم بالفعل إنشاء أي سجلات (timesheet_count أو additional_salary_count أكبر من 0).
تحديث الحقل بعد إنشاء السجلات:
يتم تحديث self.timesheets_created بعد معالجة جميع السجلات، كما هو متوقع.
حفظ التغييرات:
تأكد من استخدام self.save() لحفظ التغييرات في قاعدة البيانات.
نصيحة إضافية:
استخدم السجلات اللوجية أو frappe.msgprint للتأكد من أن الكود يتم تنفيذه كما هو متوقع، حتى تتمكن من تتبع القيم والحالة. هذا سيساعد في ضمان معالجة البيانات بشكل صحيح وإظهار أي تغييرات في القيم.
إذا استمرت المشكلة بعد هذه التعديلات، تحقق من سياق استدعاء الدالة أو أي شروط مسبقة قد تمنع هذه التغييرات.