// 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
// frm.fields_dict['timesheet_tool_details'].grid.wrapper.on('click', '.grid-static-col[data-fieldname="attendance"]', function(event) {
// let row = $(this).closest('.grid-row');
// let row_doc = locals[frm.fields_dict['timesheet_tool_details'].grid.doctype][row.attr("data-name")];
// if (row_doc) {
// openActivityTypeDialog(frm, row_doc);
// }
// });
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) {
// Target each "Absent" button within the sub-table
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(' Edit Activity Type');
}
});
}
frappe.ui.form.on('Timesheet Tool Details', {
refresh: function(frm, cdt, cdn) {
setTimeout(function() {
update_absent_buttons(frm);
}, 300);
},
edit_activity_type: function(frm, cdt, cdn) {
let child = frappe.get_doc(cdt, cdn);
let employeeName = child.employee_name
frappe.call({
method: "frappe.client.get_list",
args: {
doctype: "Activity Type",
fields: ["name"]
},
callback: function(response) {
if (response.message) {
let activity_types = response.message.map(item => item.name);
code
let dialog = new frappe.ui.Dialog({
title: "Select Activity Type",
fields: [
{
"fetch_from": "employee.employee_name",
"fieldname": "employee_name",
"fieldtype": "Read Only",
"label": "Member Name"
},
{
fieldname: "activity_container",
fieldtype: "HTML"
}
],
size: "large"
});
// Set the value of the employee_name field
dialog.fields_dict.employee_name.set_value(employeeName);
let $container = $(dialog.fields_dict.activity_container.wrapper);
$container.css({
"display": "grid",
"grid-template-columns": "repeat(auto-fit, minmax(120px, 1fr))",
"gap": "15px",
"margin-top": "20px",
"padding": "20px",
"border-radius": "8px",
"background-color": "#f7f7f7",
"box-shadow": "0 2px 10px rgba(0, 0, 0, 0.1)"
});
activity_types.forEach(type => {
let $btn = $(`<button class="btn btn-primary">${type}</button>`);
// Design of the button
$btn.css({
"padding": "15px",
"font-size": "14px",
"text-align": "center",
"border-radius": "5px",
"border": "none",
"transition": "background-color 0.3s, transform 0.2s",
"background-color": "#21bdad",
"color": "#fff",
"box-shadow": "0 4px 6px rgba(0, 0, 0, 0.1)"
});
// The button's on the pass.
$btn.on("mouseenter", function() {
$(this).css("background-color", "#20887d");
$(this).css("transform", "scale(1.05)");
});
$btn.on("mouseleave", function() {
$(this).css("background-color", "#21bdad");
$(this).css("transform", "scale(1)");
});
// When you press the button
$btn.on("click", function() {
frappe.model.set_value(cdt, cdn, 'attendance', type);
frappe.model.set_value(cdt, cdn, 'hour', 0);
dialog.hide();
frm.refresh_field('timesheet_tool_details');
});
$container.append($btn);
});
dialog.show();
}
}
});
}
});
Assistant
Your JavaScript code appears to be part of a Frappe application designed to manage timesheets, allowing users to capture employee attendance, manage projects, and handle timesheet submissions and creations. The code provided includes functionalities for fetching employees based on projects, showing dialog boxes for selecting activity types, and managing UI components in the timesheet form.
Here’s a breakdown of some key features and logic in your code:
Key Features
Dynamic Employee Queries: The employee fields in multiple child tables (like timesheet_tool_details, timesheet_tool_details_over_time, and timesheet_tool_details_deduction) are filtered to show only active employees with salary structure assignments.
Button Management: The code manages the visibility of buttons within the child tables, hiding the add/remove row actions to restrict user inputs and control the data integrity.
Project Dependency: Various functions check whether a project is selected before allowing the fetching of employees, ensuring that users make logical choices based on the application state.
Custom Buttons for Timesheet Operations: It includes functionality to create and submit timesheets based on user roles, with confirmation dialogs before performing significant actions.
UI Enhancements: The code modifies the appearance of buttons dynamically and binds complex behaviors (like mouse events) to enhance user experience.
Activity Type Editing: The edit_activity_type function allows users to select an activity type from a list, presenting it in a styled dialog box and updating the respective data in the form.
Areas for Potential Improvement or Customization
Error Handling: While the code does basic checks (like confirming unsaved changes), you could implement more robust error handling around API calls and user interactions to ensure better user feedback in case of failures.
User Feedback: Adding more visual or auditory cues can enhance user experience, especially when operations take varying amounts of time (e.g., fetching data).
Optimization of Callbacks: Combine redundant calls (frm.refresh_field()) into single calls to reduce load and improve performance, especially for lengthy operations.
Dynamic Configuration: Instead of hardcoding settings, consider loading them from the server to allow adjustments without modifying code. This could include visibility settings for buttons or required fields based on user roles.
User
اريد عند الضغط على الزر get_employee قبل جلب البيانات ان تظهر للمستخدم رساله تطلب منه الموافقة على جلب البيانات والا الرفض
Assistant
لتنفيذ هذه المتطلبات، يمكنك تعديل وظيفة get_employee لإضافة تأكيد قبل إجراء استدعاء البيانات. سنستخدم frappe.confirm لإظهار رسالة تأكيد للمستخدم. إليك كيف يمكنك فعل ذلك:
javascript
get_employee(frm) {
// تحقق مما إذا كان المشروع مطلوباً
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
// عرض رسالة التأكيد
frappe.confirm(
__('Are you sure you want to fetch employees?'),
function() {
// إذا أكد المستخدم، قم بجلب البيانات
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);
}
}
});
},
function() {
// إذا رفض المستخدم، قم بإظهار رسالة توضيحية (اختياري)
frappe.msgprint(__('Employee fetching has been canceled.'));
}
);
},
شرح الكود:
رسالة التأكيد: نستخدم frappe.confirm لعرض رسالة للمستخدم تطلب منه تأكيد العملية.
وظيفة التأكيد: إذا قام المستخدم بالضغط على "موافق"، يتم تنفيذ استدعاء frappe.call لجلب الموظفين.
وظيفة الرفض: إذا قام المستخدم بالضغط على "رفض"، يمكن (اختياريًا) إظهار رسالة تفيد بأن العملية قد تم إلغاؤها.
هذا يضمن أن المستخدم لديه الفرصة للموافقة أو الرفض قبل القيام بعملية جلب البيانات.
User
// 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
Assistant
الكود الذي قمت بتعديله يضيف ميزة التأكيد قبل جلب بيانات الموظفين عند الضغط على الزر "Get Employee". يعمل هذا التعديل على إظهار رسالة للمستخدم يتطلب فيها تأكيده قبل متابعة عملية جلب البيانات. سأعرض أدناه الكود المعدل مع توضيحات بسيطة حول إجراء التعديلات:
الكود المعدل
javascript
User
اريد ان يكون لون الخليه Hour في الجدول الفرعي Timesheet Tool Details
بالون الاخضر
Assistant
لتغيير لون خلية معينة في الجدول الفرعي (Child Table) “Timesheet Tool Details” إلى اللون الأخضر، يمكنك استخدام CSS لتطبيق هذا التغيير. يتطلب ذلك تعديل الكود في الجزء الذي يعرض الجدول الفرعي.
سأقوم بتوجيهك إلى كيفية القيام بذلك دون إضافة كود CSS خارجي، بل يمكنك استخدام JavaScript وتعديل خاصية style مباشرة.
الخطوات التي يجب اتباعها:
بعد أن يتم تكوين الجدول الفرعي (Timesheet Tool Details) في التحميل أو التحديث، يمكنك استخدام jQuery لاختيار خلية "Hour" وتغيير لونها.
قم بإضافة الكود التالي بعد عملية تحميل الجدول أو داخل دالة refresh الخاصة بـ Timesheet Tool Details.
إضافة الكود:
javascript
frappe.ui.form.on('Timesheet Tool Details', {
refresh: function(frm, cdt, cdn) {
setTimeout(function() {
update_absent_buttons(frm);
// تغيير لون خلية "Hour" إلى اللون الأخضر
changeHourCellColor(frm, cdt, cdn);
}, 300);
},
// دالة لتغيير لون الخلية "Hour"
changeHourCellColor(frm, cdt, cdn) {
const row = frm.fields_dict['timesheet_tool_details'].grid.get_row(cdt, cdn);
if (row) {
const hourCell = row.wrapper.find('[data-fieldname="hour"]'); // ابحث عن الخلية الخاصة بالحقل "Hour"
hourCell.css('background-color', 'green'); // تغيير لون الخلفية إلى الأخضر
}
},
edit_activity_type: function(frm, cdt, cdn) {
// بقية كود الدالة كما هو
}
});
تفسير الكود:
تحديد العنصر: نستخدم row.wrapper.find('[data-fieldname="hour"]') للعثور على الخلية الخاصة بالحقل "Hour".
تغيير اللون: نستخدم css('background-color', 'green') لتغيير لون الخلفية للخلية إلى اللون الأخضر.
التحكم في التوقيت: نستخدم setTimeout لضمان أن يتم تنفيذ الكود بعد أن يتم تحميل البيانات في الجدول الفرعي.
ملحوظة:
قد تحتاج إلى التحقق من أنه يتم تنفيذ الكود بعد تحميل البيانات في الجدول بشكل كامل. إذا لم يكن هناك استجابة كما هو متوقع، يمكنك محاولة وضع الكود داخل أماكن أخرى في دورة حياة الجداول.
بهذه الطريقة، ستكون خلية "Hour" في جدول "Timesheet Tool Details" ملونة باللون الأخضر كما تريد.
User
لم يتم تغيير لون الخليه
Assistant
إذا لم يتم تغيير لون خلية "Hour" كما هو متوقع، قد تحتاج إلى التحقق من بعض النقاط الأساسية أو استخدام طريقة أخرى. دعنا نحاول طريقة مختلفة للتأكد من تغيير لون الخلية بشكل صحيح في الجدول الفرعي.
خطوات للتأكد من تنفيذ البرنامج بشكل صحيح:
تحديد موقع الجدول الفرعي: تأكد من أنك تقوم بتحديد الخلية الصحيحة في الجدول الفرعي. يجب أن يتم ذلك بعد تحميل البيانات مباشرة أو عند تحديث الجدول.
تطبيق النمط بعد تحميل الجدول: عليك تطبيق التغيير بعد عملية التحميل مباشرة، لذا سأقوم بتعديل الكود مع تضمين عملية تنفيذ وظيفة بعد تحديث بيانات الجدول.
الكود المعدل:
javascript
frappe.ui.form.on('Timesheet Tool Details', {
refresh: function(frm, cdt, cdn) {
setTimeout(function() {
update_absent_buttons(frm);
// تغيير لون جميع خلايا "Hour" إلى اللون الأخضر
changeHourCellColor(frm);
}, 300);
},
changeHourCellColor(frm) {
// ابحث عن جميع الصفوف في الجدول الفرعي
const rows = frm.fields_dict['timesheet_tool_details'].grid.grid_rows;
rows.forEach(row => {
let hourCell = row.$row.find('[data-fieldname="hour"]'); // ابحث عن الخلية الخاصة بالحقل "Hour"
if (hourCell.length) {
hourCell.css('background-color', 'green'); // تغيير لون الخلفية إلى الأخضر
}
});
},
edit_activity_type: function(frm, cdt, cdn) {
// بقية كود الدالة كما هو
}
});
توضيحات:
تحديد الخلية بشكل ديناميكي: بدلاً من محاولة الحصول على خلية واحدة، نقوم الآن بالبحث عبر جميع الصفوف في الجدول الفرعي باستخدام frm.fields_dict['timesheet_tool_details'].grid.grid_rows.
تعميم التطبيق: باستخدام حلقة forEach، نقوم بتطبيق تغيير اللون على كل خلية تنتمي للحقل "Hour".
تأخير العملية: باستخدام setTimeout، نضمن أن جميع البيانات في الجدول قد تم تحميلها قبل محاولة تغيير اللون.
التحقق من العمل:
تأكد من أنه يوجد لديك بيانات في الجدول الفرعي للتأكد من أن التغييرات تنفذ.
تأكد من عدم وجود أي تعارضات مع أنماط CSS أخرى قد تجعل خلية "Hour" تظهر بألوان مختلفة.
الاختبار:
بعد إعادة تنفيذ الكود، تحقق مما إذا كان الخلايا الخاصة بـ "Hour" تتغير إلى اللون الأخضر. إذا كانت لا تزال لا تعمل، قد تحتاج إلى التحقق من الأخطاء في وحدة التحكم (console) في أدوات المطور بالمتصفح لرؤية ما إذا كانت هناك أي أخطاء تحدث.
User
Assistant
لتغيير لون خلية "Hour" في الجدول الفرعي "Timesheet Tool Details" إلى اللون الأخضر بشكل مباشر باستخدام CSS أو JavaScript، تحتاج إلى تحديد الخلية المستهدفة من خلال الـ DOM.
طريقة تغيير اللون باستخدام CSS
إذا كنت ترغب في استخدام CSS فقط، يمكنك إضافة كود CSS إلى ملف الأنماط الخاص بك. إليك كود CSS بسيط يغير لون الخلفية لخلية "Hour":
css
[data-fieldname="hour"] .static-area {
background-color: green;
color: white; /* اختيارياً: لجعل النص يظهر بوضوح */
}
طريقة تغيير اللون باستخدام JavaScript
إذا كنت تفضل استخدام JavaScript لتغيير لون الخلية ديناميكيًا، قم بتعديل جافا سكريبت كما يلي:
كود JavaScript جديد لتغيير لون الخلية
يمكنك إضافة الكود التالي إلى كود JavaScript الموجود لديك:
javascript
frappe.ui.form.on('Timesheet Tool Details', {
refresh: function(frm, cdt, cdn) {
setTimeout(function() {
update_absent_buttons(frm);
changeHourCellColor(frm);
}, 300);
},
changeHourCellColor(frm) {
// ابحث عن جميع الصفوف في الجدول الفرعي
const rows = frm.fields_dict['timesheet_tool_details'].grid.grid_rows;
rows.forEach(row => {
// ابحث عن خلية "Hour"
let hourCell = row.$row.find('[data-fieldname="hour"] .static-area');
if (hourCell.length) {
hourCell.css('background-color', 'green'); // تغيير لون الخلفية إلى الأخضر
hourCell.css('color', 'white'); // تغيير لون النص إلى الأبيض إذا لزم الأمر
}
});
}
});
خطوات التنفيذ:
إضافة الكود: تأكد من إضافة الكود السابق في حدث refresh لدالة Timesheet Tool Details.
تأكد من وجود بيانات: تأكد من أن الجدول يحتوي على بيانات وأن الـ DOM قد تم تحميله بالكامل قبل محاولة تطبيق الأنماط.
تحديث الملف: بعد إضافة الكود، قم بتحديث التطبيق الخاص بك في Frappe وتحقق مما إذا كان لون الخلية "Hour" قد تم تغييره إلى اللون الأخضر.
ملاحظات:
يمكنك تعديل اللون كما هو مطلوب عن طريق تغيير background-color في كود CSS أو JavaScript.
إذا لم ينعكس التغيير، تأكد من عدم وجود CSS آخر أو JavaScript يتداخل مع هذه الأنماط. قد تحتاج إلى استخدام أدوات المطور في المتصفح للتحقق من ذلك.
تأكد من إضافة الكود داخل السياق المناسب حيث يتم تفعيل الكود عند تحميل البيانات في الجدول.
User
لم يتم تغيير اللون
Assistant
إذا لم يتم تغيير لون خلية "Hour" في جدول "Timesheet Tool Details" كما هو متوقع، دعني أوضح كيفية التأكد من أن العملية تتم بشكل صحيح. سأقدم لك خطوات مفصلة وأمثلة لكود يمكن أن يساعدك على تنفيذ ذلك بنجاح.
تأكّد من أن خلية "Hour" تم تحديدها بالضبط
تحقق من وجود العنصر: تأكد من أن خلية "Hour" موجودة بالفعل في وقت تنفيذ الكود. يمكن أن يتم ذلك من خلال أدوات المطور (Developer Tools) في المتصفح.
استمع إلى حدث التحديث: تأكد من أن التعليمات البرمجية التي تغير اللون تُنفذ بعد إضافة البيانات إلى الجدول.
كود JavaScript المعدل
إليك طريقة بسيطة للتأكد من تحديد خلية "Hour" بشكل صحيح وتغيير لونها:
javascript
frappe.ui.form.on('Timesheet Tool Details', {
refresh: function(frm, cdt, cdn) {
setTimeout(function() {
update_absent_buttons(frm);
changeHourCellColor(frm);
}, 300); // يُعطى بعض الوقت للجدول للتحديث
}
});
// دالة لتغيير لون خلية "Hour"
function changeHourCellColor(frm) {
const rows = frm.fields_dict['timesheet_tool_details'].grid.grid_rows;
rows.forEach(row => {
// ابحث عن خلية "Hour"
let hourCell = row.$row.find('[data-fieldname="hour"] .static-area');
if (hourCell.length) {
hourCell.css('background-color', 'green'); // تغيير لون الخلفية إلى الأخضر
hourCell.css('color', 'white'); // اختيارياً تغيير لون النص لزيادة الوضوح
}
});
}
تأكيد التحديد:
التحقق من الصناديق النصية: إذا كانت لديك أدلة نصية أو أدوات مطور، تحقق مما إذا كانت العقد التي تستهدفها تظهر في الهيكلية DOM الخاصة بك.
استخدام frappe.after_ajax (بديل):
إذا كانت المشكلة ما تزال قائمة، جرب استخدام frappe.after_ajax لضمان تحديث الخلايا بعد تحميل البيانات أخيرًا.
javascript
frappe.ui.form.on('Timesheet Tool Details', {
refresh: function(frm, cdt, cdn) {
frappe.after_ajax(function() {
// تنفيذ هذا بعد الانتهاء من جميع استدعاءات AJAX
update_absent_buttons(frm);
changeHourCellColor(frm);
});
}
});
الاختبار والتحقق:
تحقق من الرسائل: اضمن أنك ترى أي رسائل في وحدة التحكم (console) في أدوات المطور، مما قد يشير إلى أخطاء.
التحقق من التغييرات: بعد تنفيذ الكود، تابع وحدة التحكم أو عرض علامة "المراقبة" لبعض العناصر، وتأكد أن العنصر المحدد للعنصر "hour" هو بالضبط ما تتوقعه.
ملاحظات:
تأكد من أنك قد قمت بإضافة الكود داخل الحوافز الصحيحة وبدون أي تعارض خارجي مع التعليمات البرمجية الأخرى.
استخدم أدوات المطور لجعل عناوين الخلايا مرئية إذا كانت مخفية عن طريق CSS آخر.
User
لم يتم تغيير اللون
Assistant
إذا لم يتم تغيير اللون بعد تطبيق الكود، فلنقم بتجربة بعض الخطوات والأساليب الإضافية لضمان تحقيق ذلك. سأتأكد من أننا نستهدف خلية "Hour" بشكل صحيح وننفذ التغييرات في الوقت المناسب.
خطوات تفصيلية للتأكد من تغيير لون خلية "Hour":
التأكد من عنصر الخلية: قم بتضمين تعليمات console.log للتحقق مما إذا كانت البيانات متاحة والعنصر مستهدف بشكل صحيح.
تطبيق التغييرات في الموقِع الصحيح: تأكد من تنفيذ الشيفرة البرمجية بعد تحميل البيانات في الجدول.
كود JavaScript المعدل
قم بإضافة الكود أدناه إلى وظيفتك التي تتحكم في الجدول الفرعي "Timesheet Tool Details"، وتأكد من تنفيذه بعد تحميل البيانات في الجدول.
javascript
frappe.ui.form.on('Timesheet Tool Details', {
refresh: function(frm, cdt, cdn) {
// أدخل هذا مباشرة بعد تحميل البيانات
setTimeout(function() {
update_absent_buttons(frm);
changeHourCellColor(frm);
}, 500); // زيادة الوقت إذا لزم الأمر
}
});
// دالة لتغيير لون خلية "Hour"
function changeHourCellColor(frm) {
const rows = frm.fields_dict['timesheet_tool_details'].grid.grid_rows || []; // تأكد من وجود الصفوف
rows.forEach(row => {
// ابحث عن خلية "Hour"
let hourCell = row.$row.find('[data-fieldname="hour"] .static-area');
console.log(hourCell); // سجل الخلية للتحقق من وجودها
if (hourCell.length) {
hourCell.css('background-color', 'green');
hourCell.css('color', 'white'); // إذا كنت تريد النص أبيض للتباين
}
});
// دليل إضافي: إذا كنت بحاجة إلى التحقق من النتائج
console.log('تم تغيير لون خلية الساعة.');
}
إضافات مهمة:
console.log: هذه الرسائل ستساعدك في التأكد من أن الكود يستهدف الخلية الصحيحة ويعمل كما هو متوقع، لذا ألقِ نظرة على الـ Console في أدوات المطور (Developer Tools) في متصفحك.
User
لم يظهر شيئ في console
Assistant
إذا لم تظهر أي رسائل في وحدة التحكم (Console) عند تنفيذ الكود، فهذا يشير إلى أن الكود قد لا يعمل كما هو متوقع، أو أن الدالة refresh لم تُستدعى بسبب عدم استيفاء الشروط اللازمة. إليك خطوات لحل هذه المشكلة:
خطوات للتحقق
تأكد من Load الحقول بشكل صحيح: تأكد من أن حقل Timesheet Tool Details يتم تحميله بشكل صحيح وأن هناك بيانات فيه عند تنفيذ الكود.
تحديد مكان التنفيذ: تريد التأكد من أن الكود يُنفذ في المكان الصحيح، لذا سنجرب استخدام حدث validate أو onload عوضًا عن refresh، لأن refresh قد لا تعمل في كل الأحيان حسب السياق.
كود JavaScript المعدل
قم بتجربة هذا الكود المعدل، حيث نقوم بتطبيق التغييرات على مستوى الوثيقة أثناء تحميلها:
javascript
frappe.ui.form.on('Timesheet Tool', {
onload: function(frm) {
// ننتظر قليلاً بعد تحميل البيانات
setTimeout(function() {
update_absent_buttons(frm);
changeHourCellColor(frm); // استدعاء تغيير اللون هنا
}, 500); // يمكن زيادة الوقت إذا كانت البيانات تأخذ وقتًا لتحميلها
}
});
function changeHourCellColor(frm) {
const rows = frm.fields_dict['timesheet_tool_details'].grid.grid_rows || []; // تأكد من وجود الصفوف
console.log("Total Rows:", rows.length); // تحقق من عدد الصفوف
rows.forEach(row => {
// ابحث عن خلية "Hour"
let hourCell = row.$row.find('[data-fieldname="hour"] .static-area');
console.log(hourCell); // سجل الخلية للتحقق من وجودها
if (hourCell.length) {
hourCell.css('background-color', 'green');
hourCell.css('color', 'white'); // إذا كنت تريد النص أبيض للتباين
}
});
// دليل إضافي: إذا كنت بحاجة إلى التحقق من النتائج
console.log('تم تغيير لون خلية الساعة.');
}
الملاحظات:
Not yet included in a published release.
Unit Testing: If possible, implement some form of unit testing for the critical parts of the code, especially those managing business logic and data handling. This will help ensure reliability as changes are made in the future.
Conclusion
Overall, the code effectively handles the various features necessary for a timesheet management tool within a Frappe application. Keep best practices in mind as you continue to enhance and maintain the application, focusing on user experience and performance optimization.
// frm.fields_dict['timesheet_tool_details'].grid.wrapper.on('click', '.grid-static-col[data-fieldname="attendance"]', function(event) {
// let row = $(this).closest('.grid-row');
// let row_doc = locals[frm.fields_dict['timesheet_tool_details'].grid.doctype][row.attr("data-name")];
// if (row_doc) {
// openActivityTypeDialog(frm, row_doc);
// }
// });
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.confirm(
__('Are you sure you want to fetch employees?'),
function() {
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);
}
}
});
},
function() {
frappe.msgprint(__('Employee fetching has been canceled.'));
}
);
},
get_employee_over_time(frm) {
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
// عرض رسالة التأكيد
frappe.confirm(
__('Are you sure you want to fetch employees?'),
function() {
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");
}
}
});
},
function() {
frappe.msgprint(__('Employee fetching has been canceled.'));
}
);
},
get_employee_deduction(frm) {
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
// عرض رسالة التأكيد
frappe.confirm(
__('Are you sure you want to fetch employees?'),
function() {
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");
}
}
});
},
function() {
frappe.msgprint(__('Employee fetching has been canceled.'));
}
);
},
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) {
// Target each "Absent" button within the sub-table
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(' Edit Activity Type');
}
});
}
frappe.ui.form.on('Timesheet Tool Details', {
refresh: function(frm, cdt, cdn) {
setTimeout(function() {
update_absent_buttons(frm);
}, 300);
},
edit_activity_type: function(frm, cdt, cdn) {
let child = frappe.get_doc(cdt, cdn);
let employeeName = child.employee_name
frappe.call({
method: "frappe.client.get_list",
args: {
doctype: "Activity Type",
fields: ["name"]
},
callback: function(response) {
if (response.message) {
let activity_types = response.message.map(item => item.name);
code
let dialog = new frappe.ui.Dialog({
title: "Select Activity Type",
fields: [
{
"fetch_from": "employee.employee_name",
"fieldname": "employee_name",
"fieldtype": "Read Only",
"label": "Member Name"
},
{
fieldname: "activity_container",
fieldtype: "HTML"
}
],
size: "large"
});
// Set the value of the employee_name field
dialog.fields_dict.employee_name.set_value(employeeName);
let $container = $(dialog.fields_dict.activity_container.wrapper);
$container.css({
"display": "grid",
"grid-template-columns": "repeat(auto-fit, minmax(120px, 1fr))",
"gap": "15px",
"margin-top": "20px",
"padding": "20px",
"border-radius": "8px",
"background-color": "#f7f7f7",
"box-shadow": "0 2px 10px rgba(0, 0, 0, 0.1)"
});
activity_types.forEach(type => {
let $btn = $(`<button class="btn btn-primary">${type}</button>`);
// Design of the button
$btn.css({
"padding": "15px",
"font-size": "14px",
"text-align": "center",
"border-radius": "5px",
"border": "none",
"transition": "background-color 0.3s, transform 0.2s",
"background-color": "#21bdad",
"color": "#fff",
"box-shadow": "0 4px 6px rgba(0, 0, 0, 0.1)"
});
// The button's on the pass.
$btn.on("mouseenter", function() {
$(this).css("background-color", "#20887d");
$(this).css("transform", "scale(1.05)");
});
$btn.on("mouseleave", function() {
$(this).css("background-color", "#21bdad");
$(this).css("transform", "scale(1)");
});
// When you press the button
$btn.on("click", function() {
frappe.model.set_value(cdt, cdn, 'attendance', type);
frappe.model.set_value(cdt, cdn, 'hour', 0);
dialog.hide();
frm.refresh_field('timesheet_tool_details');
});
$container.append($btn);
});
dialog.show();
}
}
});
}
});
// 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) {
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);
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"
};
};
// تكرار استدعاء employee query لبقية الجدول
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', () => {
return {
filters: { company: frm.doc.company }
};
});
},
get_employee(frm) {
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
// عرض رسالة التأكيد
frappe.confirm(
__('Are you sure you want to fetch employees?'),
function() { // إذا أكد المستخدم
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);
}
}
});
},
function() { // إذا رفض المستخدم
frappe.msgprint(__('Employee fetching has been canceled.'));
}
);
},
get_employee_over_time(frm) {
// نفس المنطق في get_employee
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
frappe.confirm(
__('Are you sure you want to fetch employees?'),
function() {
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");
}
}
});
},
function() {
frappe.msgprint(__('Employee fetching has been canceled.'));
}
);
},
get_employee_deduction(frm) {
// نفس المنطق في get_employee
if (settings.is_project_mandatory && !frm.doc.project) {
frappe.msgprint(__('Please select a Project before fetching employees.'));
return;
}
frappe.confirm(
__('Are you sure you want to fetch employees?'),
function() {
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");
}
}
});
},
function() {
frappe.msgprint(__('Employee fetching has been canceled.'));
}
);
},
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);
}
});
},
});
// تابع للتعامل مع أزرار إنشاء وإرسال السجل
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."
);
}
// تابع للتعامل مع زر إرسال السجل
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."
);
}
// تابع لفحص الأدوار
function hasRole(roleName) {
return frappe.user.has_role(roleName);
}
// بقية الأكواد كما هي...
تحسينات وإضافات:
تأكيد قبل الجلب: تم إضافة وظيفة frappe.confirm قبل جلب بيانات الموظفين، مما يمنع المستخدم من إجراء العمليات غير المقصودة.
رسالة إلغاء: عند رفض المستخدم، يتم عرض رسالة توضح أن العملية قد تم إلغاؤها.
ملحوظات:
تأكد من أن جميع الدوال الأخرى في الكود مثل handle_button تعمل بشكل متسق مع التعديلات.
يمكنك تحسين تجربة المستخدم دائماً بإضافة خيارات رسائل أو إشعارات أخرى حسب حاجة التطبيق.
تغيير الوقت: قمت بزيادة وقت الانتظار إلى 500 ملي ثانية في setTimeout للسماح بتأخير إضافي في تحميل البيانات. يمكنك زيادة المدة إذا ظل اللون غير متغير.
تأكد من تحميل البيانات: تأكد من أن الجدول يحتوي على بيانات عند تنفيذ الكود. إذا كان الجدول فارغًا، فلن يتم تغيير أي لون.
إذا استمرت المشكلة:
تحقق من Conflict (تعارض): تأكد من عدم وجود أي CSS آخر يقوم بإصدار تعيين لون مماثل بحيث يكون له أولوية أعلى.
تحقق من الإدراج في .static-area: قد تحتاج إلى استهداف عنصر مختلف بناءً على هيكل HTML يمكنك مشاركته، لذا إذا كانت لديك فارق بين هيكلة HTML التي تشاركها ومحتوى DOM النهائي، قد تحتاج إلى تكييف الكود وفقًا لذلك.
استخدام التعليقات التوضيحية:
إذا لم تتمكن من تغيير اللون بعد كل هذه المحاولات، سأكون سعيدًا بمساعدتك إذا قمت بمشاركة الأخطاء التي تراها في وحدة التحكم أو توضيح مزيد من التفاصيل حول هيكل الكود الحالي.
حدث onload: استخدم onload بدلاً من refresh، حيث يتم تنفيذ الكود عند تحميل الوثيقة. تأكد من أن الجدول قد تم تحميله قبل تشغيل changeHourCellColor.
سجلات توضيحية: تمت إضافة رسائل توضيحية لتحديد ما إذا كانت الصفوف موجودة وما إذا تم العثور على hourCell. هذا سيساعدك في فهم مكان المشكلة.
تأكيد التحميل: تأكد من أنك تتأكد من تحميل بيانات الجدول قبل تنفيذ الدالة.
نصائح للتنقيح:
افتح أدوات المطور في متصفحك (عادةً بالضغط على F12).
اذهب إلى علامة التبويب "Console" وتأكد من عدم وجود أخطاء. إذا كنت ترى شيءًا متعلقًا بالخطأ، فسيساعد ذلك في تحديد الخطأ.
تأكد من أن الجدول يحتوي على بيانات عند تحميل الوثيقة.
إذا لم تكن لديك أي رسائل تظهر في وحدة التحكم، فقد تحتاج إلى التحقق مما إذا كانت الوظيفة تدفع في مكان استدعاء صحيح عبر البيئة أو التحقق من هيكل DOM باستخدام أدوات المطور.