لدي مل باسم timesheet_tool.py وفيه دالتين بام check_missing_records , check_missing_records_for_approval ولتي يوجد فيها اشياء متشابهه بشكل كبير مما يادي ال تكرار الكود وكبر حجمه وانا اريد منك ان ستاعدني في تقليل الكود وتحسينة بحيث يكون كود احترافي ومنظم
Assistant
بالطبع، يمكن تحسين الكود الخاص بك وجعله أكثر تنظيمًا واحترافيًا عبر استخراج الأجزاء المشتركة بين الدالتين ووضعها في وظيفة مستقلة يمكن إعادة استخدامها. الطريقة المعروفة لتحقيق ذلك هي استخدام وظائف "مساعدة" Helper Functions. بهذه الطريقة، يمكن تجنب تكرار الكود، وتحقيق ما يسمى بـ DRY Principle (Don’t Repeat Yourself).
الخطوات:
حدد الأجزاء المتكررة في الدالتين check_missing_records و check_missing_records_for_approval.
قسّم الكود المشترك إلى وظائف مستقلة.
استخدم الدوال التي أنشأتها داخل check_missing_records و check_missing_records_for_approval.
مثال لتحسين الكود:
لنفرض أن الكود التالي يمثل الدالتين لديك مع بعض التكرار:
python
# الدالة الأولى
def check_missing_records(data):
results = []
for record in data:
if record.get('status') == 'missing':
results.append(record)
return results
# الدالة الثانية
def check_missing_records_for_approval(data):
approval_needed = []
for record in data:
if record.get('status') == 'missing' and record.get('approval') is False:
approval_needed.append(record)
return approval_needed
يمكنك ملاحظة أن هناك تكرارًا في تحليل السجلات داخل القوائم. لتحسين هذه الدالتين، يمكننا إنشاء دالة مساعدة تقوم بالتصفية بناءً على المعايير.
الكود المحسّن:
python
# دالة مساعدة لتصفية السجلات بناءً على شروط معينة
def filter_records(data, condition):
return [record for record in data if condition(record)]
# الدالة الأولى - للمفقودات
def check_missing_records(data):
return filter_records(data, lambda record: record.get('status') == 'missing')
# الدالة الثانية - للمفقودات التي تحتاج موافقة
def check_missing_records_for_approval(data):
return filter_records(data, lambda record: record.get('status') == 'missing' and not record.get('approval'))
الشرح:
قمنا بإنشاء دالة مساعدة اسمها filter_records تأخذ قائمة من البيانات (data) وشرطًا (condition) عبارة عن دالة مجهولة (lambda).
الدالة filter_records تتحقق من جميع السجلات وتعيد السجلات التي تحقق الشروط المحددة في condition.
استخدمنا هذه الدالة في كل من check_missing_records و check_missing_records_for_approval مع شروط مختلفة بناءً على متطلبات كل دالة.
فوائد هذا التحسين:
تقليل حجم الكود: أصبحنا نعيد استخدام الكود المشترك بدل تكراره.
سهولة الصيانة: إذا أردت تعديل منطق التصفية، فسيتطلب الأمر تعديل دالة واحدة فقط.
تنظيم الكود: الفصل بين المسؤوليات يجعل الكود مقروءًا ومرنًا.
هل تحتاج إلى المزيد من التوضيح أو أمثلة أكثر تعقيدًا؟
User
import
Assistant
بالنظر إلى الكود الذي أرسلته، يبدو أن الدالتين check_missing_records وcheck_missing_records_for_approval تقومان بالكثير من العمليات المتشابهة. يمكننا تقليل التكرار وفصل الأجزاء المشتركة ضمن دوال مساعدة، مما يجعل الكود أكثر تنظيمًا وأكثر سهولة في التحديث والصيانة. سنركز على الأمور التالية:
إعادة استخدام الكود المشترك: الأجزاء المشتركة بين الدالتين مثل استرجاع الإعدادات وتصفية السجلات.
تبسيط المنطق: تجنب التكرار في الحلقات واستخدام الدوال المساعدة.
إليك النسخة المحسنة للكود:
الكود المحسن:
python
User
لقد كنت اقوم باستدعاء الدوال السالبقه في ملف timesheet_tool.js ولذي سوف ارسل لك الكود الخاص به وظائف هذه الدوال هي التحكم في تفعيل وتعطيل ازرار Create Attendance , Approval Attendance وكانتا الدوال تعملان بشكل جيد قبل تحسين الكود والان بعد ان قمت بتحسين الكود اصبح الزر Approval Attendance يعمل بشكل جيد كما كان يعمل في السابق ولاكن الزر Create Attendance لم يعد يعمل مثل السابق ويضل فعال في كل الاحوال ولا يتم تعطيلة
Assistant
عندما تقوم بتحسين الكود الخاص بوظائف Python، قد تتأثر الطرق التي يتم فيها استدعاء هذه الوظائف من JavaScript. من ما توضحه، يبدو أن هناك مشكلة في استجابة زر Create Attendance حيث كان سابقًا يتم تعطيله أو تمكينه بناءً على نتيجة دالة check_missing_records. المفتاح هنا هو التحقق من كيفية استدعاء هذه الوظيفة ومعالجة النتيجة في ملف timesheet_tool.js.
لنختبر الكود خطوة بخطوة ونحلل السبب المحتمل للمشكلة:
الكود الحالي في ملف timesheet_tool.js
يرجى مشاركة الكود المتعلق بالزرين في ملف timesheet_tool.js، ولكن بناءً على وصفك، يمكننا أن نفترض وجود جزء يشبه التالي:
javascript
frappe.ui.form.on('Timesheet Tool', {
refresh: function(frm) {
frm.add_custom_button(__('Create Attendance'), function() {
frappe.call({
method: "your_app.timesheet_tool.check_missing_records",
args: {
timesheet_tool_name: frm.doc.name // اسم الـ timesheet الحالي
},
callback: function(r) {
if (r.message === "missing") {
frm.set_df_property("create_attendance", "read_only", 1); // تعطيل الزر
frappe.msgprint(__('There are missing records.'));
} else {
frm.set_df_property("create_attendance", "read_only", 0); // تمكين الزر
}
}
});
}).css({
'background-color': '#ff7043',
'color': '#fff'
});
frm.add_custom_button(__('Approval Attendance'), function() {
frappe.call({
method: "your_app.timesheet_tool.check_missing_records_for_approval",
args: {
timesheet_tool_name: frm.doc.name
},
callback: function(r) {
if (r.message === "missing") {
frappe.msgprint(__('Please approve all records before proceeding.'));
} else {
frappe.msgprint(__('All records are approved.'));
}
}
});
});
}
});
User
//
Assistant
من خلال قراءة الكود الخاص بك، يبدو أن المشكلة تتعلق بكيفية التحكم في زر Create Attendance واستخدام وظيفة handle_button لمعالجته. بناءً على التحليل، المشكلة الأبرز هي أنه يتم دائمًا إضافة زر مخصص (Custom Button) أو تمكينه بدون التأكد من تعطيله عند الحاجة.
المشكلة:
المشكلة الرئيسية:
response.message من وظيفة Python check_missing_records لم تُعالج بشكل صحيح داخل دالة handle_button.
في حالة response.message تساوي "complete"، الزر لا يتم تعطيله فعليًا.
كيفية إنشاء الأزرار:
الزر دومًا مضاف باستخدام frm.add_custom_button، ولكن التحكم الحالي لا يعطل الزر إذا لم يكن مفترضًا أن يُستخدم.
زر Create Attendance:
في هذا السيناريو، يبدو أنه بمجرد استدعاء الدالة handle_button، الزر Create Attendance يظل متاحًا بغض النظر عن الحالة.
التغييرات المطلوبة:
الخطوة 1. تحديث وظيفة handle_button لتتعامل مع حالة التعطيل بشكل صحيح:
بدلًا من إضافة الزر مباشرة في كل حالة، دعنا نفرق بشكل صحيح بين حالتي التفعيل (enabled) والتعطيل (disabled).
النسخة المعدلة لدالة handle_button:
javascript
User
لا يجب الاستغناء عن additional_salary_filters = [
(over_time_h, salary_component_overtime_h, ">", 0),
(over_time_n, salary_component_overtime_n, ">", 0),
(deduction, salary_component_deduction, ">", 0)
] عند تحسين الكود الخاص بملف timesheet_tool.py
Assistant
شكرًا للتوضيح! سأضمن وجود additional_salary_filters في تحسين الكود لأنه من الواضح أنها تلعب دورًا مهمًا حيث تكون جزءًا أساسيًا من منطق الفحص وربما تستخدم كعامل للتكرار على السجلات للتحقق من القيم.
سنضمن وجود هذه القائمة، وسنقوم بإجراء التحقق باستخدامها، مع الحفاظ على المنطق التنظيمي الذي تم تقديمه سابقًا، وإعادة استخدام الكود بحيث يتم تحسينه ولكن بدون تجاوز المنطق الحالي.
الكود المحسّن النهائي (مع الاحتفاظ بـ additional_salary_filters):
python
User
import frappe
@frappe.whitelist()
def get_active_employees_with_salary(doctype, txt, searchfield, start, page_len, filters):
"""
Returns a list of active employees who have an approved Salary Structure Assignment.
"""
return frappe.db.sql("""
SELECT
emp.name, emp.employee_name
FROM
tabEmployee emp
INNER JOIN
tabSalary Structure Assignment ssa
ON emp.name = ssa.employee
WHERE
emp.status = 'Active'
AND ssa.docstatus = 1
AND emp.name LIKE %s
LIMIT %s, %s
""", ("%%%s%%" % txt, start, page_len), as_list=True)
@frappe.whitelist()
def check_missing_records(timesheet_tool_name):
"""
Check if there are employees without Timesheets or incomplete Additional Salaries.
"""
# Get Settings
settings = get_timesheet_tool_setting()
@frappe.whitelist()
def check_missing_records_for_approval(timesheet_tool_name):
"""
Check if all the related Timesheets and Additional Salaries are approved.
"""
# Get Settings
settings = get_timesheet_tool_setting()
الكود الذي قدمته متماسك وهيكلته جيدة بالفعل، فهو يحافظ على الفصل بين الوظائف المختلفة، ويعتمد على منهجية واضحة لتنظيم وترتيب الوظائف. مع ذلك، لنقم بتحليل كل جزء للتأكد من أن جميع الوظائف تعمل بشكل صحيح وفعال، وتحديد أي تحسينات إضافية قد تكون مفيدة.
النقاط التي يمكن التأكد منها:
1. get_timesheet_tool_setting
تقوم هذه الدالة بجلب القيم الثلاثة المطلوبة (salary_component_overtime_n، salary_component_overtime_h، salary_component_deduction) من إعدادات Timesheet Tool Setting.
التحقق:
تأكد من وجود الإعدادات المطلوبة في قاعدة البيانات.
راجع الهيكل الخاص بـ Timesheet Tool Setting وتأكد من أن الحقول المطلوبة موجودة وأنه لا يتم استدعاء الدالة إذا كانت الحقول غير معرفة.
تحسين طفيف:
يمكن إضافة تفاصيل أكثر توضيحًا في رسائل الخطأ (frappe.throw) لإرشاد المستخدم أو المطورين في حالة حدوث خطأ. مثلًا:
python
frappe.throw("Salary component `overtime_n` is missing in Timesheet Tool Settings")
2. validate_additional_salary
تتحقق هذه الدالة من وجود سجل Additional Salary وربما يكون معتمدًا.
تحقق:
هذا الجزء يحتوي على منطق قوي للتحقق إذا كان هناك سجل لـ Additional Salary اعتمادًا على القيمتين value و salary_component.
التحسين المقترح:
قد يكون من المفيد تقديم رسائل خطأ دقيقة في حال الفشل (Debugging logs)، مثل وضع frappe.logger() لاكتشاف حالة معينة أثناء التصحيح، على سبيل المثال:
python
if not additional_salary:
frappe.logger().error(f"Missing Additional Salary for Employee: {employee}, Component: {salary_component}.")
3. check_timesheet_exists
تتحقق هذه الدالة مما إذا كان هناك سجل لـ Timesheet وتمت الموافقة عليه عند الحاجة.
تحقق:
تسمح هذه الوظيفة بتخصيص التحقق بناءً على إذا ما كان السجل يجب أن يكون معتمدًا ().
User
اعد كتابة الكود المحسن كامل مع الحفاظ على additional_salary_filters
Assistant
بالطبع! إليك نسخة مُحسنة ومُعّدة من الكود مع الحفاظ على استخدام additional_salary_filters لتبسيط المنطق وكتابة الكود بصورة جيدة مع مراعاة التنظيم وإعادة الاستخدام.
الكود المحسن
python
Not yet included in a published release.
@frappe.whitelist()
def get_active_employees_with_salary(doctype, txt, searchfield, start, page_len, filters):
"""
Returns a list of active employees who have an approved Salary Structure Assignment.
"""
return frappe.db.sql("""
SELECT
emp.name, emp.employee_name
FROM
`tabEmployee` emp
INNER JOIN
`tabSalary Structure Assignment` ssa
ON emp.name = ssa.employee
WHERE
emp.status = 'Active'
AND ssa.docstatus = 1
AND emp.name LIKE %s
LIMIT %s, %s
""", ("%%%s%%" % txt, start, page_len), as_list=True)
@frappe.whitelist()
def check_missing_records(timesheet_tool_name):
"""
Check if there are employees without Timesheets or Additional Salaries incomplete in timesheet_tool_details.
"""
missing_records = False
# Retrieval of Values from Timesheet Tool Setting
timesheet_tool_setting = frappe.db.get_value(
"Timesheet Tool Setting",
None, # you can modify this if specific filters are needed
["salary_component_overtime_n", "salary_component_overtime_h", "salary_component_deduction"],
as_dict=True
)
if not timesheet_tool_setting:
frappe.throw("No Timesheet Tool Setting found")
# Extract values for salary components
salary_component_overtime_n = timesheet_tool_setting.get("salary_component_overtime_n")
salary_component_overtime_h = timesheet_tool_setting.get("salary_component_overtime_h")
salary_component_deduction = timesheet_tool_setting.get("salary_component_deduction")
# If the fields aren't in Timesheet Tool Setting, make a mistake
if not salary_component_overtime_n or not salary_component_overtime_h or not salary_component_deduction:
frappe.throw("Missing salary components in Timesheet Tool Setting")
# Retrieval of staff details from the schedule_tool_details
timesheet_tool_details = frappe.db.get_all(
"Timesheet Tool Details",
filters={"parent": timesheet_tool_name},
fields=["employee", "hour", "over_time_h", "over_time_n", "deduction"]
)
for detail in timesheet_tool_details:
employee = detail.get("employee")
hour = detail.get("hour")
over_time_h = detail.get("over_time_h")
over_time_n = detail.get("over_time_n")
deduction = detail.get("deduction")
# Check the missing timesheet records.
if hour and hour > 0:
timesheet_exists = frappe.db.exists(
"Timesheet",
{"employee": employee, "timesheet_tool": timesheet_tool_name}
)
if not timesheet_exists:
missing_records = True
continue
# Verification of missing records of Additional Salary
additional_salary_filters = [
(over_time_h, salary_component_overtime_h, ">", 0),
(over_time_n, salary_component_overtime_n, ">", 0),
(deduction, salary_component_deduction, ">", 0)
]
for value, salary_component, operator, target in additional_salary_filters:
if value is not None and isinstance(value, (int, float)):
if operator == ">" and value > target:
additional_salary_exists = frappe.db.exists(
"Additional Salary",
{
"employee": employee,
"timesheet_tool": timesheet_tool_name,
"salary_component": salary_component
}
)
if not additional_salary_exists:
missing_records = True
continue
return "missing" if missing_records else "complete"
@frappe.whitelist()
def check_missing_records_for_approval(timesheet_tool_name):
"""
تحقق من إذا كانت جميع السجلات المرتبطة (Timesheets و Additional Salaries) معتمدة.
"""
missing_records = True
# استرجاع الإعدادات من Timesheet Tool Setting
timesheet_tool_setting = frappe.db.get_value(
"Timesheet Tool Setting",
None,
["salary_component_overtime_n", "salary_component_overtime_h", "salary_component_deduction"],
as_dict=True
)
if not timesheet_tool_setting:
frappe.throw("No Timesheet Tool Setting found")
# استخراج القيم للـ salary components
salary_component_overtime_n = timesheet_tool_setting.get("salary_component_overtime_n")
salary_component_overtime_h = timesheet_tool_setting.get("salary_component_overtime_h")
salary_component_deduction = timesheet_tool_setting.get("salary_component_deduction")
# تحقق من وجود جميع الحقول في الإعدادات
if not salary_component_overtime_n or not salary_component_overtime_h or not salary_component_deduction:
frappe.throw("Missing salary components in Timesheet Tool Setting")
# استرجاع التفاصيل من Timesheet Tool Details
timesheet_tool_details = frappe.db.get_all(
"Timesheet Tool Details",
filters={"parent": timesheet_tool_name},
fields=["employee", "hour", "over_time_h", "over_time_n", "deduction"]
)
for detail in timesheet_tool_details:
employee = detail.get("employee")
hour = detail.get("hour")
over_time_h = detail.get("over_time_h")
over_time_n = detail.get("over_time_n")
deduction = detail.get("deduction")
# التحقق من أن الـ Timesheet تم اعتماده
if hour and hour > 0:
timesheet = frappe.db.get_value(
"Timesheet",
{"employee": employee, "timesheet_tool": timesheet_tool_name},
["name", "docstatus"], # نتحقق من DocStatus لاعتماد Timesheet
as_dict=True
)
if not timesheet or timesheet.get("docstatus") == 0:
missing_records = True
continue
# التحقق من Additional Salary لكل من overtime والدين
additional_salary_filters = [
(over_time_h, salary_component_overtime_h, ">", 0),
(over_time_n, salary_component_overtime_n, ">", 0),
(deduction, salary_component_deduction, ">", 0)
]
for value, salary_component, operator, target in additional_salary_filters:
if value is not None and isinstance(value, (int, float)):
if operator == ">" and value > target:
additional_salary = frappe.db.get_value(
"Additional Salary",
{
"employee": employee,
"timesheet_tool": timesheet_tool_name,
"salary_component": salary_component
},
["name", "docstatus"], # نتحقق من DocStatus لاعتماد Additional Salary
as_dict=True
)
if not additional_salary or additional_salary.get("docstatus") == 0:
missing_records = True
continue
# إرجاع النتيجة النهائية
return "missing" if missing_records else "complete" ```
import frappe
def get_timesheet_tool_setting():
"""
Retrieve Timesheet Tool Setting and validate required components.
"""
settings = frappe.db.get_value(
"Timesheet Tool Setting",
None,
["salary_component_overtime_n", "salary_component_overtime_h", "salary_component_deduction"],
as_dict=True
)
if not settings:
frappe.throw("No Timesheet Tool Setting found")
# Validate all required fields
if not all([settings.get("salary_component_overtime_n"),
settings.get("salary_component_overtime_h"),
settings.get("salary_component_deduction")]):
frappe.throw("Missing salary components in Timesheet Tool Setting")
return settings
def validate_additional_salary(employee, timesheet_tool_name, value, salary_component, condition=">"):
"""
Validate if Additional Salary exists based on given conditions.
"""
if value is not None and isinstance(value, (int, float)) and value > 0:
additional_salary = frappe.db.get_value(
"Additional Salary",
{
"employee": employee,
"timesheet_tool": timesheet_tool_name,
"salary_component": salary_component
},
["name", "docstatus"],
as_dict=True
)
return additional_salary and additional_salary.get("docstatus") == 1 # Ensures it's approved
return True
def check_timesheet_exists(employee, timesheet_tool_name, require_approval=False):
"""
Check if Timesheet exists and optionally check if it's approved.
"""
timesheet = frappe.db.get_value(
"Timesheet",
{"employee": employee, "timesheet_tool": timesheet_tool_name},
["name", "docstatus"],
as_dict=True
)
if not timesheet:
return False
if require_approval and timesheet.get("docstatus") != 1: # Not approved
return False
return True
def process_timesheet_tool_details(timesheet_tool_details, timesheet_tool_name, settings, require_approval=False):
"""
Process records from Timesheet Tool Details and validate Timesheets and Additional Salaries.
"""
for detail in timesheet_tool_details:
employee = detail.get("employee")
hour = detail.get("hour")
over_time_h = detail.get("over_time_h")
over_time_n = detail.get("over_time_n")
deduction = detail.get("deduction")
# Check Timesheet
if hour and hour > 0:
if not check_timesheet_exists(employee, timesheet_tool_name, require_approval):
return "missing"
# Check Additional Salaries
additional_salary_checks = [
(over_time_h, settings["salary_component_overtime_h"]),
(over_time_n, settings["salary_component_overtime_n"]),
(deduction, settings["salary_component_deduction"])
]
for value, component in additional_salary_checks:
if not validate_additional_salary(employee, timesheet_tool_name, value, component):
return "missing"
return "complete"
@frappe.whitelist()
def check_missing_records(timesheet_tool_name):
"""
Check if there are employees without Timesheets or incomplete Additional Salaries.
"""
# Get Settings
settings = get_timesheet_tool_setting()
# Get Timesheet Tool Details
timesheet_tool_details = frappe.db.get_all(
"Timesheet Tool Details",
filters={"parent": timesheet_tool_name},
fields=["employee", "hour", "over_time_h", "over_time_n", "deduction"]
)
# Process Tool Details
return process_timesheet_tool_details(timesheet_tool_details, timesheet_tool_name, settings)
@frappe.whitelist()
def check_missing_records_for_approval(timesheet_tool_name):
"""
Check if all the related Timesheets and Additional Salaries are approved.
"""
# Get Settings
settings = get_timesheet_tool_setting()
# Get Timesheet Tool Details
timesheet_tool_details = frappe.db.get_all(
"Timesheet Tool Details",
filters={"parent": timesheet_tool_name},
fields=["employee", "hour", "over_time_h", "over_time_n", "deduction"]
)
# Process Tool Details with approval required
return process_timesheet_tool_details(timesheet_tool_details, timesheet_tool_name, settings, require_approval=True)
التغييرات التي أُجريت:
استخراج إعدادات Timesheet Tool Setting:
أنشأنا دالة جديدة get_timesheet_tool_setting لإعادة الإعدادات والتحقق من وجود جميع المكونات اللازمة.
التحقق من Timesheet:
نقل عملية التحقق من وجود السجل (وأحيانًا الموافقة عليه) إلى الدالة check_timesheet_exists.
التحقق من Additional Salary:
تمت إضافة دالة validate_additional_salary للتحقق من وجود السجل بناءً على القيم والمكونات.
معالجة التفاصيل:
أنشأنا دالة process_timesheet_tool_details لتنفيذ المنطق المشترك بين الدالتين، مع إضافة خيار لتحديد ما إذا كانت الموافقة مطلوبة (require_approval).
إعادة استخدام الدوال المساعدة:
تم دمج الدالتين check_missing_records و check_missing_records_for_approval لاستخدام نفس الدوال المساعدة وتبسيط المنطق.
فوائد التحسين:
إعادة استخدام الكود: فصلت الأجزاء المشتركة في دوال نظيفة قابلة لإعادة الاستخدام.
تنظيم الكود: أصبحت الدوال أكثر تنظيمًا وقابلة للقراءة.
سهولة الصيانة: في حال تغيير منطق العمل، يمكنك تعديل دالة مساعدة واحدة بدلاً من التعديل في كلا الدالتين.
إذا كان لديك أي استفسارات أخرى أو نقاط إضافية لتحسين الكود، فلا تتردد! 🎉
تحليل المشكلة:
الزر Create Attendance دائمًا مفعّل:
ربما الدالة check_missing_records لا تعود بالقيمة الصحيحة ("missing" أو "complete").
قمنا بتحسين الكود بحيث أن هناك اعتماد الآن على وظيفة process_timesheet_tool_details. ربما المنطق في الوظيفة لا يعيد القيمة المتوقعة (مثل "missing") في حالة وجود سجلات ناقصة.
زر Approval Attendance يعمل كما هو متوقع:
يبدو أن الدالة المسؤولة (هنا ستكون check_missing_records_for_approval) تعمل بشكل صحيح مع المعادلات والإرجاع.
كيفية تصحيح المشكلة في check_missing_records:
اختبار دالة check_missing_records:
أضف frappe.logger() أو print() داخل process_timesheet_tool_details لمعرفة أين تتوقف الدالة ولماذا لا تعود بالقيمة "missing".
تأكد من القيمة المرجعة (Return Value) دائمًا دقيقة:
داخل process_timesheet_tool_details، تأكد من أنك تعيد القيمة "missing" إذا كانت هناك سجلات غير مكتملة (إما Timesheet أو Additional Salary مفقودة).
تأكد من أن الـ return لا يتم تجاوزه لحالات أخرى.
اختبار استدعاء الدالة:
افتح الـ Developer Console في المتصفح واكتب:
javascript
frappe.call({
method: "your_app.timesheet_tool.check_missing_records",
args: { timesheet_tool_name: "SOME_TIMESHEET_NAME" },
callback: function(r) {
console.log(r.message); // تحقق إذا كانت الرسالة "missing" أو "complete"
}
});
تحديث الكود في ملف timesheet_tool.js:
نسخة محسنة من الكود:
لنقم بالتأكد من أن JavaScript يعالج النتيجة المناسبة:
javascript
frappe.ui.form.on('Timesheet Tool', {
refresh: function(frm) {
// زر إنشاء الحضور
frm.add_custom_button(__('Create Attendance'), function() {
frappe.call({
method: "your_app.timesheet_tool.check_missing_records",
args: {
timesheet_tool_name: frm.doc.name
},
callback: function(r) {
if (r.message === "missing") {
frm.set_df_property("create_attendance", "read_only", 1); // تعطيل الزر
frappe.msgprint(__('There are missing records. Cannot create attendance.'));
} else if (r.message === "complete") {
frm.set_df_property("create_attendance", "read_only", 0); // تمكين الزر
frappe.msgprint(__('You can now create attendance.'));
} else {
frappe.msgprint(__("Unexpected result from server: " + r.message));
}
}
});
});
// زر الموافقة على الحضور
frm.add_custom_button(__('Approval Attendance'), function() {
frappe.call({
method: "your_app.timesheet_tool.check_missing_records_for_approval",
args: {
timesheet_tool_name: frm.doc.name
},
callback: function(r) {
if (r.message === "missing") {
frappe.msgprint(__('Please approve all records before proceeding.'));
} else {
frappe.msgprint(__('All records are approved.'));
}
}
});
});
}
});
النقطة الأهم:
تأكد من أن الدالة check_missing_records تُرجع القيمة الصحيحة ("missing" أو "complete") عندما يتم استدعاؤها.
جرب مراقبة الـ Logs (السجلات) من خلال print أو frappe.logger() داخل الدالة في Python لتأكد من سير المنطق كما هو متوقع.
جرب استدعاء الدالة check_missing_records مباشرة من وحدة التحكم في المتصفح وراقب النتيجة.
إذا لم تحل المشكلة بشكل كامل بعد هذه الخطوات، شاركني نتيجة الاختبار من المتصفح (console.log) وكذلك أي سجلات (logs) يمكن الحصول عليها من الدالة في الخادم (Python). سأكون سعيدًا بمساعدتك! 🚀
// For license information, please see license.txt
// timesheet_tool.js
let settings = {};
frappe.ui.form.on("Timesheet Tool", {
refresh(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"
};
};
// Fetch settings and dynamically update mandatory fields
frappe.call({
method: "fetch_settings_and_update_mandatory",
doc: frm.doc,
callback: function(response) {
if (response.message) {
settings = response.message;
frm.toggle_reqd("project", settings.is_project_mandatory);
frm.toggle_reqd("company", settings.is_company_mandatory);
}
}
});
// Management of the "Create Attendance" button
if (frm.doc.docstatus === 0 && !frm.doc.__islocal) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records",
"Create Attendance",
"Attendance records have been created successfully.",
"All records have already been created."
);
}
// Management "Approval Attendance"
if (frm.doc.docstatus === 1) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
"Approval Attendance",
"Attendance records have been approved successfully.",
"All records have already been approved."
);
}
// Management of "Approval Attendance"
if (frm.doc.docstatus === 1) {
frappe.call({
method: "frappe.client.get_list",
args: {
doctype: "Timesheet",
filters: {
timesheet_tool: frm.doc.name,
docstatus: ["!=", 1] // Check all records.
},
fields: ["name"]
},
callback: function(response) {
if (response.message.length > 0) {
// If there's an unapproved Timesheets, display the button
frm.add_custom_button(__("Approval Attendance"), function() {
frappe.call({
method: "approval_attendance",
doc: frm.doc,
callback: function() {
frm.reload_doc();
frappe.msgprint(__('Attendance records have been approved successfully.'));
}
});
});
} else {
// If the records are all certified, disable the button.
frm.add_custom_button(__("Approval Attendance"), function() {
frappe.throw(__('Attendance has already been approved and cannot be approved again.'));
}).prop("disabled", true);
}
}
});
}
},
// "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");
frappe.msgprint(__('Employees have been fetched successfully.'));
}
}
});
},
// Update the fields when adjusting the Table "Timesheet Tool Details"
timesheet_tool_details: {
hour(frm, cdt, cdn) {
let row = frappe.get_doc(cdt, cdn);
row.total_working_hours = row.hour * row.ratio_attendance;
frm.refresh_field("timesheet_tool_details");
},
over_time_h(frm, cdt, cdn) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
}
});
},
over_time_n(frm, cdt, cdn) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
}
});
},
deduction(frm, cdt, cdn) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
}
});
}
}
});
function handle_button(frm, method, btn_label, success_msg, fail_msg) {
frappe.call({
method: method,
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
console.log("****************************",response.message)
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: btn_label.toLowerCase().replace(" ", "_"),
doc: frm.doc,
callback: function() {
frm.reload_doc();
frappe.msgprint(__(success_msg));
}
});
});
} else {
frm.add_custom_button(__(btn_label), function() {
frappe.throw(__(fail_msg));
}).prop("disabled", true);
}
}
});
} ```
function handle_button(frm, method, btn_label, success_msg, fail_msg) {
frappe.call({
method: method,
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
console.log("Response from " + method + ":", response.message);
// Remove old buttons (if any)
frm.clear_custom_buttons();
// Check the server response status
if (response.message === "missing") {
// Add enabled button
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: btn_label.toLowerCase().replace(" ", "_"),
doc: frm.doc,
callback: function() {
frm.reload_doc();
frappe.msgprint(__(success_msg));
}
});
});
} else if (response.message === "complete") {
// Button should be disabled
frm.add_custom_button(__(btn_label), function() {
frappe.throw(__(fail_msg));
}).prop("disabled", true);
} else {
// Unexpected Result (failsafe)
frappe.msgprint(__("Unexpected response: " + response.message));
}
}
});
}
الخطوة 2. تحديث استدعاء handle_button في منطق الزر Create Attendance:
في refresh function، الزر Create Attendance يجب أن يُعالج بصورة صحيحة:
javascript
// Management of the "Create Attendance" button
if (frm.doc.docstatus === 0 && !frm.doc.__islocal) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records",
"Create Attendance",
"Attendance records have been created successfully.",
"All records have already been created."
);
}
تم تحسين وظيفة handle_button لمعالجة استجابة الخادم بشكل مناسب.
الخطوة 3. إضافة سجل لتصحيح الأخطاء (Logging):
لتحليل المشكلة بشكل أفضل، أضف console.log أو frappe.msgprint في أجزاء مختلفة من الكود، وخاصةً عندما يتم الرد من الخادم:
واختبر إذا كانت النتيجة تصل بصورة صحيحة إلى الـ handle_button.
الخطوة 4. اختبار عملك:
افتح النموذج الخاص بـ Timesheet Tool في المتصفح.
افحص الـ Developer Console لمعرفة النتيجة التي تعود من الخادم (Response from check_missing_records).
تأكد أن الزر Create Attendance يصبح معطلًا (أو مفعّلًا) حسب النتيجة التي يتم إرجاعها.
ملاحظات إضافية:
في الكود السابق للدالة handle_button، تم استخدام .prop("disabled", true) لتعطيل الزر. إذا كان هذا غير كافٍ، يمكنك استخدام .css('pointer-events', 'none') بالإضافة إلى .css('opacity', '0.5') لجعل الزر يبدو فعلاً معطلاً بشكل واضح.
تأكد من أن وظيفة Python check_missing_records تعيد القيم "missing" و "complete" فقط، ولا شيء مختلف، حتى تتم معالجة المنطق بشكل صحيح في JavaScript.
ملخص:
تم ضبط handle_button للتعامل بشكل دقيق مع الحالات المختلفة (missing، complete).
تُزيل frm.clear_custom_buttons() الأزرار القديمة لتجنب التكرارات.
يتم الآن التمييز بين الأزرار المفعّلة والمعطّلة بناءً على استجابة الخادم.
تم تصميم الكود ليكون مرنًا وسهل الصيانة، مع سجلات واضحة لتصحيح الأخطاء.
جرب هذا الحل وإذا كانت المشكلة لا تزال قائمة، شاركني بمزيد من التفاصيل عن السجلات أو النتائج لتحليل المشكلة بشكل أفضل. 😊
import frappe
def get_timesheet_tool_setting():
"""
Retrieve Timesheet Tool Setting and validate required components.
"""
settings = frappe.db.get_value(
"Timesheet Tool Setting",
None,
["salary_component_overtime_n", "salary_component_overtime_h", "salary_component_deduction"],
as_dict=True
)
if not settings:
frappe.throw("No Timesheet Tool Setting found")
# Validate all required fields
if not all([settings.get("salary_component_overtime_n"),
settings.get("salary_component_overtime_h"),
settings.get("salary_component_deduction")]):
frappe.throw("Missing salary components in Timesheet Tool Setting")
return settings
def validate_additional_salary(employee, timesheet_tool_name, value, salary_component, operator, target):
"""
Validate if Additional Salary exists based on given conditions.
"""
if value is not None and isinstance(value, (int, float)):
if operator == ">" and value > target:
additional_salary = frappe.db.get_value(
"Additional Salary",
{
"employee": employee,
"timesheet_tool": timesheet_tool_name,
"salary_component": salary_component
},
["name", "docstatus"],
as_dict=True
)
return additional_salary and additional_salary.get("docstatus") == 1 # Ensures it's approved
return True
def check_timesheet_exists(employee, timesheet_tool_name, require_approval=False):
"""
Check if Timesheet exists and optionally check if it's approved.
"""
timesheet = frappe.db.get_value(
"Timesheet",
{"employee": employee, "timesheet_tool": timesheet_tool_name},
["name", "docstatus"],
as_dict=True
)
if not timesheet:
return False
if require_approval and timesheet.get("docstatus") != 1: # Not approved
return False
return True
def process_timesheet_tool_details(timesheet_tool_details, timesheet_tool_name, settings, require_approval=False):
"""
Process records from Timesheet Tool Details and validate Timesheets and Additional Salaries.
"""
for detail in timesheet_tool_details:
employee = detail.get("employee")
hour = detail.get("hour")
over_time_h = detail.get("over_time_h")
over_time_n = detail.get("over_time_n")
deduction = detail.get("deduction")
# Check Timesheet if hours exist
if hour and hour > 0:
if not check_timesheet_exists(employee, timesheet_tool_name, require_approval):
return "missing"
# Prepare filters for Additional Salary
additional_salary_filters = [
(over_time_h, settings["salary_component_overtime_h"], ">", 0),
(over_time_n, settings["salary_component_overtime_n"], ">", 0),
(deduction, settings["salary_component_deduction"], ">", 0)
]
# Validate each condition in additional_salary_filters
for value, component, operator, target in additional_salary_filters:
if not validate_additional_salary(employee, timesheet_tool_name, value, component, operator, target):
return "missing"
return "complete"
@frappe.whitelist()
def check_missing_records(timesheet_tool_name):
"""
Check if there are employees without Timesheets or incomplete Additional Salaries.
"""
# Get Settings
settings = get_timesheet_tool_setting()
# Get Timesheet Tool Details
timesheet_tool_details = frappe.db.get_all(
"Timesheet Tool Details",
filters={"parent": timesheet_tool_name},
fields=["employee", "hour", "over_time_h", "over_time_n", "deduction"]
)
# Process Tool Details
return process_timesheet_tool_details(timesheet_tool_details, timesheet_tool_name, settings)
@frappe.whitelist()
def check_missing_records_for_approval(timesheet_tool_name):
"""
Check if all the related Timesheets and Additional Salaries are approved.
"""
# Get Settings
settings = get_timesheet_tool_setting()
# Get Timesheet Tool Details
timesheet_tool_details = frappe.db.get_all(
"Timesheet Tool Details",
filters={"parent": timesheet_tool_name},
fields=["employee", "hour", "over_time_h", "over_time_n", "deduction"]
)
# Process Tool Details with approval required
return process_timesheet_tool_details(timesheet_tool_details, timesheet_tool_name, settings, require_approval=True)
التعديلات المهمة:
additional_salary_filters:
تم الاحتفاظ بالحقلين over_time_h و over_time_n و deduction في قائمة additional_salary_filters.
تمت معالجة الشروط (مثل التحقق من القيم وصحة وجود السجلات).
التحقق من "Additional Salary":
دالة validate_additional_salary أصبحت مسؤولة عن التحقق من وجود السجل والموافقة عليه بناءً على معايير additional_salary_filters.
التنظيم وإعادة الاستخدام:
توحيد منطق معالجة التفاصيل من خلال الدالة العامة process_timesheet_tool_details.
إرجاع الرسالة "missing" أو "complete":
إرجاع "missing" في حال وجود أي شرط غير متحقق، مما يجعل المنطق واضحًا ومتوافقًا.
مرونة التحقّق:
أضفنا دعمًا للتأكيد على الموافقة (require_approval في check_timesheet_exists) عند التحقق من السجلات.
كيف يظل additional_salary_filters في مكانه وعلاقته بالفحص؟
additional_salary_filters تُستخدم كوسيلة لتحديد كل "القيم" و"Salary Components" التي تحتاج إلى تحقق.
نمر عليها بعلاقة شرطية (for loop) مع مراعاة المنطق الموجود في الدالة validate_additional_salary.
كيف يتفاعل مع ملف JavaScript؟
هذا التحسين لا يغير واجهة الاتصال (API)، مما يعني أن الكود الخاص بـ JavaScript (timesheet_tool.js) سيستمر في العمل إذا كانت الاستجابة (response.message) تتضمن "missing" أو "complete". فقط تأكد أن الاستجابة في Python تُرجع القيم بالشكل التالي:
"missing": إذا كانت هناك سجلات ناقصة.
"complete": إذا كان كل شيء صحيحًا ومرّ بجميع الشروط.
إذا كنت بحاجة إلى المزيد من المساعدة أو إذا ظهرت أي مشاكل إضافية، لا تتردد في التواصل. 😊
if not settings:
frappe.throw("No Timesheet Tool Setting found")
# Validate all required fields
if not all([settings.get("salary_component_overtime_n"),
settings.get("salary_component_overtime_h"),
settings.get("salary_component_deduction")]):
frappe.throw("Missing salary components in Timesheet Tool Setting")
return settings
def validate_additional_salary(employee, timesheet_tool_name, value, salary_component, condition=">"):
"""
Validate if Additional Salary exists based on given conditions.
"""
if value is not None and isinstance(value, (int, float)) and value > 0:
additional_salary = frappe.db.get_value(
"Additional Salary",
{
"employee": employee,
"timesheet_tool": timesheet_tool_name,
"salary_component": salary_component
},
["name", "docstatus"],
as_dict=True
)
return additional_salary and additional_salary.get("docstatus") == 1 # Ensures it's approved
return True
def check_timesheet_exists(employee, timesheet_tool_name, require_approval=False):
"""
Check if Timesheet exists and optionally check if it's approved.
"""
timesheet = frappe.db.get_value(
"Timesheet",
{"employee": employee, "timesheet_tool": timesheet_tool_name},
["name", "docstatus"],
as_dict=True
)
if not timesheet:
return False
code
if require_approval and timesheet.get("docstatus") != 1: # Not approved
return False
return True
def process_timesheet_tool_details(timesheet_tool_details, timesheet_tool_name, settings, require_approval=False):
"""
Process records from Timesheet Tool Details and validate Timesheets and Additional Salaries.
"""
for detail in timesheet_tool_details:
employee = detail.get("employee")
hour = detail.get("hour")
over_time_h = detail.get("over_time_h")
over_time_n = detail.get("over_time_n")
deduction = detail.get("deduction")
code
# Check Timesheet
if hour and hour > 0:
if not check_timesheet_exists(employee, timesheet_tool_name, require_approval):
return "missing"
# Check Additional Salaries
additional_salary_checks = [
(over_time_h, settings["salary_component_overtime_h"]),
(over_time_n, settings["salary_component_overtime_n"]),
(deduction, settings["salary_component_deduction"])
]
for value, component in additional_salary_checks:
if not validate_additional_salary(employee, timesheet_tool_name, value, component):
return "missing"
return "complete"
require_approval
التحسين المقترح:
أضف سجلات (Logs) عند الفشل، حيث قد تكون مفيدة أثناء التصحيح.
للتأكد من أن الفشل لا يؤدي إلى التوقف غير المتوقع، أضف info تفصيلية عند الخطأ:
python
if not timesheet:
frappe.logger().info(f"No Timesheet found for Employee: {employee}")
4. process_timesheet_tool_details
الوظيفة المسؤولة عن معالجة تفاصيل أداة Timesheet Tool.
ملخص الخطوات التي تقوم بها الوظيفة:
التحقق إذا كان هناك ما يتعلق بالساعات (hour) وما إذا كان فحص Timesheet يمر بالشروط.
التحقق من additional_salary_checks عن طريق إعداد قائمة تضم الحقول والقيم ومجموعة الشروط.
المراجعة:
أنشأت الوظيفة قائمة additional_salary_checks وهي قائمة تحتوي على الحقول التي سيتم فحصها.
مقارنة القيم في هذه القائمة ضد البيانات في النظام.
إذا لم تتحقق أي من الشروط، سترجع "missing".
التحسين:
يمكن إعداد سجلات (Logs) عند أي حالة فشل أثناء additional_salary_checks لتسجيل الأسباب. مثلًا:
python
for value, component in additional_salary_checks:
if not validate_additional_salary(employee, timesheet_tool_name, value, component):
frappe.logger().info(f"Missing Additional Salary for Employee: {employee}, Component: {component}, Value: {value}")
return "missing"
5. check_missing_records
تجمع السجلات من التفاصيل وتستخدم الوظائف المساعدة (Helper Functions) مثل process_timesheet_tool_details للتحقق مما إذا كانت هناك سجلات ناقصة.
التحقق:
الدالة تعتمد على المنطق المشترك لجميع الحقول ذات الصلة (hour, over_time_h, over_time_n, deduction) للتأكد من أن كل شيء مكتمل أو غير مكتمل.
التحسين:
حاليًا الكود شامل بالنسبة للوظيفة. يمكن اختبار الاستدعاءات فقط من JavaScript للتأكد من عملها الصحيح (راجع "تحقق من الاتصال بين الـ JS-Python" أدناه).
تحقق من العلاقة مع JavaScript:
اختبر الدالتين check_missing_records و check_missing_records_for_approval مباشرة من المتصفح باستخدام وحدة التحكم (Console) بعد نشر الكود. على سبيل المثال:
javascript
frappe.call({
method: "your_app.timesheet_tool.check_missing_records",
args: { timesheet_tool_name: "TS-0001" },
callback: function(r) {
console.log(r.message); // يجب أن تكون "missing" أو "complete"
}
});
تأكد من أن النتيجة:
"missing" إذا كانت هناك أي سجلات غير مكتملة.
"complete" إذا كانت جميع السجلات موجودة ومعتمدة.
ملاحظات ختامية:
الكود يبدو نظيفًا ومنظمًا بالفعل، وتم التعامل مع معظم التفاصيل الدقيقة بشكل احترافي. التحسينات التي تم اقتراحها هنا تتمحور حول:
توثيق أسباب الفشل أو الحدوث باستخدام frappe.logger() أو info logs.
إضافة رسائل أكثر تفصيلًا في حال وجود استثناءات (frappe.throw).