Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

209 рядки
6.3 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import frappe
  5. from frappe import _
  6. from frappe.utils import now_datetime, cint
  7. import re
  8. def set_new_name(doc):
  9. """
  10. Sets the `name` property for the document based on various rules.
  11. 1. If amended doc, set suffix.
  12. 2. If `autoname` method is declared, then call it.
  13. 3. If `autoname` property is set in the DocType (`meta`), then build it using the `autoname` property.
  14. 4. If no rule defined, use hash.
  15. :param doc: Document to be named.
  16. """
  17. doc.run_method("before_naming")
  18. autoname = frappe.get_meta(doc.doctype).autoname or ""
  19. if autoname.lower() != "prompt" and not frappe.flags.in_import:
  20. doc.name = None
  21. if getattr(doc, "amended_from", None):
  22. _set_amended_name(doc)
  23. return
  24. elif getattr(doc.meta, "issingle", False):
  25. doc.name = doc.doctype
  26. else:
  27. doc.run_method("autoname")
  28. if not doc.name and autoname:
  29. if autoname.startswith('field:'):
  30. fieldname = autoname[6:]
  31. doc.name = (doc.get(fieldname) or "").strip()
  32. if not doc.name:
  33. frappe.throw(_("{0} is required").format(doc.meta.get_label(fieldname)))
  34. raise Exception('Name is required')
  35. if autoname.startswith("naming_series:"):
  36. set_name_by_naming_series(doc)
  37. elif "#" in autoname:
  38. doc.name = make_autoname(autoname)
  39. elif autoname.lower()=='prompt':
  40. # set from __newname in save.py
  41. if not doc.name:
  42. frappe.throw(_("Name not set via prompt"))
  43. if not doc.name or autoname=='hash':
  44. doc.name = make_autoname('hash', doc.doctype)
  45. doc.name = validate_name(doc.doctype, doc.name, frappe.get_meta(doc.doctype).get_field("name_case"))
  46. def set_name_by_naming_series(doc):
  47. """Sets name by the `naming_series` property"""
  48. if not doc.naming_series:
  49. doc.naming_series = get_default_naming_series(doc.doctype)
  50. if not doc.naming_series:
  51. frappe.throw(frappe._("Naming Series mandatory"))
  52. doc.name = make_autoname(doc.naming_series+'.#####', '', doc)
  53. def make_autoname(key='', doctype='', doc=''):
  54. """
  55. Creates an autoname from the given key:
  56. **Autoname rules:**
  57. * The key is separated by '.'
  58. * '####' represents a series. The string before this part becomes the prefix:
  59. Example: ABC.#### creates a series ABC0001, ABC0002 etc
  60. * 'MM' represents the current month
  61. * 'YY' and 'YYYY' represent the current year
  62. *Example:*
  63. * DE/./.YY./.MM./.##### will create a series like
  64. DE/09/01/0001 where 09 is the year, 01 is the month and 0001 is the series
  65. """
  66. if key=="hash":
  67. return frappe.generate_hash(doctype, 10)
  68. if not "#" in key:
  69. key = key + ".#####"
  70. elif not "." in key:
  71. frappe.throw(_("Invalid naming series (. missing)") + (_(" for {0}").format(doctype) if doctype else ""))
  72. parts = key.split('.')
  73. n = parse_naming_series(parts, doctype, doc)
  74. return n
  75. def parse_naming_series(parts, doctype= '', doc = ''):
  76. n = ''
  77. series_set = False
  78. today = now_datetime()
  79. for e in parts:
  80. part = ''
  81. if e.startswith('#'):
  82. if not series_set:
  83. digits = len(e)
  84. part = getseries(n, digits, doctype)
  85. series_set = True
  86. elif e=='YY':
  87. part = today.strftime('%y')
  88. elif e=='MM':
  89. part = today.strftime('%m')
  90. elif e=='DD':
  91. part = today.strftime("%d")
  92. elif e=='YYYY':
  93. part = today.strftime('%Y')
  94. elif doc and doc.get(e):
  95. part = doc.get(e)
  96. else: part = e
  97. if isinstance(part, basestring):
  98. n+=part
  99. return n
  100. def getseries(key, digits, doctype=''):
  101. # series created ?
  102. current = frappe.db.sql("select `current` from `tabSeries` where name=%s for update", (key,))
  103. if current and current[0][0] is not None:
  104. current = current[0][0]
  105. # yes, update it
  106. frappe.db.sql("update tabSeries set current = current+1 where name=%s", (key,))
  107. current = cint(current) + 1
  108. else:
  109. # no, create it
  110. frappe.db.sql("insert into tabSeries (name, current) values (%s, 1)", (key,))
  111. current = 1
  112. return ('%0'+str(digits)+'d') % current
  113. def revert_series_if_last(key, name):
  114. if ".#" in key:
  115. prefix, hashes = key.rsplit(".", 1)
  116. if "#" not in hashes:
  117. return
  118. else:
  119. prefix = key
  120. count = cint(name.replace(prefix, ""))
  121. current = frappe.db.sql("select `current` from `tabSeries` where name=%s for update", (prefix,))
  122. if current and current[0][0]==count:
  123. frappe.db.sql("update tabSeries set current=current-1 where name=%s", prefix)
  124. def get_default_naming_series(doctype):
  125. """get default value for `naming_series` property"""
  126. naming_series = frappe.get_meta(doctype).get_field("naming_series").options or ""
  127. if naming_series:
  128. naming_series = naming_series.split("\n")
  129. return naming_series[0] or naming_series[1]
  130. else:
  131. return None
  132. def validate_name(doctype, name, case=None, merge=False):
  133. if not name: return 'No Name Specified for %s' % doctype
  134. if name.startswith('New '+doctype):
  135. frappe.throw(_('There were some errors setting the name, please contact the administrator'), frappe.NameError)
  136. if case=='Title Case': name = name.title()
  137. if case=='UPPER CASE': name = name.upper()
  138. name = name.strip()
  139. if not frappe.get_meta(doctype).get("issingle") and (doctype == name) and (name!="DocType"):
  140. frappe.throw(_("Name of {0} cannot be {1}").format(doctype, name), frappe.NameError)
  141. special_characters = "<>"
  142. if re.findall("[{0}]+".format(special_characters), name):
  143. message = ", ".join("'{0}'".format(c) for c in special_characters)
  144. frappe.throw(_("Name cannot contain special characters like {0}").format(message), frappe.NameError)
  145. return name
  146. def _set_amended_name(doc):
  147. am_id = 1
  148. am_prefix = doc.amended_from
  149. if frappe.db.get_value(doc.doctype, doc.amended_from, "amended_from"):
  150. am_id = cint(doc.amended_from.split('-')[-1]) + 1
  151. am_prefix = '-'.join(doc.amended_from.split('-')[:-1]) # except the last hyphen
  152. doc.name = am_prefix + '-' + str(am_id)
  153. return doc.name
  154. def append_number_if_name_exists(doctype, name, fieldname='name', separator='-'):
  155. if frappe.db.exists(doctype, name):
  156. last = frappe.db.sql("""select name from `tab{doctype}`
  157. where {fieldname} regexp '^{name}{separator}[[:digit:]]+'
  158. order by length({fieldname}) desc,
  159. {fieldname} desc limit 1""".format(doctype=doctype,
  160. name=name, fieldname=fieldname, separator=separator))
  161. if last:
  162. count = str(cint(last[0][0].rsplit("-", 1)[1]) + 1)
  163. else:
  164. count = "1"
  165. name = "{0}{1}{2}".format(name, separator, count)
  166. return name