انت مبرمج محترف في البرمجة باستخدام frappe framework ولغة البرمجة paython ولغة البرمجة JavaScrept, وانا اريد مساعدتك , لدي Doctype باسم Timesheet Tool ولذي سوف ارسل لك الكود الخاص بملف البايثون وملف الجافاء سكربت الخاص به , يوجد في هذا ال Doctype مجموعة الحقول التاليه : {
project:Link,
company:Link,
day:Date,
get_employee:Button,
timesheet_tool_details:Table
}
اريد ان تظهر رساله تاكيد عند الضغط على زر الانشاء و زر الاعتماد [Create Timesheets,Submit Timesheets] , الان اريد منك انتساعدني في اضافة هذه الميزة واريد منك انا تخبرني كيف ابداء بارسال محتواء الملفات اليك وماهي الخطوات التي اتبعها للتعامل معك , المخرجات اريد ان تكون مخرجات كود كل ملف بعد التعديل وشرح للتعديلات.
Assistant
بالطبع، سأكون سعيداً بمساعدتك في إضافة ميزة رسالة التأكيد عند الضغط على زري "Create Timesheets" و"Submit Timesheets" في Doctype الخاص بك.
الخطوات التي يجب اتباعها
تقديم الكود: يمكنك نسخ ولصق محتويات ملفات بايثون وجافا سكريبت هنا في المحادثة، حتى أتمكن من مراجعتها.
شرح المخرجات: سأنظر في الكود وأقدم لك التعديلات اللازمة مع شرح لكيفية تنفيذها.
تعديل الكود
بعد حصولي على الكود الخاص بك، سأقوم بتعديل الأجزاء المطلوبة لإضافة ميزة رسالة التأكيد، وسأقوم بإرجاع الكود المعدل وأشرح أعلاه التعديلات التي تمت.
خطوات التخزين z
أرسل الكود الخاص بملف بايثون (Python File) وملف الجافا سكريبت (JavaScript File), باستخدام نسق:
plaintext
## كود بايثون
(هنا ضع كود بايثون الخاص بك)
## كود جافا سكريبت
(هنا ضع كود جافا سكريبت الخاص بك)
بمجرد أن أحصل على الكود، سأقوم بمراجعته وتنفيذ التعديلات المطلوبة.
User
Assistant
User
Assistant
User

AttributeError: module 'frappe' has no attribute 'confirm'
Assistant
// Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
// For license information, please see license.txt
// timesheet_tool.js
let settings = {};
frappe.ui.form.on("Timesheet Tool", {
refresh(frm) {
code
attachHideEventHandlers(frm);
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"
};
};
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: { project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
}
}
});
},
project(frm) {
frappe.call({
method: "clear_timesheet_tool_details_table",
doc: frm.doc,
callback: function(response) {
frm.refresh_field("timesheet_tool_details");
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 approved successfully.",
"All records have already been approved."
);
}
// A function to handle buttons
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
}
}
});
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);
}
// 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
}
});
}
لإضافة ميزة رسالة التأكيد عند الضغط على زري "Create Timesheets" و"Submit Timesheets" في Doctype الخاص بك، سنقوم بتعديل كود JavaScript الذي قمت بمشاركته. إليك كيفية القيام بذلك:
التعديلات المطلوبة
إضافة رسائل التأكيد: سنقوم بإضافة رسائل التأكيد قبل استدعاء الدالة التي تتعامل مع إنشاء أو تقديم الأوراق الزمنية.
الكود المعدل
هنا هو الكود المعدل مع الشرح المبين أدناه:
javascript
// 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) {
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"
};
};
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: { project: frm.doc.project || null },
callback: function(response) {
if (!response.exc) {
frm.refresh_field("timesheet_tool_details");
attachHideEventHandlers(frm);
hideGridButtons(frm);
}
}
});
},
project(frm) {
frappe.call({
method: "clear_timesheet_tool_details_table",
doc: frm.doc,
callback: function(response) {
frm.refresh_field("timesheet_tool_details");
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 approved successfully.",
"All records have already been approved."
);
}
// A function to handle buttons with confirmation
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."));
}
// Add confirmation before proceeding
frappe.confirm(
__('Are you sure you want to proceed?'),
function() { // Yes callback
frappe.call({
method: def,
doc: frm.doc,
callback: function() {
frm.reload_doc();
frappe.msgprint(__(success_msg));
}
});
},
function() { // No callback
// Do nothing if the user cancels
}
);
});
button_visible = true; // Mark button as visible
}
}
});
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);
}
// 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');
});
gridWrapper.find('.row-index').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) {
frm.fields_dict['timesheet_tool_details'].grid.wrapper.on('keydown', function(event) {
if (event.ctrlKey && event.key === "ArrowDown") {
return false; // Preventing further treatment of the event
}
});
}
الشرح:
إضافة تأكيد عند الضغط على الأزرار:
تم إدخال دالة frappe.confirm داخل الدالة handle_button. هذه الدالة تظهر رسالة تأكيدية قبل تنفيذ الإجراء.
إذا ضغط المستخدم "نعم"، يتم متابعة تنفيذ العملية. إذا ضغط "لا"، فإن العملية تتوقف.
تعديل دالة handle_button:
بدلاً من استدعاء frappe.call مباشرةً، أصبح هناك تأكيد يطلب من المستخدم ما إذا كان متأكدًا من المتابعة.
بهذا الشكل، ستكون قد أضفت ميزة رسالة التأكيد المطلوبة بنجاح! إذا كان لديك أي استفسارات أخرى أو احتجت إلى مزيد من المساعدة، فلا تتردد في طرحها.
Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
For license information, please see license.txt
timesheet_tool.py
import frappe
from frappe.model.document import Document
from frappe import _
import datetime
from time_sheet_tool.time_sheet_tool.utils.timesheet_tool import check_missing_records
class TimesheetTool(Document):
@frappe.whitelist()
def clear_timesheet_tool_details_table(self):
# Clear the Timesheet Tool Details table
self.set("timesheet_tool_details", [])
code
@frappe.whitelist()
def get_all_employees(self, project=None):
settings = get_settings()
default_activity = settings.dufault_activity
ratio_attendance = settings.ratio_attendance
dufault_working_hours = settings.dufault_working_hours
self.clear_timesheet_tool_details_table()
# Fetch employees depending on the project
if project:
# Fetch employees from Project Team, ensure all conditions are met
employees = frappe.db.sql("""
SELECT DISTINCT
pt.employee AS name,
pt.employee_name,
ss.hour_rate AS hourly_rate,
ssa.salary_structure
FROM
`tabProject Team` pt
INNER JOIN
`tabSalary Structure Assignment` ssa ON pt.employee = ssa.employee
INNER JOIN
`tabSalary Structure` ss ON ssa.salary_structure = ss.name
WHERE
pt.parent = %s
AND pt.fetch_to_timesheet_tool = 1
AND ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
AND ss.docstatus = 1 -- Ensure only approved Salary Structure
AND ss.salary_slip_based_on_timesheet = 1 -- Ensure timesheet-based salary is required
""", (project,), as_dict=True)
if not employees:
frappe.throw(_("No employees found in the Project Team with a valid Salary Structure Assignment and salary slip based on timesheet for the selected project."))
else:
# Fetch active employees directly when no project is selected
employees = frappe.db.sql("""
SELECT DISTINCT
emp.name AS name,
emp.employee_name AS employee_name,
ss.hour_rate AS hourly_rate,
ssa.salary_structure
FROM
`tabEmployee` emp
INNER JOIN
`tabSalary Structure Assignment` ssa ON emp.name = ssa.employee
INNER JOIN
`tabSalary Structure` ss ON ssa.salary_structure = ss.name
WHERE
emp.status = 'Active'
AND ssa.docstatus = 1 -- Ensure only approved Salary Structure Assignments
AND ss.docstatus = 1 -- Ensure only approved Salary Structure
AND ss.salary_slip_based_on_timesheet = 1 -- Ensure timesheet-based salary is required
""", as_dict=True)
# Append employees to the child table
for emp in employees:
self.append("timesheet_tool_details", {
"employee": emp.get('name'),
"employee_name": emp.get('employee_name'),
"hourly_rate": emp.get('hourly_rate'),
"attendance": default_activity,
"ratio_attendance": ratio_attendance,
"salary_structure":emp.get('salary_structure'),
"hour":dufault_working_hours,
})
# Return employees after fetching
return employees
@frappe.whitelist()
def create_attendance(self):
"""
A function to implement all accounts and create the required records.
"""
timesheet_count = 0
additional_salary_count = 0
settings = get_settings()
print("*"*50,self.timesheets_created)
# Preparation of Fields of Settings
salary_component_overtime_h = settings.salary_component_overtime_h
salary_component_overtime_n = settings.salary_component_overtime_n
salary_component_deduction = settings.salary_component_deduction
from_time = f"{self.day} {settings.from_time}"
# Check for values
if not all([salary_component_overtime_h, salary_component_overtime_n, salary_component_deduction]):
frappe.throw(_("Please configure the Salary Components in Timesheet Tool Settings."))
for detail in self.timesheet_tool_details:
try:
if detail.hour:
# total_working_hours
totalhours = detail.hour * detail.ratio_attendance
create_timesheet(self, detail, totalhours, from_time)
timesheet_count += 1
# Additional Salary (Overtime H, Overtime N, Deduction)
if detail.over_time_h:
total_over_time_h = detail.over_time_h * settings.h_over_time
detail.total_payment = total_over_time_h * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_h, detail.total_payment)
additional_salary_count += 1
if detail.over_time_n:
total_over_time_n = detail.over_time_n * settings.n_over_time
detail.total_payment = total_over_time_n * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_n, detail.total_payment)
additional_salary_count += 1
if detail.deduction:
detail.total_payment = detail.deduction * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_deduction, detail.total_payment)
additional_salary_count += 1
except Exception as e:
frappe.log_error(f"Error processing detail for employee {detail.employee}: {str(e)}")
frappe.msgprint(_("Error processing detail for employee {}: {}").format(detail.employee, str(e)))
# Update timesheets_created to True after successfully creating the records
self.db_set("timesheets_created", 1)
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
@frappe.whitelist()
def approval_attendance(self):
"""Approves all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets()
self.approval_additional_salaries()
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been approved successfully."))
self.db_set("timesheets__submited", 1)
except Exception as e:
frappe.throw(_("An error occurred during approval: {0}").format(str(e)))
def approval_timesheets(self, cancel=False):
"""Shared logic for approving or canceling Timesheets."""
timesheet_list = frappe.get_all("Timesheet",
filters={
"timesheet_tool": self.name
},
)
record_num = 0
for timesheet in timesheet_list:
document = frappe.get_doc("Timesheet", timesheet.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
record_num += 1
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Timesheet {0} has been cancelled.").format(document.name))
frappe.msgprint(_("Timesheet {0} has been approved.").format(record_num))
def approval_additional_salaries(self, cancel=False):
"""Shared logic for approving or canceling Additional Salaries."""
additional_salary_list = frappe.get_all("Additional Salary",
filters={
"timesheet_tool": self.name
},
)
record_num = 0
for additional_salary in additional_salary_list:
document = frappe.get_doc("Additional Salary", additional_salary.name)
if not cancel and document.docstatus == 0: # Approve
document.submit()
frappe.db.commit()
record_num +=1
elif cancel and document.docstatus == 1: # Cancel
document.cancel()
frappe.db.commit()
frappe.msgprint(_("Additional Salary {0} has been approved.").format(record_num))
def cancel_attendance(self):
"""Cancels all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets(cancel=True)
self.approval_additional_salaries(cancel=True)
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been cancelled successfully."))
except Exception as e:
frappe.throw(_("An error occurred during cancellation: {0}").format(str(e)))
def on_cancel(self):
# Cancel Timesheets and Additional Salaries when Timesheet Tool is cancelled.
self.cancel_attendance()
def on_submit(self):
self.check_future_day()
self.check_values_in_timesheet_tool_details()
self.check_zero_values_in_timesheet_tool_details()
self.check_over_time_values()
def before_save(self):
pass
def validate(self):
self.ensure_unique_employee()
self.check_limits_in_timesheet_tool_details()
def check_future_day(self):
settings = get_settings()
future_day = settings.future_day
today = datetime.date.today()
# Turn self.day from text to date object
try:
day_date = datetime.datetime.strptime(self.day, "%Y-%m-%d").date()
except ValueError:
frappe.throw(_("Invalid date format for day. Please use YYYY-MM-DD."))
# See if the settings allow future dates.
if not future_day and day_date > today:
frappe.throw(_("Company settings do not allow the establishment of a future date schedule."))
def check_zero_values_in_timesheet_tool_details(self):
"""Check for zero values in timesheet_tool_details and raise an error if found."""
error_rows = []
for idx, detail in enumerate(self.timesheet_tool_details):
# Check if hourly_rate, over_time_n, over_time_h and deduction are all zero
if detail.ratio_attendance != 0:
if detail.hour == 0 and detail.over_time_n == 0 and detail.over_time_h == 0 and detail.deduction == 0:
error_rows.append(idx + 1) # Save the row number (1-based index)
if error_rows:
error_message = _("The following rows have Hour, Over Time N, and Over Time H all equal to 0 in rows: {rows}").format(rows=" , ".join(map(str, error_rows)))
frappe.throw(error_message)
def check_values_in_timesheet_tool_details(self):
if not self.timesheet_tool_details:
frappe.throw(_("Cannot proceed: No records found in Timesheet Tool Details."))
def check_over_time_values(self):
"""Check that values over_time_n,over_time_h cannot be entered for the staff member on the same date."""
for idx, row in enumerate(self.timesheet_tool_details):
if row.over_time_n > 0 and row.over_time_h > 0:
employee_name = row.employee
frappe.throw(
_("Neither of the values Over Time N, Over Time H can be entered for employee {0} at row {1}.").format(employee_name, idx + 1)
)
def check_limits_in_timesheet_tool_details(self):
settings = get_settings()
max_n_over_time = settings.maximum_n_over_time
max_h_over_time = settings.maximum_h_over_time
max_deduction = settings.maximum_deduction
max_standard_working_hours = settings.maximum_standard_working_hours
for idx, detail in enumerate(self.timesheet_tool_details):
if detail.hour is not None and detail.hour > max_standard_working_hours:
frappe.throw(_(f"Row {idx + 1}: The value of 'Hour' cannot exceed the maximum standard working hours ({max_standard_working_hours})."))
if detail.over_time_n is not None and detail.over_time_n > max_n_over_time:
frappe.throw(_(f"Row {idx + 1}: The value of 'Over Time N' cannot exceed the maximum allowed overtime hours (normal) ({max_n_over_time})."))
if detail.over_time_h is not None and detail.over_time_h > max_h_over_time:
frappe.throw(_(f"Row {idx + 1}: The value of 'Over Time H' cannot exceed the maximum allowed overtime hours (holiday) ({max_h_over_time})."))
if detail.deduction is not None and detail.deduction > max_deduction:
frappe.throw(_(f"Row {idx + 1}: The value of 'Deduction' cannot exceed the maximum deduction allowed ({max_deduction})."))
def ensure_unique_employee(self):
"""
Check not to repeat the selection of the same employee in Timesheet Tool Details.
"""
timesheet_tool_details = [os.employee for os in self.timesheet_tool_details if os.employee]
if len(timesheet_tool_details) != len(set(timesheet_tool_details)):
frappe.throw(_("The same employee cannot be selected more than once."))
لإضافة ميزة رسالة التأكيد عند الضغط على زري "Create Timesheets" و"Submit Timesheets" في ملف Python الخاص بـ Timesheet Tool، سنقوم بتحسين تجربة المستخدم من خلال التأكد أن المستخدم يوافق على العملية قبل تنفيذ أي تغييرات. يتطلب ذلك إضافة منطق للتحقق من التصريحات.
التعديلات المطلوبة:
تعديل وظائف create_attendance وapproval_attendance لإضافة تأكيد قبل القيام بأي عمليات.
استخدام frappe.confirm لإظهار رسالة التأكيد.
الكود المعدل:
إليك كيف سيكون الكود بعد تعديل الدالتين create_attendance وapproval_attendance:
python
@frappe.whitelist()
def create_attendance(self):
"""
A function to implement all accounts and create the required records.
"""
# Confirm action
if not frappe.confirm(_("Are you sure you want to create attendance records?")):
return # Exit if user cancels
timesheet_count = 0
additional_salary_count = 0
settings = get_settings()
print("*"*50, self.timesheets_created)
# Preparation of Fields of Settings
salary_component_overtime_h = settings.salary_component_overtime_h
salary_component_overtime_n = settings.salary_component_overtime_n
salary_component_deduction = settings.salary_component_deduction
from_time = f"{self.day} {settings.from_time}"
# Check for values
if not all([salary_component_overtime_h, salary_component_overtime_n, salary_component_deduction]):
frappe.throw(_("Please configure the Salary Components in Timesheet Tool Settings."))
for detail in self.timesheet_tool_details:
try:
if detail.hour:
# total_working_hours
totalhours = detail.hour * detail.ratio_attendance
create_timesheet(self, detail, totalhours, from_time)
timesheet_count += 1
# Additional Salary (Overtime H, Overtime N, Deduction)
if detail.over_time_h:
total_over_time_h = detail.over_time_h * settings.h_over_time
detail.total_payment = total_over_time_h * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_h, detail.total_payment)
additional_salary_count += 1
if detail.over_time_n:
total_over_time_n = detail.over_time_n * settings.n_over_time
detail.total_payment = total_over_time_n * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_n, detail.total_payment)
additional_salary_count += 1
if detail.deduction:
detail.total_payment = detail.deduction * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_deduction, detail.total_payment)
additional_salary_count += 1
except Exception as e:
frappe.log_error(f"Error processing detail for employee {detail.employee}: {str(e)}")
frappe.msgprint(_("Error processing detail for employee {}: {}").format(detail.employee, str(e)))
# Update timesheets_created to True after successfully creating the records
self.db_set("timesheets_created", 1)
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
@frappe.whitelist()
def approval_attendance(self):
"""Approves all associated Timesheets and Additional Salaries."""
# Confirm action
if not frappe.confirm(_("Are you sure you want to approve all attendance records?")):
return # Exit if user cancels
try:
self.approval_timesheets()
self.approval_additional_salaries()
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been approved successfully."))
self.db_set("timesheets__submited", 1)
except Exception as e:
frappe.throw(_("An error occurred during approval: {0}").format(str(e)))
الشرح:
إضافة رسالة التأكيد:
قبل تنفيذ الكود داخل دالة create_attendance وapproval_attendance، نتحقق من رغبة المستخدم في المتابعة باستخدام frappe.confirm.
إذا ضغط المستخدم "لا"، يتم إرجاع الدالة للخروج دون أي تغيير.
استخدام frappe.confirm:
frappe.confirm يستخدم لطلب التأكيد من المستخدم ويحتوي على نص الرسالة.
تواصل العملية فقط إذا تم تأكيدها ("نعم").
بهذا الشكل، قد أضفنا ميزة التأكيد على العمليات الهامة في الأزرار، مما يحسن تجربة المستخدم ويقلل من الأخطاء الناتجة عن العمليات غير المقصودة. إذا كان لديك أي استفسارات أخرى أو تحتاج إلى مزيد من التعديلات، فلا تتردد في أن تسأل!
عذرًا على الإرباك. في إطار عمل Frappe، لا توجد دالة مدمجة مثل frappe.confirm في بايثون. الرسائل التفاعلية، مثل تأكيد المستخدم، ينبغي أن تتم معالجتها من جانب واجهة المستخدم باستخدام JavaScript وليس من جانب الخادم.
كيفية إضافة تأكيد على العمليات:
لإظهار رسالة تأكيد قبل تنفيذ العمليات في الخادم (مثل إنشاء أو الموافقة على السجلات)، يمكنك القيام بما يلي:
تعديل كود JavaScript لاستدعاء دالة التأكيد قبل تنفيذ الطلبات إلى الخادم.
استخدام frappe.confirm في ملف جافا سكريبت حيث يتم التعامل مع ضغط الأزرار.
خطوات التنفيذ:
سأوضح لك كيف يمكنك تعديل كود JavaScript الخاص بك لاستدعاء التأكيد قبل الضغط على الأزرار "Create Timesheets" و"Submit Timesheets". وسأقوم أيضاً بتعديل الملف timesheet_tool.py حيث لم يعد من الضروري التعامل مع التأكيد في جانب الخادم.
1. تعديل كود JavaScript:
ها هو الكود المعدل مع frappe.confirm قبل تنفيذ الطلبات إلى الخادم للسماح للمستخدم بتأكيد العملية.
javascript
// A function to handle the "Create Timesheet" button
function handleCreateTimesheetButton(frm) {
frm.add_custom_button(__('Create Timesheets'), function() {
frappe.confirm(
__('Are you sure you want to create attendance records?'),
function() { // Yes callback
frappe.call({
method: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.create_attendance",
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
frm.reload_doc();
frappe.msgprint(__('Timesheets have been created successfully.'));
}
});
},
function() { // No callback
// Do nothing if the user cancels
}
);
});
}
// A function to handle the "Submit Timesheet" button
function handleSubmitTimesheetButton(frm) {
frm.add_custom_button(__('Submit Timesheets'), function() {
frappe.confirm(
__('Are you sure you want to approve all attendance records?'),
function() { // Yes callback
frappe.call({
method: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.approval_attendance",
args: { timesheet_tool_name: frm.doc.name },
callback: function(response) {
frm.reload_doc();
frappe.msgprint(__('All Timesheets and Additional Salaries have been approved successfully.'));
}
});
},
function() { // No callback
// Do nothing if the user cancels
}
);
});
}
2. تعديل كود Python:
يمكنك إزالة أي منطق تأكيد من ملف timesheet_tool.py، حيث لم يعد هذا مطلوبًا لأن لدينا التأكيد في JavaScript.
الكود المحدث لـ timesheet_tool.py:
python
@frappe.whitelist()
def create_attendance(self):
"""
A function to implement all accounts and create the required records.
"""
timesheet_count = 0
additional_salary_count = 0
settings = get_settings()
# Preparation of Fields of Settings
salary_component_overtime_h = settings.salary_component_overtime_h
salary_component_overtime_n = settings.salary_component_overtime_n
salary_component_deduction = settings.salary_component_deduction
from_time = f"{self.day} {settings.from_time}"
# Check for values
if not all([salary_component_overtime_h, salary_component_overtime_n, salary_component_deduction]):
frappe.throw(_("Please configure the Salary Components in Timesheet Tool Settings."))
for detail in self.timesheet_tool_details:
try:
if detail.hour:
# total_working_hours
totalhours = detail.hour * detail.ratio_attendance
create_timesheet(self, detail, totalhours, from_time)
timesheet_count += 1
# Additional Salary (Overtime H, Overtime N, Deduction)
if detail.over_time_h:
total_over_time_h = detail.over_time_h * settings.h_over_time
detail.total_payment = total_over_time_h * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_h, detail.total_payment)
additional_salary_count += 1
if detail.over_time_n:
total_over_time_n = detail.over_time_n * settings.n_over_time
detail.total_payment = total_over_time_n * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_overtime_n, detail.total_payment)
additional_salary_count += 1
if detail.deduction:
detail.total_payment = detail.deduction * detail.hourly_rate
create_additional_salary(self, detail.employee, salary_component_deduction, detail.total_payment)
additional_salary_count += 1
except Exception as e:
frappe.log_error(f"Error processing detail for employee {detail.employee}: {str(e)}")
frappe.msgprint(_("Error processing detail for employee {}: {}").format(detail.employee, str(e)))
# Update timesheets_created to True after successfully creating the records
self.db_set("timesheets_created", 1)
frappe.msgprint(_("Created {0} Timesheets and {1} Additional Salaries.").format(timesheet_count, additional_salary_count))
@frappe.whitelist()
def approval_attendance(self):
"""Approves all associated Timesheets and Additional Salaries."""
try:
self.approval_timesheets()
self.approval_additional_salaries()
frappe.msgprint(_("All Timesheets and Additional Salaries associated with this document have been approved successfully."))
self.db_set("timesheets__submited", 1)
except Exception as e:
frappe.throw(_("An error occurred during approval: {0}").format(str(e)))
الخلاصة:
تأكدت من إضافة التأكيد للعمليات المهمة عبر واجهة المستخدم باستخدام JavaScript.
تركنا الـ Python لمعالجة الطلبات بدون أي تأكيد، حيث أصبح من المهم القيام بالتأكيد قبل استدعاء هذه الدوال.
الآن يمكنك تنفيذ هذا الكود، وسأكون سعيدًا بالإجابة عن أي أسئلة أخرى لديك!