// Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
// For license information, please see license.txt
// timesheet_tool.js
let settings = {};
function getEmployeeData(frm, child_table) {
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: child_table,
project: frm.doc.project || null
},
callback: function(response) {
if (response.exc) {
frappe.msgprint(__("Error fetching employees: {0}", [response.exc]));
return;
}
frm.refresh_field(child_table);
switch (child_table) {
case "timesheet_tool_details":
applyBlueColorHour(COLOR_HOUR); // Use constant
attachHideEventHandlers(frm);
hideGridButtons(frm);
break;
case "timesheet_tool_details_over_time":
applyBlueColorToOverTime(COLOR_HOUR); // Use constant
break;
case "timesheet_tool_details_deduction":
applyBlueColorDeduction(COLOR_DEDUCTION); // Use constant
break;
}
},
error: function(err) {
frappe.msgprint(__("An unexpected error occurred. Please check the console."));
console.error(err);
}
});
},
function() {
frappe.msgprint(__('Employee fetching has been canceled.'));
}
);
Assistant
User
اريد قبل عرض الدايلو ان يتم الاستعلم عن Desk Theme الخاص بالمستخدم الحالي وتغيير تنسيق حاوية الازرار داخل الدايلوق لتتناسب مع الثيم اذا كان الثيم Light تكون خلفيت حاوية الازرار ابيض اما اذا كان
Assistant
User
request.js:473 Traceback (most recent call last):
File "apps/frappe/frappe/app.py", line 114, in application
response = frappe.api.handle(request)
File "apps/frappe/frappe/api/init.py", line 49, in handle
data = endpoint(**arguments)
File "apps/frappe/frappe/api/v1.py", line 36, in handle_rpc_call
return frappe.handler.handle()
File "apps/frappe/frappe/handler.py", line 49, in handle
data = execute_cmd(cmd)
File "apps/frappe/frappe/handler.py", line 85, in execute_cmd
return frappe.call(method, **frappe.form_dict)
File "apps/frappe/frappe/init.py", line 1725, in call
return fn(*args, **newargs)
File "apps/frappe/frappe/utils/typing_validations.py", line 31, in wrapper
return func(*args, **kwargs)
File "apps/frappe/frappe/client.py", line 153, in get_single_value
return frappe.db.get_single_value(doctype, field)
File "apps/frappe/frappe/database/database.py", line 842, in get_single_value
frappe.throw(
File "apps/frappe/frappe/init.py", line 602, in throw
msgprint(
File "apps/frappe/frappe/init.py", line 567, in msgprint
_raise_exception()
File "apps/frappe/frappe/init.py", line 518, in _raise_exception
raise exc
frappe.exceptions.ValidationError: Field Administrator does not exist on User
80
contentscript.js:31 Uncaught TypeError: Cannot read properties of null (reading 'querySelector')
Assistant
الخطأ المعروض يشير إلى مشكلتين قد تواجهك في تطبيق Frappé الخاص بك. دعنا نناقش الخطأين وكيف يمكنك معالجتهما.
1. خطأ في الوصول إلى الحقل Administrator على نموذج User:
frappe.exceptions.ValidationError: Field Administrator does not exist on User
هذا الخطأ يشير إلى أنك تحاول الحصول على قيمة حقل غير موجود في نموذج . في هذا المثال، يبدو أنك تحاول استعلام عن حقل ، لكن يبدو أنه غير موجود في النموذج.
User
اريد قبل عرض الدايلو ان يتم الاستعلم عن Desk Theme الخاص بالمستخدم الحالي وتغيير تنسيق حاوية الازرار داخل الدايلوق لتتناسب مع الثيم اذا كان الثيم Light تكون خلفيت حاوية الازرار ابيض اما اذا كان

Assistant
}
function addEditActivityButton(frm) {
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
const btnSelector = '.grid-buttons .grid-edit-activity'; // Define the selector
// Check if the button already exists in the right context
if (gridWrapper.find(btnSelector).length > 0) {
return;
}
let edit_button = `<button type="button" class="btn btn-xs btn-success grid-edit-activity" style="display: none;"><svg class="icon icon-sm" style="margin-right: 5px; color : white;"><use href="#icon-edit"></use></svg>Edit Activity Type</button>`;
gridWrapper.find('.grid-buttons').append(edit_button);
function toggle_edit_button_visibility() {
let selected_rows = frm.fields_dict['timesheet_tool_details'].grid.get_selected();
if (selected_rows.length > 0) {
gridWrapper.find(btnSelector).show();
} else {
gridWrapper.find(btnSelector).hide();
}
}
toggle_edit_button_visibility();
gridWrapper.on('click', '.grid-row-check', function() {
toggle_edit_button_visibility();
});
gridWrapper.on('click', btnSelector, function() {
editActivityTypeForSelected(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.exc) {
frappe.msgprint(__("Error during {0}: {1}", [btn_label, response.exc]));
return;
}
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(response) {
if (response.exc) {
frappe.msgprint(__("Error during {0}: {1}", [btn_label, response.exc]));
return;
}
frm.reload_doc();
frappe.msgprint(__(success_msg));
}
});
},
() => {
frappe.msgprint(__("Action cancelled."));
}
);
});
}
},
error: function(err) {
frappe.msgprint(__("An unexpected error occurred. Please check the console."));
console.error(err);
}
});
}
// 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
const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
gridWrapper.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
}
});
}
// A function to modify the activity type of the selected rows
function editActivityTypeForSelected(frm) {
let selectedRows = [];
// استخدام خانة الاختيار الموجودة (row-check) لتحديد الصفوف
frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check:checked').each(function() {
let row = $(this).closest('.grid-row'); // الحصول على الصف الأب
let rowName = row.data('name'); // استخراج اسم الصف من البيانات
selectedRows.push(rowName);
});
if (selectedRows.length === 0) {
frappe.msgprint(__('Please select at least one row.'));
return;
}
// تجميع أسماء الموظفين
let employeeNames = selectedRows.map(rowName => {
let child = frappe.get_doc('Timesheet Tool Details', rowName);
return child ? child.employee_name : null;
}).filter(name => name !== null);
// استدعاء دالة editActivityType مع قائمة الصفوف وأسماء الموظفين
editActivityType(selectedRows, employeeNames, () => {
frm.refresh_field('timesheet_tool_details');
attachHideEventHandlers(frm);
hideGridButtons(frm);
});
}
// Function to create an activity type selection dialog
// Function to create an activity type selection dialog
function editActivityType(rowNames, employeeNames, callback) {
// Get the user's desk theme
frappe.db.get_single_value('User', frappe.session.user, 'desk_theme')
.then(desk_theme => {
// Apply CSS based on desk theme
let dialog_style = '';
let card_background_color = ''; // Variable for the card's background color
if (desk_theme === 'Dark') {
dialog_style = `
.frappe-ui-dialog {
background-color: #333;
color: #fff;
}
.frappe-ui-dialog .btn-primary {
background-color: #555;
color: #fff;
border: 1px solid #777;
}
.frappe-ui-dialog .btn-primary:hover {
background-color: #777;
}
`;
card_background_color = '#444'; // Darker background for dark theme
} else {
// Light theme (default) or any other theme handling can be added here
dialog_style = `
.frappe-ui-dialog {
background-color: #fff;
color: #000;
}
.frappe-ui-dialog .btn-primary {
background-color: #21bdad;
color: #fff;
border: 1px solid #21bdad;
}
.frappe-ui-dialog .btn-primary:hover {
background-color: #21bdad;
}
`;
card_background_color = '#fff'; // White background for light theme
}
// Create a style element for the dialog
let style_element = document.createElement('style');
style_element.innerHTML = dialog_style;
document.head.appendChild(style_element);
frappe.call({
method: "frappe.client.get_list",
args: {
doctype: "Activity Type",
fields: ["name"]
},
callback: function(response) {
if (response.exc) {
frappe.msgprint(__("Error fetching activity types: {0}", [response.exc]));
return;
}
if (response.message) {
let activity_types = response.message.map(item => item.name);
let dialog = new frappe.ui.Dialog({
title: "Select Activity Type",
fields: [{
"fieldname": "employee_names",
"fieldtype": "Small Text",
"label": "Member Names",
"read_only": 1,
"bold": 1,
},
{
fieldname: "activity_container",
"fieldtype": "HTML"
}
],
size: "large",
onhide: () => {
// Remove style element when dialog is closed
document.head.removeChild(style_element);
}
});
// عرض قائمة بأسماء الموظفين في الحقل Read Only
dialog.fields_dict.employee_names.set_value(employeeNames.join(', '));
let $container = $(dialog.fields_dict.activity_container.wrapper);
// Apply the background color dynamically to the card
$container.html(`<div class="card" style="padding: 20px; border-radius: 8px; background-color: ${card_background_color};"></div>`);
let $card = $container.find('.card');
$card.css({
"display": "grid",
"grid-template-columns": "repeat(auto-fit, minmax(120px, 1fr))",
"gap": "15px",
"margin-top": "20px",
});
activity_types.forEach(type => {
let $btn = $(`<button class="btn btn-primary">${type}</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)"
});
// حدث الزر
$btn.on("click", function() {
// تحديث Attendance لجميع الصفوف المحددة
rowNames.forEach(rowName => {
let child = frappe.get_doc('Timesheet Tool Details', rowName);
if (child) {
frappe.model.set_value(child.doctype, child.name, 'attendance', type);
frappe.model.set_value(child.doctype, child.name, 'hour', 0);
}
});
dialog.hide();
// استدعاء دالة callback بعد إغلاق مربع الحوار
if (callback) {
callback();
}
});
$card.append($btn);
});
dialog.show();
}
},
error: function(err) {
frappe.msgprint(__("An unexpected error occurred. Please check the console."));
console.error(err);
}
});
});
}
// Apply "#dff0d8" background to 'Hour' and 'Edit Activity Type' column dynamically
function applyBlueColorHour(color) {
const hourHeader = document.querySelector('[data-fieldname="hour"] .static-area');
if (hourHeader) {
hourHeader.style.backgroundColor = color;
hourHeader.style.color = "black"; // Ensure text is readable
}
}
// Apply "#dff0d8" background to 'Over Time N' and 'Over Time H' column dynamically
function applyBlueColorToOverTime(color) {
const overTimeNColumn = document.querySelector('[data-fieldname="over_time_n"] .static-area');
if (overTimeNColumn) {
overTimeNColumn.style.backgroundColor = color;
overTimeNColumn.style.color = "black"; // Ensure text is readable
}
const overTimeHColumn = document.querySelector('[data-fieldname="over_time_h"] .static-area');
if (overTimeHColumn) {
overTimeHColumn.style.backgroundColor = color;
overTimeHColumn.style.color = "black"; // Ensure text is readable
}
}
// Apply "#c56565" background to 'Deduction' column dynamically
function applyBlueColorDeduction(color) {
const deductionColumn = document.querySelector('[data-fieldname="deduction"] .static-area');
if (deductionColumn) {
deductionColumn.style.backgroundColor = color;
deductionColumn.style.color = "black"; // Ensure text is readable
}
}
The provided JavaScript code appears to be part of a web application that integrates with a system called Frappe and is likely used for managing timesheets within an organization. Below is a summary and some explanations about the key components and functionalities in the script:
Overview
The script defines behaviors for a "Timesheet Tool" form in a Frappe application. It handles various aspects, such as fetching employee data, managing timesheet entries, dynamically altering UI elements, and reacting to user interactions.
Key Components
Constants:
EMPLOYEE_QUERY: A query string that likely points to a method for fetching employees.
COLOR_HOUR and COLOR_DEDUCTION: Constants used for coloring specific areas in the UI.
Event Listeners:
frappe.ui.form.on: This is Frappe's way of handling form events, such as refresh, project, or button clicks.
Functions for Employee Retrieval:
get_employee, get_employee_over_time, and get_employee_deduction: Call enhance user interaction by allowing to fetch employees based on project selections for different types of timesheet entries.
Dynamic Queries and Filtering:
The employee query is filtered to return only active employees with assignments related to Salary Structure.
Button Management:
Functions like handleCreateTimesheetButton and handleSubmitTimesheetButton manage the creation and submission of timesheet records based on user permissions.
UI Enhancements:
Functions such as applyBlueColorHour, applyBlueColorToOverTime, and applyBlueColorDeduction modify background colors of specific columns in the timesheet for better readability.
Confirmation and Error Handling:
frappe.confirm is used for showing confirmation dialogs before proceeding with significant actions.
Error handling is present in various functions, usually accompanied by user feedback via frappe.msgprint.
Edit Activity Functionality:
The script allows the user to edit activity types for selected rows using a modal dialog. It gathers selected rows and manages their state efficiently.
Maintaining Code Quality
Modularity: The code is quite modular, dividing functionality into separate functions, which helps maintainability.
Error Handling: While there are checks and error messages, consider uniformity—some error messages provide good feedback while others imply a generic issue.
Suggestions for Improvement
Commenting and Code Clarity: More comments explaining non-obvious sections or complex logic could help future developers understand intent and functionality quickly.
DRY Principle: There may be opportunities to consolidate repeated logic (like checking roles or handling button visibility).
Unit Tests: Integration of unit tests for critical JS functions can ensure that future changes do not break existing functionality.
Conclusion
This code snippet is a comprehensive part of a targeted timesheet management tool that exemplifies good practices in Frappe development. By systematically approaching data retrieval, UI handling, and user experience, it aims to create a quality application for managing timesheets effectively.
لتحقيق ما تطلبه، يمكننا تعديل دالة editActivityType بحيث نقوم بالتحقق من ثيم المستخدم الحالي (Desk Theme) ومن ثم نغير تنسيق حاوية الأزرار في dawla (Dialog) بناءً على هذا الثيم.
إليك كيف يمكن تعديل الكود:
function editActivityType(rowNames, employeeNames, callback) {
// Get the user's desk theme
frappe.db.get_single_value('User', frappe.session.user, 'desk_theme')
.then(desk_theme => {
// Define CSS styles based on the desk theme
let dialog_style = '';
let button_background_color = ''; // Variable for button's background color
let card_background_color = ''; // Variable for the card's background color
if (desk_theme === 'Dark') {
dialog_style = `
.frappe-ui-dialog {
background-color: #333;
color: #fff;
}
.frappe-ui-dialog .btn-primary {
background-color: #555;
color: #fff;
border: 1px solid #777;
}
.frappe-ui-dialog .btn-primary:hover {
background-color: #777;
}
`;
card_background_color = '#444'; // Darker background for dark theme
button_background_color = '#555'; // Button background for dark theme
} else {
// Light theme (default) handling
dialog_style = `
.frappe-ui-dialog {
background-color: #fff;
color: #000;
}
.frappe-ui-dialog .btn-primary {
background-color: #21bdad;
color: #fff;
border: 1px solid #21bdad;
}
.frappe-ui-dialog .btn-primary:hover {
background-color: #21bdad;
}
`;
card_background_color = '#fff'; // White background for light theme
button_background_color = '#21bdad'; // Button background for light theme
}
// Create a style element for the dialog
let style_element = document.createElement('style');
style_element.innerHTML = dialog_style;
document.head.appendChild(style_element);
frappe.call({
method: "frappe.client.get_list",
args: {
doctype: "Activity Type",
fields: ["name"]
},
callback: function(response) {
if (response.exc) {
frappe.msgprint(__("Error fetching activity types: {0}", [response.exc]));
return;
}
if (response.message) {
let activity_types = response.message.map(item => item.name);
let dialog = new frappe.ui.Dialog({
title: "Select Activity Type",
fields: [{
"fieldname": "employee_names",
"fieldtype": "Small Text",
"label": "Member Names",
"read_only": 1,
"bold": 1,
},
{
fieldname: "activity_container",
"fieldtype": "HTML"
}
],
size: "large",
onhide: () => {
// Remove style element when dialog is closed
document.head.removeChild(style_element);
}
});
// Display the employee names in the Read Only field
dialog.fields_dict.employee_names.set_value(employeeNames.join(', '));
let $container = $(dialog.fields_dict.activity_container.wrapper);
// Apply the background color dynamically to the card
$container.html(`<div class="card" style="padding: 20px; border-radius: 8px; background-color: ${card_background_color};"></div>`);
let $card = $container.find('.card');
$card.css({
"display": "grid",
"grid-template-columns": "repeat(auto-fit, minmax(120px, 1fr))",
"gap": "15px",
"margin-top": "20px",
});
activity_types.forEach(type => {
let $btn = $(`<button class="btn btn-primary" style="background-color: ${button_background_color};">${type}</button>`);
// Button styling
$btn.css({
"padding": "15px",
"font-size": "14px",
"text-align": "center",
"border-radius": "5px",
"border": "none",
"transition": "background-color 0.3s, transform 0.2s",
"color": "#fff",
"box-shadow": "0 4px 6px rgba(0, 0, 0, 0.1)"
});
// Button event
$btn.on("click", function() {
// Update Attendance for all selected rows
rowNames.forEach(rowName => {
let child = frappe.get_doc('Timesheet Tool Details', rowName);
if (child) {
frappe.model.set_value(child.doctype, child.name, 'attendance', type);
frappe.model.set_value(child.doctype, child.name, 'hour', 0);
}
});
dialog.hide();
// Call callback after closing the dialog
if (callback) {
callback();
}
});
$card.append($btn);
});
dialog.show();
}
},
error: function(err) {
frappe.msgprint(__("An unexpected error occurred. Please check the console."));
console.error(err);
}
});
});
}
التعديلات المضافة:
تحديد لون الخلفية لحاوية الأزرار: إذا كان ثيم المستخدم هو "Dark" سيُستخدم لون داكن، وإذا كان "Light" سيتم استخدام لون خلفية أبيض.
تعديل زر النشاط: يتم تعيين لون الخلفية للأزرار حسب الثيم.
بهذا الشكل، ستحصل على تنسيق مناسب لحاوية الأزرار في نافذة الحوار، مما يحسن من تجربة المستخدم.
User
Administrator
الخطوات للتصحيح:
تحقق من نموذج User في تطبيق Frappé لديك وتأكد من أنك تشير إلى حقل موجود.
إذا كان هدفك هو التحقق من وظيفة المستخدم، يمكنك استخدام frappe.get_roles(frappe.session.user) بدلاً من النظر في حقل غير موجود.
par مثال لتصحيح الجزء:
// بدلاً من
frappe.db.get_single_value('User', frappe.session.user, 'desk_theme')
// يمكنك استخدام
frappe.get_roles(frappe.session.user).then((roles) => {
// تحقق من وجود الدور أو استخدامه كما هو مطلوب
});
2. خطأ في contentscript.js:
Uncaught TypeError: Cannot read properties of null (reading 'querySelector')
هذا الخطأ يعني أنك تحاول استخدام querySelector على عنصر غير موجود في الصفحة (null).
الخطوات للتصحيح:
تأكد من أن العناصر التي تحاول الوصول إليها موجودة في DOM قبل محاولة الاستعلام عنها.
يمكنك استخدام شرط لتجنب هذا الخطأ، مثل:
const hourHeader = document.querySelector('[data-fieldname="hour"] .static-area');
if (hourHeader) {
hourHeader.style.backgroundColor = color;
hourHeader.style.color = "black"; // Ensure text is readable
} else {
console.error("Element for hour header does not exist.");
}
الخطوات العامة للتصحيح:
تأكد من وجود الحقول: تحقق من أن جميع الحقول التي تستعلم عنها موجودة في النموذج.
إضافة معالجة الأخطاء: دائمًا من الجيد إضافة معالجة أخطاء في موقع للحصول على معلومات تفصيلية عند حدوث مشاكل في الوصول إلى عناصر DOM.
استخدم أدوات المطور: استخدم أدوات المطور (DevTools) في المتصفح للتأكد من وجود العناصر المطلوبة ومراقبة الأخطاء.
بعد تنفيذ هذه التعديلات، يجب أن تقلل من الأخطاء وتتيح لك تدفق العمل بشكل أكثر سلاسة.
يمكنك تنفيذ ما طلبته بتعديل دالة editActivityType للتحقق من الثيم الخاص بالمستخدم قبل عرض حاوية الأزرار في الدايلوق (Dialog). سيتيح لك هذا تغيير تنسيق حاوية الأزرار بناءً على الثيم، بحيث تكون الخلفية بيضاء إذا كان الثيم "Light"، وأي خلفية مناسبة أخرى إذا كان الثيم مختلفاً.
إليك كيفية تنفيذ ذلك:
function editActivityType(rowNames, employeeNames, callback) {
// احصل على ثيم الدسكتوب الخاص بالمستخدم
frappe.db.get_single_value('User', frappe.session.user, 'desk_theme')
.then(desk_theme => {
// تعريف التنسيقات بناءً على ثيم المستخدم
let dialog_style = '';
let button_background_color = ''; // لون خلفية الأزرار
let card_background_color = ''; // لون خلفية الحاوية
if (desk_theme === 'Dark') {
dialog_style = `
.frappe-ui-dialog {
background-color: #333;
color: #fff;
}
.frappe-ui-dialog .btn-primary {
background-color: #555;
color: #fff;
border: 1px solid #777;
}
.frappe-ui-dialog .btn-primary:hover {
background-color: #777;
}
`;
card_background_color = '#444'; // خلفية داكنة للثيم الداكن
button_background_color = '#555'; // لون خلفية الأزرار
} else {
// الثيم الفاتح (Light)
dialog_style = `
.frappe-ui-dialog {
background-color: #fff;
color: #000;
}
.frappe-ui-dialog .btn-primary {
background-color: #21bdad;
color: #fff;
border: 1px solid #21bdad;
}
.frappe-ui-dialog .btn-primary:hover {
background-color: #21bdad;
}
`;
card_background_color = '#fff'; // خلفية بيضاء للثيم الفاتح
button_background_color = '#21bdad'; // لون خلفية الأزرار
}
// إنشاء عنصر تنسيق للدايلوق
let style_element = document.createElement('style');
style_element.innerHTML = dialog_style;
document.head.appendChild(style_element);
frappe.call({
method: "frappe.client.get_list",
args: {
doctype: "Activity Type",
fields: ["name"]
},
callback: function(response) {
if (response.exc) {
frappe.msgprint(__("Error fetching activity types: {0}", [response.exc]));
return;
}
if (response.message) {
let activity_types = response.message.map(item => item.name);
let dialog = new frappe.ui.Dialog({
title: "Select Activity Type",
fields: [{
"fieldname": "employee_names",
"fieldtype": "Small Text",
"label": "Member Names",
"read_only": 1,
"bold": 1,
},
{
fieldname: "activity_container",
"fieldtype": "HTML"
}
],
size: "large",
onhide: () => {
// إزالة عنصر التنسيق عند إغلاق الدايلوق
document.head.removeChild(style_element);
}
});
// عرض أسماء الموظفين في الحقل Read Only
dialog.fields_dict.employee_names.set_value(employeeNames.join(', '));
let $container = $(dialog.fields_dict.activity_container.wrapper);
// تطبيق لون الخلفية بشكل ديناميكي على الحاوية
$container.html(`<div class="card" style="padding: 20px; border-radius: 8px; background-color: ${card_background_color};"></div>`);
let $card = $container.find('.card');
$card.css({
"display": "grid",
"grid-template-columns": "repeat(auto-fit, minmax(120px, 1fr))",
"gap": "15px",
"margin-top": "20px",
});
activity_types.forEach(type => {
let $btn = $(`<button class="btn btn-primary" style="background-color: ${button_background_color};">${type}</button>`);
// تصميم الزر
$btn.css({
"padding": "15px",
"font-size": "14px",
"text-align": "center",
"border-radius": "5px",
"border": "none",
"transition": "background-color 0.3s, transform 0.2s",
"color": "#fff",
"box-shadow": "0 4px 6px rgba(0, 0, 0, 0.1)"
});
// حدث الزر
$btn.on("click", function() {
// تحديث Attendance لجميع الصفوف المحددة
rowNames.forEach(rowName => {
let child = frappe.get_doc('Timesheet Tool Details', rowName);
if (child) {
frappe.model.set_value(child.doctype, child.name, 'attendance', type);
frappe.model.set_value(child.doctype, child.name, 'hour', 0);
}
});
dialog.hide();
// استدعاء دالة callback بعد إغلاق مربع الحوار
if (callback) {
callback();
}
});
$card.append($btn);
});
dialog.show();
}
},
error: function(err) {
frappe.msgprint(__("An unexpected error occurred. Please check the console."));
console.error(err);
}
});
});
}
الشرح:
التحقق من الثيم: نستعلم عن desk_theme الخاص بالمستخدم من جدول User.
تنسيق حاوية الأزرار: نحدد نمط حاوية الأزرار وخلفيتها بناءً على ما إذا كان الثيم "Light" أو "Dark".
تحديث كود الزر: بينما نصنع الأزرار، نتأكد من تعيين خلفية الزر المناسبة بناءً على الثيم.
إزالة التنسيق عند إغلاق الدايلوق: نتأكد من إزالة عناصر النمط عند إغلاق حوار المستخدم.
بهذا الشكل، سيكون لديك حاوية أزرار ملائمة وثيم محترف يتناسب مع إضاءة الواجهة.