Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

206 righe
6.2 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. """Sets the `name`` property for the document based on various rules.
  10. 1. If amened doc, set suffix.
  11. 3. If `autoname` method is declared, then call it.
  12. 4. If `autoname` property is set in the DocType (`meta`), then build it using the `autoname` property.
  13. 2. If `name` is already defined, use that name
  14. 5. If no rule defined, use hash.
  15. #### Note:
  16. :param doc: Document to be named."""
  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. n = ''
  73. l = key.split('.')
  74. series_set = False
  75. today = now_datetime()
  76. for e in l:
  77. part = ''
  78. if e.startswith('#'):
  79. if not series_set:
  80. digits = len(e)
  81. part = getseries(n, digits, doctype)
  82. series_set = True
  83. elif e=='YY':
  84. part = today.strftime('%y')
  85. elif e=='MM':
  86. part = today.strftime('%m')
  87. elif e=='DD':
  88. part = today.strftime("%d")
  89. elif e=='YYYY':
  90. part = today.strftime('%Y')
  91. elif doc and doc.get(e):
  92. part = doc.get(e)
  93. else: part = e
  94. if isinstance(part, basestring):
  95. n+=part
  96. return n
  97. def getseries(key, digits, doctype=''):
  98. # series created ?
  99. current = frappe.db.sql("select `current` from `tabSeries` where name=%s for update", (key,))
  100. if current and current[0][0] is not None:
  101. current = current[0][0]
  102. # yes, update it
  103. frappe.db.sql("update tabSeries set current = current+1 where name=%s", (key,))
  104. current = cint(current) + 1
  105. else:
  106. # no, create it
  107. frappe.db.sql("insert into tabSeries (name, current) values (%s, 1)", (key,))
  108. current = 1
  109. return ('%0'+str(digits)+'d') % current
  110. def revert_series_if_last(key, name):
  111. if ".#" in key:
  112. prefix, hashes = key.rsplit(".", 1)
  113. if "#" not in hashes:
  114. return
  115. else:
  116. prefix = key
  117. count = cint(name.replace(prefix, ""))
  118. current = frappe.db.sql("select `current` from `tabSeries` where name=%s for update", (prefix,))
  119. if current and current[0][0]==count:
  120. frappe.db.sql("update tabSeries set current=current-1 where name=%s", prefix)
  121. def get_default_naming_series(doctype):
  122. """get default value for `naming_series` property"""
  123. naming_series = frappe.get_meta(doctype).get_field("naming_series").options or ""
  124. if naming_series:
  125. naming_series = naming_series.split("\n")
  126. return naming_series[0] or naming_series[1]
  127. else:
  128. return None
  129. def validate_name(doctype, name, case=None, merge=False):
  130. if not name: return 'No Name Specified for %s' % doctype
  131. if name.startswith('New '+doctype):
  132. frappe.throw(_('There were some errors setting the name, please contact the administrator'), frappe.NameError)
  133. if case=='Title Case': name = name.title()
  134. if case=='UPPER CASE': name = name.upper()
  135. name = name.strip()
  136. if not frappe.get_meta(doctype).get("issingle") and (doctype == name) and (name!="DocType"):
  137. frappe.throw(_("Name of {0} cannot be {1}").format(doctype, name), frappe.NameError)
  138. special_characters = "<>"
  139. if re.findall("[{0}]+".format(special_characters), name):
  140. message = ", ".join("'{0}'".format(c) for c in special_characters)
  141. frappe.throw(_("Name cannot contain special characters like {0}").format(message), frappe.NameError)
  142. return name
  143. def _set_amended_name(doc):
  144. am_id = 1
  145. am_prefix = doc.amended_from
  146. if frappe.db.get_value(doc.doctype, doc.amended_from, "amended_from"):
  147. am_id = cint(doc.amended_from.split('-')[-1]) + 1
  148. am_prefix = '-'.join(doc.amended_from.split('-')[:-1]) # except the last hyphen
  149. doc.name = am_prefix + '-' + str(am_id)
  150. return doc.name
  151. def append_number_if_name_exists(doctype, name, fieldname='name', separator='-'):
  152. if frappe.db.exists(doctype, name):
  153. last = frappe.db.sql("""select name from `tab{doctype}`
  154. where {fieldname} regexp '^{name}{separator}[[:digit:]]+'
  155. order by length({fieldname}) desc,
  156. {fieldname} desc limit 1""".format(doctype=doctype,
  157. name=name, fieldname=fieldname, separator=separator))
  158. if last:
  159. count = str(cint(last[0][0].rsplit("-", 1)[1]) + 1)
  160. else:
  161. count = "1"
  162. name = "{0}{1}{2}".format(name, separator, count)
  163. return name