بالطبع، سأقوم بإعادة كتابة كود timesheet_tool.py مع التعديلات اللازمة للإبلاغ عن عدد سجلات "Timesheets" و"Additional Salaries" التي تم إنشاؤها، وكذلك كود timesheet_tool.js بعد التحديثات اللازمة.
الكود المعدل لـ timesheet_tool.py
# 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", [])
@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:
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
AND ss.docstatus = 1
AND ss.salary_slip_based_on_timesheet = 1
""", (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:
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
AND ss.docstatus = 1
AND ss.salary_slip_based_on_timesheet = 1
""", 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
@frappe.whitelist()
def create_attendance(self):
"""
A function to implement all accounts and create the required records.
"""
timesheet_count = 0
additional_salary_count = 0
self.calculate_details()
for detail in self.timesheet_tool_details:
if detail.hour:
totalhours = detail.hour * detail.ratio_attendance
create_timesheet(self, detail, totalhours, f"{self.day} {get_settings().from_time}")
timesheet_count += 1
if detail.over_time_h:
total_over_time_h = detail.over_time_h * get_settings().h_over_time
detail.total_payment = total_over_time_h * detail.hourly_rate
create_additional_salary(self, detail.employee, get_settings().salary_component_overtime_h, detail.total_payment)
additional_salary_count += 1
if detail.over_time_n:
total_over_time_n = detail.over_time_n * get_settings().n_over_time
detail.total_payment = total_over_time_n * detail.hourly_rate
create_additional_salary(self, detail.employee, get_settings().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, get_settings().salary_component_deduction, detail.total_payment)
additional_salary_count += 1
# Return counts to the frontend
return {
"created_timesheets": timesheet_count,
"created_additional_salaries": additional_salary_count
}
@frappe.whitelist()
def approval_attendance(self):
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 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.js
// 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" 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);
}
});
},
});
// 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",
"create_timesheet_message", // Use a key for the message
"All records have already been created."
).then(showCreateButton => {
if (showCreateButton) {
frm.remove_custom_button("Submit Timesheet");
}
});
}
// 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_key, 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(createResponse) {
// Display message based on the number of records created
const { created_timesheets, created_additional_salaries } = createResponse.message;
if (created_timesheets || created_additional_salaries) {
frappe.msgprint(__("Created {0} Timesheets and {1} Additional Salaries.").format(
created_timesheets || 0,
created_additional_salaries || 0
));
} else {
frappe.msgprint(__(fail_msg));
}
frm.reload_doc();
}
});
});
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
}
});
}
النقاط الرئيسية التي تمت تغطيتها في التعديلات
-
إرجاع عدد السجلات: تم تعديل دالة create_attendance لتعيد عدد سجلات "Timesheets" و"Additional Salaries" التي تم إنشاؤها.
-
تحديث JavaScript: تم تعديل دالة handle_button لتعرض العدد الفعلي للسجلات التي تم إنشاؤها عند نجاح العملية.
-
رسائل المستخدم: تم تحسين الرسائل المنبثقة لتكون أكثر وضوحًا حول ما تم تحقيقه عند إنشاء السجلات.
بهذا الشكل، يتم تعزيز تجربة المستخدم بتوفير معلومات دقيقة حول الإجراءات التي تمت.
إذا كان لديك أي استفسارات أو تحتاج إلى المزيد من التعديلات، فلا تتردد في طرح ذلك!