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.
 
 
 
 
 
 

258 line
8.6 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. # model __init__.py
  23. from __future__ import unicode_literals
  24. import webnotes
  25. no_value_fields = ['Section Break', 'Column Break', 'HTML', 'Table', 'FlexTable', 'Button', 'Image', 'Graph']
  26. default_fields = ['doctype','name','owner','creation','modified','modified_by','parent','parentfield','parenttype','idx','docstatus']
  27. #=================================================================================
  28. def insert(doclist):
  29. from webnotes.model.doclist import DocList
  30. for d in doclist:
  31. d["__islocal"] = 1
  32. dl = DocList(doclist)
  33. dl.save()
  34. return dl
  35. def check_if_doc_is_linked(dt, dn):
  36. """
  37. Raises excption if the given doc(dt, dn) is linked in another record.
  38. """
  39. sql = webnotes.conn.sql
  40. ll = get_link_fields(dt)
  41. for l in ll:
  42. link_dt, link_field = l
  43. issingle = sql("select issingle from tabDocType where name = '%s'" % link_dt)
  44. # no such doctype (?)
  45. if not issingle: continue
  46. if issingle[0][0]:
  47. item = sql("select doctype from `tabSingles` where field='%s' and value = '%s' and doctype = '%s' " % (link_field, dn, l[0]))
  48. if item:
  49. webnotes.msgprint("Cannot delete %s <b>%s</b> because it is linked in <b>%s</b>" % (dt, dn, item[0][0]), raise_exception=1)
  50. else:
  51. item = None
  52. try:
  53. item = sql("select name, parent, parenttype from `tab%s` where `%s`='%s' and docstatus!=2 limit 1" % (link_dt, link_field, dn))
  54. except Exception, e:
  55. if e.args[0]==1146: pass
  56. else: raise e
  57. if item:
  58. 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)
  59. @webnotes.whitelist()
  60. def delete_doc(doctype=None, name=None, doclist = None, force=0):
  61. """
  62. Deletes a doc(dt, dn) and validates if it is not submitted and not linked in a live record
  63. """
  64. import webnotes.model.meta
  65. sql = webnotes.conn.sql
  66. # get from form
  67. if not doctype:
  68. doctype = webnotes.form_dict.get('dt')
  69. name = webnotes.form_dict.get('dn')
  70. if not doctype:
  71. webnotes.msgprint('Nothing to delete!', raise_exception =1)
  72. # already deleted..?
  73. if not webnotes.conn.exists(doctype, name):
  74. return
  75. tablefields = webnotes.model.meta.get_table_fields(doctype)
  76. # check if submitted
  77. d = webnotes.conn.sql("select docstatus from `tab%s` where name=%s" % (doctype, '%s'), name)
  78. if d and int(d[0][0]) == 1:
  79. webnotes.msgprint("Submitted Record '%s' '%s' cannot be deleted" % (doctype, name))
  80. raise Exception
  81. # call on_trash if required
  82. from webnotes.model.code import get_obj
  83. if doclist:
  84. obj = get_obj(doclist=doclist)
  85. else:
  86. obj = get_obj(doctype, name)
  87. if hasattr(obj,'on_trash'):
  88. obj.on_trash()
  89. if doctype=='DocType':
  90. webnotes.conn.sql("delete from `tabCustom Field` where dt = %s", name)
  91. webnotes.conn.sql("delete from `tabCustom Script` where dt = %s", name)
  92. webnotes.conn.sql("delete from `tabProperty Setter` where doc_type = %s", name)
  93. webnotes.conn.sql("delete from `tabSearch Criteria` where doc_type = %s", name)
  94. # check if links exist
  95. if not force:
  96. check_if_doc_is_linked(doctype, name)
  97. # remove tags
  98. from webnotes.widgets.tags import clear_tags
  99. clear_tags(doctype, name)
  100. try:
  101. webnotes.conn.sql("delete from `tab%s` where name='%s' limit 1" % (doctype, name))
  102. for t in tablefields:
  103. webnotes.conn.sql("delete from `tab%s` where parent = %s" % (t[0], '%s'), name)
  104. except Exception, e:
  105. if e.args[0]==1451:
  106. webnotes.msgprint("Cannot delete %s '%s' as it is referenced in another record. You must delete the referred record first" % (doctype, name))
  107. raise e
  108. return 'okay'
  109. def get_search_criteria(dt):
  110. import webnotes.model.doc
  111. # load search criteria for reports (all)
  112. dl = []
  113. try: # bc
  114. sc_list = webnotes.conn.sql("select name from `tabSearch Criteria` where doc_type = '%s' or parent_doc_type = '%s' and (disabled!=1 OR disabled IS NULL)" % (dt, dt))
  115. for sc in sc_list:
  116. dl += webnotes.model.doc.get('Search Criteria', sc[0])
  117. except Exception, e:
  118. pass # no search criteria
  119. return dl
  120. # Rename Doc
  121. #=================================================================================
  122. def rename(doctype, old, new, is_doctype=0, debug=1):
  123. import webnotes.model.rename_doc
  124. webnotes.model.rename_doc.rename_doc(doctype, old, new, is_doctype, debug)
  125. def get_link_fields(dt):
  126. """
  127. Returns linked fields for dt as a tuple of (linked_doctype, linked_field)
  128. """
  129. import webnotes.model.rename_doc
  130. link_fields = webnotes.model.rename_doc.get_link_fields(dt)
  131. link_fields = [[lf['parent'], lf['fieldname']] for lf in link_fields]
  132. return link_fields
  133. #=================================================================================
  134. def clear_recycle_bin():
  135. """
  136. Clears temporary records that have been deleted
  137. """
  138. sql = webnotes.conn.sql
  139. tl = sql('show tables')
  140. total_deleted = 0
  141. for t in tl:
  142. fl = [i[0] for i in sql('desc `%s`' % t[0])]
  143. if 'name' in fl:
  144. total_deleted += sql("select count(*) from `%s` where name like '__overwritten:%%'" % t[0])[0][0]
  145. sql("delete from `%s` where name like '__overwritten:%%'" % t[0])
  146. if 'parent' in fl:
  147. total_deleted += sql("select count(*) from `%s` where parent like '__oldparent:%%'" % t[0])[0][0]
  148. sql("delete from `%s` where parent like '__oldparent:%%'" % t[0])
  149. total_deleted += sql("select count(*) from `%s` where parent like 'oldparent:%%'" % t[0])[0][0]
  150. sql("delete from `%s` where parent like 'oldparent:%%'" % t[0])
  151. total_deleted += sql("select count(*) from `%s` where parent like 'old_parent:%%'" % t[0])[0][0]
  152. sql("delete from `%s` where parent like 'old_parent:%%'" % t[0])
  153. webnotes.msgprint("%s records deleted" % str(int(total_deleted)))
  154. # Make Table Copy
  155. #=================================================================================
  156. def copytables(srctype, src, srcfield, tartype, tar, tarfield, srcfields, tarfields=[]):
  157. import webnotes.model.doc
  158. if not tarfields:
  159. tarfields = srcfields
  160. l = []
  161. data = webnotes.model.doc.getchildren(src.name, srctype, srcfield)
  162. for d in data:
  163. newrow = webnotes.model.doc.addchild(tar, tarfield, tartype, local = 1)
  164. newrow.idx = d.idx
  165. for i in range(len(srcfields)):
  166. newrow.fields[tarfields[i]] = d.fields[srcfields[i]]
  167. l.append(newrow)
  168. return l
  169. # DB Exists
  170. #=================================================================================
  171. def db_exists(dt, dn):
  172. import webnotes
  173. return webnotes.conn.exists(dt, dn)
  174. def delete_fields(args_dict, delete=0):
  175. """
  176. Delete a field.
  177. * Deletes record from `tabDocField`
  178. * If not single doctype: Drops column from table
  179. * If single, deletes record from `tabSingles`
  180. args_dict = { dt: [field names] }
  181. """
  182. import webnotes.utils
  183. for dt in args_dict.keys():
  184. fields = args_dict[dt]
  185. if not fields: continue
  186. webnotes.conn.sql("""\
  187. DELETE FROM `tabDocField`
  188. WHERE parent=%s AND fieldname IN (%s)
  189. """ % ('%s', ", ".join(['"' + f + '"' for f in fields])), dt)
  190. # Delete the data / column only if delete is specified
  191. if not delete: continue
  192. is_single = webnotes.conn.sql("select issingle from tabDocType where name = '%s'" % dt)
  193. is_single = is_single and webnotes.utils.cint(is_single[0][0]) or 0
  194. if is_single:
  195. webnotes.conn.sql("""\
  196. DELETE FROM `tabSingles`
  197. WHERE doctype=%s AND field IN (%s)
  198. """ % ('%s', ", ".join(['"' + f + '"' for f in fields])), dt)
  199. else:
  200. existing_fields = webnotes.conn.sql("desc `tab%s`" % dt)
  201. existing_fields = existing_fields and [e[0] for e in existing_fields] or []
  202. query = "ALTER TABLE `tab%s` " % dt + \
  203. ", ".join(["DROP COLUMN `%s`" % f for f in fields if f in existing_fields])
  204. webnotes.conn.commit()
  205. webnotes.conn.sql(query)