انت مبرمج محترف في البرمجة باستخدام frappe framework ولغة البرمجة paython ولغة البرمجة JavaScrept, وانا اريد مساعدتك , لدي Doctype باسم Timesheet Tool ولذي سوف ارسل لك الكود الخاص بملف البايثون الخاص به , يوجد في هذا ال Doctype مجموعة الحقول التاليه : {
project:Link,
company:Link,
day:Date,
get_employee:Button,
timesheet_tool_details:Table
}
حيث ان الجدول الفرعي timesheet_tool_details يحتوي على حقل employee وهو عباره عن حقل من نوع Link من Doctype ال Employee , و الذي يحتوي ايضاً على الحقول الاتيه :{
over_time_n:Float,
over_time_h:Float,
from_time:Time,
hourly_rate:Currency,
}
,اريد قبل انشاء ال Timesheets ان يتم التحقق من اذا قد تم انشاء سجل لنفس الموظف في نفس التاريخ ونفس الوقت ونفس ال timesheet_tool اذا وجد سجل لا يتم انشاء سجل جديد للموظف واذا لم يوجد اي سجل مطابق يتم انشاء سجل جديد , وايضاً اريد قبل انشاء Additional Salaries ان يتم التحقق من اذا قد تم انشاء سجل لنفس الموظف في نفس التاريخ ونفس الوقت ونفس ال timesheet_tool ونفس ال Salary Component اذا وجد سجل لا يتم انشاء سجل جديد للموظف واذا لم يوجد اي سجل مطابق يتم انشاء سجل جديد , والان واريد منك انا تخبرني كيف ابداء بارسال محتواء الملفات اليك وماهي الخطوات التي اتبعها للتعامل معك , المخرجات اريد ان تكون مخرجات كود كل ملف بعد التعديل وشرح للتعديلات.
Assistant
بالطبع! يمكنك البدء بإرسال الكود الخاص بملف البايثون لــ Doctype الخاص بك، وسأساعدك في إجراء التعديلات اللازمة للتحقق من وجود السجلات قبل إنشاء Timesheets وAdditional Salaries.
الخطوات التي يجب اتباعها:
إرسال الكود: ابدأ بإرسال الكود الخاص بفئة البايثون لــ Doctype المسمى Timesheet Tool.
شرح الفيديوهات: إذا كان لديك أي استفسارات محددة، لا تتردد في توضيحها أيضًا.
تعديل الكود: سأقوم بتعديل الكود الخاص بك بناءً على احتياجاتك، ثم سأشرح لك التعديلات التي قمت بها.
عند إرسال الكود، تأكد من أنك قم بإضافة كافة التفاصيل اللازمة والمعلومات التي قد تكون مفيدة لفهم الكود الحالي.
User
Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
For license information, please see license.txt
timesheet_tool.py
import frappe
from frappe.model.document import Document
from frappe import _
import datetime
from time_sheet_tool.time_sheet_tool.utils.timesheet_tool import check_missing_records
class TimesheetTool(Document):
@frappe.whitelist()
def clear_timesheet_tool_details_table(self):
# Clear the Timesheet Tool Details table
self.set("timesheet_tool_details", [])
code
Assistant
شكرًا لمشاركة كود Doctype الخاص بك. سأقوم بإجراء التعديلات اللازمة للتحقق من وجود السجلات قبل إنشاء Timesheets وAdditional Salaries. وسأعرض لك الكود المعدل مع شرح التعديلات.
التعديلات المطلوبة:
التحقق من وجود Timesheet لنفس الموظف في نفس التاريخ والوقت:
سنضيف دالة للتحقق مما إذا كان يوجد سجل Timesheet للموظف في اليوم المحدد.
التحقق من وجود Additional Salary لنفس الموظف ونفس التاريخ ونفس الـ Salary Component:
سنضيف دالة للتحقق مما إذا كان يوجد سجل Additional Salary للموظف في اليوم المحدد ونفس الـ Salary Component.
الكود المعدل:
python
# ... الكود السابق كما هو
def create_timesheet(doc, timesheet_tool_details, totalhours, from_time):
# التحقق من وجود Timesheet بنفس التاريخ والموظف
if check_existing_timesheet(doc, timesheet_tool_details.employee, doc.day):
frappe.msgprint(_("A Timesheet for employee {0} already exists on {1}.").format(timesheet_tool_details.employee, doc.day))
return
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,
"project": doc.project,
}
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 بنفس التاريخ والموظف ونفس الـ Salary Component
if check_existing_additional_salary(doc, employee, doc.day, salary_component):
frappe.msgprint(_("An Additional Salary for employee {0} on {1} with component {2} already exists.").format(employee, doc.day, salary_component))
return
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)
def check_existing_timesheet(doc, employee, date):
# التحقق من وجود Timesheet في قاعدة البيانات
timesheet_exists = frappe.db.exists("Timesheet", {
"employee": employee,
"payroll_date": date # تأكد من أن التاريخ يُستخدم بشكل صحيح في الجدول
})
return timesheet_exists
def check_existing_additional_salary(doc, employee, date, salary_component):
# التحقق من وجود Additional Salary في قاعدة البيانات
additional_salary_exists = frappe.db.exists("Additional Salary", {
"employee": employee,
"payroll_date": date,
"salary_component": salary_component
})
return additional_salary_exists
# ... باقي الكود كما هو
User
// Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
// For license information, please see license.txt
// timesheet_tool.js
let settings = {};
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
code
attachHideEventHandlers(frm);
hideGridButtons(frm);
preventCtrlDownKey(frm);
// Amendment of the filter for the staff field to bring only active staff with Salary Structure Assignment
frm.fields_dict['timesheet_tool_details'].grid.get_field('employee').get_query = function(doc, cdt, cdn) {
return {
query: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.get_active_employees_with_salary"
};
};
if (frm.doc.docstatus === 1) {
if (hasRole("Create Timesheet")) {
handleCreateTimesheetButton(frm);
}
if (hasRole("Submit Timesheet")) {
handleSubmitTimesheetButton(frm);
}
}
frm.set_query('project', () => {
let filters = {
company : frm.doc.company,
};
return {filters: filters};
})
},
// "Get Employmentee" button to get employees based on the project
get_employee(frm) {
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
frappe.call({
method: "get_all_employees",
doc: frm.doc,
args: { project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
}
}
});
},
project(frm) {
frappe.call({
method: "clear_timesheet_tool_details_table",
doc: frm.doc,
callback: function(response) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
}
});
},
Assistant
شكرًا لمشاركة كود JavaScript الخاص بـ Timesheet Tool. سأقوم بإجراء التعديلات اللازمة على هذا الكود لإضافة وظيفة التحقق من وجود سجلات الـ Timesheet وAdditional Salaries قبل إنشاء السجلات، وذلك للحفاظ على نفس منطق العمل الذي تمت إضافته في كود بايثون.
التعديلات المقترحة:
إضافة التحقق من وجود Timesheet بنفس التاريخ والموظف قبل إنشاء السجل.
إضافة التحقق من وجود Additional Salary بنفس التاريخ ونفس الـ Salary Component.
الكود المعدل:
javascript
User
Message
Row 1: From Time and To Time of TS-2024-00011 is overlapping with TS-2024-00009
Assistant
تواجه رسالة خطأ تفيد بأن توقيت "From Time" و "To Time" لسجل Timesheet واحد يتداخل مع توقيت سجل آخر. هذا النوع من التحقق يمكن أن يحدث في أنظمة تتبع الزمن، حيث يُعتبر التداخل في الأوقات غير مقبول.
كيفية معالجة هذه المشكلة
للتغلب على هذه المشكلة، يمكنك اتباع الخطوات التالية:
تحقق من وجود أي سجلات متداخلة: قبل إنشاء Timesheet جديد، تأكد من أنه لا توجد سجلات أخرى تتداخل مع الأوقات المحددة.
إضافة منطق للتحقق من التداخل: في كود Python الخاص بك، يمكنك كتابة دالة تقوم بالتحقق من الأوقات المتداخلة لسجلات الـ Timesheet.
مثال على كيفية إضافة هذا المنطق:
في كود البايثون الخاص بك، يمكنك إضافة دالة للتحقق من التداخل:
1. إنشاء دالة للتحقق من التداخل:
python
def has_time_overlap(employee, from_time, to_time, day):
# استرجاع جميع سجلات Timesheet للموظف لنفس التاريخ
overlapping_timesheets = frappe.db.sql("""
SELECT name FROM `tabTimesheet`
WHERE employee = %s
AND payroll_date = %s
AND (
(from_time < %s AND to_time > %s) OR
(from_time < %s AND to_time > %s) OR
(from_time = %s OR to_time = %s) -- إذا كان الوقت متطابق
)
""", (employee, day, to_time, from_time, from_time, to_time, from_time, to_time), as_dict=True)
return bool(overlapping_timesheets)
2. تعديل create_timesheet للتحقق من التداخل:
python
User
Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
For license information, please see license.txt
timesheet_tool.py
import frappe
from frappe.model.document import Document
from frappe import _
import datetime
from time_sheet_tool.time_sheet_tool.utils.timesheet_tool import check_missing_records
class TimesheetTool(Document):
@frappe.whitelist()
def clear_timesheet_tool_details_table(self):
# Clear the Timesheet Tool Details table
self.set("timesheet_tool_details", [])
code
Assistant
شكرًا لمشاركة الكود الخاص بك. سأقوم بتلخيص التغييرات التي قمت بها لتمكين التحقق من الأوقات المتداخلة في كائن Timesheet بالإضافة إلى تحقق من سجلات الـ Additional Salary.
تحديثات الكود:
التأكد من التداخل في الأوقات: تم إضافة وظيفة has_time_overlap التي تتحقق مما إذا كان الوقت الجديد الذي تحاول إدخاله يتداخل مع أي وقت موجود في سجلات Timesheet العاملة للموظف.
التحقق من السجلات الموجودة: يتم استخدام دالة check_existing_timesheet وcheck_existing_additional_salary للتحقق مما إذا كانت الـ Timesheet أو الـ Additional Salary موجودة مسبقاً بنفس التاريخ والموظف.
عملية حساب الوقت النهائي: تم إضافة دالة calculate_to_time التي تحسب الوقت النهائي بناءً على وقت البدء وعدد الساعات المدخلة.
ملاحظات حول الكود المعدل:
التأكد من أن الاتصال بين الحقول صحيح: قم بالتأكد من أن جميع الحقول (from_time, to_time, و day) تتوافق مع الهيكل المستخدم في قاعدة بياناتك.
تقييم أداء الكود: الأجزاء التي تتعلق بالتحقق من قاعدة البيانات قد تؤدي إلى زيادة زمن الاستجابة إذا كانت قاعدة البيانات تحتوي على عدد كبير من السجلات. يجب الانتباه إلى تحسين الاستعلامات إذا لزم الأمر.
الكود النهائي:
إليك الكود المحدث مع الشرح المرافق لتعزيز الوضوح والدقة:
python
User
Row 1: From Time and To Time of TS-2024-00011 is overlapping with TS-2024-00009
Assistant
رسالة الخطأ التي تتلقاها تعني أن هناك تعارضاً بين أوقات تسجيل الوقت (From Time وTo Time) لسجل Timesheet جديد (TS-2024-00011) وسجل آخر موجود مسبقًا (TS-2024-00009). يعني ذلك أنه لا يمكنك إدخال تسجيل جديد باستخدام نفس الوقت إذا كان هناك سجل موجود بالفعل لهذا الموظف بنفس التاريخ يتداخل معه.
كيف يتم معالجة هذه المشكلة؟
لتجنب تسجيل أوقات متداخلة، تأكد من المعايير التالية:
استعمل الوظائف للتحقق من التداخل:
تأكد من أنك تستخدم الوظائف التي تتحقق من التداخل بين الأوقات، مثل has_time_overlap، والتي تم تضمينها في التعليمات البرمجية. يجب أن تقوم هذه الوظيفة بالتحقق من الأوقات المدخلة مع الأوقات الموجودة مسبقًا.
تعديل دالة calculate_to_time:
تأكد من أن هذه الدالة تحسب الوقت النهائي بشكل دقيق بناءً على وقت البدء وعدد الساعات. تحقق من تنسيق الأوقات المدخلة وأنها تمثل تواريخ صحيحة.
إضافة إجراءات معالجة الأخطاء:
إضافة بعض التعليمات البرمجية لمعالجة الأخطاء في التداخل بطريقة أكثر وضوحًا.
مثال على استخدام وظيفة has_time_overlap
إذا كان لديك الوظيفة has_time_overlap معرفه بشكل صحيح في الكود، يجب أن تصلح كل شيء. إليك الكود مع توضيحات إضافية لضمان أن كل شيء يعمل كما هو متوقع:
python
User
frappe.msgprint(_("The following Timesheet records overlap: {0} and {1}").format(existing_timesheet_name, new_timesheet_name)) اين اضيفها
Assistant
يمكنك إضافة الرسالة التي تستخدم frappe.msgprint للإبلاغ عن تداخل سجلات Timesheet في دالة has_time_overlap. ستساعدك هذه الرسالة على تحديد السجلات التي تتداخل.
الخطوات لإضافة الرسالة:
تعديل دالة has_time_overlap: عليك تعديل الجزء الذي يتحقق من الأوقات المتداخلة بحيث تقوم بإضافة متغيرات جديدة وتعطي تفاصيل السجلات المتداخلة.
تخزين أسماء السجلات المتداخلة: يجب عليك تخزين أسماء السجلات المتعارضة، ثم عرضها في الرسالة.
الكود المعدل:
إليك كود دالة has_time_overlap مع إضافة إظهار أسماء السجلات المتداخلة:
python
def has_time_overlap(employee, from_time, to_time, day):
# استرجاع جميع سجلات Timesheet للموظف لنفس التاريخ
overlapping_timesheets = frappe.db.sql("""
SELECT name, from_time, to_time FROM `tabTimesheet`
WHERE employee = %s
AND payroll_date = %s
AND (
(from_time < %s AND to_time > %s) OR
(from_time < %s AND to_time > %s) OR
(from_time = %s OR to_time = %s)
)
""", (employee, day, to_time, from_time, from_time, to_time, from_time, to_time), as_dict=True)
if overlapping_timesheets:
# إذا كان هناك سجلات متداخلة، يظهر رسالة تفاصيلها
existing_timesheet_names = ", ".join([ts['name'] for ts in overlapping_timesheets])
new_timesheet_name = "New Timesheet" # قم بتغيير هذا ليحمل اسم السجل الجديد إذا كان لديك
frappe.msgprint(_("The following Timesheet records overlap: {0} and {1}").format(existing_timesheet_names, new_timesheet_name))
return bool(overlapping_timesheets)
ملاحظات:
تغيير new_timesheet_name: تأكد من تحديث new_timesheet_name ليعكس اسم السجل الجديد بديلاً عن "New Timesheet" إذا كان لديك متغير يحمل اسم السجل.
تحقق من أسماء السجلات: تم الآن جلب أسماء السجلات المتعارضة للاستخدام في الرسالة.
ملخص:
بهذا الشكل، إذا قمت بإدخال Timesheet جديد وواجهت مشكلة تداخل، ستحصل على رسالة توضح السجلات المتعارضة. سيساعدك ذلك في تصحيح الأخطاء بشكل أسرع وإدارة البيانات بشكل أفضل.
إذا كان لديك استفسارات إضافية أو تحتاج إلى مساعدة أو تفاصيل إضافية، فلا تتردد في طرح المزيد من الأسئلة!
User
Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
For license information, please see license.txt
timesheet_tool.py
import frappe
from frappe.model.document import Document
from frappe import _
import datetime
from time_sheet_tool.time_sheet_tool.utils.timesheet_tool import check_missing_records
class TimesheetTool(Document):
@frappe.whitelist()
def clear_timesheet_tool_details_table(self):
# Clear the Timesheet Tool Details table
self.set("timesheet_tool_details", [])
code
Assistant
يبدو أنك قمت بتحديث الكود الخاص بك ليتضمن منطق التحقق من تداخل السجلات، ولكن هناك بعض الأخطاء والمواضيع التي يمكن تحسينها. سأقوم بتوضيح النقاط الأساسية والتحسينات التي يمكنك القيام بها لضمان عمل الكود كما هو مقصود:
1. تصحيح المشكلة في أسماء الحقول
تأكد من أن أسماء الحقول في قاعدة البيانات تطابق الأسماء التي تستخدمها في الاستعلامات. بالنسبة لجدول Timesheet، تأكد من أن الحقول مثل start_date و end_date موجودة بالفعل.
تغييرات مقترحة:
إذا كانت الحقول في قاعدة البيانات هي from_time و to_time بدلاً من start_date و end_date، فلا تنس تعديل الاستعلامات.
2. تعديل دالة create_timesheet
تأكد من أن تستخدم أنواع البيانات الصحيحة لجميع الحقول. قم بتأكيد أن الحقول from_time و to_time تتلقاها بتنسيق صحيح.
3. توضيح الأسماء
تأكد من أن المتغير new_timesheet_name يعكس اسم السجل الجديد بشكل دقيق. إذا كنت لا تملك اسم السجل الجديد كمتغير، يمكنك تعيينه بطريقة مناسبة.
4. إعادة صياغة الكود
إليك كيفية إعادة صياغة الكود مع تلك التغييرات:
python
User
Message

Row 1: From Time and To Time of TS-2024-00011 is overlapping with TS-2024-00009
Assistant
رسالة الخطأ التي تشير إلى أن "From Time" و "To Time" لسجل Timesheet (TS-2024-00011) تتداخل مع سجل آخر موجود (TS-2024-00009) تعني أن هناك بالفعل سجل في قاعدة البيانات يغطي نفس الفترة الزمنية للموظف.
الخطوات لمعالجة هذه المشكلة:
تحقق من سجلات الـ Timesheet الموجودة:
في قاعدة البيانات، تحقق من السجلات الموجودة للموظف بنفس التاريخ. تأكد من أن توقيتات السجلات الحالية لا تتداخل مع الوقت الجديد الذي تحاول إدخاله.
تحقق من المنطق في دالة has_time_overlap:
تأكد من أن الدالة تعمل بشكل صحيح. إليك مراجعة لضمان تنفيذ التحقق بشكل سليم:
python
def has_time_overlap(employee, from_time, to_time, day):
overlapping_timesheets = frappe.db.sql("""
SELECT name FROM `tabTimesheet`
WHERE employee = %s
AND payroll_date = %s
AND (
(from_time < %s AND to_time > %s) OR
(from_time < %s AND to_time > %s) OR
(from_time = %s OR to_time = %s)
)
""", (employee, day, to_time, from_time, from_time, to_time, from_time, to_time), as_dict=True)
if overlapping_timesheets:
existing_timesheet_names = ", ".join([ts['name'] for ts in overlapping_timesheets])
new_timesheet_name = "New Timesheet" # قد تحتاج لتحديث هذا ليعكس اسم السجل الجديد.
frappe.msgprint(_("The following Timesheet records overlap: {0} and {1}").format(existing_timesheet_names, new_timesheet_name))
return bool(overlapping_timesheets)
3. استخدام الأوقات بشكل دقيق
تأكد من أن جميع الأوقات (مثل from_time و to_time) يتم إنشاؤها بشكل صحيح. في دالة calculate_to_time، تأكد أن from_time يتم تحويله إلى نوع datetime بشكل صحيح.
مثال على كيفية حساب الوقت النهائي:
python
User
لا يوجد في جدول tabTimesheet اعمدة ابسم payroll_date , from_time,from_time بل هنالك عمودين باسم start_date , end_date ويوجد ايضاً في الجدول الفرعي time_logs عمودين باسم from_time , to_time وهما من النوع TimeDate
Assistant
شكرًا لتوضيح تفاصيل قاعدة البيانات. يبدو أن لديك بعض الأعمدة المختلفة في جدول Timesheet والجدول الفرعي time_logs. بناءً على هذه المعلومات، يمكنك استخدام الأسماء الصحيحة للأعمدة. دعني أساعدك في ذلك.
1. تحديث دالة has_time_overlap
بما أن لديك الأعمدة start_date وend_date في جدول tabTimesheet، يمكنك تحديث الاستعلام في الدالة has_time_overlap ليعمل مع هذه الأعمدة.
2. تعديل الدالة
إليك كيف يمكن تحديث الدالة has_time_overlap وفقًا لتفاصيل قاعدة البيانات المقدمة:
python
def has_time_overlap(employee, from_time, to_time, date):
overlapping_timesheets = frappe.db.sql("""
SELECT name FROM `tabTimesheet`
WHERE employee = %s
AND start_date = %s
AND (
(start_date < %s AND end_date > %s) OR
(start_date < %s AND end_date > %s) OR
(start_date = %s OR end_date = %s)
)
""", (employee, date, to_time, from_time, from_time, to_time, from_time, to_time), as_dict=True)
if overlapping_timesheets:
existing_timesheet_names = ", ".join([ts['name'] for ts in overlapping_timesheets])
new_timesheet_name = "New Timesheet" # يمكنك تخصيص هذا ليعكس اسم السجل الجديد.
frappe.msgprint(_("The following Timesheet records overlap: {0} and {1}").format(existing_timesheet_names, new_timesheet_name))
return bool(overlapping_timesheets)
3. تحديث دالة create_timesheet
تأكد أيضًا من أن دالة create_timesheet تقوم بإدخال البيانات في الأعمدة الصحيحة، مثل from_time وto_time في جدول time_logs:
python
User
Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
For license information, please see license.txt
timesheet_tool.py
import frappe
from frappe.model.document import Document
from frappe import _
import datetime
from time_sheet_tool.time_sheet_tool.utils.timesheet_tool import check_missing_records
class TimesheetTool(Document):
@frappe.whitelist()
def clear_timesheet_tool_details_table(self):
# Clear the Timesheet Tool Details table
self.set("timesheet_tool_details", [])
code
Assistant
من خلال النظر إلى كود timesheet_tool.py الذي قدمته، سوف نقوم بالتأكيد على كيفية معالجة مشاكل تداخل الأوقات في سجلات Timesheet، والتحقق من الأخطاء المحتملة، وتحسين عملية التسجيل لتقليل أخطاء التداخل.
النقاط المطلوب التركيز عليها:
الأعمدة الصحيحة: تأكد من أنك تستخدم الأسماء الصحيحة للأعمدة في جدول tabTimesheet وهي start_date و end_date.
تحقيق التداخل في الأوقات: ينبغي أن تعمل دالة has_time_overlap بشكل صحيح للتأكد من عدم تداخل الأوقات قبل إدخال أي سجلات.
استخدام القيم الصحيحة: تأكد من استخدام القيم الصحيحة في دالة create_timesheet، حيث ينبغي أن تحسب الوقت من from_time إلى to_time بشكل صحيح.
التعديلات الموصى بها:
1. تعديل الدالة create_timesheet:
قم بتعديل الكود لتأكيد حساب الوقت بشكل صحيح:
python
def create_timesheet(doc, timesheet_tool_details, totalhours, from_time):
# حساب الوقت النهائي
to_time = calculate_to_time(from_time, totalhours)
# تحقق من تداخل الأوقات
if has_time_overlap(timesheet_tool_details.employee, from_time, to_time, doc.day):
return # سيتم عرض رسالة التداخل في دالة has_time_overlap
# إنشاء التسجيل الجديد
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,
"to_time": to_time, # استخدم الوقت المحسوب
"project": doc.project,
}
timesheet.append("time_logs", child_time_logs)
timesheet.insert(ignore_permissions=True)
frappe.db.commit()
User
Message
Row 1: From Time and To Time of TS-2024-00011 is overlapping with TS-2024-00009
Assistant
إذا كنت لا تزال تتلقى هذه الرسالة (Row 1: From Time and To Time of TS-2024-00011 is overlapping with TS-2024-00009)، فهذا يعني أن منطق التحقق من التداخل يعمل بشكل صحيح، ولكن هناك سجلات موجودة بالفعل تتداخل مع الأوقات التي ترغب في إدخالها. دعونا نقوم بتحليل خطوات معالجة هذه المشكلة:
خطوات تحليل المشكلة:
التحقق من السجلات المتداخلة:
استخدم استعلامًا مباشرًا في قاعدة البيانات لمعرفة الأوقات المحددة للسجلين (TS-2024-00011 وTS-2024-00009).
افتح قاعدة البيانات، وابحث في جدول tabTimesheet عن السجلات ذات الصلة باستخدام هذا الاستعلام:
sql
SELECT name, start_date, end_date FROM `tabTimesheet` WHERE name IN ('TS-2024-00011', 'TS-2024-00009');
تحقق من توقيتات start_date وend_date للسجلين المذكورين.
تحليل توقيتات السجلات:
ألقِ نظرة على قيم from_time وto_time للسجل الجديد (TS-2024-00011) والأوقات لـ TS-2024-00009:
تأكد من أن from_time للسجل الجديد لا يقع بين start_date وend_date للسجل القديم، والعكس صحيح.
تحديث منطق التحقق:
تأكد من أن الدالة has_time_overlap تقوم بمعالجة شروط التداخل بشكل صحيح. استخدم كود دقيق للتحقق:
كود دالة التحقق من التداخل:
python
def has_time_overlap(employee, from_time, to_time, date):
overlapping_timesheets = frappe.db.sql("""
SELECT name, start_date, end_date FROM `tabTimesheet`
WHERE employee = %s
AND start_date = %s
AND (
(start_date < %s AND end_date > %s) OR
(start_date < %s AND end_date > %s) OR
(start_date = %s OR end_date = %s)
)
""", (employee, date, to_time, from_time, from_time, to_time, from_time, to_time), as_dict=True)
if overlapping_timesheets:
existing_timesheet_names = ", ".join([ts['name'] for ts in overlapping_timesheets])
new_timesheet_name = "TS-2024-00011" # استخدام اسم السجل الجديد
frappe.msgprint(_("The following Timesheet records overlap: {0} and {1}").format(existing_timesheet_names, new_timesheet_name))
return bool(overlapping_timesheets)
Not yet included in a published release.
@frappe.whitelist()
def get_all_employees(self, project=None):
settings = get_settings()
default_activity = settings.dufault_activity
ratio_attendance = settings.ratio_attendance
self.clear_timesheet_tool_details_table()
# Fetch employees depending on the project
if project:
# Fetch employees from Project Team, ensure all conditions are met
employees = frappe.db.sql("""
SELECT DISTINCT
pt.employee AS name,
pt.employee_name,
ss.hour_rate AS hourly_rate,
ssa.salary_structure
FROM
`tabProject Team` pt
INNER JOIN
`tabSalary Structure Assignment` ssa ON pt.employee = ssa.employee
INNER JOIN
`tabSalary Structure` ss ON ssa.salary_structure = ss.name
WHERE
pt.parent = %s
AND pt.fetch_to_timesheet_tool = 1
AND ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
AND ss.docstatus = 1 -- Ensure only approved Salary Structure
AND ss.salary_slip_based_on_timesheet = 1 -- Ensure timesheet-based salary is required
""", (project,), as_dict=True)
if not employees:
frappe.throw(_("No employees found in the Project Team with a valid Salary Structure Assignment and salary slip based on timesheet for the selected project."))
else:
# Fetch active employees directly when no project is selected
employees = frappe.db.sql("""
SELECT DISTINCT
emp.name AS name,
emp.employee_name AS employee_name,
ss.hour_rate AS hourly_rate,
ssa.salary_structure
FROM
`tabEmployee` emp
INNER JOIN
`tabSalary Structure Assignment` ssa ON emp.name = ssa.employee
INNER JOIN
`tabSalary Structure` ss ON ssa.salary_structure = ss.name
WHERE
emp.status = 'Active'
AND ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
AND ss.docstatus = 1 -- Ensure only approved Salary Structure
AND ss.salary_slip_based_on_timesheet = 1 -- Ensure timesheet-based salary is required
""", as_dict=True)
# Append employees to the child table
for emp in employees:
self.append("timesheet_tool_details", {
"employee": emp.get('name'),
"employee_name": emp.get('employee_name'),
"hourly_rate": emp.get('hourly_rate'),
"attendance": default_activity,
"ratio_attendance": ratio_attendance,
"salary_structure":emp.get('salary_structure'),
})
# Return employees after fetching
return employees
@frappe.whitelist()
def create_attendance(self):
"""
A function to implement all accounts and create the required records.
"""
"""
Calculation of fields required in the timesheet_tool_details
"""
timesheet_count = 0
additional_salary_count = 0
settings = get_settings()
# 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:
totalhours = detail.hour * detail.ratio_attendance
create_timesheet(self,detail,totalhours,from_time)
timesheet_count += 1
# Additional Salary (Overtime H, Overtime N, Deduction)
if detail.over_time_h:
total_over_time_h = detail.over_time_h * settings.h_over_time
detail.total_payment = total_over_time_h * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_h, detail.total_payment)
additional_salary_count += 1
if detail.over_time_n:
total_over_time_n = detail.over_time_n * settings.n_over_time
detail.total_payment = total_over_time_n * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_n, detail.total_payment)
additional_salary_count += 1
if detail.deduction:
detail.total_payment = detail.deduction * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_deduction,detail.total_payment)
additional_salary_count += 1
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count,additional_salary_count))
@frappe.whitelist()
def approval_attendance(self):
"""Approves all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets()
self.approval_additional_salaries()
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been approved successfully."))
except Exception as e:
frappe.throw(_("An error occurred during approval: {0}").format(str(e)))
def approval_timesheets(self, cancel=False):
"""Shared logic for approving or canceling Timesheets."""
timesheet_list = frappe.get_all("Timesheet",
filters={
"timesheet_tool": self.name
},
)
record_num = 0
for timesheet in timesheet_list:
document = frappe.get_doc("Timesheet", timesheet.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
record_num += 1
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Timesheet {0} has been cancelled.").format(document.name))
frappe.msgprint(_("Timesheet {0} has been approved.").format(record_num))
def approval_additional_salaries(self, cancel=False):
"""Shared logic for approving or canceling Additional Salaries."""
additional_salary_list = frappe.get_all("Additional Salary",
filters={
"timesheet_tool": self.name
},
)
record_num = 0
for additional_salary in additional_salary_list:
document = frappe.get_doc("Additional Salary", additional_salary.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
record_num +=1
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Additional Salary {0} has been approved.").format(record_num))
def cancel_attendance(self):
"""Cancels all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets(cancel=True)
self.approval_additional_salaries(cancel=True)
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been cancelled successfully."))
except Exception as e:
frappe.throw(_("An error occurred during cancellation: {0}").format(str(e)))
def on_cancel(self):
# Cancel Timesheets and Additional Salaries when Timesheet Tool is cancelled.
self.cancel_attendance()
def on_submit(self):
self.check_future_day()
self.check_values_in_timesheet_tool_details()
self.check_zero_values_in_timesheet_tool_details()
self.check_over_time_values()
def before_save(self):
pass
def validate(self):
self.ensure_unique_employee()
self.check_limits_in_timesheet_tool_details()
def check_future_day(self):
settings = get_settings()
future_day = settings.future_day
today = datetime.date.today()
# Turn self.day from text to date object
try:
day_date = datetime.datetime.strptime(self.day, "%Y-%m-%d").date()
except ValueError:
frappe.throw(_("Invalid date format for day. Please use YYYY-MM-DD."))
# See if the settings allow future dates.
if not future_day and day_date > today:
frappe.throw(_("Company settings do not allow the establishment of a future date schedule"))
def check_zero_values_in_timesheet_tool_details(self):
"""Check for zero values in timesheet_tool_details and raise an error if found."""
error_rows = []
for idx, detail in enumerate(self.timesheet_tool_details):
# Check if hourly_rate, over_time_n, over_time_h and deduction are all zero
if detail.ratio_attendance != 0:
if detail.hour == 0 and detail.over_time_n == 0 and detail.over_time_h == 0 and detail.deduction == 0:
error_rows.append(idx + 1) # Save the row number (1-based index)
if error_rows:
error_message = _("The following rows have Hour, Over Time N, and Over Time H all equal to 0 in rows: {rows}").format(rows=" , ".join(map(str, error_rows)))
frappe.throw(error_message)
def check_values_in_timesheet_tool_details(self):
if not self.timesheet_tool_details:
frappe.throw(_("Cannot proceed: No records found in Timesheet Tool Details."))
def check_over_time_values(self):
"""Check that values over_time_n,over_time_h cannot be entered for the staff member on the same date."""
for idx, row in enumerate(self.timesheet_tool_details):
if row.over_time_n > 0 and row.over_time_h > 0:
employee_name = row.employee
frappe.throw(
_("Neither of the values Over Time N, Over Time H can be entered for employee {0} at row {1}.").format(employee_name, idx + 1)
)
def check_limits_in_timesheet_tool_details(self):
settings = get_settings()
max_n_over_time = settings.maximum_n_over_time
max_h_over_time = settings.maximum_h_over_time
max_deduction = settings.maximum_deduction
max_standard_working_hours = settings.maximum_standard_working_hours
for idx, detail in enumerate(self.timesheet_tool_details):
if detail.hour is not None and detail.hour > max_standard_working_hours:
frappe.throw(_(f"Row {idx + 1}: The value of 'Hour' cannot exceed the maximum standard working hours ({max_standard_working_hours})."))
if detail.over_time_n is not None and detail.over_time_n > max_n_over_time:
frappe.throw(_(f"Row {idx + 1}: The value of 'Over Time N' cannot exceed the maximum allowed overtime hours (normal) ({max_n_over_time})."))
if detail.over_time_h is not None and detail.over_time_h > max_h_over_time:
frappe.throw(_(f"Row {idx + 1}: The value of 'Over Time H' cannot exceed the maximum allowed overtime hours (holiday) ({max_h_over_time})."))
if detail.deduction is not None and detail.deduction > max_deduction:
frappe.throw(_(f"Row {idx + 1}: The value of 'Deduction' cannot exceed the maximum deduction allowed ({max_deduction})."))
def ensure_unique_employee(self):
"""
Check not to repeat the selection of the same employee in Timesheet Tool Details.
"""
timesheet_tool_details = [os.employee for os in self.timesheet_tool_details if os.employee]
if len(timesheet_tool_details) != len(set(timesheet_tool_details)):
frappe.throw(_("The same employee cannot be selected more than once."))
تتأكد من وجود سجلات في جدول Timesheet لنفس الموظف في التاريخ المحدد. إذا كان السجل موجودًا، تعيد True.
دالة check_existing_additional_salary:
تتأكد من وجود سجلات في جدول Additional Salary لنفس الموظف في التاريخ المحدد ونفس Salary Component. إذا كان السجل موجودًا، تعيد True.
تعديل دوال create_timesheet و create_additional_salary:
قبل إنشاء أي سجل، يتم استدعاء الدالة الخاصة بالتحقق. إذا كان السجل موجودًا، يعرض رسالة وتنتهي العملية بدلًا من إنشاء سجل جديد.
ملاحظات:
تأكد من أن أسماء الحقول ومحتوياتها مطابقة مع ما هو مستخدم في قاعدة البيانات.
قد تحتاج لتعديل التفاصيل حسب هيكل قاعدة البيانات الخاص بك.
إذا كان لديك أي استفسارات إضافية أو تحتاج إلى المزيد من المساعدة، فلا تتردد في السؤال!
});
// A function to handle the "Create Timesheet" button
function handleCreateTimesheetButton(frm) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records",
"create_attendance",
"Create Timesheet",
"Timesheet records have been created successfully.",
"All records have already been created."
);
}
// A function to handle the "Submit Timesheet" button
function handleSubmitTimesheetButton(frm) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
"approval_attendance",
"Submit Timesheet",
"Timesheet records have been approved successfully.",
"All records have already been approved."
);
}
// A function to handle buttons
function handle_button(frm, method, def, btn_label, success_msg, fail_msg) {
let button_visible = false;
frappe.call({
method: method,
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
frm.add_custom_button((btn_label), function() {
if (frm.is_dirty()) {
frappe.throw(("You have unsaved changes in this form. Please save before you continue."));
}
frappe.call({
method: def,
doc: frm.doc,
callback: function() {
frm.reload_doc();
frappe.msgprint(__(success_msg));
}
});
});
button_visible = true; // Mark button as visible
}
}
});
return button_visible; // Return whether the button is visible
}
// Function to check if the user has a specific role
function hasRole(roleName) {
return frappe.user.has_role(roleName);
}
// Hide specified DVD using jQuery
function hideTargetDiv(selector) {
const targetDiv = $(selector);
if (targetDiv.length) {
targetDiv.hide();
}
}
// Add processors to buttons
function attachHideEventHandlers(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.find('.btn-open-row').on('click', function() {
hideTargetDiv('span.row-actions');
hideTargetDiv('div.grid-footer-toolbar');
});
// A function to hide buttons in the table.
function hideGridButtons(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.find('.grid-add-row').hide();
gridWrapper.find('.grid-remove-rows').hide();
gridWrapper.find('.grid-row-check').closest('.row-check').hide();
}
// A function for general treatment
function processAll(frm) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
}
});
}
// A function to prevent "Ctrl + Down" in the table
function preventCtrlDownKey(frm) {
// Listening to the keydown event in the table
frm.fields_dict['timesheet_tool_details'].grid.wrapper.on('keydown', function(event) {
// Check if the user presses "Ctrl + Down"
if (event.ctrlKey && event.key === "ArrowDown") {
return false; // Preventing further treatment of the event
}
});
}
// 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) {
attachHideEventHandlers(frm);
hideGridButtons(frm);
preventCtrlDownKey(frm);
// Amendment of the filter for the staff field to bring only active staff with Salary Structure Assignment
frm.fields_dict['timesheet_tool_details'].grid.get_field('employee').get_query = function(doc, cdt, cdn) {
return {
query: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.get_active_employees_with_salary"
};
};
if (frm.doc.docstatus === 1) {
if (hasRole("Create Timesheet")) {
handleCreateTimesheetButton(frm);
}
if (hasRole("Submit Timesheet")) {
handleSubmitTimesheetButton(frm);
}
}
frm.set_query('project', () => {
let filters = {
company : frm.doc.company,
};
return {filters: filters};
});
},
get_employee(frm) {
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
frappe.call({
method: "get_all_employees",
doc: frm.doc,
args: { project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
}
}
});
},
project(frm) {
frappe.call({
method: "clear_timesheet_tool_details_table",
doc: frm.doc,
callback: function(response) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
}
});
},
});
// A function to handle the "Create Timesheet" button
function handleCreateTimesheetButton(frm) {
frappe.call({
method: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records",
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
frm.add_custom_button(__('Create Timesheet'), function() {
if (frm.is_dirty()) {
frappe.throw(__('You have unsaved changes in this form. Please save before you continue.'));
}
// Call function to create timesheets
createTimesheets(frm);
});
}
}
});
}
// Custom function to create Timesheets
function createTimesheets(frm) {
frappe.call({
method: "create_attendance",
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response && !response.exc) {
frm.reload_doc();
frappe.msgprint(__('Timesheet records have been created successfully.'));
}
}
});
}
// A function to handle the "Submit Timesheet" button
function handleSubmitTimesheetButton(frm) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
"approval_attendance",
"Submit Timesheet",
"Timesheet records have been approved successfully.",
"All records have already been approved."
);
}
// A function to handle buttons
function handle_button(frm, method, def, btn_label, success_msg, fail_msg) {
let button_visible = false;
frappe.call({
method: method,
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
if (response.message && response.message === "missing") {
frm.add_custom_button__(btn_label, function() {
if (frm.is_dirty()) {
frappe.throw(__("You have unsaved changes in this form. Please save before you continue."));
}
frappe.call({
method: def,
doc: frm.doc,
callback: function() {
frm.reload_doc();
frappe.msgprint(__(success_msg));
}
});
});
button_visible = true; // Mark button as visible
}
}
});
return button_visible; // Return whether the button is visible
}
// Function to check if the user has a specific role
function hasRole(roleName) {
return frappe.user.has_role(roleName);
}
// Hide specified DVD using jQuery
function hideTargetDiv(selector) {
const targetDiv = $(selector);
if (targetDiv.length) {
targetDiv.hide();
}
}
// Add processors to buttons
function attachHideEventHandlers(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.find('.btn-open-row').on('click', function() {
hideTargetDiv('span.row-actions');
hideTargetDiv('div.grid-footer-toolbar');
});
gridWrapper.find('.row-index').on('click', function() {
hideTargetDiv('span.row-actions');
hideTargetDiv('div.grid-footer-toolbar');
});
}
// A function to hide buttons in the table.
function hideGridButtons(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.find('.grid-add-row').hide();
gridWrapper.find('.grid-remove-rows').hide();
gridWrapper.find('.grid-row-check').closest('.row-check').hide();
}
// A function for general treatment
function processAll(frm) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
}
});
}
// A function to prevent "Ctrl + Down" in the table
function preventCtrlDownKey(frm) {
// Listening to the keydown event in the table
frm.fields_dict['timesheet_tool_details'].grid.wrapper.on('keydown', function(event) {
// Check if the user presses "Ctrl + Down"
if (event.ctrlKey && event.key === "ArrowDown") {
return false; // Preventing further treatment of the event
}
});
}
شرح التعديلات:
وظيفة createTimesheets:
أضفت دالة جديدة لتحسين منطق عملية إنشاء Timesheets، تقوم بإجراء عملية التحقق من وجود السجلات قبل إنشاء أي Timesheet.
تعديل handleCreateTimesheetButton:
عند النقر على زر "Create Timesheet"، يتم التحقق عن طريق createTimesheets، والتي تتأكد من عدم وجود سجلات وتقوم بإنشاء السجلات إذا لم تكن موجودة.
إضافة فحص إضافي:
يمكنك إضافة نفس المنطق لفحص الـ Additional Salary عن طريق توسيع الفحوصات والوظائف الخاصة بذلك إذا لزم الأمر.
ملاحظات إضافية:
تأكد من أن أسماء الحقول في get_query وfilter موجودة بدقة ولديها استعلامات صحيحة تتناسب مع الهيكل الخاص بقاعدة بياناتك.
قد تحتاج لتعديل بعض رسائل الخطأ أو النجاح لتناسب أسلوبك الخاص.
إذا كان لديك أي استفسارات أخرى أو تحتاج إلى مساعدة إضافية، فلا تتردد في السؤال!
def create_timesheet(doc, timesheet_tool_details, totalhours, from_time):
# Check for overlapping timesheets
if has_time_overlap(timesheet_tool_details.employee, from_time, calculate_to_time(from_time, totalhours), doc.day):
frappe.msgprint(_("Row {0}: From Time and To Time of {1} is overlapping.").format(timesheet_tool_details.employee, doc.name))
return
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,
"to_time": calculate_to_time(from_time, totalhours), # توضيح انتهاء الوقت
"project": doc.project,
}
timesheet.append("time_logs", child_time_logs)
timesheet.insert(ignore_permissions=True)
frappe.db.commit()
def calculate_to_time(from_time, totalhours):
# يجب تعديل هذه الدالة بناء على كيفية حساب الوقت النهائي
start_datetime = datetime.datetime.strptime(from_time, "%Y-%m-%d %H:%M:%S") # قالب التاريخ والوقت كإدخال
end_datetime = start_datetime + datetime.timedelta(hours=totalhours) # إضافة الساعات
return end_datetime.strftime("%Y-%m-%d %H:%M:%S") # عائد بصيغة التاريخ
كيف يعمل الكود:
دالة has_time_overlap:
تقوم بالتحقق من وجود أي سجلات Timesheet تتداخل مع الأوقات المحددة. إذا كانت هناك سجلات متداخلة، تعيد True.
تعديل create_timesheet:
إذا كانت الوظيفة has_time_overlap تُرجع True، سيقوم الكود بعرض رسالة الخطأ والرجوع.
دالة calculate_to_time:
تحسب وقت الانتهاء بناءً على وقت البدء وساعات العمل المحددة.
ملاحظات:
تأكد من إدخال توقيتات من نوع datetime والمتوافقة مع التنسيقات الصحيحة.
قد تحتاج إلى تعديل الاستعلام في دالة has_time_overlap ليتوافق مع تهيئة عملك الخاصة.
إذا كان لديك أي استفسارات أو تحتاج مزيدًا من المساعدة في تنفيذ هذه الأفكار، فلا تتردد في طرح المزيد من الأسئلة!
@frappe.whitelist()
def get_all_employees(self, project=None):
settings = get_settings()
default_activity = settings.dufault_activity
ratio_attendance = settings.ratio_attendance
self.clear_timesheet_tool_details_table()
# Fetch employees depending on the project
if project:
# Fetch employees from Project Team, ensure all conditions are met
employees = frappe.db.sql("""
SELECT DISTINCT
pt.employee AS name,
pt.employee_name,
ss.hour_rate AS hourly_rate,
ssa.salary_structure
FROM
`tabProject Team` pt
INNER JOIN
`tabSalary Structure Assignment` ssa ON pt.employee = ssa.employee
INNER JOIN
`tabSalary Structure` ss ON ssa.salary_structure = ss.name
WHERE
pt.parent = %s
AND pt.fetch_to_timesheet_tool = 1
AND ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
AND ss.docstatus = 1 -- Ensure only approved Salary Structure
AND ss.salary_slip_based_on_timesheet = 1 -- Ensure timesheet-based salary is required
""", (project,), as_dict=True)
if not employees:
frappe.throw(_("No employees found in the Project Team with a valid Salary Structure Assignment and salary slip based on timesheet for the selected project."))
else:
# Fetch active employees directly when no project is selected
employees = frappe.db.sql("""
SELECT DISTINCT
emp.name AS name,
emp.employee_name AS employee_name,
ss.hour_rate AS hourly_rate,
ssa.salary_structure
FROM
`tabEmployee` emp
INNER JOIN
`tabSalary Structure Assignment` ssa ON emp.name = ssa.employee
INNER JOIN
`tabSalary Structure` ss ON ssa.salary_structure = ss.name
WHERE
emp.status = 'Active'
AND ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
AND ss.docstatus = 1 -- Ensure only approved Salary Structure
AND ss.salary_slip_based_on_timesheet = 1 -- Ensure timesheet-based salary is required
""", as_dict=True)
# Append employees to the child table
for emp in employees:
self.append("timesheet_tool_details", {
"employee": emp.get('name'),
"employee_name": emp.get('employee_name'),
"hourly_rate": emp.get('hourly_rate'),
"attendance": default_activity,
"ratio_attendance": ratio_attendance,
"salary_structure":emp.get('salary_structure'),
})
# Return employees after fetching
return employees
@frappe.whitelist()
def create_attendance(self):
"""
A function to implement all accounts and create the required records.
"""
"""
Calculation of fields required in the timesheet_tool_details
"""
timesheet_count = 0
additional_salary_count = 0
settings = get_settings()
# 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:
totalhours = detail.hour * detail.ratio_attendance
create_timesheet(self,detail,totalhours,from_time)
timesheet_count += 1
# Additional Salary (Overtime H, Overtime N, Deduction)
if detail.over_time_h:
total_over_time_h = detail.over_time_h * settings.h_over_time
detail.total_payment = total_over_time_h * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_h, detail.total_payment)
additional_salary_count += 1
if detail.over_time_n:
total_over_time_n = detail.over_time_n * settings.n_over_time
detail.total_payment = total_over_time_n * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_n, detail.total_payment)
additional_salary_count += 1
if detail.deduction:
detail.total_payment = detail.deduction * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_deduction,detail.total_payment)
additional_salary_count += 1
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count,additional_salary_count))
@frappe.whitelist()
def approval_attendance(self):
"""Approves all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets()
self.approval_additional_salaries()
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been approved successfully."))
except Exception as e:
frappe.throw(_("An error occurred during approval: {0}").format(str(e)))
def approval_timesheets(self, cancel=False):
"""Shared logic for approving or canceling Timesheets."""
timesheet_list = frappe.get_all("Timesheet",
filters={
"timesheet_tool": self.name
},
)
record_num = 0
for timesheet in timesheet_list:
document = frappe.get_doc("Timesheet", timesheet.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
record_num += 1
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Timesheet {0} has been cancelled.").format(document.name))
frappe.msgprint(_("Timesheet {0} has been approved.").format(record_num))
def approval_additional_salaries(self, cancel=False):
"""Shared logic for approving or canceling Additional Salaries."""
additional_salary_list = frappe.get_all("Additional Salary",
filters={
"timesheet_tool": self.name
},
)
record_num = 0
for additional_salary in additional_salary_list:
document = frappe.get_doc("Additional Salary", additional_salary.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
record_num +=1
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Additional Salary {0} has been approved.").format(record_num))
def cancel_attendance(self):
"""Cancels all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets(cancel=True)
self.approval_additional_salaries(cancel=True)
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been cancelled successfully."))
except Exception as e:
frappe.throw(_("An error occurred during cancellation: {0}").format(str(e)))
def on_cancel(self):
# Cancel Timesheets and Additional Salaries when Timesheet Tool is cancelled.
self.cancel_attendance()
def on_submit(self):
self.check_future_day()
self.check_values_in_timesheet_tool_details()
self.check_zero_values_in_timesheet_tool_details()
self.check_over_time_values()
def before_save(self):
pass
def validate(self):
self.ensure_unique_employee()
self.check_limits_in_timesheet_tool_details()
def check_future_day(self):
settings = get_settings()
future_day = settings.future_day
today = datetime.date.today()
# Turn self.day from text to date object
try:
day_date = datetime.datetime.strptime(self.day, "%Y-%m-%d").date()
except ValueError:
frappe.throw(_("Invalid date format for day. Please use YYYY-MM-DD."))
# See if the settings allow future dates.
if not future_day and day_date > today:
frappe.throw(_("Company settings do not allow the establishment of a future date schedule"))
def check_zero_values_in_timesheet_tool_details(self):
"""Check for zero values in timesheet_tool_details and raise an error if found."""
error_rows = []
for idx, detail in enumerate(self.timesheet_tool_details):
# Check if hourly_rate, over_time_n, over_time_h and deduction are all zero
if detail.ratio_attendance != 0:
if detail.hour == 0 and detail.over_time_n == 0 and detail.over_time_h == 0 and detail.deduction == 0:
error_rows.append(idx + 1) # Save the row number (1-based index)
if error_rows:
error_message = _("The following rows have Hour, Over Time N, and Over Time H all equal to 0 in rows: {rows}").format(rows=" , ".join(map(str, error_rows)))
frappe.throw(error_message)
def check_values_in_timesheet_tool_details(self):
if not self.timesheet_tool_details:
frappe.throw(_("Cannot proceed: No records found in Timesheet Tool Details."))
def check_over_time_values(self):
"""Check that values over_time_n,over_time_h cannot be entered for the staff member on the same date."""
for idx, row in enumerate(self.timesheet_tool_details):
if row.over_time_n > 0 and row.over_time_h > 0:
employee_name = row.employee
frappe.throw(
_("Neither of the values Over Time N, Over Time H can be entered for employee {0} at row {1}.").format(employee_name, idx + 1)
)
def check_limits_in_timesheet_tool_details(self):
settings = get_settings()
max_n_over_time = settings.maximum_n_over_time
max_h_over_time = settings.maximum_h_over_time
max_deduction = settings.maximum_deduction
max_standard_working_hours = settings.maximum_standard_working_hours
for idx, detail in enumerate(self.timesheet_tool_details):
if detail.hour is not None and detail.hour > max_standard_working_hours:
frappe.throw(_(f"Row {idx + 1}: The value of 'Hour' cannot exceed the maximum standard working hours ({max_standard_working_hours})."))
if detail.over_time_n is not None and detail.over_time_n > max_n_over_time:
frappe.throw(_(f"Row {idx + 1}: The value of 'Over Time N' cannot exceed the maximum allowed overtime hours (normal) ({max_n_over_time})."))
if detail.over_time_h is not None and detail.over_time_h > max_h_over_time:
frappe.throw(_(f"Row {idx + 1}: The value of 'Over Time H' cannot exceed the maximum allowed overtime hours (holiday) ({max_h_over_time})."))
if detail.deduction is not None and detail.deduction > max_deduction:
frappe.throw(_(f"Row {idx + 1}: The value of 'Deduction' cannot exceed the maximum deduction allowed ({max_deduction})."))
def ensure_unique_employee(self):
"""
Check not to repeat the selection of the same employee in Timesheet Tool Details.
"""
timesheet_tool_details = [os.employee for os in self.timesheet_tool_details if os.employee]
if len(timesheet_tool_details) != len(set(timesheet_tool_details)):
frappe.throw(_("The same employee cannot be selected more than once."))
def create_timesheet(doc, timesheet_tool_details, totalhours, from_time):
# Check for overlapping timesheets
if has_time_overlap(timesheet_tool_details.employee, from_time, calculate_to_time(from_time, totalhours), doc.day):
frappe.msgprint(_("Row {0}: From Time and To Time of {1} is overlapping.").format(timesheet_tool_details.employee, doc.name))
return
def create_additional_salary(doc, employee, salary_component, amount):
# Verification of additional salary on the same date, staff member and salary component
if check_existing_additional_salary(doc, employee, doc.day, salary_component):
frappe.msgprint(_("An Additional Salary for employee {0} on {1} with component {2} already exists.").format(employee, doc.day, salary_component))
return
def check_existing_timesheet(doc, employee, date):
# Check the presence of Timesheet in the database
timesheet_exists = frappe.db.exists("Timesheet", {
"employee": employee,
"payroll_date": date
})
return timesheet_exists
def check_existing_additional_salary(doc, employee, date, salary_component):
# Verification of additional salary in the database
additional_salary_exists = frappe.db.exists("Additional Salary", {
"employee": employee,
"payroll_date": date,
"salary_component": salary_component
})
return additional_salary_exists
def has_time_overlap(employee, from_time, to_time, day):
# استرجاع جميع سجلات Timesheet للموظف لنفس التاريخ
overlapping_timesheets = frappe.db.sql("""
SELECT name FROM tabTimesheet
WHERE employee = %s
AND payroll_date = %s
AND (
(from_time < %s AND to_time > %s) OR
(from_time < %s AND to_time > %s) OR
(from_time = %s OR to_time = %s) -- إذا كان الوقت متطابق
)
""", (employee, day, to_time, from_time, from_time, to_time, from_time, to_time), as_dict=True)
code
return bool(overlapping_timesheets)
def calculate_to_time(from_time, totalhours):
# يجب تعديل هذه الدالة بناء على كيفية حساب الوقت النهائي
start_datetime = datetime.datetime.strptime(from_time, "%Y-%m-%d %H:%M:%S") # قالب التاريخ والوقت كإدخال
end_datetime = start_datetime + datetime.timedelta(hours=totalhours) # إضافة الساعات
return end_datetime.strftime("%Y-%m-%d %H:%M:%S") # عائد بصيغة التاريخ
def create_timesheet(doc, timesheet_tool_details, totalhours, from_time):
# Check for overlapping timesheets
if has_time_overlap(timesheet_tool_details.employee, from_time, calculate_to_time(from_time, totalhours), doc.day):
frappe.msgprint(_("Row {0}: From Time and To Time of {1} is overlapping.").format(timesheet_tool_details.employee, doc.name))
return
timesheet = frappe.get_doc({
"doctype": "Timesheet",
"timesheet_tool": doc.name,
"company": doc.company,
"parent_project": doc.project,
"employee": timesheet_tool_details.employee,
"time_logs": []
})
# Logging the details of time
child_time_logs = {
"activity_type": timesheet_tool_details.attendance,
"hours": totalhours,
"from_time": from_time,
"to_time": calculate_to_time(from_time, totalhours),
"project": doc.project,
}
timesheet.append("time_logs", child_time_logs)
timesheet.insert(ignore_permissions=True)
frappe.db.commit()
def create_additional_salary(doc, employee, salary_component, amount):
# Verification of additional salary on the same date, staff member and salary component
if check_existing_additional_salary(doc, employee, doc.day, salary_component):
frappe.msgprint(_("An Additional Salary for employee {0} on {1} with component {2} already exists.").format(employee, doc.day, salary_component))
return
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)
def check_existing_timesheet(doc, employee, date):
# Check the presence of Timesheet in the database
timesheet_exists = frappe.db.exists("Timesheet", {
"employee": employee,
"payroll_date": date
})
return timesheet_exists
def check_existing_additional_salary(doc, employee, date, salary_component):
# Verification of additional salary in the database
additional_salary_exists = frappe.db.exists("Additional Salary", {
"employee": employee,
"payroll_date": date,
"salary_component": salary_component
})
return additional_salary_exists
def has_time_overlap(employee, from_time, to_time, day):
# استرجاع جميع سجلات Timesheet للموظف لنفس التاريخ
overlapping_timesheets = frappe.db.sql("""
SELECT name FROM `tabTimesheet`
WHERE employee = %s
AND payroll_date = %s
AND (
(from_time < %s AND to_time > %s) OR
(from_time < %s AND to_time > %s) OR
(from_time = %s OR to_time = %s)
)
""", (employee, day, to_time, from_time, from_time, to_time, from_time, to_time), as_dict=True)
return bool(overlapping_timesheets)
def calculate_to_time(from_time, totalhours):
# يجب تعديل هذه الدالة بناء على كيفية حساب الوقت النهائي
start_datetime = datetime.datetime.strptime(from_time, "%Y-%m-%d %H:%M:%S")
end_datetime = start_datetime + datetime.timedelta(hours=totalhours)
return end_datetime.strftime("%Y-%m-%d %H:%M:%S")
النهاية:
هذا الكود يجب أن يوفر لك التحكم اللازم للتحقق من أي تقاطعات في الأوقات وضمان إنشاء Timesheets وAdditional Salaries بدون تداخل. إذا واجهت أي مشاكل أخرى أو تحتاج إلى المزيد من الأوضاع، فلا تتردد في التواصل.
def create_timesheet(doc, timesheet_tool_details, totalhours, from_time):
# Calculate the 'to_time' based on 'from_time' and totalhours
to_time = calculate_to_time(from_time, totalhours)
# Check for overlapping timesheets
if has_time_overlap(timesheet_tool_details.employee, from_time, to_time, doc.day):
frappe.msgprint(_("Row {0}: From Time and To Time of {1} is overlapping.").format(timesheet_tool_details.employee, doc.name))
return
timesheet = frappe.get_doc({
"doctype": "Timesheet",
"timesheet_tool": doc.name,
"company": doc.company,
"parent_project": doc.project,
"employee": timesheet_tool_details.employee,
"time_logs": []
})
# Setting up time logs with correct from_time and to_time
child_time_logs = {
"activity_type": timesheet_tool_details.attendance,
"hours": totalhours,
"from_time": from_time,
"to_time": to_time, # Correctly using the calculated to_time
"project": doc.project,
}
timesheet.append("time_logs", child_time_logs)
timesheet.insert(ignore_permissions=True)
frappe.db.commit()
def has_time_overlap(employee, from_time, to_time, day):
# Fetch existing timesheets for the same employee and date
overlapping_timesheets = frappe.db.sql("""
SELECT name FROM `tabTimesheet`
WHERE employee = %s
AND payroll_date = %s
AND (
(from_time < %s AND to_time > %s) OR
(from_time < %s AND to_time > %s) OR
(from_time = %s OR to_time = %s)
)
""", (employee, day, to_time, from_time, from_time, to_time, from_time, to_time), as_dict=True)
return bool(overlapping_timesheets)
كيفية المتابعة:
اختبر الكود: تأكد من إدخال سجلات جديدة باستخدام توقيتات لا تتعارض مع السجلات الموجودة.
تحليل الأخطاء: إذا استمرت المشكلة، يمكنك استخدام frappe.msgprint() لعرض الأوقات المُدخلة وأوقات السجلات المتعارضة حالما يتم اكتشافها.
نصائح حول تصحيح الأخطاء:
يمكنك تسليط الضوء على تفاصيل الأوقات المشكلة عند تسجيل الرسالة بحيث يمكنك معرفة الجذور بشكل أفضل:
python
frappe.msgprint(_("The following Timesheet records overlap: {0} and {1}").format(existing_timesheet_name, new_timesheet_name))
إذا كنت بحاجة إلى مزيد من المساعدة أو لديك أسئلة إضافية، فلا تتردد في طرحها!
@frappe.whitelist()
def get_all_employees(self, project=None):
settings = get_settings()
default_activity = settings.dufault_activity
ratio_attendance = settings.ratio_attendance
self.clear_timesheet_tool_details_table()
# Fetch employees depending on the project
if project:
# Fetch employees from Project Team, ensure all conditions are met
employees = frappe.db.sql("""
SELECT DISTINCT
pt.employee AS name,
pt.employee_name,
ss.hour_rate AS hourly_rate,
ssa.salary_structure
FROM
`tabProject Team` pt
INNER JOIN
`tabSalary Structure Assignment` ssa ON pt.employee = ssa.employee
INNER JOIN
`tabSalary Structure` ss ON ssa.salary_structure = ss.name
WHERE
pt.parent = %s
AND pt.fetch_to_timesheet_tool = 1
AND ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
AND ss.docstatus = 1 -- Ensure only approved Salary Structure
AND ss.salary_slip_based_on_timesheet = 1 -- Ensure timesheet-based salary is required
""", (project,), as_dict=True)
if not employees:
frappe.throw(_("No employees found in the Project Team with a valid Salary Structure Assignment and salary slip based on timesheet for the selected project."))
else:
# Fetch active employees directly when no project is selected
employees = frappe.db.sql("""
SELECT DISTINCT
emp.name AS name,
emp.employee_name AS employee_name,
ss.hour_rate AS hourly_rate,
ssa.salary_structure
FROM
`tabEmployee` emp
INNER JOIN
`tabSalary Structure Assignment` ssa ON emp.name = ssa.employee
INNER JOIN
`tabSalary Structure` ss ON ssa.salary_structure = ss.name
WHERE
emp.status = 'Active'
AND ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
AND ss.docstatus = 1 -- Ensure only approved Salary Structure
AND ss.salary_slip_based_on_timesheet = 1 -- Ensure timesheet-based salary is required
""", as_dict=True)
# Append employees to the child table
for emp in employees:
self.append("timesheet_tool_details", {
"employee": emp.get('name'),
"employee_name": emp.get('employee_name'),
"hourly_rate": emp.get('hourly_rate'),
"attendance": default_activity,
"ratio_attendance": ratio_attendance,
"salary_structure":emp.get('salary_structure'),
})
# Return employees after fetching
return employees
@frappe.whitelist()
def create_attendance(self):
"""
A function to implement all accounts and create the required records.
"""
"""
Calculation of fields required in the timesheet_tool_details
"""
timesheet_count = 0
additional_salary_count = 0
settings = get_settings()
# 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:
totalhours = detail.hour * detail.ratio_attendance
create_timesheet(self,detail,totalhours,from_time)
timesheet_count += 1
# Additional Salary (Overtime H, Overtime N, Deduction)
if detail.over_time_h:
total_over_time_h = detail.over_time_h * settings.h_over_time
detail.total_payment = total_over_time_h * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_h, detail.total_payment)
additional_salary_count += 1
if detail.over_time_n:
total_over_time_n = detail.over_time_n * settings.n_over_time
detail.total_payment = total_over_time_n * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_n, detail.total_payment)
additional_salary_count += 1
if detail.deduction:
detail.total_payment = detail.deduction * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_deduction,detail.total_payment)
additional_salary_count += 1
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count,additional_salary_count))
@frappe.whitelist()
def approval_attendance(self):
"""Approves all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets()
self.approval_additional_salaries()
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been approved successfully."))
except Exception as e:
frappe.throw(_("An error occurred during approval: {0}").format(str(e)))
def approval_timesheets(self, cancel=False):
"""Shared logic for approving or canceling Timesheets."""
timesheet_list = frappe.get_all("Timesheet",
filters={
"timesheet_tool": self.name
},
)
record_num = 0
for timesheet in timesheet_list:
document = frappe.get_doc("Timesheet", timesheet.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
record_num += 1
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Timesheet {0} has been cancelled.").format(document.name))
frappe.msgprint(_("Timesheet {0} has been approved.").format(record_num))
def approval_additional_salaries(self, cancel=False):
"""Shared logic for approving or canceling Additional Salaries."""
additional_salary_list = frappe.get_all("Additional Salary",
filters={
"timesheet_tool": self.name
},
)
record_num = 0
for additional_salary in additional_salary_list:
document = frappe.get_doc("Additional Salary", additional_salary.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
record_num +=1
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Additional Salary {0} has been approved.").format(record_num))
def cancel_attendance(self):
"""Cancels all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets(cancel=True)
self.approval_additional_salaries(cancel=True)
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been cancelled successfully."))
except Exception as e:
frappe.throw(_("An error occurred during cancellation: {0}").format(str(e)))
def on_cancel(self):
# Cancel Timesheets and Additional Salaries when Timesheet Tool is cancelled.
self.cancel_attendance()
def on_submit(self):
self.check_future_day()
self.check_values_in_timesheet_tool_details()
self.check_zero_values_in_timesheet_tool_details()
self.check_over_time_values()
def before_save(self):
pass
def validate(self):
self.ensure_unique_employee()
self.check_limits_in_timesheet_tool_details()
def check_future_day(self):
settings = get_settings()
future_day = settings.future_day
today = datetime.date.today()
# Turn self.day from text to date object
try:
day_date = datetime.datetime.strptime(self.day, "%Y-%m-%d").date()
except ValueError:
frappe.throw(_("Invalid date format for day. Please use YYYY-MM-DD."))
# See if the settings allow future dates.
if not future_day and day_date > today:
frappe.throw(_("Company settings do not allow the establishment of a future date schedule"))
def check_zero_values_in_timesheet_tool_details(self):
"""Check for zero values in timesheet_tool_details and raise an error if found."""
error_rows = []
for idx, detail in enumerate(self.timesheet_tool_details):
# Check if hourly_rate, over_time_n, over_time_h and deduction are all zero
if detail.ratio_attendance != 0:
if detail.hour == 0 and detail.over_time_n == 0 and detail.over_time_h == 0 and detail.deduction == 0:
error_rows.append(idx + 1) # Save the row number (1-based index)
if error_rows:
error_message = _("The following rows have Hour, Over Time N, and Over Time H all equal to 0 in rows: {rows}").format(rows=" , ".join(map(str, error_rows)))
frappe.throw(error_message)
def check_values_in_timesheet_tool_details(self):
if not self.timesheet_tool_details:
frappe.throw(_("Cannot proceed: No records found in Timesheet Tool Details."))
def check_over_time_values(self):
"""Check that values over_time_n,over_time_h cannot be entered for the staff member on the same date."""
for idx, row in enumerate(self.timesheet_tool_details):
if row.over_time_n > 0 and row.over_time_h > 0:
employee_name = row.employee
frappe.throw(
_("Neither of the values Over Time N, Over Time H can be entered for employee {0} at row {1}.").format(employee_name, idx + 1)
)
def check_limits_in_timesheet_tool_details(self):
settings = get_settings()
max_n_over_time = settings.maximum_n_over_time
max_h_over_time = settings.maximum_h_over_time
max_deduction = settings.maximum_deduction
max_standard_working_hours = settings.maximum_standard_working_hours
for idx, detail in enumerate(self.timesheet_tool_details):
if detail.hour is not None and detail.hour > max_standard_working_hours:
frappe.throw(_(f"Row {idx + 1}: The value of 'Hour' cannot exceed the maximum standard working hours ({max_standard_working_hours})."))
if detail.over_time_n is not None and detail.over_time_n > max_n_over_time:
frappe.throw(_(f"Row {idx + 1}: The value of 'Over Time N' cannot exceed the maximum allowed overtime hours (normal) ({max_n_over_time})."))
if detail.over_time_h is not None and detail.over_time_h > max_h_over_time:
frappe.throw(_(f"Row {idx + 1}: The value of 'Over Time H' cannot exceed the maximum allowed overtime hours (holiday) ({max_h_over_time})."))
if detail.deduction is not None and detail.deduction > max_deduction:
frappe.throw(_(f"Row {idx + 1}: The value of 'Deduction' cannot exceed the maximum deduction allowed ({max_deduction})."))
def ensure_unique_employee(self):
"""
Check not to repeat the selection of the same employee in Timesheet Tool Details.
"""
timesheet_tool_details = [os.employee for os in self.timesheet_tool_details if os.employee]
if len(timesheet_tool_details) != len(set(timesheet_tool_details)):
frappe.throw(_("The same employee cannot be selected more than once."))
def create_timesheet(doc, timesheet_tool_details, totalhours, from_time):
# Check for overlapping timesheets
if has_time_overlap(timesheet_tool_details.employee, from_time, calculate_to_time(from_time, totalhours), doc.day):
frappe.msgprint(_("Row {0}: From Time and To Time of {1} is overlapping.").format(timesheet_tool_details.employee, doc.name))
return
def create_additional_salary(doc, employee, salary_component, amount):
# Verification of additional salary on the same date, staff member and salary component
if check_existing_additional_salary(doc, employee, doc.day, salary_component):
frappe.msgprint(_("An Additional Salary for employee {0} on {1} with component {2} already exists.").format(employee, doc.day, salary_component))
return
def check_existing_timesheet(doc, employee, date):
# Check the presence of Timesheet in the database
timesheet_exists = frappe.db.exists("Timesheet", {
"employee": employee,
"start_date": date
})
return timesheet_exists
def check_existing_additional_salary(doc, employee, date, salary_component):
# Verification of additional salary in the database
additional_salary_exists = frappe.db.exists("Additional Salary", {
"employee": employee,
"payroll_date": date,
"salary_component": salary_component
})
return additional_salary_exists
def has_time_overlap(employee, from_time, to_time, day):
# Retrieval of all Timesheet records of the employee for the same date
overlapping_timesheets = frappe.db.sql("""
SELECT name FROM tabTimesheet
WHERE employee = %s
AND start_date = %s
AND (
(start_date < %s AND end_date > %s) OR
(start_date < %s AND end_date > %s) OR
(start_date = %s OR end_date = %s)
)
""", (employee, day, to_time, from_time, from_time, to_time, from_time, to_time), as_dict=True)
code
if overlapping_timesheets:
# إذا كان هناك سجلات متداخلة، يظهر رسالة تفاصيلها
existing_timesheet_names = ", ".join([ts['name'] for ts in overlapping_timesheets])
new_timesheet_name = "New Timesheet" # قم بتغيير هذا ليحمل اسم السجل الجديد إذا كان لديك
frappe.msgprint(_("The following Timesheet records overlap: {0} and {1}").format(existing_timesheet_names, new_timesheet_name))
return bool(overlapping_timesheets)
قبل محاولة إدخال سجل جديد، تأكد من أنه لا توجد سجلات متداخلة في قاعدة البيانات. إذا وجدت تواريخ أو أوقات متداخلة، يجب عليك اتخاذ إجراء:
إما المفروض تعديل السجل السابق (إن كان ذلك مناسباً)
أو عرض رسالة تشير إلى أنك بحاجة إلى تعديل المدخلات.
5. تحسين الجلسات
تأكد من أن الحل دائمًا يعيد الكائن المناسب ويقوم بإدارة الأخطاء بشكل جيد.
مثال على كيفية استخدام هذه الدالة في مكان إدخال السجل:
عند إدخال Timesheet جديدة:
python
# الحالة المعتادة لإدخال سجل Timesheet
if create_timesheet(self, detail, totalhours, from_time):
timesheet_count += 1 # إذا أنشئت Successfully
ملخص
إذا استمرت المشكلة بعد الفحص، يمكنك استخدام frappe.msgprint لتتبع خطأ يتم التحقق منه عن طريق طباعته مع توقيتات السجلات المتداخلة. تأكد من مراجعة توقيتات كل سجل في قاعدة البيانات قبل إدخال سجل جديد.
إذا كانت لديك أي المزيد من الأسئلة، لا تتردد في طرحها!
def create_timesheet(doc, timesheet_tool_details, totalhours, from_time):
# حساب الوقت النهائي
to_time = calculate_to_time(from_time, totalhours)
# Check for overlapping timesheets
if has_time_overlap(timesheet_tool_details.employee, from_time, to_time, doc.day):
return # تم طباعة الرسالة داخل الدالة
# إنشاء التسجيل الجديد خالية من الأخطاء
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,
"to_time": to_time, # استخدم الوقت المحسوب
"project": doc.project,
}
timesheet.append("time_logs", child_time_logs)
timesheet.insert(ignore_permissions=True)
frappe.db.commit()
4. استخدام الأعمدة الصحيحة
تأكد من استخدام الأعمدة الصحيحة في كل مكان في الكود الخاص بك. لذا تأكد من تحديث جميع أجزاء الكود حيث يتم استخدام وسوم payroll_date، from_time، وto_time.
5. متابعة الأخطاء
إذا استمرت الرسالة بعد هذه التغييرات، تأكد من اختبار الكود بشكل جيد، وإذا حصل خطأ، يمكنك استخدام دالة frappe.msgprint لتتبع الأخطاء ومعرفة تفاصيل القيم المدخلة.
إذا كانت لديك أي أسئلة أو تحتاج لمزيد من التوضيحات، لا تتردد في طرحها!
@frappe.whitelist()
def get_all_employees(self, project=None):
settings = get_settings()
default_activity = settings.dufault_activity
ratio_attendance = settings.ratio_attendance
self.clear_timesheet_tool_details_table()
# Fetch employees depending on the project
if project:
# Fetch employees from Project Team, ensure all conditions are met
employees = frappe.db.sql("""
SELECT DISTINCT
pt.employee AS name,
pt.employee_name,
ss.hour_rate AS hourly_rate,
ssa.salary_structure
FROM
`tabProject Team` pt
INNER JOIN
`tabSalary Structure Assignment` ssa ON pt.employee = ssa.employee
INNER JOIN
`tabSalary Structure` ss ON ssa.salary_structure = ss.name
WHERE
pt.parent = %s
AND pt.fetch_to_timesheet_tool = 1
AND ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
AND ss.docstatus = 1 -- Ensure only approved Salary Structure
AND ss.salary_slip_based_on_timesheet = 1 -- Ensure timesheet-based salary is required
""", (project,), as_dict=True)
if not employees:
frappe.throw(_("No employees found in the Project Team with a valid Salary Structure Assignment and salary slip based on timesheet for the selected project."))
else:
# Fetch active employees directly when no project is selected
employees = frappe.db.sql("""
SELECT DISTINCT
emp.name AS name,
emp.employee_name AS employee_name,
ss.hour_rate AS hourly_rate,
ssa.salary_structure
FROM
`tabEmployee` emp
INNER JOIN
`tabSalary Structure Assignment` ssa ON emp.name = ssa.employee
INNER JOIN
`tabSalary Structure` ss ON ssa.salary_structure = ss.name
WHERE
emp.status = 'Active'
AND ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
AND ss.docstatus = 1 -- Ensure only approved Salary Structure
AND ss.salary_slip_based_on_timesheet = 1 -- Ensure timesheet-based salary is required
""", as_dict=True)
# Append employees to the child table
for emp in employees:
self.append("timesheet_tool_details", {
"employee": emp.get('name'),
"employee_name": emp.get('employee_name'),
"hourly_rate": emp.get('hourly_rate'),
"attendance": default_activity,
"ratio_attendance": ratio_attendance,
"salary_structure":emp.get('salary_structure'),
})
# Return employees after fetching
return employees
@frappe.whitelist()
def create_attendance(self):
"""
A function to implement all accounts and create the required records.
"""
"""
Calculation of fields required in the timesheet_tool_details
"""
timesheet_count = 0
additional_salary_count = 0
settings = get_settings()
# 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:
totalhours = detail.hour * detail.ratio_attendance
create_timesheet(self,detail,totalhours,from_time)
timesheet_count += 1
# Additional Salary (Overtime H, Overtime N, Deduction)
if detail.over_time_h:
total_over_time_h = detail.over_time_h * settings.h_over_time
detail.total_payment = total_over_time_h * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_h, detail.total_payment)
additional_salary_count += 1
if detail.over_time_n:
total_over_time_n = detail.over_time_n * settings.n_over_time
detail.total_payment = total_over_time_n * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_n, detail.total_payment)
additional_salary_count += 1
if detail.deduction:
detail.total_payment = detail.deduction * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_deduction,detail.total_payment)
additional_salary_count += 1
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count,additional_salary_count))
@frappe.whitelist()
def approval_attendance(self):
"""Approves all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets()
self.approval_additional_salaries()
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been approved successfully."))
except Exception as e:
frappe.throw(_("An error occurred during approval: {0}").format(str(e)))
def approval_timesheets(self, cancel=False):
"""Shared logic for approving or canceling Timesheets."""
timesheet_list = frappe.get_all("Timesheet",
filters={
"timesheet_tool": self.name
},
)
record_num = 0
for timesheet in timesheet_list:
document = frappe.get_doc("Timesheet", timesheet.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
record_num += 1
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Timesheet {0} has been cancelled.").format(document.name))
frappe.msgprint(_("Timesheet {0} has been approved.").format(record_num))
def approval_additional_salaries(self, cancel=False):
"""Shared logic for approving or canceling Additional Salaries."""
additional_salary_list = frappe.get_all("Additional Salary",
filters={
"timesheet_tool": self.name
},
)
record_num = 0
for additional_salary in additional_salary_list:
document = frappe.get_doc("Additional Salary", additional_salary.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
record_num +=1
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Additional Salary {0} has been approved.").format(record_num))
def cancel_attendance(self):
"""Cancels all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets(cancel=True)
self.approval_additional_salaries(cancel=True)
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been cancelled successfully."))
except Exception as e:
frappe.throw(_("An error occurred during cancellation: {0}").format(str(e)))
def on_cancel(self):
# Cancel Timesheets and Additional Salaries when Timesheet Tool is cancelled.
self.cancel_attendance()
def on_submit(self):
self.check_future_day()
self.check_values_in_timesheet_tool_details()
self.check_zero_values_in_timesheet_tool_details()
self.check_over_time_values()
def before_save(self):
pass
def validate(self):
self.ensure_unique_employee()
self.check_limits_in_timesheet_tool_details()
def check_future_day(self):
settings = get_settings()
future_day = settings.future_day
today = datetime.date.today()
# Turn self.day from text to date object
try:
day_date = datetime.datetime.strptime(self.day, "%Y-%m-%d").date()
except ValueError:
frappe.throw(_("Invalid date format for day. Please use YYYY-MM-DD."))
# See if the settings allow future dates.
if not future_day and day_date > today:
frappe.throw(_("Company settings do not allow the establishment of a future date schedule"))
def check_zero_values_in_timesheet_tool_details(self):
"""Check for zero values in timesheet_tool_details and raise an error if found."""
error_rows = []
for idx, detail in enumerate(self.timesheet_tool_details):
# Check if hourly_rate, over_time_n, over_time_h and deduction are all zero
if detail.ratio_attendance != 0:
if detail.hour == 0 and detail.over_time_n == 0 and detail.over_time_h == 0 and detail.deduction == 0:
error_rows.append(idx + 1) # Save the row number (1-based index)
if error_rows:
error_message = _("The following rows have Hour, Over Time N, and Over Time H all equal to 0 in rows: {rows}").format(rows=" , ".join(map(str, error_rows)))
frappe.throw(error_message)
def check_values_in_timesheet_tool_details(self):
if not self.timesheet_tool_details:
frappe.throw(_("Cannot proceed: No records found in Timesheet Tool Details."))
def check_over_time_values(self):
"""Check that values over_time_n,over_time_h cannot be entered for the staff member on the same date."""
for idx, row in enumerate(self.timesheet_tool_details):
if row.over_time_n > 0 and row.over_time_h > 0:
employee_name = row.employee
frappe.throw(
_("Neither of the values Over Time N, Over Time H can be entered for employee {0} at row {1}.").format(employee_name, idx + 1)
)
def check_limits_in_timesheet_tool_details(self):
settings = get_settings()
max_n_over_time = settings.maximum_n_over_time
max_h_over_time = settings.maximum_h_over_time
max_deduction = settings.maximum_deduction
max_standard_working_hours = settings.maximum_standard_working_hours
for idx, detail in enumerate(self.timesheet_tool_details):
if detail.hour is not None and detail.hour > max_standard_working_hours:
frappe.throw(_(f"Row {idx + 1}: The value of 'Hour' cannot exceed the maximum standard working hours ({max_standard_working_hours})."))
if detail.over_time_n is not None and detail.over_time_n > max_n_over_time:
frappe.throw(_(f"Row {idx + 1}: The value of 'Over Time N' cannot exceed the maximum allowed overtime hours (normal) ({max_n_over_time})."))
if detail.over_time_h is not None and detail.over_time_h > max_h_over_time:
frappe.throw(_(f"Row {idx + 1}: The value of 'Over Time H' cannot exceed the maximum allowed overtime hours (holiday) ({max_h_over_time})."))
if detail.deduction is not None and detail.deduction > max_deduction:
frappe.throw(_(f"Row {idx + 1}: The value of 'Deduction' cannot exceed the maximum deduction allowed ({max_deduction})."))
def ensure_unique_employee(self):
"""
Check not to repeat the selection of the same employee in Timesheet Tool Details.
"""
timesheet_tool_details = [os.employee for os in self.timesheet_tool_details if os.employee]
if len(timesheet_tool_details) != len(set(timesheet_tool_details)):
frappe.throw(_("The same employee cannot be selected more than once."))
def create_timesheet(doc, timesheet_tool_details, totalhours, from_time):
# حساب الوقت النهائي
to_time = calculate_to_time(from_time, totalhours)
code
# Check for overlapping timesheets
if has_time_overlap(timesheet_tool_details.employee, from_time, to_time, doc.day):
return # تم طباعة الرسالة داخل الدالة
# إنشاء التسجيل الجديد خالية من الأخطاء
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,
"to_time": to_time, # استخدم الوقت المحسوب
"project": doc.project,
}
timesheet.append("time_logs", child_time_logs)
timesheet.insert(ignore_permissions=True)
frappe.db.commit()
def create_additional_salary(doc, employee, salary_component, amount):
# Verification of additional salary on the same date, staff member and salary component
if check_existing_additional_salary(doc, employee, doc.day, salary_component):
frappe.msgprint(_("An Additional Salary for employee {0} on {1} with component {2} already exists.").format(employee, doc.day, salary_component))
return
def check_existing_timesheet(doc, employee, date):
# Check the presence of Timesheet in the database
timesheet_exists = frappe.db.exists("Timesheet", {
"employee": employee,
"start_date": date
})
return timesheet_exists
def check_existing_additional_salary(doc, employee, date, salary_component):
# Verification of additional salary in the database
additional_salary_exists = frappe.db.exists("Additional Salary", {
"employee": employee,
"payroll_date": date,
"salary_component": salary_component
})
return additional_salary_exists
def has_time_overlap(employee, from_time, to_time, date):
overlapping_timesheets = frappe.db.sql("""
SELECT name FROM tabTimesheet
WHERE employee = %s
AND start_date = %s
AND (
(start_date < %s AND end_date > %s) OR
(start_date < %s AND end_date > %s) OR
(start_date = %s OR end_date = %s)
)
""", (employee, date, to_time, from_time, from_time, to_time, from_time, to_time), as_dict=True)
code
if overlapping_timesheets:
existing_timesheet_names = ", ".join([ts['name'] for ts in overlapping_timesheets])
new_timesheet_name = "New Timesheet" # يمكنك تخصيص هذا ليعكس اسم السجل الجديد.
frappe.msgprint(_("The following Timesheet records overlap: {0} and {1}").format(existing_timesheet_names, new_timesheet_name))
return bool(overlapping_timesheets)
عدل الكود ليستخدم start_date و end_date في قاعدة البيانات بشكل مناسب:
python
def has_time_overlap(employee, from_time, to_time, date):
overlapping_timesheets = frappe.db.sql("""
SELECT name FROM `tabTimesheet`
WHERE employee = %s
AND start_date = %s
AND (
(start_date < %s AND end_date > %s) OR
(start_date < %s AND end_date > %s) OR
(start_date = %s OR end_date = %s)
)
""", (employee, date, to_time, from_time, from_time, to_time, from_time, to_time), as_dict=True)
if overlapping_timesheets:
existing_timesheet_names = ", ".join([ts['name'] for ts in overlapping_timesheets])
new_timesheet_name = "New Timesheet" # قم بتحديثه حسب الحاجة
frappe.msgprint(_("The following Timesheet records overlap: {0} and {1}").format(existing_timesheet_names, new_timesheet_name))
return bool(overlapping_timesheets)
تحقق من قاعدة البيانات: تأكد من سلامة البيانات المدخلة في قاعدة البيانات وعدم وجود سجلات قديمة أو خاطئة تؤدي إلى تداخل.
الملخص:
بهذه التعديلات، يتوجب أن تعمل منطق التحقق من التداخل بشكل فعال وتقوم بإخطار المستخدم في حال حدوث تداخل. إذا واجهت أي مشاكل أو تحتاج لمزيد من المساعدة، فلا تتردد في طرح المزيد من الأسئلة!
كيف يمكن التعامل مع هذه المشكلة؟
تعديل السجل: إذا كان المدخل الجديد يتداخل مع سجل موجود، يمكنك تعديل توقيت الإدخال الجديد لجعله ضمن الأمن المقبول.
إزالة السجل القديم: إذا لم يكن السجل القديم ضروريًا، يمكنك إزالته من قاعدة البيانات.
تعديل البيانات: تأكد من أن التاريخ والأوقات يتم إدخالها بشكل منطقي وبدون تداخل.
استجابة العمل:
قم بتطبيق التغييرات، ثم اختبر إدخال علامات جديدة. إذا ظهرت الرسالة مرة أخرى، يمكنك استخدام استعلامات SQL للتحقق من الأوقات في السجلات الموجودة. هذه العملية ستساعدك في فحص الأخطاء بشكل فعال.
إذا احتجت إلى المزيد من المساعدة أو لديك استفسارات إضافية، فلا تتردد في التواصل.