Server Script Scheduler Event

Hi Community !!

In Employee Doctype, i have added one field “custom_years_of_service_”. It should be added for calculating the service year. Its calculating based on date of joining & current date. So i use server script (Doctype Event : Scheduler Type) to trigger every hours (for testing) but its not trigger or calculating the value. I have attached the code below. Please suggest me a solution.

def execute():
    logging.info("Starting Year of Service calculation")
    employees = frappe.get_all("Employee", filters={
        "date_of_joining": ["!=", None],
        "custom_years_of_service_": ["=", None]
    }, fields=["name", "date_of_joining", "date"])

    for employee in employees:
        date_of_joining = employee.date_of_joining
        current_date = nowdate()

        days_of_service = get_diff(date_of_joining, current_date)
        year_of_service = abs(round(days_of_service / 365.25, 2))

        frappe.db.set_value("Employee", employee.name, "custom_years_of_service_", year_of_service)

    frappe.db.commit()
    logging.info("Year of Service calculation completed")

Why not just trigger the recalculation from an on_open event. ?? …

Becoz, i have done one custom bar chart by using custom html block. The bar chart should show the count of employee tenure length 0-1yr, 1-2yr, 2-3yr etc,… So, the chart only takes last saved values from employee master. Problem is, if we do on open event, we should save all the employee documents every day, then only it get the latest value to generate the bar chart.

@Syed_Ahamed , If chart is the only place you need information means, it better to calculate in js while creating chart…

1 Like

Actually, the system has to open the document record in order to read it … and you need to read it in order to access the values for the graph … hence, the data will always be valid when you look at it …

That is, unless you are interrogating the database directly … in which case you can still calculate the value in the fly.

For the record, and looking at it from my perspective as a retired software engineer, I don’t see any reason to store the value at all …

but if you do, then the on-open event can update the fields and present the data whenever the doc is opened, and the same applies if you are going straight to the database using SQL.

All the best …

K