Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

263 linhas
7.5 KiB

  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. # remove tags
  160. from webnotes.widgets.tags import clear_tags
  161. clear_tags(doctype, name)
  162. try:
  163. webnotes.conn.sql("delete from `tab%s` where name='%s' limit 1" % (doctype, name))
  164. for t in tablefields:
  165. webnotes.conn.sql("delete from `tab%s` where parent = %s" % (t[0], '%s'), name)
  166. except Exception, e:
  167. if e.args[0]==1451:
  168. webnotes.msgprint("Cannot delete %s '%s' as it is referenced in another record. You must delete the referred record first" % (doctype, name))
  169. raise e
  170. return 'okay'
  171. def check_if_doc_is_linked(dt, dn):
  172. """
  173. Raises excption if the given doc(dt, dn) is linked in another record.
  174. """
  175. sql = webnotes.conn.sql
  176. from webnotes.model.rename_doc import get_link_fields
  177. link_fields = get_link_fields(dt)
  178. link_fields = [[lf['parent'], lf['fieldname']] for lf in link_fields]
  179. for l in link_fields:
  180. link_dt, link_field = l
  181. issingle = sql("select issingle from tabDocType where name = '%s'" % link_dt)
  182. # no such doctype (?)
  183. if not issingle: continue
  184. if issingle[0][0]:
  185. item = sql("select doctype from `tabSingles` where field='%s' and value = '%s' and doctype = '%s' " % (link_field, dn, l[0]))
  186. if item:
  187. webnotes.msgprint("Cannot delete %s <b>%s</b> because it is linked in <b>%s</b>" % (dt, dn, item[0][0]), raise_exception=1)
  188. else:
  189. item = None
  190. try:
  191. # (ifnull(parent, '')='' or `%s`!=`parent`)
  192. # this condition ensures that it allows deletion when child table field references parent
  193. item = sql("select name, parent, parenttype from `tab%s` where `%s`='%s' and docstatus!=2 and (ifnull(parent, '')='' or `%s`!=`parent`) \
  194. limit 1" % (link_dt, link_field, dn, link_field))
  195. except Exception, e:
  196. if e.args[0]==1146: pass
  197. else: raise e
  198. if item:
  199. 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)
  200. def round_floats_in_doc(doc, precision_map):
  201. from webnotes.utils import flt
  202. for fieldname, precision in precision_map.items():
  203. doc.fields[fieldname] = flt(doc.fields.get(fieldname), precision)
  204. def set_default(doc, key):
  205. if not doc.is_default:
  206. webnotes.conn.set(doc, "is_default", 1)
  207. webnotes.conn.sql("""update `tab%s` set `is_default`=0
  208. where `%s`=%s and name!=%s""" % (doc.doctype, key, "%s", "%s"),
  209. (doc.fields.get(key), doc.name))