refactor: generate naming series preview without DB calls

This commit is contained in:
Ankush Menat 2022-05-31 11:23:44 +05:30
parent 5590cb0be8
commit b7a032e7e8
3 changed files with 13 additions and 10 deletions

View file

@ -8,7 +8,7 @@ import frappe
from frappe import _
from frappe.core.doctype.doctype.doctype import validate_series
from frappe.model.document import Document
from frappe.model.naming import NamingSeries, make_autoname
from frappe.model.naming import NamingSeries, parse_naming_series
from frappe.permissions import get_doctypes_with_read
from frappe.utils import cint
@ -173,24 +173,17 @@ class DocumentNamingSettings(Document):
def preview_series(self) -> str:
"""Preview what the naming series will generate."""
generated_names = []
series = self.try_naming_series
if not series:
return ""
try:
doc = self._fetch_last_doc_if_available()
for _count in range(3):
generated_names.append(make_autoname(series, doc=doc))
return "\n".join(NamingSeries(series).get_preview(doc=doc))
except Exception as e:
if frappe.message_log:
frappe.message_log.pop()
return _("Failed to generate names from the series") + f"\n{str(e)}"
# Explcitly rollback in case any changes were made to series table.
frappe.db.rollback() # nosemgrep
return "\n".join(generated_names)
def _fetch_last_doc_if_available(self):
"""Fetch last doc for evaluating naming series with fields."""
try:

View file

@ -3,7 +3,6 @@
import frappe
from frappe.core.doctype.document_naming_settings.document_naming_settings import (
NAMING_SERIES_PATTERN,
DocumentNamingSettings,
)
from frappe.model.naming import get_default_naming_series

View file

@ -80,6 +80,17 @@ class NamingSeries:
return prefix
def get_preview(self, doc=None) -> List[str]:
"""Generate preview of naming series without using DB counters"""
generated_names = []
for count in range(1, 4):
def fake_counter(_prefix, digits):
return str(count).zfill(digits)
generated_names.append(parse_naming_series(self.series, doc=doc, number_generator=fake_counter))
return generated_names
def set_new_name(doc):
"""