您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

453 行
18 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. import webnotes
  23. def import_docs(docs = []):
  24. from webnotes.model.doc import Document
  25. import webnotes.model.code
  26. doc_list = {}
  27. created_docs = []
  28. already_exists = []
  29. out, tmp ="", ""
  30. for d in docs:
  31. cur_doc = Document(fielddata = d)
  32. if not cur_doc.parent in already_exists: # parent should not exist
  33. try:
  34. cur_doc.save(1)
  35. out += "Created: " + cur_doc.name + "\n"
  36. created_docs.append(cur_doc)
  37. # make in groups
  38. if cur_doc.parent:
  39. if not doc_list.has_key(cur_doc.parent):
  40. doc_list[cur_doc.parent] = []
  41. doc_list[cur_doc.parent].append(cur_doc)
  42. except Exception, e:
  43. out += "Creation Warning/Error: " + cur_doc.name + " :"+ str(e) + "\n"
  44. already_exists.append(cur_doc.name)
  45. # Run scripts for main docs
  46. for m in created_docs:
  47. if doc_list.has_key(m.name):
  48. tmp = webnotes.model.code.run_server_obj(webnotes.model.code.get_server_obj(m, doc_list.get(m.name, [])),'on_update')
  49. # update database (in case of DocType)
  50. if m.doctype=='DocType':
  51. import webnotes.model.doctype
  52. try: webnotes.model.doctype.update_doctype(doc_list.get(m.name, []))
  53. except: pass
  54. out += 'Executed: '+ str(m.name) + ', Err:' + str(tmp) + "\n"
  55. return out
  56. #======================================================================================================================================
  57. import webnotes
  58. import webnotes.utils
  59. sql = webnotes.conn.sql
  60. flt = webnotes.utils.flt
  61. cint = webnotes.utils.cint
  62. cstr = webnotes.utils.cstr
  63. class CSVImport:
  64. def __init__(self):
  65. self.msg = []
  66. self.csv_data = None
  67. self.import_date_format = None
  68. def validate_doctype(self, dt_list):
  69. cl, tables, self.dt_list, self.prompt_autoname_flag = 0, [t[0] for t in sql("show tables")], [], 0
  70. self.msg.append('<p><b>Identifying Documents</b></p>')
  71. dtd = sql("select name, istable, autoname from `tabDocType` where name = '%s' " % dt_list[0])
  72. if dtd and dtd[0][0]:
  73. self.msg.append('<div style="color: GREEN">Identified Document: ' + dt_list[0] + '</div>')
  74. self.dt_list.append(dt_list[0])
  75. if dtd[0][2] and 'Prompt' in dtd[0][2]: self.prompt_autoname_flag = 1
  76. if flt(dtd[0][1]):
  77. res1 = sql("select parent, fieldname from tabDocField where options='%s' and fieldtype='Table' and docstatus!=2" % self.dt_list[0])
  78. if res1 and res1[0][0] == dt_list[1]:
  79. self.msg.append('<div style="color: GREEN">Identified Document: ' + dt_list[1] + '</div>')
  80. self.dt_list.append(dt_list[1])
  81. else :
  82. self.msg.append('<div style="color:RED"> Error: At Row 1, Column 2 => %s is not a valid Document </div>' % dt_list[1])
  83. self.validate_success = 0
  84. if res1 and res1[0][1] == dt_list[2]:
  85. self.msg.append('<div style="color: GREEN" >Identified Document Fieldname: ' + dt_list[2] + '</div>')
  86. self.dt_list.append(dt_list[2])
  87. else :
  88. self.msg.append('<div style="color:RED"> Error: At Row 1, Column 3 => %s is not a valid Fieldname </div>' % dt_list[2])
  89. self.validate_success = 0
  90. elif dt_list[1]:
  91. self.msg.append('<div style="color:RED"> Error: At Row 1, Column 1 => %s is not a Table. </div>' % dt_list[0])
  92. self.validate_success = 0
  93. else:
  94. self.msg.append('<div style="color:RED"> Error: At Row 1, Column 1 => %s is not a valid Document </div>' % dt_list[0])
  95. self.validate_success = 0
  96. def validate_fields(self, lb_list):
  97. self.msg.append('<p><b>Checking fieldnames for %s</b></p>' % self.dt_list[0])
  98. if self.overwrite and len(self.dt_list) == 1 and 'Name' != lb_list[0]:
  99. self.msg.append('<div style="color:RED"> Error : At Row 4 and Column 1: To Overwrite fieldname should be Name </div>')
  100. self.validate_success = 0
  101. return
  102. # labelnames
  103. res = self.validate_success and [d[0] for d in sql("select label from tabDocField where parent='%s' and docstatus!=2 and ifnull(hidden,'') in ('',0)" % self.dt_list[0])] or []
  104. if len(self.dt_list) > 1 and self.dt_list[1]:
  105. if self.dt_list[1] not in lb_list:
  106. self.msg.append('<div style="color:RED"> Error : At Row 4: There should be one column named "'+self.dt_list[1]+'"</div>')
  107. self.validate_success = 0
  108. return
  109. if 'Name' in lb_list:
  110. self.msg.append('<div style="color:RED"> Error : At Row 4: "Name" column should not be there</div>')
  111. self.validate_success = 0
  112. return
  113. self.fields.append('parent')
  114. lb_list.pop(lb_list.index(self.dt_list[1]))
  115. dtd = sql("select autoname from `tabDocType` where name = '%s' " % self.dt_list[0])[0][0]
  116. if (self.prompt_autoname_flag or self.overwrite) and len(self.dt_list) == 1:
  117. self.fields.append('name')
  118. res.append('Name')
  119. lb_list.pop(lb_list.index('Name'))
  120. cl = 1
  121. for l in lb_list:
  122. try:
  123. if l:
  124. if not (l in res):
  125. self.msg.append('<div style="color: RED">Error : At Row 4 and Column %s Field %s is not present in %s</div>' % (cl, l, self.dt_list[0]))
  126. self.validate_success = 0
  127. # this condition is for child doctype
  128. else: self.fields.append(sql("select fieldname from tabDocField where parent ='%s' and label = '%s' and ifnull(fieldname,'') !='' " % (self.dt_list[0], l))[0][0] or '')
  129. except Exception, e:
  130. self.msg.append('<div style="color: RED"> At Row 4 and Column %s : =>ERROR: %s </div>' % ( cl, e))
  131. self.validate_success = 0
  132. cl = cl + 1
  133. if not self.overwrite:
  134. # get_reqd_fields
  135. reqd_list = [d[0] for d in sql("select label from `tabDocField` where parent = '%s' and ifnull(reqd,'') not in ('', 0) and docstatus !=2" % self.dt_list[0]) if d[0] not in lb_list] or []
  136. # Check if Reqd field not present in self.fields
  137. if reqd_list:
  138. self.msg.append('<div style="color: RED"> Error : At Row 4 Mandatory Fields %s of Document %s are Required. </div>' %(reqd_list , self.dt_list[0]))
  139. self.validate_success = 0
  140. if self.validate_success:
  141. self.msg.append('<div style="color: GREEN">Fields OK for %s</div>' % self.dt_list[0])
  142. def validate_headers(self):
  143. self.validate_doctype(self.doctype_data)
  144. if self.validate_success:
  145. self.validate_fields(self.labels)
  146. # Date parsing
  147. # --------------------------------------------------------------------
  148. def parse_date(self, r, c, d):
  149. out = ''
  150. try:
  151. if self.import_date_format=='yyyy-mm-dd':
  152. tmpd = d.split('-')
  153. if len(tmpd)==3:
  154. out = tmpd[0] + '-'+tmpd[1] + '-' + tmpd[2]
  155. elif d and self.import_date_format=='dd-mm-yyyy':
  156. tmpd = d.split('-')
  157. if len(tmpd)==3:
  158. out = tmpd[2]+'-'+tmpd[1]+'-'+tmpd[0]
  159. elif d and self.import_date_format=='mm/dd/yyyy':
  160. tmpd = d.split('/')
  161. if len(tmpd)==3:
  162. out = tmpd[2]+'-'+tmpd[0]+'-'+tmpd[1]
  163. elif d and self.import_date_format=='mm/dd/yy':
  164. tmpd = d.split('/')
  165. if len(tmpd)==3:
  166. out = '20'+tmpd[2]+'-'+tmpd[0]+'-'+tmpd[1]
  167. elif d and self.import_date_format=='dd/mm/yyyy':
  168. tmpd = d.split('/')
  169. if len(tmpd)==3:
  170. out = tmpd[2]+'-'+tmpd[1]+'-'+tmpd[0]
  171. elif d and self.import_date_format=='dd/mm/yy':
  172. tmpd = d.split('/')
  173. if len(tmpd)==3:
  174. out = '20'+tmpd[2]+'-'+tmpd[1]+'-'+tmpd[0]
  175. if len(tmpd) != 3:
  176. self.msg.append('<div style="color: RED"> At Row %s and Column %s : => Date Format selected as %s does not match with Date Format in File</div>' % (r, c, str(self.import_date_format)))
  177. self.validate_success = 0
  178. else:
  179. import datetime
  180. dt = out.split('-')
  181. datetime.date(int(dt[0]),int(dt[1]), int(dt[2]))
  182. except Exception, e:
  183. self.msg.append('<div style="color: RED"> At Row %s and Column %s : =>ERROR: %s </div>' % (r, c, e))
  184. self.validate_success = 0
  185. self.msg.append(out)
  186. return out
  187. def check_select_link_data(self, r, c, f, d, s = '', l = ''):
  188. from webnotes.model.doctype import get_field_property
  189. options = ''
  190. try:
  191. if d and f:
  192. dt = get_field_property(self.dt_list[0], f, 'options')
  193. lbl = get_field_property(self.dt_list[0], f, 'label')
  194. if dt:
  195. options = l and dt and [n[0] for n in sql("select name from `tab%s` " % (('link:' in dt and dt[5:]) or dt))] or s and dt.split('\n') or ''
  196. if options and d not in options :
  197. msg = '<div style="color: RED">At Row ' + str(r) + ' and Column ' + str(c)+ ' : => Data "' + str(d) + '" in field ['+ str(lbl) +'] Not Found in '
  198. msg = msg.__add__( s and str( 'Select Options [' +str(dt.replace('\n', ',')) +']' ) or str('Master ' + str('link:' in dt and dt[5:] or dt)))
  199. msg = msg.__add__('</div>\n')
  200. self.msg.append(msg)
  201. self.validate_success = 0
  202. except Exception, e:
  203. self.msg.append('<div style="color: RED"> ERROR: %s </div>' % (str(webnotes.utils.getTraceback())))
  204. self.validate_success = 0
  205. return d
  206. def get_field_type_list(self):
  207. # get_date_fields
  208. date_list = [d[0] for d in sql("select fieldname from `tabDocField` where parent = '%s' and fieldtype='Date' and docstatus !=2" % self.dt_list[0])]
  209. # get_link_fields
  210. link_list = [d[0] for d in sql("select fieldname from `tabDocField` where parent = '%s' and ((fieldtype='Link' and ifnull(options,'') != '') or (fieldtype='Select' and ifnull(options,'') like '%%link:%%')) and docstatus !=2 " % self.dt_list[0])]
  211. # get_select_fileds
  212. select_list = [d[0] for d in sql("select fieldname from `tabDocField` where parent = '%s' and fieldtype='Select' and ifnull(options,'') not like '%%link:%%' and docstatus !=2" % self.dt_list[0])]
  213. # get_reqd_fields
  214. reqd_list = self.overwrite and ['name'] or [d[0] for d in sql("select fieldname from `tabDocField` where parent = '%s' and ifnull(reqd,'') not in ('', 0) and docstatus !=2" % self.dt_list[0])]
  215. if len(self.dt_list)> 1 and 'parent' not in reqd_list: reqd_list.append('parent')
  216. if self.prompt_autoname_flag and 'name' not in reqd_list: reqd_list.append('name')
  217. return date_list, link_list, select_list, reqd_list
  218. def validate_data(self):
  219. self.msg.append('<p><b>Checking Data for %s</b></p>' % self.dt_list[0])
  220. date_list, link_list, select_list, reqd_list = self.get_field_type_list()
  221. # Delete all data of child tables before over-writing
  222. if len(self.dt_list) > 1 and self.overwrite:
  223. webnotes.conn.sql("delete from `tab%s`" % self.dt_list[0])
  224. self.msg.append('<div style="color: ORANGE">Deleted all data from %s before re-importing</div>' % self.dt_list[0])
  225. # load data
  226. row = 5
  227. for d in self.data:
  228. self.validate_success, fd, col = 1, {}, 1
  229. self.msg.append('<p><b>Checking Row %s </b></p>' % (row))
  230. for i in range(len(d)):
  231. if i < len(self.fields):
  232. f = self.fields[i]
  233. try:
  234. # Check Reqd Fields
  235. if (f in reqd_list) and not d[i]:
  236. self.msg.append('<div style="color: RED">Error: At Row %s and Column %s, Field %s is Mandatory.</div>' % (row, col, f))
  237. self.validate_success = 0
  238. # Check Date Fields
  239. if d[i] and f and f in date_list : fd[f] = self.parse_date(row, col, d[i])
  240. # Check Link Fields
  241. elif d[i] and f in link_list:
  242. fd[f] = self.check_select_link_data(row, col, f, d[i], l='Link')
  243. # Check Select Fields
  244. elif d[i] and f in select_list:
  245. fd[f] = self.check_select_link_data(row, col, f, d[i], s= 'Select')
  246. # Need To Perform Check For Other Data Type Too
  247. else: fd[f] = d[i]
  248. except Exception:
  249. self.msg.append('<div style="color: RED"> ERROR: %sData:%s and %s and %s and %s</div>' % (str(webnotes.utils.getTraceback()) + '\n', str(d), str(f), str(date_list), str(link_list)))
  250. self.validate_success = 0
  251. elif d[i]:
  252. self.validate_success = 0
  253. self.msg.append('<div style="color: RED">At Row %s and Column %s</div>' % (row,col))
  254. self.msg.append('<div style="color: ORANGE">Ignored</div>')
  255. col = col + 1
  256. if self.validate_success:
  257. self.msg.append('<div style="color: GREEN">At Row %s and Column %s, Data Verification Completed </div>' % (row,col))
  258. self.update_data(fd,row)
  259. row = row + 1
  260. def update_data(self, fd, row):
  261. # load metadata
  262. from webnotes.model.doc import Document
  263. cur_doc = Document(fielddata = fd)
  264. cur_doc.doctype, cur_doc.parenttype, cur_doc.parentfield = self.dt_list[0], len(self.dt_list) > 1 and self.dt_list[1] or '', len(self.dt_list) > 1 and self.dt_list[2] or ''
  265. obj = ''
  266. webnotes.message_log = []
  267. # save the document
  268. try:
  269. if webnotes.conn.in_transaction:
  270. sql("COMMIT")
  271. sql("START TRANSACTION")
  272. if cur_doc.name and webnotes.conn.exists(self.dt_list[0], cur_doc.name):
  273. if self.overwrite:
  274. cur_doc.save()
  275. obj = webnotes.model.code.get_obj(cur_doc.parent and cur_doc.parent_type or cur_doc.doctype, cur_doc.parent or cur_doc.name, with_children = 1)
  276. self.msg.append('<div style="color: ORANGE">Row %s => Over-written: %s</div>' % (row, cur_doc.name))
  277. else:
  278. self.msg.append('<div style="color: ORANGE">Row %s => Ignored: %s</div>' % (row, cur_doc.name))
  279. elif cur_doc.parent and webnotes.conn.exists(cur_doc.parenttype, cur_doc.parent) or not cur_doc.parent:
  280. cur_doc.save(1)
  281. obj = webnotes.model.code.get_obj(cur_doc.parent and cur_doc.parenttype or cur_doc.doctype, cur_doc.parent or cur_doc.name, with_children = 1)
  282. self.msg.append('<div style="color: GREEN">Row %s => Created: %s</div>' % (row, cur_doc.name))
  283. else:
  284. self.msg.append('<div style="color: RED">Row %s => Invalid %s : %s</div>' % (row, cur_doc.parenttype, cur_doc.parent))
  285. except Exception:
  286. self.msg.append('<div style="color: RED"> Validation: %s</div>' % str(webnotes.utils.getTraceback()))
  287. try:
  288. if obj:
  289. if hasattr(obj, 'validate') : obj.validate()
  290. if hasattr(obj, 'on_update') : obj.on_update()
  291. if hasattr(obj, 'on_submit') : obj.on_submit()
  292. sql("COMMIT")
  293. except Exception:
  294. sql("ROLLBACK")
  295. self.msg.append('<div style="color: RED"> Validation Error: %s</div>' % str((webnotes.message_log and webnotes.message_log[0]) or webnotes.utils.getTraceback()))
  296. self.msg.append('<div style="color: RED"> Did not import</div>')
  297. # do import
  298. # --------------------------------------------------------------------
  299. def import_csv(self, csv_data, import_date_format = 'yyyy-mm-dd', overwrite = 0):
  300. import csv
  301. self.validate_success = 1
  302. self.csv_data = self.convert_csv_data_into_list(csv.reader(csv_data.splitlines()))
  303. self.import_date_format, self.overwrite = import_date_format, overwrite
  304. if len(self.csv_data) > 4:
  305. self.doctype_data, self.labels, self.data = self.csv_data[0][:4], self.csv_data[3], self.csv_data[4:]
  306. self.fields = []
  307. import webnotes.model.code
  308. from webnotes.model.doc import Document
  309. sql = webnotes.conn.sql
  310. self.validate_headers()
  311. if self.validate_success:
  312. self.validate_data()
  313. else:
  314. self.msg.append('<p><b>No data entered in file.</b></p>')
  315. return '\n'.join([m.encode('utf-8') for m in self.msg])
  316. def convert_csv_data_into_list(self,csv_data):
  317. st_list = []
  318. for s in csv_data:
  319. st_list.append([d.strip() for d in s])
  320. return st_list
  321. # Get Template method
  322. # -----------------------------------------------------------------
  323. def get_template():
  324. import webnotes.model
  325. from webnotes.utils import getCSVelement
  326. form = webnotes.form
  327. sql = webnotes.conn.sql
  328. # get form values
  329. dt = form.getvalue('dt')
  330. overwrite = cint(form.getvalue('overwrite')) or 0
  331. pt, pf = '', ''
  332. tmp_lbl, tmp_ml = [],[]
  333. # is table?
  334. dtd = sql("select istable, autoname from tabDocType where name='%s'" % dt)
  335. if dtd and dtd[0][0]:
  336. res1 = sql("select parent, fieldname from tabDocField where options='%s' and fieldtype='Table' and docstatus!=2" % dt)
  337. if res1:
  338. pt, pf = res1[0][0], res1[0][1]
  339. # line 1
  340. dset = []
  341. if pt and pf:
  342. lbl, ml = [pt], ['[Mandatory]']
  343. line1 = '%s,%s,%s' % (getCSVelement(dt), getCSVelement(pt), getCSVelement(pf))
  344. line2 = ',,,,,,Please fill valid %(p)s No in %(p)s column.' % {'p':getCSVelement(pt)}
  345. else:
  346. if dtd[0][1]=='Prompt' or overwrite:
  347. lbl, ml= ['Name'], ['[Mandatory][Special Characters are not allowed]']
  348. else:
  349. lbl, ml= [], []
  350. line1 = '%s' % getCSVelement(dt)
  351. line2 = (overwrite and ',,,,,,Please fill valid %(d)s No in %(n)s' % {'d':dt,'n': 'Name'}) or ',,'
  352. # Help on Line
  353. line1 = line1 + ',,,Please fill columns which are Mandatory., Please do not modify the structure'
  354. # fieldnames
  355. res = sql("select fieldname, fieldtype, label, reqd, hidden from tabDocField where parent='%s' and docstatus!=2" % dt)
  356. for r in res:
  357. # restrict trash_reason field, hidden and required fields
  358. if not r[1] in webnotes.model.no_value_fields and r[0] != 'trash_reason' and not r[4] and not r[3]:
  359. tmp_lbl.append(getCSVelement(r[2]))
  360. tmp_ml.append('')
  361. # restrict trash_reason field and hidden fields and add Mandatory indicator for required fields
  362. elif not r[1] in webnotes.model.no_value_fields and r[0] != 'trash_reason' and not r[4] and r[3]:
  363. lbl.append(getCSVelement(r[2]))
  364. ml.append(getCSVelement('[Mandatory]'))
  365. dset.append(line1)
  366. dset.append(line2)
  367. dset.append(','.join(ml + tmp_ml))
  368. dset.append(','.join(lbl + tmp_lbl))
  369. txt = '\n'.join(dset)
  370. webnotes.response['result'] = txt
  371. webnotes.response['type'] = 'csv'
  372. webnotes.response['doctype'] = dt