Auto STOP Material Request

I try to create server script scheduler event to automatically STOP material request documents that have a required date of more than 2 days from the current date.

Here’s the script I use :

material_requests = frappe.get_all('Material Request', filters = {'status': 'Partially Ordered'}, fields = ['name'])
now_date = str(frappe.utils.nowdate())

for row in material_requests:
    if row.schedule_date:
        schedule_date = frappe.utils.data.getdate(str(row.schedule_date))

        if now_date > frappe.utils.data.add_days(schedule_date, 2):
            mr = frappe.get_doc('Material Request', row.name)
            mr.status = "Stopped"
            mr.save()

The script can be executed without errors but does not change the status of the material request.
Please help me with this?

This is the actual code when user clicks to “Stop” button.

You may try:

mr.update_status(status="Stopped")

Try debugging using frappe.log_error() within the if conditions, to see if the conditions are being satisfied (also use logs of the date variables, to see if they are what you expect them to be).

My guess would be the now_date and schedule date comparison, one is str while the other is a date time object?

Try debugging to solve it.

It’s solved btw.
Thanks for the answer.

What was the error?

It would be helpfull for the community if you can share the code.

1 Like

hello mate…
apologize for the delay.
here’s the code I used to fix it…

mr_list = frappe.get_all('Material Request', filters={'status': 'Partially Ordered', 'docstatus': 1, 'material_request_type': 'Material Transfer'}, fields=['name', 'schedule_date'])
now_date = str(frappe.utils.nowdate())

for row in mr_list:
    ex_date = str(row.schedule_date)
    date_diff = frappe.utils.date_diff(now_date, ex_date)
    
    if date_diff > 2:
        this_mr = frappe.get_doc('Material Request', row.name)
        frappe.db.set_value('Material Request', this_mr.name, 'status', 'Stopped')
        this_mr.reload()
1 Like

I think using my recommendation is better because it also checks if whether status can be changed or not.

For instance you can get “You can’t change the status. Status is already closed.” It’s a little bit more straightforward.

1 Like