// 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
انت مبرمج محترف في جافاء سكربت وانا اريد مساعدتك في تنظيم الكود الذي ارسلت لك بحيت يتم تقليل تكرار الكود ويتم اعادة استخدام الاكواد في الجزاء هذا // إخفاء الـ div باستخدام jQuery frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.btn-open-row').on('click', function() { const targetDiv = $('span.row-actions'); if (targetDiv.length) { targetDiv.hide(); } }); frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.row-index').on('click', function() { const targetDiv = $('span.row-actions'); if (targetDiv.length) { targetDiv.hide(); } }); frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.btn-open-row').on('click', function() { const targetDiv = $('div.grid-footer-toolbar'); if (targetDiv.length) { targetDiv.hide(); } }); frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.row-index').on('click', function() { const targetDiv = $('div.grid-footer-toolbar'); if (targetDiv.length) { targetDiv.hide(); } });
Assistant
لتقليل تكرار الكود وزيادة قابليته لإعادة الاستخدام في الجزء الذي ذكرته، يمكنك كتابة دالة مشتركة للتعامل مع إخفاء العناصر المستهدفة بدلاً من تكرار الكود لكل حدث. إليك كيف يمكن أن يبدو الكود بعد التحسين:
javascript
User
شكراً لك
Assistant
عفواً! إذا كان لديك أي أسئلة أخرى أو تحتاج إلى مزيد من المساعدة في البرمجة أو أي موضوع آخر، فلا تتردد في طرحها. أنا هنا للمساعدة! بالتوفيق في مشروعك!
User
Assistant
// إخفاء الـ div باستخدام jQuery
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.btn-open-row').on('click', function() {
const targetDiv = $('span.row-actions');
if (targetDiv.length) {
targetDiv.hide();
}
});
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.row-index').on('click', function() {
const targetDiv = $('span.row-actions');
if (targetDiv.length) {
targetDiv.hide();
}
});
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.btn-open-row').on('click', function() {
const targetDiv = $('div.grid-footer-toolbar');
if (targetDiv.length) {
targetDiv.hide();
}
});
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.row-index').on('click', function() {
const targetDiv = $('div.grid-footer-toolbar');
if (targetDiv.length) {
targetDiv.hide();
}
});
// Hide the addition button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-add-row').hide();
// hide the deletion button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-remove-rows').hide();
// hide the selection box in each row .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check').closest('.row-check').hide();
// Management of the "Create Attendance" button .
if (frm.doc.docstatus === 1 && hasRole("Create Timesheet")) {
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("Submit Timesheet");
}
}
// Management "Approval Attendance"
if (frm.doc.docstatus === 1 && hasRole("Submit Timesheet")) {
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."
);
}
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");
frappe.msgprint(__('All active personnel with Salary Structure Assignment were brought in.'));
}
}
});
},
project(frm) {
frappe.call({
method: "clear_timesheet_tool_details_table",
doc: frm.doc,
callback: function(response) {
frm.refresh_field("timesheet_tool_details");
}
});
},
// 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) {
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.remove_custom_button("Approval Timesheet");
// frm.add_custom_button((btn_label), function() {
// frappe.throw(__(fail_msg));
// }).prop("disabled", true);
}
}
});
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);
}
The timesheet_tool.js script shown here appears to be part of a custom application in Frappe/ERPNext, which is a framework for building applications, specifically in the area of resource management like timesheets. Below is a breakdown of its functionalities and a few potential improvements or notes regarding its design:
Features Implemented in the Script
Filter for Active Employees:
The employee field in the timesheet_tool_details grid is filtered to show only active employees with a salary structure assignment.
UI Enhancements:
Several buttons, like the addition and deletion buttons in the grid, are hidden.
Specific divs (like grid-footer-toolbar and row-actions) are hidden on button clicks to streamline the UI.
Role Management for Buttons:
The visibility of the "Create Timesheet" and "Approval Attendance" buttons is managed based on user roles and the status of the document.
Custom messages are shown upon successfully creating or approving timesheet records.
Dynamic Queries:
A query for the project field is dynamically generated to filter related projects based on the selected company.
Employee Retrieval:
A method to retrieve employees based on the project the user selects.
Field Updates in the Details Table:
Modifications in the timesheet_tool_details such as calculations for total working hours, overtime, and deductions trigger refreshes of the field for real-time updates.
Potential Improvements and Notes
Code Duplication:
There is duplicated code for hiding elements (e.g., the .btn-open-row event handler). Consider consolidating this to avoid redundancy.
Error Handling:
While there's existing logic for showing messages upon certain actions, consider adding error handling for network requests (like in the frappe.call methods) to notify users of failures or exceptions gracefully.
Performance Optimization:
If the grid has a significant number of rows, consider optimizing the UI updates (e.g., using a batch process for large updates).
User Feedback:
Including a loading spinner or indication during the execution of calls (like frappe.call()) can improve user experience, especially for potentially long-running processes.
Role Check Functionality:
The hasRole function checks user permissions. Client-side validation is good, but sensitive operations (like creating or submitting records) should still be validated on the server side.
Scalability:
As features expand, consider organizing the code into separate modules or files for maintainability.
Conclusion
Overall, the script you provided is a solid example of how to manage user interactions and data flows in a Frappe/ERPNext application. It effectively addresses the primary functionalities of managing timesheets while considering the user experience. With some refinements and optimizations, it can become even more robust and responsive.
// إخفاء الديف المحدد باستخدام jQuery
function hideTargetDiv(selector) {
const targetDiv = $(selector);
if (targetDiv.length) {
targetDiv.hide();
}
}
// إضافة المعالجات للأزرار
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');
});
}
// في دالة refresh، يمكنك استدعاء attachHideEventHandlers
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
// بقية الكود...
// استدعاء دالة إضافة أحداث الإخفاء
attachHideEventHandlers(frm);
// بقية الكود...
}
});
كيفية عمل التحسينات
دالة مشتركة: قمنا بإنشاء دالة hideTargetDiv التي تأخذ selector كوسيلة محددة وتقوم بإخفاء العنصر إذا كان موجودًا.
مرفق الأحداث: قمنا بإنشاء دالة attachHideEventHandlers التي تتولى إضافة معالجات الأحداث إلى الأزرار. يتم استدعاء دالة hideTargetDiv لإخفاء العناصر اللازمة لكل حدث.
استدعاء في refresh: تحدث المعالجات في دالة refresh، مما يبقي الكود منظمًا وسهل التعديل.
فوائد هذا التصميم
تكرار أقل: تم تقليل الكود المتكرر، مما يجعل الكود أسهل في القراءة والإدارة.
سهولة التعديل: إذا كنت بحاجة لتغيير طريقة إخفاء عنصر أو تعديل سلوك معين، يمكنك تخصيص ذلك في مكان واحد فقط.
قابلية إعادة الاستخدام: الدالة hideTargetDiv يمكن استخدامها في أجزاء أخرى من الكود إذا لزم الأمر.
بهذه الطريقة، نحافظ على هيكلية الكود ونقلل من التعقيد، مما يسهل العمل مستقبلاً.
// 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);
// 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"
};
};
// Hide the addition button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-add-row').hide();
// hide the deletion button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-remove-rows').hide();
// hide the selection box in each row .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check').closest('.row-check').hide();
// Management of the "Create Attendance" button .
if (frm.doc.docstatus === 1 && hasRole("Create Timesheet")) {
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("Submit Timesheet");
}
}
// Management "Approval Attendance"
if (frm.doc.docstatus === 1 && hasRole("Submit Timesheet")) {
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."
);
}
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);
// Hide the addition button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-add-row').hide();
// hide the deletion button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-remove-rows').hide();
// hide the selection box in each row .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check').closest('.row-check').hide();
frappe.msgprint(__('All active personnel with Salary Structure Assignment were brought in.'));
}
}
});
},
project(frm) {
frappe.call({
method: "clear_timesheet_tool_details_table",
doc: frm.doc,
callback: function(response) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
// Hide the addition button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-add-row').hide();
// hide the deletion button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-remove-rows').hide();
// hide the selection box in each row .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check').closest('.row-check').hide();
}
});
},
// 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");
attachHideEventHandlers(frm);
// Hide the addition button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-add-row').hide();
// hide the deletion button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-remove-rows').hide();
// hide the selection box in each row .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check').closest('.row-check').hide();
},
over_time_h(frm, cdt, cdn) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
// Hide the addition button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-add-row').hide();
// hide the deletion button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-remove-rows').hide();
// hide the selection box in each row .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check').closest('.row-check').hide();
}
});
},
over_time_n(frm, cdt, cdn) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
// Hide the addition button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-add-row').hide();
// hide the deletion button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-remove-rows').hide();
// hide the selection box in each row .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check').closest('.row-check').hide();
}
});
},
deduction(frm, cdt, cdn) {
frappe.call({
method: "process_all",
doc: frm.doc,
callback: function() {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
// Hide the addition button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-add-row').hide();
// hide the deletion button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-remove-rows').hide();
// hide the selection box in each row .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check').closest('.row-check').hide();
}
});
}
}
});
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.remove_custom_button("Approval Timesheet");
// frm.add_custom_button((btn_label), function() {
// frappe.throw(__(fail_msg));
// }).prop("disabled", true);
}
}
});
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);
}
// إخفاء الديف المحدد باستخدام jQuery
function hideTargetDiv(selector) {
const targetDiv = $(selector);
if (targetDiv.length) {
targetDiv.hide();
}
}
// إضافة المعالجات للأزرار
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');
});