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.
 
 
 
 
 
 

264 lines
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. if doclist and hasattr(doclist[0],'fields'):
  49. docs = [d.fields for d in doclist]
  50. else:
  51. docs = doclist
  52. kl, vl = {}, []
  53. forbidden = ['server_code_compiled']
  54. # scan for keys & values
  55. for d in docs:
  56. dt = d['doctype']
  57. if not (dt in kl.keys()):
  58. kl[dt] = ['doctype','localname','__oldparent','__unsaved']
  59. # add client script for doctype, doctype due to ambiguity
  60. if dt=='DocType' and '__client_script' not in kl[dt]:
  61. kl[dt].append('__client_script')
  62. for f in d.keys():
  63. if not (f in kl[dt]) and not (f in forbidden):
  64. # if key missing, then append
  65. kl[dt].append(f)
  66. # build values
  67. tmp = []
  68. for f in kl[dt]:
  69. v = d.get(f)
  70. if type(v)==long:
  71. v=int(v)
  72. tmp.append(v)
  73. vl.append(tmp)
  74. return {'_vl':vl,'_kl':kl}
  75. def getlist(doclist, field):
  76. from webnotes.utils import cint
  77. l = []
  78. for d in doclist:
  79. if d.parentfield == field:
  80. l.append(d)
  81. l.sort(lambda a, b: cint(a.idx) - cint(b.idx))
  82. return l
  83. def copy_doclist(doclist, no_copy = []):
  84. """
  85. Save & return a copy of the given doclist
  86. Pass fields that are not to be copied in `no_copy`
  87. """
  88. from webnotes.model.doc import Document
  89. cl = []
  90. # main doc
  91. c = Document(fielddata = doclist[0].fields.copy())
  92. # clear no_copy fields
  93. for f in no_copy:
  94. if c.fields.has_key(f):
  95. c.fields[f] = None
  96. c.name = None
  97. c.save(1)
  98. cl.append(c)
  99. # new parent name
  100. parent = c.name
  101. # children
  102. for d in doclist[1:]:
  103. c = Document(fielddata = d.fields.copy())
  104. c.name = None
  105. # clear no_copy fields
  106. for f in no_copy:
  107. if c.fields.has_key(f):
  108. c.fields[f] = None
  109. c.parent = parent
  110. c.save(1)
  111. cl.append(c)
  112. return cl
  113. def getvaluelist(doclist, fieldname):
  114. """
  115. Returns a list of values of a particualr fieldname from all Document object in a doclist
  116. """
  117. l = []
  118. for d in doclist:
  119. l.append(d.fields[fieldname])
  120. return l
  121. def delete_doc(doctype=None, name=None, doclist = None, force=0):
  122. """
  123. Deletes a doc(dt, dn) and validates if it is not submitted and not linked in a live record
  124. """
  125. import webnotes.model.meta
  126. sql = webnotes.conn.sql
  127. # get from form
  128. if not doctype:
  129. doctype = webnotes.form_dict.get('dt')
  130. name = webnotes.form_dict.get('dn')
  131. if not doctype:
  132. webnotes.msgprint('Nothing to delete!', raise_exception =1)
  133. # already deleted..?
  134. if not webnotes.conn.exists(doctype, name):
  135. return
  136. # permission
  137. if webnotes.session.user!="Administrator" and not webnotes.has_permission(doctype, "cancel"):
  138. webnotes.msgprint("User not allowed to delete.", raise_exception=1)
  139. tablefields = webnotes.model.meta.get_table_fields(doctype)
  140. # check if submitted
  141. d = webnotes.conn.sql("select docstatus from `tab%s` where name=%s" % (doctype, '%s'), name)
  142. if d and int(d[0][0]) == 1:
  143. webnotes.msgprint("Submitted Record '%s' '%s' cannot be deleted" % (doctype, name))
  144. raise Exception
  145. # call on_trash if required
  146. from webnotes.model.code import get_obj
  147. if doclist:
  148. obj = get_obj(doclist=doclist)
  149. else:
  150. obj = get_obj(doctype, name)
  151. if hasattr(obj,'on_trash'):
  152. obj.on_trash()
  153. if doctype=='DocType':
  154. webnotes.conn.sql("delete from `tabCustom Field` where dt = %s", name)
  155. webnotes.conn.sql("delete from `tabCustom Script` where dt = %s", name)
  156. webnotes.conn.sql("delete from `tabProperty Setter` where doc_type = %s", name)
  157. webnotes.conn.sql("delete from `tabSearch Criteria` where doc_type = %s", name)
  158. # check if links exist
  159. if not force:
  160. check_if_doc_is_linked(doctype, name)
  161. # remove tags
  162. from webnotes.widgets.tags import clear_tags
  163. clear_tags(doctype, name)
  164. try:
  165. webnotes.conn.sql("delete from `tab%s` where name='%s' limit 1" % (doctype, name))
  166. for t in tablefields:
  167. webnotes.conn.sql("delete from `tab%s` where parent = %s" % (t[0], '%s'), name)
  168. except Exception, e:
  169. if e.args[0]==1451:
  170. webnotes.msgprint("Cannot delete %s '%s' as it is referenced in another record. You must delete the referred record first" % (doctype, name))
  171. raise e
  172. return 'okay'
  173. def check_if_doc_is_linked(dt, dn):
  174. """
  175. Raises excption if the given doc(dt, dn) is linked in another record.
  176. """
  177. sql = webnotes.conn.sql
  178. from webnotes.model.rename_doc import get_link_fields
  179. link_fields = get_link_fields(dt)
  180. link_fields = [[lf['parent'], lf['fieldname']] for lf in link_fields]
  181. for l in link_fields:
  182. link_dt, link_field = l
  183. issingle = sql("select issingle from tabDocType where name = '%s'" % link_dt)
  184. # no such doctype (?)
  185. if not issingle: continue
  186. if issingle[0][0]:
  187. item = sql("select doctype from `tabSingles` where field='%s' and value = '%s' and doctype = '%s' " % (link_field, dn, l[0]))
  188. if item:
  189. webnotes.msgprint("Cannot delete %s <b>%s</b> because it is linked in <b>%s</b>" % (dt, dn, item[0][0]), raise_exception=1)
  190. else:
  191. item = None
  192. try:
  193. # (ifnull(parent, '')='' or `%s`!=`parent`)
  194. # this condition ensures that it allows deletion when child table field references parent
  195. item = sql("select name, parent, parenttype from `tab%s` where `%s`='%s' and docstatus!=2 and (ifnull(parent, '')='' or `%s`!=`parent`) \
  196. limit 1" % (link_dt, link_field, dn, link_field))
  197. except Exception, e:
  198. if e.args[0]==1146: pass
  199. else: raise e
  200. if item:
  201. 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)
  202. def round_doc(doc, precision_map):
  203. from webnotes.utils import flt
  204. for fieldname, precision in precision_map.items():
  205. doc.fields[fieldname] = flt(doc.fields.get(fieldname), precision)
  206. def set_default(doc, key):
  207. if not doc.is_default:
  208. webnotes.conn.set(doc, "is_default", 1)
  209. webnotes.conn.sql("""update `tab%s` set `is_default`=0
  210. where `%s`=%s and name!=%s""" % (doc.doctype, key, "%s", "%s"),
  211. (doc.fields.get(key), doc.name))