# Buggy code
def process_deferred_accounting(posting_date=today()):
    """Converts deferred income/expense into income/expense
    Executed via background jobs on every month end"""

    if not cint(
        frappe.db.get_singles_value(
            "Accounts Settings", "automatically_process_deferred_accounting_entry"
        )
    ):
        return

    start_date = add_months(today(), -1)
    end_date = add_days(today(), -1)

    for record_type in ("Income", "Expense"):
        doc = frappe.get_doc(
            dict(
                doctype="Process Deferred Accounting",
                posting_date=posting_date,
                start_date=start_date,
                end_date=end_date,
                type=record_type,
            )
        )

        doc.insert()
        doc.submit()


# Traceback (KeyError)
00:14:19 Worker rq:worker:3901a0e0a9a74ce1b754e3a6dae77bcb.revant-laptop.131744.default: found an unhandled exception, quitting...
Traceback (most recent call last):
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/werkzeug/local.py", line 72, in __getattr__
return self.__storage__[self.__ident_func__()][name]
KeyError: 140528509749056

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/rq/job.py", line 54, in unpickle
obj = loads(pickled_string)
File "/home/revant/frappe-bench/apps/erpnext/erpnext/buying/doctype/purchase_order/purchase_order.py", line 20, in <module>
from erpnext.accounts.doctype.sales_invoice.sales_invoice import validate_inter_company_party, update_linked_doc,\
File "/home/revant/frappe-bench/apps/erpnext/erpnext/accounts/doctype/sales_invoice/sales_invoice.py", line 25, in <module>
from erpnext.accounts.deferred_revenue import validate_service_stop_date
File "/home/revant/frappe-bench/apps/erpnext/erpnext/accounts/deferred_revenue.py", line 202, in <module>
def process_deferred_accounting(posting_date=today()):
File "/home/revant/frappe-bench/apps/frappe/frappe/utils/data.py", line 171, in today
return nowdate()
File "/home/revant/frappe-bench/apps/frappe/frappe/utils/data.py", line 168, in nowdate
return now_datetime().strftime(DATE_FORMAT)
File "/home/revant/frappe-bench/apps/frappe/frappe/utils/data.py", line 131, in now_datetime
dt = convert_utc_to_user_timezone(datetime.datetime.utcnow())
File "/home/revant/frappe-bench/apps/frappe/frappe/utils/data.py", line 154, in convert_utc_to_user_timezone
return utcnow.astimezone(timezone(get_time_zone()))
File "/home/revant/frappe-bench/apps/frappe/frappe/utils/data.py", line 145, in get_time_zone
if frappe.local.flags.in_test:
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/werkzeug/local.py", line 74, in __getattr__
raise AttributeError(name)
AttributeError: flags

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/rq/worker.py", line 517, in work
self.execute_job(job, queue)
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/rq/worker.py", line 738, in execute_job
self.fork_work_horse(job, queue)
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/rq/worker.py", line 669, in fork_work_horse
self.main_work_horse(job, queue)
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/rq/worker.py", line 755, in main_work_horse
raise e
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/rq/worker.py", line 752, in main_work_horse
self.perform_job(job, queue)
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/rq/worker.py", line 877, in perform_job
self.prepare_job_execution(job, heartbeat_ttl)
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/rq/worker.py", line 796, in prepare_job_execution
self.procline(msg.format(job.func_name, job.origin, time.time()))
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/rq/job.py", line 250, in func_name
self._unpickle_data()
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/rq/job.py", line 218, in _unpickle_data
self._func_name, self._instance, self._args, self._kwargs = unpickle(self.data)
File "/home/revant/frappe-bench/env/lib/python3.8/site-packages/rq/job.py", line 56, in unpickle
raise UnpickleError('Could not unpickle', pickled_string, e)
rq.exceptions.UnpickleError: ('Could not unpickle', AttributeError('flags'))

# Fixed code
def process_deferred_accounting(posting_date=None):
    """Converts deferred income/expense into income/expense
    Executed via background jobs on every month end"""

    if not posting_date:
        posting_date = today()

    if not cint(
        frappe.db.get_singles_value(
            "Accounts Settings", "automatically_process_deferred_accounting_entry"
        )
    ):
        return

    start_date = add_months(today(), -1)
    end_date = add_days(today(), -1)

    for record_type in ("Income", "Expense"):
        doc = frappe.get_doc(
            dict(
                doctype="Process Deferred Accounting",
                posting_date=posting_date,
                start_date=start_date,
                end_date=end_date,
                type=record_type,
            )
        )

        doc.insert()
        doc.submit()