// 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) {
// frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row').on('click', function() {
// const targetDiv = $('div.form-in-grid.grid-header-toolbar').hide();
// if (targetDiv.length) {
// targetDiv.hide(); // Hide the div
// }
// });
code
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.row-index').on('click', function() {
const targetDiv = $('span.row-actions'); // حدد العنصر الذي ترغب في إخفائه
console.log(targetDiv);
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'); // حدد العنصر الذي ترغب في إخفائه
console.log(targetDiv);
if (targetDiv.length) {
targetDiv.hide();
}
})
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.btn-open-row').on('click', function() {
const targetDiv = $('span.row-actions'); // حدد العنصر الذي ترغب في إخفائه
console.log(targetDiv);
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'); // حدد العنصر الذي ترغب في إخفائه
console.log(targetDiv);
if (targetDiv.length) {
targetDiv.hide();
}
})
// 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");
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);
}
Assistant
The provided JavaScript code defines event handlers and configurations for a Frappe framework form named "Timesheet Tool". Below is a summary of how this code operates, alongside an explanation of its parts and functionality.
Overview of Features
Form Refresh Handling:
The refresh event configures how the form behaves when it loads or refreshes. It includes hiding certain UI elements like buttons and grid rows for better user experience.
Dynamic Element Interaction:
The script dynamically hides or shows certain elements within the grid (like action buttons) based on user interactions. Event listeners for clicks are set up on grid rows to achieve this.
Query Modifications:
The queries for fields like "employee" and "project" are customized. The employee field filter only retrieves active employees assigned to a salary structure. The project field is filtered according to the company's context.
Button Management:
Custom buttons ("Create Timesheet" and "Submit Timesheet") are conditionally added or removed based on the document status and user roles. This includes approval and creation functionalities for timesheets.
Employee Retrieval:
A method to fetch employees based on the selected project is defined (triggered by the "Get Employee" button), ensuring that the project is set before this action can take place.
Table Update Logic:
When specific fields in the "Timesheet Tool Details" table are adjusted, calculations are performed (like total working hours based on hours worked and a ratio) and the table is refreshed accordingly.
Role Management:
The script checks if the logged-in user has the required role before performing actions or showing buttons.
Key Functionalities Explained
Button Management with handle_button:
This function checks if a button should be shown based on the response from the server regarding missing records. Depending on the response, it either shows a button or does not allow a user to perform an action.
Field Calculations and Updates:
User
اريد تحسين الكود ``` frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.row-index').on('click', function() {
const targetDiv = $('span.row-actions'); // حدد العنصر الذي ترغب في إخفائه
console.log(targetDiv);
if (targetDiv.length) {
targetDiv.hide();
}
});
code
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.row-index').on('click', function() {
const targetDiv = $('div.grid-footer-toolbar'); // حدد العنصر الذي ترغب في إخفائه
console.log(targetDiv);
if (targetDiv.length) {
targetDiv.hide();
}
})
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.btn-open-row').on('click', function() {
const targetDiv = $('span.row-actions'); // حدد العنصر الذي ترغب في إخفائه
console.log(targetDiv);
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'); // حدد العنصر الذي ترغب في إخفائه
console.log(targetDiv);
if (targetDiv.length) {
targetDiv.hide();
}
}) ``` منحيث عدم تكرار الكود
Assistant
لتحسين الكود وتقليل التكرار فيه، يمكنك تعريف دالة مشتركة تعمل على إخفاء العناصر من أجل كل الأحداث بدلاً من تكرار نفس الكود عدة مرات. إليك كيف يمكنك فعل ذلك:
javascript
function hideTargetDiv(targetSelector) {
const targetDiv = $(targetSelector); // حدد العنصر (div أو span) الذي ترغب في إخفائه باستخدام المحدد
console.log(targetDiv);
if (targetDiv.length) {
targetDiv.hide();
}
}
// استخدم هذا في الحدث onclick للصفوف والأزرار
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.row-index').on('click', function() {
hideTargetDiv('span.row-actions'); // إخفاء الأزرار في الصف
hideTargetDiv('div.grid-footer-toolbar'); // إخفاء شريط الأدوات السفلي
});
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.btn-open-row').on('click', function() {
hideTargetDiv('span.row-actions'); // إخفاء الأزرار في الصف
hideTargetDiv('div.grid-footer-toolbar'); // إخفاء شريط الأدوات السفلي
});
الشرح:
تعريف دالة hideTargetDiv:
الدالة تأخذ محدد CSS كوسيلة للإخفاء. تقوم بالبحث عن العنصر، وإذا كان موجودًا، تقوم بإخفائه.
استدعاء الدالة:
تم استدعاء hideTargetDiv مرتين داخل كل من الحدثين الساخنين (click) للصفوف وأزرار فتح الصف. هذا يجعل الكود أكثر نظافة ووضوحًا، ويقلل من تكرار التعليمات البرمجية.
بهذه الطريقة، أصبح الكود أنظف وأسهل في القراءة والصيانة. يمكنك أيضًا توسيع دالة hideTargetDiv لتشمل أي منطق إضافي في المستقبل دون الحاجة إلى تعديل الكثير من الشيفرة.
User
// استخدم هذا في الحدث onclick للصفوف والأزرار
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.row-index').on('click', function() {
hideTargetDiv('span.row-actions'); // إخفاء الأزرار في الصف
hideTargetDiv('div.grid-footer-toolbar'); // إخفاء شريط الأدوات السفلي
});
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.btn-open-row').on('click', function() {
hideTargetDiv('span.row-actions'); // إخفاء الأزرار في الصف
hideTargetDiv('div.grid-footer-toolbar'); // إخفاء شريط الأدوات السفلي
}); هل يمكن اختصار الكود التالي وتقليل التكرار
Assistant
نعم، يمكن اختصار الكود وتقليل التكرار من خلال تجميع الأحداث في دالة واحدة، بحيث يتم استخدام نفس المعالج لكلا الحدثين (.row-index و.btn-open-row). يمكنك استخدام محددات متعددة لتقليل التكرار في الكود. إليك كيف يمكنك فعل ذلك:
javascript
// دالة لإخفاء العناصر المستهدفة
function hideTargetDiv(targetSelector) {
const targetDiv = $(targetSelector); // حدد العنصر (div أو span) الذي ترغب في إخفائه باستخدام المحدد
console.log(targetDiv);
if (targetDiv.length) {
targetDiv.hide();
}
}
// دمج الأحداث في حدث واحد
const combinedSelector = '.row-index, .btn-open-row'; // محدد يجمع كلا من الصف والأزرار
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find(combinedSelector).on('click', function() {
hideTargetDiv('span.row-actions'); // إخفاء الأزرار في الصف
hideTargetDiv('div.grid-footer-toolbar'); // إخفاء شريط الأدوات السفلي
});
الشرح:
تحديد أخرى:
في السطر const combinedSelector = '.row-index, .btn-open-row';، نحن نجمع محددي .row-index و.btn-open-row في محدد واحد بحيث يتم الاستماع لنفس الحدث لكلا العنصرين.
حدث مزدوج:
باستخدام هذا المحدد الجديد، يقوم المعالج بالاستجابة لحدث click بالنسبة لكلا العنصرين معًا، مما يقلل من الكود واستمرار الكتابة.
بهذه الطريقة، يتم تقليل التكرار في الكود بشكل كبير مع الحفاظ على نفس الوظيفة.
User
اريد تحسين الكود ``` // Hide the addition button .
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-add-row').hide();
code
// 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(); ``` منحيث عدم تكرار الكود
Assistant
يمكنك تحسين الكود من خلال تجميع عمليات الإخفاء في دالة واحدة وتأخذ مصفوفة من المحددات، مما يساعد على تقليل التكرار. إليك كيف يمكنك فعل ذلك:
javascript
// دالة لإخفاء العناصر المستهدفة
function hideElements(selectors) {
selectors.forEach(selector => {
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find(selector).hide();
});
}
// إخفاء الأزرار ومربعات الاختيار
hideElements([
'.grid-add-row', // إخفاء زر الإضافة
'.grid-remove-rows', // إخفاء زر الحذف
'.grid-row-check', // إخفاء مربع الاختيار في كل صف
]);
الشرح:
دالة hideElements:
تأخذ مصفوفة من المحددات (selectors) وتقوم بدورها بإخفاء كل عنصر مطابق لهذا المحدد باستخدام حلقة forEach.
استدعاء الدالة:
قمت باستدعاء hideElements مع المصفوفة التي تحتوي على جميع المحددات التي تريد إخفاءها. هذا يساهم في تقليل حجم الكود وجعله أكثر تنظيمًا وسهولة للصيانة.
بهذه الطريقة، يمكن لك أن تضيف أو تعدل أي عنصر تود إخفاءه بكل سهولة دون الحاجة إلى تكرار كود الإخفاء.
User
grid-row-check لم يتم اخفاء
Assistant
إذا لم يتم إخفاء .grid-row-check كما هو متوقع، فقد يكون السبب هو أن .grid-row-check مرتبط بعناصر أخرى أو يحتاج إلى إخفاء بطريقة مختلفة.
يمكنك استخدام .closest() بشكل صحيح لضمان أنك تخفي العنصر الصحيح. إليك كيف يمكنك التأكد من إخفاء مربع الاختيار بشكل صحيح في كل صف:
تحسين الكود:
javascript
// دالة لإخفاء العناصر المستهدفة
function hideElements(selectors) {
selectors.forEach(selector => {
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find(selector).hide();
});
}
// إخفاء الأزرار ومربعات الاختيار
hideElements([
'.grid-add-row', // إخفاء زر الإضافة
'.grid-remove-rows', // إخفاء زر الحذف
]);
// إخفاء مربع الاختيار في كل صف
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check').each(function() {
$(this).closest('.row-check').hide(); // Hide the closest row-check element
});
الشرح:
إخفاء عناصر Checkbox:
استخدمنا .each() للمرور على كل مربع اختيار (.grid-row-check)، ثم استخدمنا $(this).closest('.row-check') لإخفاء العنصر الأقرب المناسب.
مراعاة الهيكلية:
تأكد من أن الهيكلية الخاصة بك تُظهر أن .grid-row-check داخل .row-check. إذا كان الهيكل مختلفًا، ستحتاج إلى تعديل محدد الصف لتناسب الهيكل الفعلي الخاص بك.
هذا التعديل يضمن أن يتم تحديد العنصر الصحيح ويتم إخفاؤه بشكل صحيح. يُستخدم each() بالاقتران مع closest() لاستهداف أول عنصر .row-check الأقرب لمربع الاختيار المناسب.
User
hideElements(['.grid-add-row','.grid-remove-rows']);
لا تعمل ولم يتم الاخفاء
Assistant
إذا كانت دالة hideElements لا تعمل على إخفاء الأزرار .grid-add-row و.grid-remove-rows، فقد يكون هناك بعض الأسباب لذلك، مثل عدم وجود هذه العناصر في الحالة الحالية للـ DOM، أو أن عناصر أخرى تؤثر على رؤية الأزرار.
الخطوات التي يمكن اتباعها لضمان إخفاء العناصر:
التأكد من أن العناصر موجودة عند التنفيذ:
قد تكون العناصر غير موجودة في DOM عندما يتم تنفيذ الكود. يمكنك محاولة استخدام دالة setTimeout لإعطاء بعض الوقت حتى يتم تحميل العناصر قبل محاولة إخفائها. لكن، من الأفضل استخدام الأحداث المناسبة من framework.
التأكد من استخدام المحددات الصحيحة:
تأكد من أنك تستخدم المحددات الصحيحة بناءً على الهيكلية الفعلية للـ DOM.
تحديث الكود مع إضافة setTimeout (كحل مؤقت):
javascript
// دالة لإخفاء العناصر المستهدفة
function hideElements(selectors) {
selectors.forEach(selector => {
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find(selector).hide();
});
}
// إخفاء الأزرار بعد فترة قصيرة للتأكد من وجود العناصر في DOM
setTimeout(() => {
hideElements(['.grid-add-row', '.grid-remove-rows']);
}, 100); // 100 مللي ثانية كفترة انتظار
استخدام الأحداث الصحيحة:
بدلاً من استخدام setTimeout، من الأفضل استدعاء الدالة في حدث refresh أو بعد التأكد من تحميل العناصر. إذا كانت العناصر جزءًا من جدول يتم تحميله ديناميكيًا، تأكد من أنك تقوم بإخفائها بعد عملية التحميل.
مثال على استدعاء hideElements في حدث refresh:
javascript
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
hideElements(['.grid-add-row', '.grid-remove-rows']);
// إذا كنت بحاجة إلى إخفاء مربع الاختيار
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check').each(function() {
$(this).closest('.row-check').hide();
});
}
});
التحقق من الوجود:
يمكنك وضع console.log قبل محاولة الإخفاء للتأكد من أن العناصر موجودة:
javascript
console.log(frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-add-row').length); // يجب أن تكون 1 أو أكبر
console.log(frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-remove-rows').length); // يجب أن تكون 1 أو أكبر
ملخص:
تأكد من أن العناصر موجودة في الـ DOM عند وقت تنفيذ الكود واستخدم الأحداث المتاحة بشكل صحيح لضمان الحصول على العناصر المراد إخفاؤها.
Not yet included in a published release.
The script listens for changes in specific fields (hour, over_time_h, over_time_n, deduction) and updates totals or performs further processing by calling corresponding server-side methods.
Method Calls:
Calls to backend methods (defined in Python) handle business logic, ensuring that the operations performed in the UI reflect the latest data and validations from the server.
Code Readability and Maintenance Tips
Refactor Repeated Code:
Repeated sections, especially for hiding elements like span.row-actions and div.grid-footer-toolbar, can be combined into a single function to reduce redundancy.
Modularize Event Handlers:
Functions for handling specific button clicks can improve readability by keeping a clear separation of logic across the code.
Use Comments Wisely:
Maintaining comments in the code helps with understanding the functionality. Consider removing commented-out code that is no longer necessary.
Error Handling:
Introduce error handling for the various calls to server methods to account for any potential failures, ensuring robust user experience.
This JavaScript code represents a typical structure in a Frappe application, showcasing how client-side interactions can be tied into more complex form logic including server communication and role management.