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.
 
 
 
 
 
 

321 line
9.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. from __future__ import unicode_literals
  23. """
  24. Merges (syncs) incoming doclist into the database
  25. Called when:
  26. importing .txt files
  27. importing bulk records from .csv files
  28. For regular types, deletes the record and recreates it
  29. for special types: `DocType`, `Module Def`, `DocType Mapper` there are subclasses
  30. To use::
  31. set_doc(doclist, ovr=1, ingore=1, noupdate=1)
  32. """
  33. import webnotes
  34. from webnotes.model.doc import Document
  35. # this variable is a flag that transfer process is on, to the on_update
  36. # method so that if there are other processes on import, it can do so
  37. in_transfer = 0
  38. def set_doc(doclist, ovr=0, ignore=1, onupdate=1):
  39. """
  40. Wrapper function to sync a record
  41. """
  42. global in_transfer
  43. dt = doclist[0]['doctype']
  44. if webnotes.conn.exists(doclist[0]['doctype'], doclist[0]['name']):
  45. # exists, merge if possible
  46. if dt=='DocType':
  47. ud = UpdateDocType(doclist)
  48. elif dt == 'DocType Mapper':
  49. ud = UpdateDocTypeMapper(doclist)
  50. else:
  51. ud = UpdateDocument(doclist)
  52. else:
  53. ud = UpdateDocument(doclist)
  54. in_transfer = 1
  55. ud.sync()
  56. in_transfer = 0
  57. return '\n'.join(ud.log)
  58. #
  59. # Class to sync incoming document
  60. #
  61. class UpdateDocument:
  62. def __init__(self, in_doclist=[]):
  63. self.in_doclist = in_doclist
  64. self.doc = Document(fielddata = in_doclist[0])
  65. self.modified = self.doc.modified # make a copy
  66. self.doclist = []
  67. self.log = []
  68. self.exists = 0
  69. # sync
  70. def sync(self):
  71. is_mod = self.is_modified()
  72. if (not self.exists) or (is_mod):
  73. webnotes.conn.begin()
  74. if self.exists:
  75. self.delete_existing()
  76. self.save()
  77. self.update_modified()
  78. self.run_on_update()
  79. webnotes.conn.commit()
  80. # check modified
  81. def is_modified(self):
  82. try:
  83. timestamp = webnotes.conn.sql("select modified from `tab%s` where name=%s" % (self.doc.doctype, '%s'), self.doc.name)
  84. except Exception ,e:
  85. if(e.args[0]==1146):
  86. return
  87. else:
  88. raise e
  89. if timestamp:
  90. self.exists = 1
  91. if str(timestamp[0][0]) == self.doc.modified:
  92. self.log.append('%s %s, No change' % (self.doc.doctype, self.doc.name))
  93. else: return 1
  94. # delete existing
  95. def delete_existing(self):
  96. from webnotes.model import delete_doc
  97. delete_doc(self.doc.doctype, self.doc.name, force=1)
  98. # update modified timestamp
  99. def update_modified(self):
  100. webnotes.conn.set(self.doc, 'modified', self.modified)
  101. def save(self):
  102. # parent
  103. self.doc.save(new = 1, check_links=0)
  104. self.doclist = [self.doc]
  105. self.save_children()
  106. def save_children(self):
  107. for df in self.in_doclist[1:]:
  108. self.save_one_doc(df)
  109. def save_one_doc(self, df, as_new=1):
  110. d = Document(fielddata = df)
  111. d.save(new = as_new, check_links=0)
  112. self.doclist.append(d)
  113. def run_on_update(self):
  114. from webnotes.model.code import get_obj
  115. so = get_obj(doc=self.doc, doclist=self.doclist)
  116. if hasattr(so, 'on_update'):
  117. so.on_update()
  118. class UpdateDocumentMerge(UpdateDocument):
  119. def __init__(self, in_doclist):
  120. self.to_update_doctype = []
  121. UpdateDocument.__init__(self, in_doclist)
  122. def delete_existing(self):
  123. pass
  124. def get_id(self, d):
  125. pass
  126. def to_update(self, d):
  127. return 1
  128. def child_exists(self, d):
  129. return self.get_id(d)
  130. def on_save(self):
  131. pass
  132. def save(self):
  133. if self.exists:
  134. # save main doc
  135. self.keep_values(self.doc)
  136. self.doc.save(check_links=0)
  137. self.doclist.append(self.doc)
  138. self.save_children()
  139. self.on_save()
  140. self.log.append('Updated %s' % self.doc.name)
  141. else:
  142. UpdateDocument.save(self)
  143. def save_children(self):
  144. for df in self.in_doclist[1:]:
  145. d = Document(fielddata = df)
  146. # update doctype?
  147. if d.doctype in self.to_update_doctype:
  148. # update this record?
  149. if self.to_update(d):
  150. # is it new?
  151. if self.child_exists(d):
  152. self.keep_values(d)
  153. d.save(check_links=0)
  154. self.log.append('updated %s, %s' % (d.doctype, d.name))
  155. else:
  156. d.save(1, check_links=0)
  157. self.log.append('new %s' % d.doctype)
  158. self.doclist.append(d)
  159. def keep_values(self, d):
  160. if hasattr(self, 'get_orignal_values'):
  161. ov = self.get_orignal_values(d)
  162. if ov:
  163. d.fields.update(ov)
  164. class UpdateDocType(UpdateDocumentMerge):
  165. """
  166. Import a doctype from txt to database
  167. """
  168. def __init__(self, in_doclist):
  169. UpdateDocumentMerge.__init__(self, in_doclist)
  170. self.to_update_doctype = ['DocType', 'DocField']
  171. def to_update(self, d):
  172. if (d.fieldtype not in ['Section Break', 'Column Break', 'HTML']) and (d.fieldname or d.label):
  173. return 1
  174. def get_id(self, d):
  175. key = d.fieldname and 'fieldname' or 'label'
  176. if d.fields.get(key):
  177. return webnotes.conn.sql("""select name, options, permlevel, reqd, print_hide, hidden, fieldtype
  178. from tabDocField where %s=%s and parent=%s""" % (key, '%s', '%s'), (d.fields[key], d.parent))
  179. def on_save(self):
  180. self.renum()
  181. def child_exists(self, d):
  182. if d.doctype=='DocField':
  183. return self.get_id(d)
  184. def get_orignal_values(self, d):
  185. if d.doctype=='DocField':
  186. t = self.get_id(d)[0]
  187. return {'name': t[0], 'options': t[1], 'fieldtype':t[6]}
  188. if d.doctype=='DocType':
  189. return webnotes.conn.sql("select server_code, client_script from `tabDocType` where name=%s", d.name, as_dict = 1)[0]
  190. # renumber the indexes
  191. def renum(self):
  192. extra = self.get_extra_fields()
  193. self.clear_section_breaks()
  194. self.add_section_breaks_and_renum()
  195. self.fix_extra_fields(extra)
  196. # get fields not in the incoming list (to preserve order)
  197. def get_extra_fields(self):
  198. prev_field, prev_field_key, extra = '', '', []
  199. # get new fields and labels
  200. fieldnames = [d.get('fieldname') for d in self.in_doclist]
  201. labels = [d.get('label') for d in self.in_doclist]
  202. # check if all existing are present
  203. for f in webnotes.conn.sql("select fieldname, label, idx from tabDocField where parent=%s and fieldtype not in ('Section Break', 'Column Break', 'HTML') order by idx asc", self.doc.name):
  204. if f[0] and not f[0] in fieldnames:
  205. extra.append([f[0], f[1], prev_field, prev_field_key])
  206. elif f[1] and not f[1] in labels:
  207. extra.append([f[0], f[1], prev_field, prev_field_key])
  208. prev_field, prev_field_key = f[0] or f[1], f[0] and 'fieldname' or 'label'
  209. return extra
  210. # clear section breaks
  211. def clear_section_breaks(self):
  212. webnotes.conn.sql("delete from tabDocField where fieldtype in ('Section Break', 'Column Break', 'HTML') and parent=%s and ifnull(options,'')!='Custom'", self.doc.name)
  213. # add section breaks
  214. def add_section_breaks_and_renum(self):
  215. for d in self.in_doclist:
  216. if d.get('parentfield')=='fields':
  217. if d.get('fieldtype') in ('Section Break', 'Column Break', 'HTML'):
  218. tmp = Document(fielddata = d)
  219. tmp.fieldname = ''
  220. tmp.name = None
  221. tmp.save(1, check_links=0)
  222. else:
  223. webnotes.conn.sql("update tabDocField set idx=%s where %s=%s and parent=%s" % \
  224. ('%s', d.get('fieldname') and 'fieldname' or 'label', '%s', '%s'), (d.get('idx'), d.get('fieldname') or d.get('label'), self.doc.name))
  225. # adjust the extra fields
  226. def fix_extra_fields(self, extra):
  227. # push fields down at new idx
  228. for e in extra:
  229. # get idx of the prev to extra field
  230. idx = 0
  231. if e[2]:
  232. idx = webnotes.conn.sql("select idx from tabDocField where %s=%s and parent=%s" % (e[3], '%s', '%s'), (e[2], self.doc.name))
  233. idx = idx and idx[0][0] or 0
  234. if idx:
  235. webnotes.conn.sql("update tabDocField set idx=idx+1 where idx>%s and parent=%s", (idx, self.doc.name))
  236. webnotes.conn.sql("update tabDocField set idx=%s where %s=%s and parent=%s" % \
  237. ('%s', e[0] and 'fieldname' or 'label', '%s', '%s'), (idx+1, e[0] or e[1], self.doc.name))
  238. def run_on_update(self):
  239. from webnotes.model.code import get_obj
  240. so = get_obj(doc=self.doc, doclist=self.doclist)
  241. if hasattr(so, 'on_update'):
  242. so.on_update()
  243. class UpdateDocTypeMapper(UpdateDocumentMerge):
  244. """
  245. Merge `DocType Mapper`
  246. """
  247. def __init__(self, in_doclist):
  248. UpdateDocumentMerge.__init__(self, in_doclist)
  249. self.to_update_doctype = ['Field Mapper Detail', 'Table Mapper Detail']
  250. def get_id(self, d):
  251. if d.doctype=='Field Mapper Detail':
  252. return webnotes.conn.sql("select name from `tabField Mapper Detail` where from_field=%s and to_field=%s and match_id=%s and parent=%s", (d.from_field, d.to_field, d.match_id, d.parent))
  253. elif d.doctype=='Table Mapper Detail':
  254. return webnotes.conn.sql("select name from `tabTable Mapper Detail` where from_table=%s and to_table = %s and match_id=%s and validation_logic=%s and parent=%s", (d.from_table, d.to_table, d.match_id, d.validation_logic, d.parent))
  255. def get_orignal_values(self, d):
  256. if d.doctype in ['Field Mapper Detail', 'Table Mapper Detail']:
  257. return {'name': self.get_id(d)[0][0]}