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.
 
 
 
 
 
 

242 line
6.8 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 import _
  25. from webnotes.model.doc import Document
  26. """
  27. Model utilities, unclassified functions
  28. """
  29. def expand(docs):
  30. """
  31. Expand a doclist sent from the client side. (Internally used by the request handler)
  32. """
  33. def xzip(a,b):
  34. d = {}
  35. for i in range(len(a)):
  36. d[a[i]] = b[i]
  37. return d
  38. from webnotes.utils import load_json
  39. docs = load_json(docs)
  40. clist = []
  41. for d in docs['_vl']:
  42. doc = xzip(docs['_kl'][d[0]], d);
  43. clist.append(doc)
  44. return clist
  45. def compress(doclist):
  46. """
  47. Compress a doclist before sending it to the client side. (Internally used by the request handler)
  48. """
  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. cl = []
  87. # main doc
  88. c = Document(fielddata = doclist[0].fields.copy())
  89. # clear no_copy fields
  90. for f in no_copy:
  91. if c.fields.has_key(f):
  92. c.fields[f] = None
  93. c.name = None
  94. c.save(1)
  95. cl.append(c)
  96. # new parent name
  97. parent = c.name
  98. # children
  99. for d in doclist[1:]:
  100. c = Document(fielddata = d.fields.copy())
  101. c.name = None
  102. # clear no_copy fields
  103. for f in no_copy:
  104. if c.fields.has_key(f):
  105. c.fields[f] = None
  106. c.parent = parent
  107. c.save(1)
  108. cl.append(c)
  109. return cl
  110. def getvaluelist(doclist, fieldname):
  111. """
  112. Returns a list of values of a particualr fieldname from all Document object in a doclist
  113. """
  114. l = []
  115. for d in doclist:
  116. l.append(d.fields[fieldname])
  117. return l
  118. def delete_doc(doctype=None, name=None, doclist = None, force=0, ignore_doctypes=[], for_reload=False):
  119. """
  120. Deletes a doc(dt, dn) and validates if it is not submitted and not linked in a live record
  121. """
  122. import webnotes.model.meta
  123. # get from form
  124. if not doctype:
  125. doctype = webnotes.form_dict.get('dt')
  126. name = webnotes.form_dict.get('dn')
  127. if not doctype:
  128. webnotes.msgprint('Nothing to delete!', raise_exception =1)
  129. # already deleted..?
  130. if not webnotes.conn.exists(doctype, name):
  131. return
  132. if not for_reload:
  133. check_permission_and_not_submitted(doctype, name)
  134. run_on_trash(doctype, name, doclist)
  135. # check if links exist
  136. if not force:
  137. check_if_doc_is_linked(doctype, name)
  138. try:
  139. tablefields = webnotes.model.meta.get_table_fields(doctype)
  140. webnotes.conn.sql("delete from `tab%s` where name=%s" % (doctype, "%s"), name)
  141. for t in tablefields:
  142. if t[0] not in ignore_doctypes:
  143. webnotes.conn.sql("delete from `tab%s` where parent = %s" % (t[0], '%s'), name)
  144. except Exception, e:
  145. if e.args[0]==1451:
  146. webnotes.msgprint("Cannot delete %s '%s' as it is referenced in another record. You must delete the referred record first" % (doctype, name))
  147. raise e
  148. # delete attachments
  149. from webnotes.utils.file_manager import remove_all
  150. remove_all(doctype, name)
  151. return 'okay'
  152. def check_permission_and_not_submitted(doctype, name):
  153. # permission
  154. if webnotes.session.user!="Administrator" and not webnotes.has_permission(doctype, "cancel"):
  155. webnotes.msgprint(_("User not allowed to delete."), raise_exception=True)
  156. # check if submitted
  157. if webnotes.conn.get_value(doctype, name, "docstatus") == 1:
  158. webnotes.msgprint(_("Submitted Record cannot be deleted")+": "+name+"("+doctype+")",
  159. raise_exception=True)
  160. def run_on_trash(doctype, name, doclist):
  161. # call on_trash if required
  162. if doclist:
  163. obj = webnotes.get_obj(doclist=doclist)
  164. else:
  165. obj = webnotes.get_obj(doctype, name)
  166. if hasattr(obj,'on_trash'):
  167. obj.on_trash()
  168. class LinkExistsError(webnotes.ValidationError): pass
  169. def check_if_doc_is_linked(dt, dn, method="Delete"):
  170. """
  171. Raises excption if the given doc(dt, dn) is linked in another record.
  172. """
  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 link_dt, link_field in link_fields:
  177. item = webnotes.conn.get_value(link_dt, {link_field:dn}, ["name", "parent", "parenttype",
  178. "docstatus"], as_dict=True)
  179. if item and item.parent != dn and (method=="Delete" or
  180. (method=="Cancel" and item.docstatus==1)):
  181. webnotes.msgprint(method + " " + _("Error") + ":"+\
  182. ("%s (%s) " % (dn, dt)) + _("is linked in") + (" %s (%s)") %
  183. (item.parent or item.name, item.parent and item.parenttype or link_dt),
  184. raise_exception=LinkExistsError)
  185. def round_floats_in_doc(doc, precision_map):
  186. from webnotes.utils import flt
  187. for fieldname, precision in precision_map.items():
  188. doc.fields[fieldname] = flt(doc.fields.get(fieldname), precision)
  189. def set_default(doc, key):
  190. if not doc.is_default:
  191. webnotes.conn.set(doc, "is_default", 1)
  192. webnotes.conn.sql("""update `tab%s` set `is_default`=0
  193. where `%s`=%s and name!=%s""" % (doc.doctype, key, "%s", "%s"),
  194. (doc.fields.get(key), doc.name))