// Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
// For license information, please see license.txt
// timesheet_tool.js
let settings = {};
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
// Amendment of the filter for the staff field to bring only active staff with Salary Structure Assignment
frm.fields_dict['timesheet_tool_details'].grid.get_field('employee').get_query = function(doc, cdt, cdn) {
return {
query: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.get_active_employees_with_salary"
};
};
code
Assistant
User
اريد ان يتم اخفاء الزر Approval Timesheet عندما يكون الزر Create Timesheet ظاهر
Assistant
// Fetch settings and dynamically update mandatory fields
frappe.call({
method: "fetch_settings_and_update_mandatory",
doc: frm.doc,
callback: function(response) {
if (response.message) {
settings = response.message;
frm.toggle_reqd("project", settings.is_project_mandatory);
frm.toggle_reqd("company", settings.is_company_mandatory);
}
}
});
// Management of the "Create Attendance" button
if (frm.doc.docstatus === 1) {
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."
);
}
// Management "Approval Attendance"
if (frm.doc.docstatus === 1) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
"approval_attendance",
"Approval Timesheet",
"Timesheet records have been approved successfully.",
"All records have already been approved."
);
}
},
// "Get Employmentee" button to get employees based on the project
get_employee(frm) {
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
frappe.call({
method: "get_all_employees",
doc: frm.doc,
args: { project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
frappe.msgprint(__('Employees have been fetched successfully.'));
}
}
});
},
// Update the fields when adjusting the Table "Timesheet Tool Details"
timesheet_tool_details: {
hour(frm, cdt, cdn) {
let row = frappe.get_doc(cdt, cdn);
row.total_working_hours = row.hour * row.ratio_attendance;
frm.refresh_field("timesheet_tool_details");
},
over_time_h(frm, cdt, cdn) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
}
});
},
over_time_n(frm, cdt, cdn) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
}
});
},
deduction(frm, cdt, cdn) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
}
});
}
}
});
function handle_button(frm, method,def, btn_label, success_msg, fail_msg) {
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));
}
});
});
} else {
frm.add_custom_button((btn_label), function() {
frappe.throw(__(fail_msg));
}).prop("disabled", true);
}
}
});
}
The script provided is a custom Frappe form script written in JavaScript for the "Timesheet Tool" form. It includes various functionalities related to managing timesheets, including handling custom workflows, fetching employees, calculating working hours, and managing attendance approval and creation. Below is an analysis of its structure and functionality:
Fetch and Dynamically Update Mandatory Field Requirements:
Settings are fetched from the back end, and based on the response, fields in the form (project, company) are toggled as mandatory using the toggle_reqd method.
Handle Custom Buttons:
Buttons for "Create Attendance" and "Approval Attendance" are conditionally displayed and managed if the document is submitted (docstatus === 1). These buttons rely on the handle_button utility function described later.
2. Custom Button: "Get Employees"
javascript
get_employee(frm) {
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
frappe.call({
method: "get_all_employees",
doc: frm.doc,
args: { project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
frappe.msgprint(__('Employees have been fetched successfully.'));
}
}
});
},
This function allows users to load employees associated with a project.
If the project field is mandatory (validated via settings), users will be prompted to select a project before fetching employees.
After fetching employees, the timesheet_tool_details table is refreshed, and a success message is displayed.
3. Update Events in Child Table: timesheet_tool_details
The code contains multiple triggers for specific child table fields (such as hour, over_time_h, over_time_n, deduction) to perform calculations or call backend utilities.
The hour field triggers the calculation: total_working_hours = hour * ratio_attendance.
Backend Calls Triggered on Overtime and Deductions:
Other fields (over_time_h, over_time_n, deduction) trigger a backend method (process_all), which is likely processing other updates. After processing, the relevant table field is refreshed.
4. Utility Function: handle_button
javascript
function handle_button(frm, method, def, btn_label, success_msg, fail_msg) {
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));
}
});
});
} else {
frm.add_custom_button(__(btn_label), function() {
frappe.throw(__(fail_msg));
}).prop("disabled", true);
}
}
});
}
This function is a reusable utility to dynamically manage custom buttons such as "Create Timesheet" and "Approval Timesheet".
It first verifies if there are any missing records via the backend method (method) and conditionally:
Adds an actionable button if records are missing to process them via the callback (def).
Disables the button with a failure message if no action is needed.
Key Points and Considerations
Backend Integration:
Backend methods like get_active_employees_with_salary, fetch_settings_and_update_mandatory, and process_all are critical for this script to function effectively. These need to be implemented and optimized on the server side.
Dynamic Behavior:
The script dynamically updates field requirements and enables/disables buttons based on the document state and responses from the server.
Child Table Handling:
The timesheet_tool_details table is well-integrated with triggers on individual fields that trigger recalculation or processing via backend methods.
Error Handling and User Feedback:
The script effectively uses error messages (frappe.msgprint) and exceptions (frappe.throw) to guide users in case of incorrect actions or missing data.
Code Improvement Suggestions:
Comments are included, but additional inline comments would be helpful, especially in complex parts like handle_button or field triggers.
Modularize repetitive backend calls (e.g., process_all is used in three triggers).
Ensure robust error handling for backend responses (e.g., checking for both response.exc and response.message).
Summary
This form script effectively manages the "Timesheet Tool" workflows with dynamic behavior, backend integration, and robust user feedback. A few minor optimizations could further enhance readability and maintainability, but overall, it adheres to Frappe's conventions and offers a solid implementation.
لإخفاء زر "Approval Timesheet" عندما يكون زر "Create Timesheet" ظاهرًا، يمكنك تعديل الكود لإدارة إظهار الزرَّين بناءً على الحالة. يمكن تحقيق ذلك من خلال إزالة زر Approval Timesheet من العرض إذا تم إضافة زر Create Timesheet.
إليك النسخة المعدلة من الكود لتحقيق ذلك:
التعديلات المطلوبة:
في جزء الكود المسؤول عن إدارة الأزرار، سنضيف منطقًا لإخفاء زر "Approval Attendance" عندما يكون زر "Create Attendance" ظاهرًا.
الكود بعد التعديل
javascript
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
// Amendment of the filter for the staff field to bring only active staff with Salary Structure Assignment
frm.fields_dict['timesheet_tool_details'].grid.get_field('employee').get_query = function(doc, cdt, cdn) {
return {
query: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.get_active_employees_with_salary"
};
};
// Fetch settings and dynamically update mandatory fields
frappe.call({
method: "fetch_settings_and_update_mandatory",
doc: frm.doc,
callback: function(response) {
if (response.message) {
settings = response.message;
frm.toggle_reqd("project", settings.is_project_mandatory);
frm.toggle_reqd("company", settings.is_company_mandatory);
}
}
});
// Management of the "Create Attendance" button
if (frm.doc.docstatus === 1) {
let can_show_create_timesheet = 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."
);
// Hide "Approval Attendance" button if "Create Timesheet" button is visible
if (can_show_create_timesheet) {
frm.remove_custom_button("Approval Timesheet");
}
}
// Management "Approval Attendance"
if (frm.doc.docstatus === 1) {
handle_button(
frm,
"time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
"approval_attendance",
"Approval Timesheet",
"Timesheet records have been approved successfully.",
"All records have already been approved."
);
}
},
...
});
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
} else {
frm.add_custom_button(__(btn_label), function() {
frappe.throw(__(fail_msg));
}).prop("disabled", true);
}
}
});
return button_visible; // Return whether the button is visible
}
شرح التعديلات:
إخفاء زر "Approval Timesheet" إذا كان زر "Create Timesheet" ظاهرًا:
في داخل القسم الخاص بـ "Create Attendance":
javascript
if (can_show_create_timesheet) {
frm.remove_custom_button("Approval Timesheet");
}
يتم إزالة زر Approval Timesheet (إن وُجد) إذا كان زر Create Timesheet قد تم عرضه.
إرجاع حالة ظهور الزر من handle_button:
تم تعديل الدالة handle_button بحيث تُرجع قيمة (boolean) تُشير إلى ما إذا كان الزر قد أُضيف إلى النموذج.
تعديل إدارة الأزرار:
كل من زر "Create Timesheet" وزر "Approval Timesheet" يعتمدان الآن على المنطق المضاف أثناء التنفيذ.
كيف يعمل الكود؟
عند تحديث النموذج:
يتم عرض زر "Create Timesheet" أو "Approval Timesheet" بناءً على الحالة.
إذا تم عرض زر "Create Timesheet"، يتم حذف زر "Approval Timesheet".
يقوم النظام بالتحقق ديناميكيًا من الشروط التي تحدد ظهور الأزرار، مع ضمان أن "Approval Timesheet" لن يظهر إلا إذا لم يظهر "Create Timesheet".
المخرجات المتوقعة:
إذا كان زر "Create Timesheet" مرئيًا، لن يظهر زر "Approval Timesheet".
إذا لم يكن هناك حاجة لعرض زر "Create Timesheet"، سيظهر زر "Approval Timesheet" إن كان ذلك مناسبًا للحالة.
إذا واجهت أي مشاكل أثناء تنفيذ الكود، يرجى تزويدي بالتفاصيل وسأكون سعيدًا بمساعدتك! 😊