You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 7.4 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. from __future__ import unicode_literals
  23. import webnotes
  24. from webnotes.model.doc import Document
  25. """
  26. Model utilities, unclassified functions
  27. """
  28. def expand(docs):
  29. """
  30. Expand a doclist sent from the client side. (Internally used by the request handler)
  31. """
  32. def xzip(a,b):
  33. d = {}
  34. for i in range(len(a)):
  35. d[a[i]] = b[i]
  36. return d
  37. from webnotes.utils import load_json
  38. docs = load_json(docs)
  39. clist = []
  40. for d in docs['_vl']:
  41. doc = xzip(docs['_kl'][d[0]], d);
  42. clist.append(doc)
  43. return clist
  44. def compress(doclist):
  45. """
  46. Compress a doclist before sending it to the client side. (Internally used by the request handler)
  47. """
  48. from webnotes.model.doc import Document
  49. docs = [isinstance(d, Document) and d.fields or d for d in doclist]
  50. kl, vl = {}, []
  51. forbidden = ['server_code_compiled']
  52. # scan for keys & values
  53. for d in docs:
  54. dt = d['doctype']
  55. if not (dt in kl.keys()):
  56. kl[dt] = ['doctype','localname','__oldparent','__unsaved']
  57. # add client script for doctype, doctype due to ambiguity
  58. if dt=='DocType' and '__client_script' not in kl[dt]:
  59. kl[dt].append('__client_script')
  60. for f in d.keys():
  61. if not (f in kl[dt]) and not (f in forbidden):
  62. # if key missing, then append
  63. kl[dt].append(f)
  64. # build values
  65. tmp = []
  66. for f in kl[dt]:
  67. v = d.get(f)
  68. if type(v)==long:
  69. v=int(v)
  70. tmp.append(v)
  71. vl.append(tmp)
  72. return {'_vl':vl,'_kl':kl}
  73. def getlist(doclist, field):
  74. from webnotes.utils import cint
  75. l = []
  76. for d in doclist:
  77. if d.parentfield == field:
  78. l.append(d)
  79. l.sort(lambda a, b: cint(a.idx) - cint(b.idx))
  80. return l
  81. def copy_doclist(doclist, no_copy = []):
  82. """
  83. Save & return a copy of the given doclist
  84. Pass fields that are not to be copied in `no_copy`
  85. """
  86. from webnotes.model.doc import Document
  87. cl = []
  88. # main doc
  89. c = Document(fielddata = doclist[0].fields.copy())
  90. # clear no_copy fields
  91. for f in no_copy:
  92. if c.fields.has_key(f):
  93. c.fields[f] = None
  94. c.name = None
  95. c.save(1)
  96. cl.append(c)
  97. # new parent name
  98. parent = c.name
  99. # children
  100. for d in doclist[1:]:
  101. c = Document(fielddata = d.fields.copy())
  102. c.name = None
  103. # clear no_copy fields
  104. for f in no_copy:
  105. if c.fields.has_key(f):
  106. c.fields[f] = None
  107. c.parent = parent
  108. c.save(1)
  109. cl.append(c)
  110. return cl
  111. def getvaluelist(doclist, fieldname):
  112. """
  113. Returns a list of values of a particualr fieldname from all Document object in a doclist
  114. """
  115. l = []
  116. for d in doclist:
  117. l.append(d.fields[fieldname])
  118. return l
  119. def delete_doc(doctype=None, name=None, doclist = None, force=0):
  120. """
  121. Deletes a doc(dt, dn) and validates if it is not submitted and not linked in a live record
  122. """
  123. import webnotes.model.meta
  124. sql = webnotes.conn.sql
  125. # get from form
  126. if not doctype:
  127. doctype = webnotes.form_dict.get('dt')
  128. name = webnotes.form_dict.get('dn')
  129. if not doctype:
  130. webnotes.msgprint('Nothing to delete!', raise_exception =1)
  131. # already deleted..?
  132. if not webnotes.conn.exists(doctype, name):
  133. return
  134. # permission
  135. if webnotes.session.user!="Administrator" and not webnotes.has_permission(doctype, "cancel"):
  136. webnotes.msgprint("User not allowed to delete.", raise_exception=1)
  137. tablefields = webnotes.model.meta.get_table_fields(doctype)
  138. # check if submitted
  139. d = webnotes.conn.sql("select docstatus from `tab%s` where name=%s" % (doctype, '%s'), name)
  140. if d and int(d[0][0]) == 1:
  141. webnotes.msgprint("Submitted Record '%s' '%s' cannot be deleted" % (doctype, name))
  142. raise Exception
  143. # call on_trash if required
  144. from webnotes.model.code import get_obj
  145. if doclist:
  146. obj = get_obj(doclist=doclist)
  147. else:
  148. obj = get_obj(doctype, name)
  149. if hasattr(obj,'on_trash'):
  150. obj.on_trash()
  151. if doctype=='DocType':
  152. webnotes.conn.sql("delete from `tabCustom Field` where dt = %s", name)
  153. webnotes.conn.sql("delete from `tabCustom Script` where dt = %s", name)
  154. webnotes.conn.sql("delete from `tabProperty Setter` where doc_type = %s", name)
  155. webnotes.conn.sql("delete from `tabSearch Criteria` where doc_type = %s", name)
  156. # check if links exist
  157. if not force:
  158. check_if_doc_is_linked(doctype, name)
  159. try:
  160. webnotes.conn.sql("delete from `tab%s` where name='%s' limit 1" % (doctype, name))
  161. for t in tablefields:
  162. webnotes.conn.sql("delete from `tab%s` where parent = %s" % (t[0], '%s'), name)
  163. except Exception, e:
  164. if e.args[0]==1451:
  165. webnotes.msgprint("Cannot delete %s '%s' as it is referenced in another record. You must delete the referred record first" % (doctype, name))
  166. raise e
  167. return 'okay'
  168. def check_if_doc_is_linked(dt, dn, method="Delete"):
  169. """
  170. Raises excption if the given doc(dt, dn) is linked in another record.
  171. """
  172. sql = webnotes.conn.sql
  173. from webnotes.model.rename_doc import get_link_fields
  174. link_fields = get_link_fields(dt)
  175. link_fields = [[lf['parent'], lf['fieldname']] for lf in link_fields]
  176. for l in link_fields:
  177. link_dt, link_field = l
  178. issingle = sql("select issingle from tabDocType where name = '%s'" % link_dt)
  179. # no such doctype (?)
  180. if not issingle: continue
  181. if issingle[0][0]:
  182. item = sql("select doctype from `tabSingles` where field='%s' and value = '%s' and doctype = '%s' " % (link_field, dn, l[0]))
  183. if item:
  184. webnotes.msgprint("Cannot delete %s <b>%s</b> because it is linked in <b>%s</b>" % (dt, dn, item[0][0]), raise_exception=1)
  185. else:
  186. item = None
  187. try:
  188. # (ifnull(parent, '')='' or `%s`!=`parent`)
  189. # this condition ensures that it allows deletion when child table field references parent
  190. item = sql("select name, parent, parenttype from `tab%s` where `%s`='%s' and docstatus!=2 and (ifnull(parent, '')='' or `%s`!=`parent`) \
  191. limit 1" % (link_dt, link_field, dn, link_field))
  192. except Exception, e:
  193. if e.args[0]==1146: pass
  194. else: raise e
  195. if item:
  196. webnotes.msgprint("Cannot delete %s <b>%s</b> because it is linked in %s <b>%s</b>" % (dt, dn, item[0][2] or link_dt, item[0][1] or item[0][0]), raise_exception=1)
  197. def round_floats_in_doc(doc, precision_map):
  198. from webnotes.utils import flt
  199. for fieldname, precision in precision_map.items():
  200. doc.fields[fieldname] = flt(doc.fields.get(fieldname), precision)
  201. def set_default(doc, key):
  202. if not doc.is_default:
  203. webnotes.conn.set(doc, "is_default", 1)
  204. webnotes.conn.sql("""update `tab%s` set `is_default`=0
  205. where `%s`=%s and name!=%s""" % (doc.doctype, key, "%s", "%s"),
  206. (doc.fields.get(key), doc.name))