Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

156 lignes
4.8 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import webnotes
  5. from webnotes import msgprint, _
  6. import json
  7. import csv, cStringIO
  8. from webnotes.utils import encode, cstr, cint, flt
  9. def read_csv_content_from_uploaded_file(ignore_encoding=False):
  10. if getattr(webnotes, "uploaded_file", None):
  11. with open(webnotes.uploaded_file, "r") as upfile:
  12. fcontent = upfile.read()
  13. else:
  14. from webnotes.utils.file_manager import get_uploaded_content
  15. fname, fcontent = get_uploaded_content()
  16. return read_csv_content(fcontent, ignore_encoding)
  17. def read_csv_content_from_attached_file(doc):
  18. fileid = webnotes.conn.get_value("File Data", {"attached_to_doctype": doc.doctype,
  19. "attached_to_name":doc.name}, "name")
  20. if not fileid:
  21. msgprint("File not attached!")
  22. raise Exception
  23. try:
  24. from webnotes.utils.file_manager import get_file
  25. fname, fcontent = get_file(fileid)
  26. return read_csv_content(fcontent, webnotes.form_dict.get('ignore_encoding_errors'))
  27. except Exception, e:
  28. webnotes.msgprint("""Unable to open attached file. Please try again.""")
  29. raise Exception
  30. def read_csv_content(fcontent, ignore_encoding=False):
  31. rows = []
  32. decoded = False
  33. for encoding in ["utf-8", "windows-1250", "windows-1252"]:
  34. try:
  35. fcontent = unicode(fcontent, encoding)
  36. decoded = True
  37. break
  38. except UnicodeDecodeError, e:
  39. continue
  40. if not decoded:
  41. webnotes.msgprint(webnotes._("Unknown file encoding. Tried utf-8, windows-1250, windows-1252."),
  42. raise_exception=True)
  43. try:
  44. reader = csv.reader(fcontent.encode("utf-8").splitlines(True))
  45. # decode everything
  46. rows = [[unicode(val, "utf-8").strip() for val in row] for row in reader]
  47. return rows
  48. except Exception, e:
  49. webnotes.msgprint("Not a valid Comma Separated Value (CSV File)")
  50. raise
  51. @webnotes.whitelist()
  52. def send_csv_to_client(args):
  53. if isinstance(args, basestring):
  54. args = json.loads(args)
  55. args = webnotes._dict(args)
  56. webnotes.response["result"] = cstr(to_csv(args.data))
  57. webnotes.response["doctype"] = args.filename
  58. webnotes.response["type"] = "csv"
  59. def to_csv(data):
  60. writer = UnicodeWriter()
  61. for row in data:
  62. writer.writerow(row)
  63. return writer.getvalue()
  64. class UnicodeWriter:
  65. def __init__(self, encoding="utf-8"):
  66. self.encoding = encoding
  67. self.queue = cStringIO.StringIO()
  68. self.writer = csv.writer(self.queue, quoting=csv.QUOTE_NONNUMERIC)
  69. def writerow(self, row):
  70. row = encode(row, self.encoding)
  71. self.writer.writerow(row)
  72. def getvalue(self):
  73. return self.queue.getvalue()
  74. def check_record(d, parenttype=None, doctype_dl=None):
  75. """check for mandatory, select options, dates. these should ideally be in doclist"""
  76. from webnotes.utils.dateutils import parse_date
  77. if parenttype and not d.get('parent'):
  78. webnotes.msgprint(_("Parent is required."), raise_exception=1)
  79. if not doctype_dl:
  80. doctype_dl = webnotes.model.doctype.get(d.doctype)
  81. for key in d:
  82. docfield = doctype_dl.get_field(key)
  83. val = d[key]
  84. if docfield:
  85. if docfield.reqd and (val=='' or val==None):
  86. webnotes.msgprint("%s is mandatory." % docfield.label, raise_exception=1)
  87. if docfield.fieldtype=='Select' and val and docfield.options:
  88. if docfield.options.startswith('link:'):
  89. link_doctype = docfield.options.split(':')[1]
  90. if not webnotes.conn.exists(link_doctype, val):
  91. webnotes.msgprint("%s: %s must be a valid %s" % (docfield.label, val, link_doctype),
  92. raise_exception=1)
  93. elif docfield.options == "attach_files:":
  94. pass
  95. elif val not in docfield.options.split('\n'):
  96. webnotes.msgprint("%s must be one of: %s" % (docfield.label,
  97. ", ".join(filter(None, docfield.options.split("\n")))), raise_exception=1)
  98. if val and docfield.fieldtype=='Date':
  99. d[key] = parse_date(val)
  100. elif val and docfield.fieldtype in ["Int", "Check"]:
  101. d[key] = cint(val)
  102. elif val and docfield.fieldtype in ["Currency", "Float"]:
  103. d[key] = flt(val)
  104. def import_doc(d, doctype, overwrite, row_idx, submit=False, ignore_links=False):
  105. """import main (non child) document"""
  106. if d.get("name") and webnotes.conn.exists(doctype, d['name']):
  107. if overwrite:
  108. bean = webnotes.bean(doctype, d['name'])
  109. bean.ignore_links = ignore_links
  110. bean.doc.fields.update(d)
  111. if d.get("docstatus") == 1:
  112. bean.update_after_submit()
  113. else:
  114. bean.save()
  115. return 'Updated row (#%d) %s' % (row_idx + 1, getlink(doctype, d['name']))
  116. else:
  117. return 'Ignored row (#%d) %s (exists)' % (row_idx + 1,
  118. getlink(doctype, d['name']))
  119. else:
  120. bean = webnotes.bean([d])
  121. bean.ignore_links = ignore_links
  122. bean.insert()
  123. if submit:
  124. bean.submit()
  125. return 'Inserted row (#%d) %s' % (row_idx + 1, getlink(doctype,
  126. bean.doc.fields['name']))
  127. def getlink(doctype, name):
  128. return '<a href="#Form/%(doctype)s/%(name)s">%(name)s</a>' % locals()