Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

__init__.py 11 KiB

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