لدي ملف باسم timesheet_tool.py ولذي سوف ارسل لك محتواه ولدي دالىه باسم check_missing_records موجوده في المسار التالي time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records واريد ان اقوم باستدعائها في ملف timesheet_tool.py
Assistant
لجلب الدالة check_missing_records الموجودة في المسار الذي حددته داخل ملف timesheet_tool.py، تحتاج إلى استخدام استيراد الدالة بناءً على المسار الكامل.
إليك كيفية القيام بذلك:
الخطوات:
تأكد من أن الهيكل الأساسي لمجلد المشروع قد تم إعداده بالشكل الصحيح. يجب أن تكون كل المجلدات التي تحتوي على الأكواد Python Packages (أي أن تحتوي على ملف __init__.py).
استخدم عملية الاستيراد المباشر للدالة من المسار الكامل.
الكود:
افترض أن الملف timesheet_tool.py يحتوي على هذا المجلد الأساسي:
plaintext
User
Assistant
لفهم متطلباتك، لديك ملف timesheet_tool.py يحتوي على الكود الذي أرسلته، وترغب في استدعاء دالة الموجودة في مسار:
داخل الملف timesheet_tool.py في أعلى المشروع (كما قلت):
استدعِ الدالة بهذه الطريقة:
python
from time_sheet_tool.time_sheet_tool.utils.timesheet_tool import check_missing_records
# استخدام الدالة هنا
missing_records = check_missing_records()
ملاحظات:
تأكد من أن __init__.py موجود في كل المجلدات (قد تكون الملفات فارغة)، فهذا يجعل المجلد Package ويضمن القدرة على استيراد المحتويات.
إذا كنت تنفّذ المشروع من الدليل الجذر (مثلًا باستخدام python timesheet_tool.py)، فإن مسار الاستيراد أعلاه سيعمل كما هو. إذا كنت تستخدم تقسيمًا معقدًا للتنفيذ، استخدم مسارات مطلقة أو تأكد من إضافة الجذور إلى متغير البيئة PYTHONPATH.
افترضت أن الدالة check_missing_records يمكن استدعاؤها دون معاملات أو مع مدخلات تقوم بتحديدها حسب الحاجة.
إذا احتجت إلى توضيحات أكثر حول هيكلة المشروع أو استدعاء الدوال، فقط اخبرني! 😊
#
# 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 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
@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."""
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
},
)
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 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."""
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):
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,
"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 = 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) ```
إليك كيفية تعديل ملف timesheet_tool.py لاستدعاء دالة check_missing_records بشكل صحيح:
الخطوات لتعديل الكود:
استخدام طريقة الاستيراد:
أضف السطر المطلوب لاستيراد check_missing_records في بداية ملف timesheet_tool.py.
استدعاء الدالة:
استخدم تجريد الدالة (function call) في المكان المطلوب داخل ملف timesheet_tool.py.
التعديل المقترح لـ timesheet_tool.py:
أضف السطر التالي (في بداية الملف أو قسم مناسب للاستيراد):
python
from time_sheet_tool.time_sheet_tool.utils.timesheet_tool import check_missing_records
ثم استخدم الدالة check_missing_records في أي مكان ضمن كودك بهذه الطريقة:
python
# مثال على كيفية استدعاء الدالة check_missing_records
missing_records = check_missing_records()
# إذا كانت الدالة تحتاج إلى وسيطات، قم بإضافتها حسب وظيفتها.
مكان الإدراج بناءً على الكود الحالي:
أضف السطر في ملف timesheet_tool.py كاملاً في الجزء الخاص بالاستيراد (على سبيل المثال بعد استيرادات frappe والمكتبات الأخرى):
python
# Import الدوال والوظائف من utils.timesheet_tool
from time_sheet_tool.time_sheet_tool.utils.timesheet_tool import check_missing_records
ثم قم باستدعاء الدالة check_missing_records حسب الحاجة، على سبيل المثال ضمن الدالة validate:
python
def validate(self):
self.ensure_unique_employee()
# استدعاء check_missing_records هنا
missing_records = check_missing_records()
print(f"Missing Records: {missing_records}") # طباعة أو التعامل معها حسب الحاجة
ملاحظات:
إذا كانت الدالة check_missing_records تحتاج إلى معلمات مدخلة (arguments)، تحقق من ذلك وأرسل القيم لها عند الاستدعاء.
تأكد من أن مسار الملف وهيكل المشروع متوافقين مع عملية الاستيراد من Python (أي وجود __init__.py إذا كان المجلد عبارة عن حزمة Python).
أين يتم تنفيذ الملف؟:
إذا كان الملف timesheet_tool.py هو نقطة البداية (أي يجري تشغيله باستخدام python timesheet_tool.py)، فإن هذا المسار سيعمل بشكل صحيح طالما البنية صحيحة.
في حال واجهت مشاكل في الاستيراد، تحقق من إعدادات بيئة Python (PYTHONPATH) أو افحص المسار المطلق.
يمكنك اختبار الدالة check_missing_records بشكل منفصل أولًا للتأكد من عملها واستلام المخرجات الصحيحة.
إذا كنت بحاجة إلى المزيد من المساعدة، فقط أخبرني! 🎉