Skip to content

Commit

Permalink
perf(workflow): get_transitions (#18834)
Browse files Browse the repository at this point in the history
* Load from db only if doc passed is not of type Document. This was
  added earlier to load in case of dicts. ref: #11883
* Move blocks to evaluate only if required
* Add typing hints

(cherry picked from commit a093b7b)
  • Loading branch information
gavindsouza authored and mergify[bot] committed Nov 10, 2022
1 parent acc521e commit 9ec557d
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions frappe/model/workflow.py
Expand Up @@ -4,13 +4,18 @@
from __future__ import unicode_literals

import json
from typing import TYPE_CHECKING, Union

from six import string_types

import frappe
from frappe import _
from frappe.utils import cint

if TYPE_CHECKING:
from frappe.model.document import Document
from frappe.workflow.doctype.workflow.workflow import Workflow


class WorkflowStateError(frappe.ValidationError):
pass
Expand All @@ -36,20 +41,22 @@ def get_workflow_name(doctype):


@frappe.whitelist()
def get_transitions(doc, workflow=None, raise_exception=False):
def get_transitions(
doc: Union["Document", str, dict], workflow: "Workflow" = None, raise_exception: bool = False
) -> list[dict]:
"""Return list of possible transitions for the given doc"""
doc = frappe.get_doc(frappe.parse_json(doc))
from frappe.model.document import Document

if not isinstance(doc, Document):
doc = frappe.get_doc(frappe.parse_json(doc))
doc.load_from_db()

if doc.is_new():
return []

doc.load_from_db()

frappe.has_permission(doc, "read", throw=True)
roles = frappe.get_roles()
doc.check_permission("read")

if not workflow:
workflow = get_workflow(doc.doctype)
workflow = workflow or get_workflow(doc.doctype)
current_state = doc.get(workflow.workflow_state_field)

if not current_state:
Expand All @@ -59,11 +66,14 @@ def get_transitions(doc, workflow=None, raise_exception=False):
frappe.throw(_("Workflow State not set"), WorkflowStateError)

transitions = []
roles = frappe.get_roles()

for transition in workflow.transitions:
if transition.state == current_state and transition.allowed in roles:
if not is_transition_condition_satisfied(transition, doc):
continue
transitions.append(transition.as_dict())

return transitions


Expand All @@ -83,7 +93,7 @@ def get_workflow_safe_globals():
)


def is_transition_condition_satisfied(transition, doc):
def is_transition_condition_satisfied(transition, doc) -> bool:
if not transition.condition:
return True
else:
Expand Down Expand Up @@ -202,7 +212,7 @@ def validate_workflow(doc):
)


def get_workflow(doctype):
def get_workflow(doctype) -> "Workflow":
return frappe.get_doc("Workflow", get_workflow_name(doctype))


Expand Down

0 comments on commit 9ec557d

Please sign in to comment.