انت مبرمج محترف في البرمجة باستخدام frappe framework ولغة البرمجة paython ولغة البرمجة JavaScrept, وانا اريد مساعدتك , لدي Doctype باسم Timesheet Tool ولذي سوف ارسل لك الكود الخاص بملف البايثون وملف الجافاء سكربت الخاص به , لدي دالة approval_attendance اريد ان تقوم باعتماد جميع ال Timesheet وال Additional Salary المرتبطة بالمستند ويتم استدعاء هذه الدالى عند الظغط على الزر Approval Attendance واريد ايضاً ان تقوم الدالة cancel_attendance بالغاء جميع ال Timesheet وال Additional Salary المرتبطة بالمستند ويتم استدعاء هذه الدالة عند الغاء المستند Timesheet Tool , اريد منك انتساعدني في اضافة هذه الميزة , والان واريد منك انا تخبرني كيف ابداء بارسال محتواء الملفات اليك وماهي الخطوات التي اتبعها للتعامل معك , المخرجات اريد ان تكون مخرجات كود كل ملف بعد التعديل وشرح للتعديلات.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
مرحبًا! سأكون سعيدًا بمساعدتك في تحقيق المطلوب باستخدام إطار عمل Frappe Framework وPython وJavaScript.
خطواتنا للعمل معًا:
1. تجهيز الملفات:
إذا كنت قد كتبت بالفعل الكود الخاص بـ Timesheet Tool، فقم بتوفير محتوى ملف Python (backend) وملف JavaScript (frontend).
إذا كنت تحتاج ملفات جديدة من الصفر، فلا تقلق، سأقوم بإرشادك لإضافة المطلوب.
2. كيفية إرسال الملفات:
انسخ الأكواد الحالية الخاصة بالـ Python والـ JavaScript الخاصة بمستند Timesheet Tool، وقم بلصقها هنا.
إذا كانت الأكواد طويلة جدًا، يمكنك أن ترسلها على دفعات.
3. نتيجة العمل:
بعد التحدث معي عن الأكواد، سأقوم بمراجعتها وإضافة الدالتين approval_attendance وcancel_attendance وفقًا للمقترحات الخاصة بك.
سأشرح لك جميع التعديلات خطوة بخطوة حتى تفهم المنطق البرمجي.
4. تواصل معي:
إذا كان لديك أي استفسار إضافي أو طلب تعديل، سأكون جاهزًا لإعادة العمل أو تحسينه.
5. المخرجات:
نسخة محسّنة لكود Python و JavaScript.
شرح عملية الإضافة والتعديلات مفصلًا.
النقاط التي ستتم إضافتها:
زر خاص لاستدعاء approval_attendance لاعتماد جميع الوقت الإضافي (Timesheet) والراتب الإضافي (Additional Salary) المرتبط بالمستند (Timesheet Tool).
تنفيذ وظيفة cancel_attendance لإلغاء جميع التفاصيل المرتبطة عند خيار الإلغاء.
الربط بين الـ backend و frontend (JavaScript و Python).
ابدأ بإرسال الأكواد:
قم بلصق ملفات الكود الخاصة بـ timesheet_tool.py و timesheet_tool.js هنا.
إذا كنت تريد أن أعطيك التعليمات خطوة بخطوة لدمج هذه الدوال في الكود الحالي، فأخبرني. :)
بانتظار الكود الخاص بك! 💻
User
#
Assistant
شكرًا لمشاركة الكود التفصيلي! يبدو أنك قد قمت بكتابة معظم الوظائف المطلوبة، وما عليك سوى تحسين الربط بين دوال approval_attendance و**cancel_attendance** وتنفيذ بعض الربط مع الـ frontend (JavaScript).
ما قمت به:
أنشأت بالفعل وظائف approval_timesheets و**approval_additional_salaries** لاعتماد أو إلغاء الـ Timesheets وAdditional Salaries حسب الحاجة، وقمت بدمجها ضمن وظائف:
approval_attendance للموافقة
cancel_attendance للإلغاء
أضفت أيضًا استدعاء دالة الإلغاء في حدث on_cancel لضمان أن الإلغاء يتم تلقائيًا عند إلغاء وثيقة الـ Timesheet Tool.
المطلوب تنفيذه:
تحسين الرسائل لتكون أكثر وضوحًا عند تنفيذ الاعتماد أو الإلغاء.
التأكد من ربط وظيفة approval_attendance بزر في واجهة المستخدم يتم تنفيذه من خلال JavaScript.
استدعاء cancel_attendance تلقائيًا عند إلغاء المستند.
التعديلات على الملف:
1. التحديث على الملف الحالي لـ timesheet_tool.py:
لم يكن يتطلب ملف الـ Python العديد من التعديلات، لكن قمت بتحسين الرسائل وتدقيق الكود.
الكود بعد التعديل:
python
User
//
Assistant
شكرًا على تقديم كود JavaScript الخاص بـ Timesheet Tool. الكود يعمل بشكل جيد فيما يخص إدارة الأحداث واستدعاء الوظائف من backend. سأعمل على تحسينه وربط أزرار تنشيط / إلغاء الحضور بشكل أكثر كفاءة. كما سأشرح التعديلات الشاملة خطوة بخطوة.
تحليل الـ JavaScript:
يوجد بالفعل:
استدعاء أزرار مثل "Create Attendance" و"Approval Attendance".
دوال للتواصل مع الملف timesheet_tool.py واستخدام الدوال فيه عبر frappe.call.
تعامل مع الأحداث داخل الحقول (مثل التعديل في جدول تفاصيل timesheet_tool_details).
المهام المطلوبة:
تحسين زر Approval Attendance:
إضافة حالة إلغاء للحضور في حال كان المستخدم يريد ذلك.
التحقق من حالة الوثيقة قبل السماح بالاعتماد.
تحديث واجهة المستخدم بعد تنفيذ العملية.
إضافة زر لإلغاء الحضور (Cancel Attendance) بشكل ديناميكي إذا كان مستند Timesheet Tool معتمدًا.
تحسين الرسائل والـ validation لضمان تجربة مستخدم أفضل.
التأكد من أن كلا الزرين (Approval Attendance و Cancel Attendance) متوفرين فقط في الحالات المناسبة.
الكود بعد التعديل:
javascript
User
شكراً لك
Assistant
على الرحب والسعة! 😊 إذا كنت بحاجة إلى أي مساعدة إضافية في المستقبل، سواءً في البرمجة أو في أي استفسار آخر، لا تتردد في السؤال. أتمنى لك التوفيق في مشروعك! 🚀✨
دمت بخير! 💙
User
الان اريد تعديل الدالة get_all_employees اريد عند جلب الموظفين من جدول Project Team ان يتم جلب الموظفين الذين لديهم Salary Structure Assignment معتمد فقط
Assistant
لإجراء التعديل المطلوب على الدالة get_all_employees بحيث يتم جلب الموظفين المرتبطين بجدول Project Team والذين لديهم فقط Salary Structure Assignment معتمد، يمكننا تعديل استعلام SQL الحالي لإضافة شرط إضافي يتحقق من وجود تعيين راتب صالح (Approved).
الكود المعدل:
python
@frappe.whitelist()
def get_all_employees(self, project=None):
settings = get_settings()
dufault_activity = settings.dufault_activity
ratio_attendance = settings.ratio_attendance
# Clear the timesheet_tool_details table
self.set("timesheet_tool_details", [])
if project:
# Fetch employees from the project_team table, ensured they have "Salary Structure Assignment"
employees = frappe.db.sql("""
SELECT DISTINCT
pt.employee AS name,
pt.employee_name
FROM
`tabProject Team` pt
INNER JOIN
`tabSalary Structure Assignment` ssa
ON
pt.employee = ssa.employee
WHERE
pt.parent = %s AND
ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
""", (project,), as_dict=True)
if not employees:
frappe.throw(_("No employees found in the Project Team with a valid Salary Structure Assignment for the selected project."))
else:
# Fetch active employees directly when no project is selected
employees = frappe.db.sql("""
SELECT DISTINCT
emp.name AS name,
emp.employee_name AS employee_name,
emp.hourly_rate
FROM
`tabEmployee` emp
JOIN
`tabSalary Structure Assignment` ssa
ON
emp.name = ssa.employee
WHERE
emp.status = 'Active' AND
ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
""", as_dict=True)
# Append employees to the child table
for emp in employees:
self.append("timesheet_tool_details", {
"employee": emp.get('name'),
"employee_name": emp.get('employee_name'),
"hourly_rate": emp.get('hourly_rate'),
"attendance": dufault_activity,
"ratio_attendance": ratio_attendance,
})
return employees
User
شكراً لك
Assistant
على الرحب والسعة دائمًا! 😊 إذا كنت بحاجة إلى أي مساعدة مستقبلًا، سواءً في البرمجة أو أي استفسار آخر، فلا تتردد في التواصل معي. أتمنى لك كل التوفيق في مشروعك! 🚀
دمت بخير ونجاح! 💙
User
الان اريد في الجدول الفرعي timesheet_tool_details اضافة فلتر بحيث لا يظهر فيه الا الموظفين الفعالين والذين لديهم Salary Structure Assignment معتمد
Assistant
لتنفيذ طلبك، نحتاج إلى تعديل إعدادات الحقل employee في الجدول الفرعي timesheet_tool_details بحيث يتم إضافة فلتر ديناميكي يظهر فقط الموظفين الذين تنطبق عليهم الشروط التالية:
الحالة الفعّالة (Active) في جدول الموظفين tabEmployee.
لديهم Salary Structure Assignment معتمد (docstatus = 1).
الخطوات المطلوبة:
1. تحديد الفلتر للحقل employee.
2. التحقق من الشرطين أعلاه بواسطة استعلام Frappe SQL.
الكود المحدث:
في ملف timesheet_tool.js، تحتاج إلى تحديث دالة refresh بحيث يتم تعديل الفلتر الخاص بحقل employee في الجدول الفرعي.
javascript
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
// تعديل الفلتر الخاص بحقل الموظفين لجلب الموظفين الفعالين فقط مع Salary Structure Assignment معتمد
frm.fields_dict['timesheet_tool_details'].grid.get_field('employee').get_query = function(doc, cdt, cdn) {
return {
query: "your_app.your_module.utils.get_active_employees_with_salary" // نص الاستعلام (سيتم تعريفه في Python)
};
};
// باقي الكود بدون تغيير...
},
});
استحداث استعلام get_active_employees_with_salary في Python:
في الكود أعلاه، نستخدم استعلامًا مخصصًا للفلتر. يتم هذا عبر تقديم طريقة جديدة في الملف Python بحيث يتم تنفيذ استعلام SQL.
ملف Python:
أنشئ أو أضف الاستعلام التالي إلى ملف Python الخاص بك في utils.py أو أي مسار آخر تريد استخدامه:
python
User
AttributeError: module 'time_sheet_tool.time_sheet_tool.utils' has no attribute 'get_active_employees_with_salary'
Assistant
يبدو أن Frappe لم يتمكن من العثور على الدالة get_active_employees_with_salary التي من المفترض أنها تم تعريفها في الملف time_sheet_tool.time_sheet_tool.utils. هناك عدة أسباب ممكنة لهذه المشكلة، والحل يكمن في مراجعة الخطوات وتصحيح الخطأ.
نصائح لحل المشكلة:
1. تأكد من مكان الدالة:
تأكد أن الدالة get_active_employees_with_salary تم تعريفها في الملف utils.py داخل المجلد الصحيح ضمن تطبيقك.
2. هيكلية المشروع الصحيح:
تأكد من هيكلية مشروعك. على سبيل المثال:
code
time_sheet_tool/
└── time_sheet_tool/
├── __init__.py
├── config/
├── doctypes/
├── utils.py # هنا يتم تعريف دالة get_active_employees_with_salary
└── ...
3. التأكد من اسم المسار في الكود JavaScript:
في الكود الخاص بـ JavaScript، استخدم المسار الكامل للدالة التي قمت بإنشائها.
إذا كنت تستخدم تطبيقًا اسمه time_sheet_tool، يجب أن يكون اسم استدعاء الاستعلام بالشكل التالي:
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)
User
شكرهً لك
Assistant
العفو وسعيد أنّني استطعت مساعدتك! 😊 إذا احتجت أي مساعدة إضافية أو لديك أي استفسار مستقبلاً، فلا تتردد في التواصل معي.
أتمنى لك التوفيق والنجاح في مشروعك! 🚀✨
دمت بخير! 💙
User
الان سوف ارسل لك الكود الخاص بملف // timesheet_tool.js
واريد ان يتم تعطيل زر Create Attendance بعد انشاء كل السجلات وايضاً تعطيل زر Approval Attendance بعد اعتماد كل السجلات
Assistant
بالطبع! سأقوم بمراجعة الكود الخاص بك وإجراء التعديلات المطلوبة بحيث يتم تعطيل زر "Create Attendance" بعد إنشاء جميع السجلات، وأيضاً تعطيل زر "Approval Attendance" بعد اعتماد جميع السجلات. الرجاء إرسال الكود الخاص بملف timesheet_tool.js وسأبدأ العمل على التعديلات. 😊
User
//
Assistant
شكراً على الكود! سأقوم بإجراء التعديلات المطلوبة لتعطيل زر "Create Attendance" بعد إنشاء جميع السجلات، وأيضاً تعطيل زر "Approval Attendance" بعد اعتماد كل السجلات.
الخطة لتنفيذ المطلوب:
زر "Create Attendance":
سنضيف شرطاً للتأكد من وجود سجلات في جدول timesheet_tool_details. إذا كانت السجلات موجودة، سيتم تعطيل الزر.
لا يُسمح بإعادة إنشاء الحضور إذا تم التنفيذ بالفعل.
زر "Approval Attendance":
سيتم التحقق من اعتماد Timesheets وAdditional Salaries المرتبطة قبل عرض الزر.
إذا كانت جميع السجلات مُعتمدة، سيتم تعطيل الزر أو عدم عرضه.
التأكد من تحديث حالة الأزرار ديناميكياً عند إعادة تحميل الصفحة أو تحديث المستند.
الكود المُعدَّل:
javascript
User
شكراً لك
Assistant
على الرحب والسعة دائمًا! 😊 إذا كنت بحاجة إلى أي مساعدة إضافية في المستقبل في جهودك البرمجية أو أي استفسارات، فلا تتردد في التواصل معي. أتمنى لك التوفيق والنجاح في مشروعك 🎉🚀
دمت بخير ونجاح دائم! 🌟
User
الان سوف ارسل لك ملف timesheet_tool.js واريد منك اضافة ميزة اعادة تفعيل زر Create Attendance عندما يكون هنالك موظف في جدول timesheet_tool_details لم يتم انشاء له سجل في Timesheet او سجلات في Additional Salary مع العلم اننه اذا كان الحقل hour توجد فيه قيمه فيجب ان يتم انشاء Timesheet للموظف واذا كانت هنالك قيم في الحقول over_time_h , over_time_n و Deduction فيجب انا يتم انشار ثلاثه سجلات Additional Salary للموظف وهاكذا بالنسبة لزر Approval Attendance ,مع العلم ان زر
Assistant
بالتأكيد يمكننا إضافة المنطق المطلوب لزر Create Attendance وApproval Attendance بناءً على السيناريو الذي حددته. سنقوم بالتأكد أن الأزرار سيتم إعادة تفعيلها إذا كان هناك موظف ضمن جدول timesheet_tool_details لم يتم إنشاء السجلات المناسبة له (Timesheet أو Additional Salary).
الخطوات لتنفيذ المطلوب:
1. للتحقق من جاهزية زر Create Attendance:
تفقد الحقل hour للموظف.
إذا كانت به قيمة، يجب إنشاء Timesheet له.
تفقد الحقول over_time_h, over_time_n, deduction.
إذا كانت بها قيم، يجب إنشاء سجلات Additional Salary (ثلاثة أنواع: Overtime H، Overtime N، Deduction).
إذا لم يتم تنفيذ هذه العمليات لأي موظف، يجب إعادة تفعيل زر Create Attendance.
2. للتحقق من جاهزية زر Approval Attendance:
إذا كان هناك موظف ولم يتم اعتماد كل السجلات الخاصة به (Timesheet وAdditional Salary)، فإنه يجب إعادة تفعيل زر Approval Attendance.
3. الكود المنطقي المطلوب:
الحقلين Create Attendance وApproval Attendance سيعتمدان على التحقق أعلاه ويعملان ديناميكيًا بناءً على حالات الموظفين.
الكود المُحَسّن:
javascript
User
اكتب الكود الذي يتحقق:
Assistant
لتنفيذ هذه الوظيفة في Python (الدالة التي تتحقق إذا كان هناك موظفون ينقصهم سجلات Timesheets أو Additional Salaries بناءً على الشروط الموضحة)، يمكننا كتابة كود يقوم بالتحقق من حالة الموظفين في جدول timesheet_tool_details.
الكود في Python:
الدالة التالية ستقوم بالتحقق مما إذا كان هناك أي موظف في جدول timesheet_tool_details ليس لديه سجلات Timesheet أو سجلات Additional Salaries مطابقة للقيم الموجودة في الحقول hour, over_time_h, over_time_n, deduction:
python
@frappe.whitelist()
def check_missing_records(timesheet_tool_name):
"""
تحقق إذا كان هناك موظفين ليس لديهم Timesheets أو Additional Salaries ناقصة في timesheet_tool_details.
"""
missing_records = False
# استرجاع تفاصيل الموظفين من جدول 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_exists = frappe.db.exists(
"Timesheet",
{"employee": employee, "timesheet_tool": timesheet_tool_name}
)
if not timesheet_exists:
missing_records = True
continue
# التحقق من السجلات الناقصة لـ Additional Salary
additional_salary_filters = [
(over_time_h, "Overtime H", ">", 0),
(over_time_n, "Overtime N", ">", 0),
(deduction, "Deduction", ">", 0)
]
for value, salary_component, operator, target in additional_salary_filters:
if value and eval(f"value {operator} 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"
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) {
// 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"
};
};
code
Assistant
تحليل الكود الحالي:
في الكود المرفق، لديك منطق للتحكم في الأزرار "Create Attendance" و "Approval Attendance". ومع ذلك، سأقوم بتحليل النقاط الحالية وتعديلها لتطبيق منطق أكثر فعالية بناءً على الفكرة التي طلبتها:
زر "Create Attendance":
يجب أن يتم فحص حالة جميع الموظفين في timesheet_tool_details.
إذا تم العثور على موظف لم يُنشأ له أي Timesheet أو لم تُنشأ له جميع سجلات Additional Salary المطلوبة، سيتم تفعيل الزر مجددًا.
زر "Approval Attendance":
يجب أن يتم فحص جميع السجلات المرتبطة (Timesheet و Additional Salary) والتأكد من اعتمادها (docstatus = 1).
إذا وجدت سجلات غير معتمدة، سيتم تفعيل الزر.
التعديلات على الكود:
1. منطق "Create Attendance" المُحسّن:
تم تعديل منطق "Create Attendance" ليتحقق من وجود أي سجلات ناقصة:
javascript
if (frm.doc.docstatus === 0 && !frm.doc.__islocal) {
frappe.call({
method: "time_sheet_tool.time_sheet_tool.utils.check_missing_records",
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
frm.add_custom_button(__("Create Attendance"), function() {
if (frm.is_dirty()) {
frappe.throw(__("You have unsaved changes in this form. Please save before you continue."));
}
frappe.call({
method: "create_attendance",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
frm.reload_doc();
frappe.msgprint(__('Attendance records have been created successfully.'));
}
});
});
} else {
// إذا لم تكن هناك سجلات ناقصة، قم بتعطيل الزر
frm.add_custom_button(__("Create Attendance"), function() {
frappe.throw(__('All records have already been created.'));
}).prop("disabled", true);
}
}
});
}
User
Message

Failed to get method for command time_sheet_tool.time_sheet_tool.utils.check_missing_records with module 'time_sheet_tool.time_sheet_tool.utils' has no attribute 'check_missing_records'
Assistant
رسالة الخطأ تشير إلى أن Frappe لم يتمكن من العثور على الدالة check_missing_records في المسار time_sheet_tool.time_sheet_tool.utils. يمكن أن يكون السبب في هذه المشكلة واحدًا من عدة أمور، وسأشرح لك الخطوات للتأكد من حل المشكلة.
أسباب المشكلة:
الدالة غير موجودة أو لم يتم تعريفها بشكل صحيح في الملف utils.py.
المسار (path) المكتوب في JavaScript غير صحيح.
الملف utils.py أو الوحدة (module) الخاصة به قد لا تكون معرّفة في نظام Frappe بسبب نقص ملف __init__.py.
لم يتم إعادة تشغيل خدمة Frappe بعد إضافة الدالة.
الحلول الممكنة:
1. تأكد من وجود دالة check_missing_records داخل الملف utils.py:
افتح الملف utils.py في المسار التالي داخل تطبيقك:
code
/apps/time_sheet_tool/time_sheet_tool/utils.py
تأكد من وجود الكود الخاص بالدالة في الملف:
python
import frappe
@frappe.whitelist()
def check_missing_records(timesheet_tool_name):
"""
تحقق إذا كان هناك موظفون تنقصهم سجلات مثل Timesheet أو Additional Salaries.
"""
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:
# تحقق إذا لم يتم إنشاء Timesheet
if detail["hour"] > 0:
ts_exists = frappe.db.exists(
"Timesheet",
{"employee": detail["employee"], "timesheet_tool": timesheet_tool_name}
)
if not ts_exists:
return "missing"
# تحقق إذا لم يتم إنشاء Additional Salaries
additional_salary_types = [
{"value": detail["over_time_h"], "component": "Overtime H"},
{"value": detail["over_time_n"], "component": "Overtime N"},
{"value": detail["deduction"], "component": "Deduction"}
]
for item in additional_salary_types:
if item["value"] > 0:
as_exists = frappe.db.exists(
"Additional Salary",
{"employee": detail["employee"], "timesheet_tool": timesheet_tool_name, "salary_component": item["component"]}
)
if not as_exists:
return "missing"
return "complete"
# For license information, please see license.txt
# timesheet_tool.py
import frappe
from frappe.model.document import Document
from frappe import _
class TimesheetTool(Document):
@frappe.whitelist()
def get_all_employees(self, project=None):
settings = get_settings()
dufault_activity = settings.dufault_activity
ratio_attendance = settings.ratio_attendance
# Clear the timesheet_tool_details table
self.set("timesheet_tool_details", [])
if project:
# Fetch employees from the project_team child table of the given project
employees = frappe.db.sql("""
SELECT DISTINCT pt.employee As name , pt.employee_name
FROM `tabProject Team` pt
WHERE pt.parent = %s
""", (project,), as_dict=True)
if not employees:
frappe.throw(_("No employees found in the Project Team for the selected project."))
else:
# Fetch active employees directly when no project is selected
employees = frappe.db.sql("""
SELECT DISTINCT emp.name ,emp.employee_name , emp.hourly_rate
FROM `tabEmployee` emp
JOIN `tabSalary Structure Assignment` ssa
ON emp.name = ssa.employee
WHERE emp.status = 'Active'
AND ssa.docstatus = 1
""", as_dict=True)
# Append employees to the child table
for emp in employees:
self.append("timesheet_tool_details", {
"employee": emp.get('employee', emp.get('name')),
"employee_name": emp.get('employee', emp.get('employee_name')),
"hourly_rate": emp.get('employee', emp.get('hourly_rate')),
"attendance": dufault_activity,
"ratio_attendance": ratio_attendance,
})
return employees
@frappe.whitelist()
def fetch_settings_and_update_mandatory(self):
"""Fetch settings from Timesheet Tool Setting and check if project and company are mandatory."""
settings = get_settings()
# Check and update mandatory fields dynamically based on settings
is_project_mandatory = settings.is_project_mandatory
is_company_mandatory = settings.is_company_mandatory
return {
"is_project_mandatory": is_project_mandatory,
"is_company_mandatory": is_company_mandatory
}
@frappe.whitelist()
def create_attendance(self):
"""
A function to implement all accounts and create the required records.
"""
self.calculate_details()
frappe.msgprint(_("Calculations and Additional Salaries have been processed."))
@frappe.whitelist()
def approval_attendance(self):
"""Approves all associated Timesheets and Additional Salaries."""
self.approval_timesheets()
self.approval_additional_salaries()
def approval_timesheets(self,cancel = False):
"""Approves all associated Timesheets or Cancels all associated Timesheets."""
try:
timesheet_list = frappe.get_all("Timesheet",
filters={
"timesheet_tool": self.name
},
)
for timesheet in timesheet_list :
document = frappe.get_doc("Timesheet", timesheet.name)
if not cancel:
if document.docstatus == 0: # Check if not already submitted
document.submit()
frappe.db.commit()
frappe.msgprint(_("Timesheet for approved"))
else:
if document.docstatus == 1: # Check if submitted
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Timesheet forcancelled"))
except frappe.DoesNotExistError:
frappe.msgprint(_("Timesheet not found for"))
def approval_additional_salaries(self,cancel = False):
"""Approves all associated Additional Salaries or Cancels all associated Additional Salaries."""
try:
additional_salarie_list = frappe.get_all("Additional Salary",
filters={
"timesheet_tool": self.name
},
)
for additional_salarie in additional_salarie_list :
document = frappe.get_doc("Additional Salary", additional_salarie.name)
if not cancel:
if document.docstatus == 0: # Check if not already submitted
document.submit()
frappe.db.commit()
frappe.msgprint(_("Additional Salary for approved"))
else:
if document.docstatus == 1: # Check if submitted
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Additional Salary forcancelled"))
except frappe.DoesNotExistError:
frappe.msgprint(_("Additional Salary not found for"))
def calculate_details(self):
"""
Calculation of fields required in the timesheet_tool_details
"""
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 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)
# 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)
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)
if detail.deduction:
detail.total_payment = detail.deduction * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_deduction,detail.total_payment)
def cancel_attendance(self):
"""Cancels all associated Timesheets and Additional Salaries."""
self.approval_timesheets(True)
self.approval_additional_salaries(True)
def on_cancel(self):
self.cancel_attendance()
def on_submit(self):
pass
def before_save(self):
pass
def validate(self):
self.ensure_unique_employee()
def ensure_unique_employee(self):
"""
Check not to repeat the selection of the same employee in Timesheet Tool Details.
"""
timesheet_tool_details = [os.employee for os in self.timesheet_tool_details if os.employee]
if len(timesheet_tool_details) != len(set(timesheet_tool_details)):
frappe.throw(_("The same employee cannot be selected more than once."))
def get_settings():
# Fetch the latest settings
settings = frappe.get_single("Timesheet Tool Setting")
return settings
def create_timesheet(doc,timesheet_tool_details,totalhours,from_time):
timesheet = frappe.get_doc({
"doctype": "Timesheet",
"timesheet_tool":doc.name,
"company": doc.company,
"parent_project": doc.project,
"employee":timesheet_tool_details.employee,
"time_logs": []
})
child_time_logs = {
"activity_type": timesheet_tool_details.attendance,
"hours":totalhours,
"from_time":from_time,
}
timesheet.append("time_logs", child_time_logs)
timesheet.insert(ignore_permissions=True)
frappe.db.commit()
def create_additional_salary(doc,employee,salary_component,amount):
additional_salary = frappe.new_doc("Additional Salary")
additional_salary.timesheet_tool = doc.name
additional_salary.company = doc.company
additional_salary.employee = employee
additional_salary.payroll_date = doc.day
additional_salary.salary_component = salary_component
additional_salary.amount = amount
additional_salary.insert(ignore_permissions=True) ```
@frappe.whitelist()
def approval_attendance(self):
"""Approves all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets()
self.approval_additional_salaries()
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been approved successfully."))
except Exception as e:
frappe.throw(_("An error occurred during approval: {0}").format(str(e)))
@frappe.whitelist()
def cancel_attendance(self):
"""Cancels all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets(cancel=True)
self.approval_additional_salaries(cancel=True)
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been cancelled successfully."))
except Exception as e:
frappe.throw(_("An error occurred during cancellation: {0}").format(str(e)))
def approval_timesheets(self, cancel=False):
"""Shared logic for approving or canceling Timesheets."""
timesheet_list = frappe.get_all("Timesheet",
filters={
"timesheet_tool": self.name
},
)
for timesheet in timesheet_list:
document = frappe.get_doc("Timesheet", timesheet.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
frappe.msgprint(_("Timesheet {0} has been approved.").format(document.name))
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Timesheet {0} has been cancelled.").format(document.name))
def approval_additional_salaries(self, cancel=False):
"""Shared logic for approving or canceling Additional Salaries."""
additional_salary_list = frappe.get_all("Additional Salary",
filters={
"timesheet_tool": self.name
},
)
for additional_salary in additional_salary_list:
document = frappe.get_doc("Additional Salary", additional_salary.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
frappe.msgprint(_("Additional Salary {0} has been approved.").format(document.name))
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Additional Salary {0} has been cancelled.").format(document.name))
def on_cancel(self):
# Cancel Timesheets and Additional Salaries when Timesheet Tool is cancelled.
self.cancel_attendance()
الملاحظات:
الرسائل أصبحت تقوم بإظهار اسم المستند الذي تم العمل عليه (Timesheet أو Additional Salary) لتسهيل التتبّع.
التحقق من docstatus يتم بشكل أفضل لتجنب أي خطأ في اعتماد المستند أو إلغائه.
2. الملف timesheet_tool.js:
ستحتاج إلى تحرير واجهة المستخدم وإضافة زر ينفذ دالة approval_attendance. هذا الزر يجب استدعاؤه عند النقر فوقه.
الكود التالي يوضح كيفية ربط زر من واجهة المستخدم لاستدعاء approval_attendance:
javascript
frappe.ui.form.on('Timesheet Tool', {
refresh: function (frm) {
// إضافة زر Approval Attendance
if (!frm.is_new() && frm.doc.docstatus === 1) {
frm.add_custom_button(__('Approval Attendance'), function () {
frappe.call({
method: "your_app_folder.timesheet_tool.approval_attendance",
args: {
docname: frm.doc.name
},
callback: function (r) {
if (!r.exc) {
frappe.msgprint(__('Approval Attendance was successful.'));
frm.reload_doc();
}
}
});
}, __("Actions"));
}
// عند إلغاء المستند
frm.events.on_cancel = function() {
frappe.call({
method: "your_app_folder.timesheet_tool.cancel_attendance",
args: {
docname: frm.doc.name
},
callback: function (r) {
if (!r.exc) {
frappe.msgprint(__('Cancel Attendance was successful.'));
frm.reload_doc();
}
}
});
};
},
});
شرح التعديلات:
تمت إضافة زر Approval Attendance في واجهة المستخدم عند عرض مستند تم اعتماده.
عند النقر على الزر، يتم استدعاء دالة approval_attendance في الملف الخاص بـ Python لتنفيذ الاعتماد.
إذا تم إلغاء المستند (on_cancel)، يتم استدعاء cancel_attendance.
المطلوب:
حدثني إذا كان لديك أي موقع أو مجلد مخصص لتخزين الكود في المشروع.
استبدل your_app_folder باسم التطبيق الخاص بك مثل (على سبيل المثال custom_app أو hr_app).
بعد تنفيذ هذا العمل، يرجى إعلامي إذا كنت بحاجة إلى أي تحسينات أو اختبار! 😊
// For license information, please see license.txt
// timesheet_tool.js
let settings = {}
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
frm.fields_dict['timesheet_tool_details'].grid.get_field('employee').get_query = function(doc) {
return {
"filters": {
status:"Active",
}
}
};
// Fetch settings and dynamically update mandatory fields
frappe.call({
method: "fetch_settings_and_update_mandatory",
doc: frm.doc,
callback: function(response) {
if (response.message) {
// Update mandatory fields for 'project' and 'company'
settings = response.message;
frm.toggle_reqd("project", settings.is_project_mandatory);
frm.toggle_reqd("company", settings.is_company_mandatory);
}
}
});
if (frm.doc.docstatus == 0) {
frm.add_custom_button(__("Create Attendance"), function() {
if (frm.is_dirty()) {
frappe.throw(__("You have unsaved changes in this form. Please save before you continue."));
}
frappe.call({
method: "create_attendance",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
// Disable Create Attendance after Creation of Records
frm.add_custom_button(__("Create Attendance"), function() {
frappe.throw(__('Attendance has already been created and cannot be created again.'));
}).prop("disabled", true);
}
});
});
}
if (frm.doc.docstatus == 1) {
frm.add_custom_button(__("Approval Attendance"), function() {
frappe.call({
method: "approval_attendance",
doc: frm.doc,
callback: function() {
// Disable Approval Attendance after Records have been created
frm.add_custom_button(__("Approval Attendance"), function() {
frappe.throw(__('Attendance has already been Approvaled and cannot be Approvaled again.'));
}).prop("disabled", true);
}
});
});
}
},
// Event for the custom "get_employee" button
get_employee(frm) {
// Check if project is mandatory and empty
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
// Call the get_all_employees method with or without the project
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 of accounts upon adjustment of schedule
timesheet_tool_details: {
hour(frm, cdt, cdn) {
let row = frappe.get_doc(cdt, cdn);
// Update total_working_hours
row.total_working_hours = row.hour * row.ratio_attendance;
frm.refresh_field("timesheet_tool_details");
},
over_time_h(frm, cdt, cdn) {
let row = frappe.get_doc(cdt, cdn);
// Calculation of the new value of Overtime H
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
}
});
},
over_time_n(frm, cdt, cdn) {
let row = frappe.get_doc(cdt, cdn);
// Calculation of the new value of Overtime N
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");
}
});
}
}
});
// Copyright (c) 2024, Ebkar Technology And Management Solutions.
// For license information, please see license.txt
let settings = {};
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
// إعداد Query خاص بحقل الموظفين في الجدول
frm.fields_dict['timesheet_tool_details'].grid.get_field('employee').get_query = function(doc) {
return {
"filters": { status:"Active" }
}
};
// جلب الإعدادات الديناميكية وتحديث الحقول الإلزامية بناءً عليها
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);
}
}
});
// إضافة زر "Create Attendance" إذا كان المستند لم يُعتمد بعد
if (frm.doc.docstatus === 0) {
frm.add_custom_button(__("Create Attendance"), function() {
if (frm.is_dirty()) {
frappe.throw(__("You have unsaved changes in this form. Please save before you continue."));
return;
}
frappe.call({
method: "create_attendance",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
frm.reload_doc();
frappe.msgprint(__('Attendance records have been created successfully.'));
}
});
});
}
// إضافة زر "Approval Attendance" إذا تم اعتماد المستند
if (frm.doc.docstatus === 1) {
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.'));
}
});
});
// إضافة زر لإلغاء الحضور (Cancel Attendance)
frm.add_custom_button(__('Cancel Attendance'), function() {
frappe.confirm(
__('Are you sure you want to cancel all linked attendance and salary records?'),
function() {
frappe.call({
method: "cancel_attendance",
doc: frm.doc,
callback: function() {
frm.reload_doc();
frappe.msgprint(__('Attendance and salary records have been cancelled successfully.'));
}
});
}
);
}, __("Actions")); // وضع هذا الزر ضمن مجموعة الإجراءات Actions
}
},
// زر "Get Employee" لجلب الموظفين بناءً على المشروع
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.'));
}
}
});
},
// معالجة الجدول "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");
}
});
}
}
});
التعديلات الأساسية:
1. تحسين دالة refresh:
أضفت زر Cancel Attendance مع نافذة تأكيد لضمان عدم إلغاء الحضور بطريق الخطأ من قِبل المستخدم.
2. إدارة الأزرار حسب الحالة:
أزرار Create Attendance و**Approval Attendance** و**Cancel Attendance** تُظهر بناءً على حالة سجل المستند (docstatus).
3. تبسيط الرسائل:
الرسائل مثل "تم اعتماد الحضور بنجاح" أصبحت أكثر وضوحًا وسهولة في الفهم.
4. استخدام نافذة تأكيد عند تنفيذ الإلغاء:
وذلك لضمان التحقق قبل إلغاء الحضور أو الخصومات ذات الصلة.
خطة الاختبار بعد التعديلات:
حفظ مستند فارغ والتأكد من ظهور زر Create Attendance.
إذا كان لديك تعليقات إضافية أو تحتاج إلى تحسينات أخرى، فتواصل معي. 😊
التعديلات وشرح الكود:
1. التحقق من الموظفين بجداول المشروع مع Salary Structure Assignment:
تمت إضافة شرط للتحقق من أن الموظف مرتبط بـ Salary Structure Assignment بقيمة docstatus = 1 (المعتمد).
2. الجملة SQL في حالة وجود مشروع:
يتم فحص حقل pt.employee (من جدول tabProject Team) ومطابقته مع ssa.employee (من جدول tabSalary Structure Assignment).
شرط إضافي: ssa.docstatus = 1 لضمان أن التعيين المعتمد فقط هو الذي يتم أخذه بعين الاعتبار.
3. الجملة SQL في حالة عدم وجود مشروع:
جلب الموظفين النشطين من جدول tabEmployee بشرط أن يكون لديهم تعيين راتب معتمد من خلال جدول tabSalary Structure Assignment.
4. إضافة الموظفين إلى الـ timesheet_tool_details:
لكل موظف يتم إضافته إلى جدول التفاصيل، يتم تعيين القيم الافتراضية لـ:
attendance: القيمة المستخرجة من إعدادات النظام.
ratio_attendance: القيمة الافتراضية المحملة من الإعدادات.
رسائل الخطأ:
إذا لم يتم العثور على أي موظفين في مشروع مرتبط بـ Salary Structure Assignment معتمد، ستُظهر الرسالة:
"No employees found in the Project Team with a valid Salary Structure Assignment for the selected project."
الاختبار:
1. اختبار مع وجود مشروع:
قم بإنشاء مشروع جديد يتضمن موظفين في جدول Project Team، لكن تأكد من أن بعض هؤلاء الموظفين ليس لديهم Salary Structure Assignment معتمد.
نفّذ الدالة get_all_employees وتأكد من جلب الموظفين الذين لديهم تعيين راتب فقط.
2. اختبار بدون مشروع:
قم باختبار الموظفين النشطين الذين لديهم Salary Structure Assignment معتمد فقط بدون اختيار مشروع في النموذج.
إذا واجهت أي مشاكل أو ترغب في المزيد من التعديلات، لا تتردد في طلب المساعدة! 😊
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)
شرح الكود:
الـ JavaScript:
تم تعديل الفلتر للحقل employee ليستخدم استعلام مخصص.
عند اختيار الموظف في جدول timesheet_tool_details، يتم عرض النتائج بناءً على استعلام Python مهيأ مسبقًا (حسب الشروط المطلوبة).
الـ Python:
دالة get_active_employees_with_salary تقوم بالتحقق مما يلي:
الموظف يكون فعالًا (emp.status = 'Active').
الموظف لديه Salary Structure Assignment معتمد (ssa.docstatus = 1).
يتم تطبيق فلتر البحث باستخدام الكلمة المدخلة من واجهة المستخدم (emp.name LIKE %s).
يتم تحديد عدد الصفوف التي يمكن عرضها باستخدام التعداد الصفحي (LIMIT).
الإخراج:
يتم إرجاع عمودين: emp.name (لتمثيل الاسم الداخلي للموظف) و**emp.employee_name** (اسم الموظف الكامل).
استبدال your_app.your_module.utils:
استبدل your_app وyour_module باسم التطبيق والوحدة الخاصين بك. على سبيل المثال:
إذا كان تطبيقك اسمه hr_app وملف الوظائف داخل الوحدة utils.py، يمكنك استخدام:
تأكد أن ملف __init__.py موجود في المجلد time_sheet_tool وأيضًا في المجلد الداخلي time_sheet_tool (لجعل الوحدة قابلة للاستيراد).
كيفية التحقق من تصحيح الخطأ:
تأكد من أن التطبيق يتم التعرف عليه بشكل صحيح من قبل Frappe.
قم بفتح Developer Console في المتصفح (Ctrl+Shift+I) عند تكرار الخطأ وشاهد السجلات.
إذا ظهر نفس الخطأ (AttributeError: ...)، فتحقق من الوارد في القسم السابق.
إذا استمرت المشكلة:
يرجى التحقق من أنك تستخدم المسار الصحيح للدالة.
يمكنك مشاركة هيكلية الملفات لديك هنا وسأساعدك في تصحيح الأمر بدقة.
😊 بالتوفيق، وأنا هنا للمساعدة دائمًا!
// 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) {
// Update mandatory fields for 'project' and 'company'
settings = response.message;
frm.toggle_reqd("project", settings.is_project_mandatory);
frm.toggle_reqd("company", settings.is_company_mandatory);
}
}
});
if (frm.doc.docstatus == 0) {
frm.add_custom_button(__("Create Attendance"), function() {
if (frm.is_dirty()) {
frappe.throw(__("You have unsaved changes in this form. Please save before you continue."));
}
frappe.call({
method: "create_attendance",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
// Disable Create Attendance after Creation of Records
frm.add_custom_button(__("Create Attendance"), function() {
frappe.throw(__('Attendance has already been created and cannot be created again.'));
}).prop("disabled", true);
}
});
});
}
if (frm.doc.docstatus == 1) {
frm.add_custom_button(__("Approval Attendance"), function() {
frappe.call({
method: "approval_attendance",
doc: frm.doc,
callback: function() {
// Disable Approval Attendance after Records have been created
frm.add_custom_button(__("Approval Attendance"), function() {
frappe.throw(__('Attendance has already been Approvaled and cannot be Approvaled again.'));
}).prop("disabled", true);
}
});
});
}
},
// Event for the custom "get_employee" button
get_employee(frm) {
// Check if project is mandatory and empty
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
// Call the get_all_employees method with or without the project
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 of accounts upon adjustment of schedule
timesheet_tool_details: {
hour(frm, cdt, cdn) {
let row = frappe.get_doc(cdt, cdn);
// Update total_working_hours
row.total_working_hours = row.hour * row.ratio_attendance;
frm.refresh_field("timesheet_tool_details");
},
over_time_h(frm, cdt, cdn) {
let row = frappe.get_doc(cdt, cdn);
// Calculation of the new value of Overtime H
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
}
});
},
over_time_n(frm, cdt, cdn) {
let row = frappe.get_doc(cdt, cdn);
// Calculation of the new value of Overtime N
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");
}
});
}
}
});
// Copyright (c) 2024, Ebkar Technology And Management Solutions.
// For license information, please see license.txt
let settings = {};
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
// تعديل الفلتر الخاص بحقل الموظفين لجلب الموظفين الفعالين فقط مع 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);
}
}
});
// إدارة زر "Create Attendance"
if (frm.doc.docstatus === 0 && !frm.doc.__islocal) {
frappe.call({
method: "frappe.client.get_list",
args: {
doctype: "Timesheet",
filters: { timesheet_tool: frm.doc.name },
fields: ["name"]
},
callback: function(response) {
if (response.message.length > 0) {
// إذا كانت السجلات قد تم إنشاؤها، قم بتعطيل الزر
frm.add_custom_button(__("Create Attendance"), function() {
frappe.throw(__('Attendance has already been created and cannot be created again.'));
}).prop("disabled", true);
} else {
// إذا لم تكن السجلات موجودة، أضف الزر
frm.add_custom_button(__("Create Attendance"), function() {
if (frm.is_dirty()) {
frappe.throw(__("You have unsaved changes in this form. Please save before you continue."));
}
frappe.call({
method: "create_attendance",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
frm.reload_doc();
frappe.msgprint(__('Attendance records have been created successfully.'));
}
});
});
}
}
});
}
// إدارة زر "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] // تحقق من اعتماد كل السجلات
},
fields: ["name"]
},
callback: function(response) {
if (response.message.length > 0) {
// إذا كانت هناك Timesheets غير معتمدة، عرض الزر
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 {
// إذا كانت السجلات كلها معتمدة، تعطيل الزر
frm.add_custom_button(__("Approval Attendance"), function() {
frappe.throw(__('Attendance has already been approved and cannot be approved again.'));
}).prop("disabled", true);
}
}
});
}
},
// زر "Get Employee" لجلب الموظفين بناءً على المشروع
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.'));
}
}
});
},
// تحديث الحقول عند تعديل جدول "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");
}
});
}
}
});
التعديلات:
زر "Create Attendance":
تم التحقق مما إذا كانت هناك Timesheets مرتبطة بـ Timesheet Tool الحالي.
إذا كانت جميع السجلات قد أنشئت بالفعل، يتم تعطيل الزر "Create Attendance".
زر "Approval Attendance":
يتم التحقق من Timesheets ورفض الزر إذا كانت جميع السجلات قد تم اعتمادها بالفعل (docstatus = 1).
إعادة تحميل الحالة:
بعد كل عملية (إنشاء السجلات أو اعتمادها)، يتم تحديث الوثيقة باستخدام frm.reload_doc.
تجربة الكود:
إنشاء مستند جديد:
جرب الضغط على زر "Create Attendance".
تحقق من أنه يتم تعطيل الزر بعد إنشاء السجلات.
اعتماد المستند:
جرب الضغط على زر "Approval Attendance".
تحقق من أنه يتم تعطيل الزر إذا تم اعتماد كل السجلات.
إعادة تحميل المستند:
تحقق من أن الأزرار تظهر بشكل صحيح بناءً على حالة السجلات.
إذا كانت لديك أي استفسارات إضافية، لا تتردد في طلب المساعدة. 😊
// Copyright (c) 2024, Ebkar Technology And Management Solutions.
// For license information, please see license.txt
let settings = {};
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
// تعديل الفلتر الخاص بحقل الموظفين لجلب الموظفين الفعالين فقط مع 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);
}
}
});
// إدارة زر "Create Attendance"
if (frm.doc.docstatus === 0 && !frm.doc.__islocal) {
frappe.call({
method: "time_sheet_tool.time_sheet_tool.utils.check_missing_records",
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
// إذا كانت هناك سجلات ناقصة، أعد تفعيل الزر
frm.add_custom_button(__("Create Attendance"), function() {
if (frm.is_dirty()) {
frappe.throw(__("You have unsaved changes in this form. Please save before you continue."));
}
frappe.call({
method: "create_attendance",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
frm.reload_doc();
frappe.msgprint(__('Attendance records have been created successfully.'));
}
});
});
} else {
// لا توجد سجلات ناقصة، قم بتعطيل الزر
frm.add_custom_button(__("Create Attendance"), function() {
frappe.throw(__('All records have already been created.'));
}).prop("disabled", true);
}
}
});
}
// إدارة زر "Approval Attendance"
if (frm.doc.docstatus === 1) {
frappe.call({
method: "time_sheet_tool.time_sheet_tool.utils.check_missing_records_for_approval",
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
// إذا كانت هناك سجلات ناقصة للاعتماد، أعد تفعيل الزر
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 {
// لا توجد سجلات ناقصة للاعتماد، قم بتعطيل الزر
frm.add_custom_button(__("Approval Attendance"), function() {
frappe.throw(__('All records have already been approved.'));
}).prop("disabled", true);
}
}
});
}
},
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.'));
}
}
});
},
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");
}
});
}
}
});
ما قمنا به في الكود أعلاه:
1. دوال Backend مخصصة في Python:
سنحتاج إلى دوال Backend لفحص السجلات المفقودة لكل موظف:
check_missing_records: تتحقق من السجلات المفقودة لـ Timesheet وAdditional Salary.
check_missing_records_for_approval: تتحقق من السجلات غير المعتمدة.
2. التحكم في الأزرار بشكل ديناميكي:
تمت إضافة تفعيل ديناميكي للأزرار بناءً على حالة كل موظف في جدول timesheet_tool_details.
3. تحسين تجربة المستخدم:
عرض رسالة توضيحية إذا كان الزر معطلاً أو إذا كان المستخدم يحاول تنفيذ نفس الإجراء بعد اكتماله.
متطلبات Backend (Python):
تحتاج إلى إضافة دوال مثل:
python
@frappe.whitelist()
def check_missing_records(timesheet_tool_name):
"""
تحقق إذا كان هناك موظفين ليس لديهم Timesheets أو Additional Salary.
"""
# اكتب الكود الذي يتحقق:
# إذا كانت الحقول (hour, over_time_h, over_time_n, deduction) تحتوي على قيم ولا توجد سجلات
return "missing"
إذا احتجت أي مساعدة إضافية على Python، يمكنني مساعدتك في بناء الدوال! 😊
شرح الكود:
جلب تفاصيل الحقول من جدول timesheet_tool_details:
يتم استخدام الاستعلام frappe.db.get_all لتحديد الأعمدة:
أضف موظفًا مع الحقول hour, overtime, deduction ثم تحقق من منطق الأزرار.
إعادة تحميل الصفحة:
تأكد من استدعاء الـ backend وإعادة تفعيل الأزرار إذا كان هناك سجلات ناقصة.
إذا واجهت أي مشكلة أو تحتاج إلى تحسينات إضافية، أنا هنا للمساعدة دائمًا! 😊
// 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) {
frappe.call({
method: "time_sheet_tool.time_sheet_tool.utils.check_missing_records",
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
// إذا كانت هناك سجلات ناقصة، أعد تفعيل الزر
frm.add_custom_button(__("Create Attendance"), function() {
if (frm.is_dirty()) {
frappe.throw(__("You have unsaved changes in this form. Please save before you continue."));
}
frappe.call({
method: "create_attendance",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
frm.reload_doc();
frappe.msgprint(__('Attendance records have been created successfully.'));
}
});
});
} else {
// لا توجد سجلات ناقصة، قم بتعطيل الزر
frm.add_custom_button(__("Create Attendance"), function() {
frappe.throw(__('All records have already been created.'));
}).prop("disabled", true);
}
}
});
}
// إدارة زر "Approval Attendance"
if (frm.doc.docstatus === 1) {
frappe.call({
method: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
// إذا كانت هناك سجلات ناقصة للاعتماد، أعد تفعيل الزر
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 {
// لا توجد سجلات ناقصة للاعتماد، قم بتعطيل الزر
frm.add_custom_button(__("Approval Attendance"), function() {
frappe.throw(__('All records have already been approved.'));
}).prop("disabled", true);
}
}
});
}
// 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");
}
});
}
}
});
2. منطق "Approval Attendance" المُحسّن:
تم تعديل منطق "Approval Attendance" بحيث يتحقق ديناميكياً إذا كانت هناك سجلات غير معتمدة:
javascript
if (frm.doc.docstatus === 1) {
frappe.call({
method: "time_sheet_tool.time_sheet_tool.utils.check_missing_records_for_approval",
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
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 {
// إذا تم اعتماد كافة السجلات، قم بتعطيل الزر
frm.add_custom_button(__("Approval Attendance"), function() {
frappe.throw(__('All records have already been approved.'));
}).prop("disabled", true);
}
}
});
}
التعديلات على ملف الـ Backend (Python):
1. دالة check_missing_records:
ستقوم الدالة بالتحقق مما إذا كان هناك أي سجل ناقص للموظفين:
python
@frappe.whitelist()
def check_missing_records(timesheet_tool_name):
"""
تحقق إذا كان هناك موظفين ليس لديهم Timesheets أو Additional Salaries ناقصة في timesheet_tool_details.
"""
timesheet_tool_details = frappe.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:
# تحقق إذا كان هناك Timesheet مفقود
if detail["hour"] > 0:
ts_exists = frappe.db.exists(
"Timesheet",
{"employee": detail["employee"], "timesheet_tool": timesheet_tool_name}
)
if not ts_exists:
return "missing"
# تحقق إذا كانت هناك Additional Salaries مفقودة
additional_salary_types = [
{"value": detail["over_time_h"], "component": "Overtime H"},
{"value": detail["over_time_n"], "component": "Overtime N"},
{"value": detail["deduction"], "component": "Deduction"}
]
for item in additional_salary_types:
if item["value"] > 0:
as_exists = frappe.db.exists(
"Additional Salary",
{"employee": detail["employee"], "timesheet_tool": timesheet_tool_name, "salary_component": item["component"]}
)
if not as_exists:
return "missing"
return "complete"
2. دالة check_missing_records_for_approval:
ستتحقق الدالة مما إذا كانت هناك أي سجلات غير معتمدة:
python
@frappe.whitelist()
def check_missing_records_for_approval(timesheet_tool_name):
"""
تحقق إذا كانت السجلات المرتبطة (Timesheets وAdditional Salaries) قد تم اعتمادها.
"""
# تحقق من Timesheets غير معتمدة
unapproved_timesheets = frappe.get_all(
"Timesheet",
filters={"timesheet_tool": timesheet_tool_name, "docstatus": ["!=", 1]},
fields=["name"]
)
# تحقق من Additional Salaries غير معتمدة
unapproved_additional_salaries = frappe.get_all(
"Additional Salary",
filters={"timesheet_tool": timesheet_tool_name, "docstatus": ["!=", 1]},
fields=["name"]
)
if unapproved_timesheets or unapproved_additional_salaries:
return "missing"
return "complete"
النقاط المحسنة:
زر Create Attendance:
تم تفعيله ديناميكياً إذا كان هناك سجلات ناقصة في جدول timesheet_tool_details.
زر Approval Attendance:
تم تفعيله ديناميكياً إذا كانت هناك سجلات غير معتمدة.
تحكم ديناميكي في الأزرار:
جعل الأزرار تستجيب بناءً على حالة البيانات بدون الحاجة لإعادة تشغيل النموذج.
اختبار النظام بعد التعديلات:
إنشاء نموذج جديد:
قم بإضافة موظفين في جدول timesheet_tool_details.
تحقق من عمل الزر "Create Attendance" إذا كانت هناك سجلات ناقصة.
اعتماد السجلات:
تحقق من زر "Approval Attendance" إذا كانت هناك سجلات غير معتمدة.
إعادة التحميل:
تأكد أن الأزرار مفعلة بشكل صحيح بعد إعادة تحميل المستند.
إذا كنت بحاجة إلى أي تحسين إضافي، فلا تتردد في طلب المساعدة! 😊
2. تأكد من استخدام المسار الصحيح داخل JavaScript:
استخدم المسار الكامل لـ check_missing_records كما هو معرف في الملف utils.py.