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.
 
 
 
 
 
 

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