// 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", {
// onload: function(frm) {
// // إضافة حدث على جدول التفاصيل لإظهار Popup عند التحويم فوق الخلايا
// frm.fields_dict['timesheet_tool_details_over_time'].grid.wrapper.on('mouseenter', '.grid-static-col', function(event) {
// let cell_content = $(this).text().trim(); // محتوى الخلية
// if (cell_content) {
// showPreviewPopup(event, cell_content);
// }
// });
code
Assistant
// // إزالة الـ Popup عند مغادرة الخلية
// frm.fields_dict['timesheet_tool_details_over_time'].grid.wrapper.on('mouseleave', '.grid-static-col', function() {
// $('.preview-popup').remove();
// });
// },
refresh(frm) {
// تأكد من أن الحدث يُطبق فقط بعد تحميل النموذج
frm.fields_dict['timesheet_tool_details'].grid.wrapper.on('click', '.grid-static-col[data-fieldname="attendance"]', function(event) {
let row = frm.fields_dict['timesheet_tool_details'].grid.get_row(this);
openActivityTypeDialog(frm, row);
});
update_absent_buttons(frm);
let grid_wrapper = frm.fields_dict.timesheet_tool_details.grid.wrapper.get(0);
let observer = new MutationObserver(function(mutations) {
update_absent_buttons(frm);
});
observer.observe(grid_wrapper, { childList: true, subtree: true });
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"
};
};
frm.fields_dict['timesheet_tool_details_over_time'].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"
};
};
frm.fields_dict['timesheet_tool_details_deduction'].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") && !frm.doc.timesheets_created) {
handleCreateTimesheetButton(frm);
}
if (hasRole("Submit Timesheet") && frm.doc.timesheets_created && !frm.doc.timesheets__submited) {
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: {child_table:"timesheet_tool_details", project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
}
}
});
},
get_employee_over_time(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: {child_table:"timesheet_tool_details_over_time", project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details_over_time");
}
}
});
},
get_employee_deduction(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: {child_table:"timesheet_tool_details_deduction", project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details_deduction");
}
}
});
},
project(frm) {
frappe.call({
method: "clear_timesheet_tool_details_table",
doc: frm.doc,
callback: function(response) {
frm.refresh_field("timesheet_tool_details");
frm.refresh_field("timesheet_tool_details_over_time");
frm.refresh_field("timesheet_tool_details_deduction");
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 Timesheets",
"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 Timesheets",
"Timesheet records have been submitted successfully.",
"All records have already been approved."
);
}
// A function to handle buttons
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() {
frappe.confirm(
Are you sure you want to ${btn_label.toLowerCase()}?,
() => {
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));
}
});
},
() => {
frappe.msgprint(("Action cancelled."));
}
);
});
}
}
});
}
// 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
}
});
}
function update_absent_buttons(frm) {
// استهداف كل زر "Absent" داخل الجدول الفرعي
frm.fields_dict.timesheet_tool_details.grid.wrapper
.find('[data-fieldname="absent"] button')
.each(function() {
let btn=(this);
if (!btn.hasClass('styled')) {
btn.addClass('btn btn-danger styled');
btn.html('<i class="fa fa-user-times"></i> Absent');
}
});
}
frappe.ui.form.on('Timesheet Tool Details', {
refresh: function(frm, cdt, cdn) {
setTimeout(function() {
update_absent_buttons(frm);
}, 300);
},
absent: function(frm, cdt, cdn) {
// عند الضغط على زر Absent، تعيين قيمة attendance إلى "Absent"
frappe.model.set_value(cdt, cdn, 'attendance', 'Absent');
frappe.msgprint(__('Attendance marked as Absent.'));
// تأخير إعادة التطبيق للتنسيق بعد التغيير
setTimeout(function() {
update_absent_buttons(frm);
}, 300);
},
// attendance: function(frm, cdt, cdn) {
// let row = frappe.get_doc(cdt, cdn);
// openActivityTypeDialog(frm, row);
// }
});
// دالة لإظهار Popup عند التحويم
// function showPreviewPopup(event, content) {
// // إزالة أي نوافذ منبثقة سابقة
// ('.preview-popup').remove();
// // إنشاء النافذة المنبثقة الجديدة
// var popup=('' + content + '').appendTo('body');
// let dialog = new frappe.ui.Dialog({
// title: __("Select Activity Type"),
// fields: [{
// fieldname: "activity_type",
// fieldtype: "Select",
// label: __("Activity Type"),
// options: activity_types.join("\n"),
// default: row.attendance // تعيين القيمة الحالية إن وجدت
// }],
// size: 'small',
// primary_action: function() {
// let selected_value = dialog.get_value('activity_type');
// if (selected_value) {
// frappe.model.set_value(cdt, row.name, 'attendance', selected_value);
// dialog.hide();
// }
// },
// primary_action_label: __("Select")
// });
// dialog.show();
// }
// }
// });
// }
The provided code is a JavaScript file intended for a timesheet management system in the Frappe framework, which is commonly used with ERPNext. Below is a brief overview of its components and functionality, followed by insights and recommendations for improvements.
Overview:
Initialization and Event Handlers:
The script binds various event handlers to the "Timesheet Tool" form, responding to user interactions.
The refresh method implements custom logic to handle clicks on attendance cells, setup queries for employee dropdowns, and display buttons based on user roles.
Employee Management:
Methods like get_employee, get_employee_over_time, and get_employee_deduction are defined to fetch employees based on project selections.
There are validation checks to ensure a project is selected before fetching employees.
Button Management:
Functions are defined to handle the creation and submission of timesheets, UI elements are dynamically altered based on data availability.
Grid Management:
The script manages how grids display various timesheet details. It both hides certain buttons and customizes grid rows to enhance user experience.
Popup Dialogs:
It creates popups to manage attendance activity types based on user input, showing a list of selectable options (currently commented out).
Suggested Improvements:
Clear Separation of Concerns:
It may be beneficial to separate constants and configuration settings into their own module to improve maintainability.
Error Handling:
Implement proper error handling for all asynchronous calls. For example, if an API call fails, the user should receive a meaningful error message.
Performance Optimization:
The creation of event listeners every time the user refreshes the form can lead to memory leaks or performance issues. Consider using one-time event listeners or unbinding events before re-binding.
Code Comments and Documentation:
While there are comments present, enhancing documentation and commenting for more complex parts of the code would aid future developers in understanding the logic and changes made.
User Experience (UX):
Ensure that buttons and dialogs use consistent design language and responsive design principles to cater to different screen sizes.
The dialog for selecting Activity Type could be improved by pre-filling it or providing additional context or data about the activities.
Refactoring of Repeated Logic:
Consider refactoring the repeated logic for fetching employees into a more generic method, reducing redundancy in code.
Overall, the script is structured well and implements a robust feature set for a timesheet management system. Making the improvements highlighted could enhance its maintainability, user experience, and reliability in a production environment.