Efficient Document State Management with Empress' Docstatus Feature

Introduction

This guide provides a comprehensive walkthrough for the Docstatus feature in Empress, a Python-based framework for building business applications. The Docstatus is a crucial aspect of tracking the status of transactions in Empress. It is an integral part of the framework’s backend functionality, allowing for efficient state management of documents and transactions.

Understanding Docstatus

The Docstatus feature is essentially a state tracker for documents within your application. It can hold one of three values:

  • Draft (value: 0)
  • Submitted (value: 1)
  • Cancelled (value: 2)

These states are important as they dictate the permissible actions on a document. Documents that are not submittable remain in the “draft” state. Submittable documents can transition from the “draft” state to the “submitted”, and then to the “cancelled” state. Once a document is submitted or cancelled, it cannot be edited, except for fields explicitly configured to permit edits in the submitted state.

The Docstatus values are stored as integer values in each Doctype table of the database, allowing for efficient querying and manipulation.

Working with Docstatus

Empress provides a helper class, DocStatus, to interact with the docstatus of a document. Here’s how you can use it:

import frappe
from frappe.model.docstatus import DocStatus

# Fetching draft invoices
draft_invoice_names = frappe.get_list(
    "Sales Invoice",
    filters={"docstatus": DocStatus.draft()},
    pluck="name"
)

# Getting a document and checking its docstatus
invoice_doc = frappe.get_doc("Sales Invoice", draft_invoice_names[0])
invoice_doc.docstatus == DocStatus.draft() # -> True
invoice_doc.docstatus.is_draft() # -> True
invoice_doc.docstatus.is_submitted() # -> False
invoice_doc.docstatus.is_cancelled() # -> False

# Submitting a document
invoice_doc.submit()
invoice_doc.docstatus == DocStatus.submitted() # -> True
invoice_doc.docstatus.is_draft() # -> False
invoice_doc.docstatus.is_submitted() # -> True
invoice_doc.docstatus.is_cancelled() # -> False

# Cancelling a document
invoice_doc.cancel()
invoice_doc.docstatus == DocStatus.cancelled() # -> True
invoice_doc.docstatus.is_draft() # -> False
invoice_doc.docstatus.is_submitted() # -> False
invoice_doc.docstatus.is_cancelled() # -> True

This code demonstrates how you can fetch documents in a specific state, check the status of a document, and change the state of a document.

Conclusion

The Docstatus feature provides a powerful and elegant mechanism for managing the lifecycle of documents in Empress-based applications. By understanding and utilizing this feature, developers can create more robust and maintainable applications. The ability to control and track the state of documents is an essential capability for any business application, and Empress’ Docstatus feature makes it easy and intuitive.