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.

288 lines
11 KiB

  1. # Copyright 2014-2017 Akretion (http://www.akretion.com).
  2. # @author Alexis de Lattre <alexis.delattre@akretion.com>
  3. # @author Sébastien BEAU <sebastien.beau@akretion.com>
  4. # Copyright 2019 Eficent Business and IT Consulting Services, S.L.
  5. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  6. import xlrd
  7. import logging
  8. import datetime as dtm
  9. from datetime import datetime
  10. from odoo import _, api, fields, models
  11. from odoo.exceptions import UserError
  12. import re
  13. from io import StringIO
  14. _logger = logging.getLogger(__name__)
  15. try:
  16. import csv
  17. except (ImportError, IOError) as err:
  18. _logger.debug(err)
  19. class AccountBankStatementImport(models.TransientModel):
  20. _inherit = 'account.bank.statement.import'
  21. txt_map_id = fields.Many2one(
  22. comodel_name='account.bank.statement.import.map',
  23. string='Txt map',
  24. readonly=True,
  25. )
  26. @api.model
  27. def _get_txt_encoding(self):
  28. if self.txt_map_id.file_encoding:
  29. return self.txt_map_id.file_encoding
  30. return 'utf-8-sig'
  31. @api.model
  32. def _get_txt_str_data(self, data_file):
  33. if not isinstance(data_file, str):
  34. data_file = data_file.decode(self._get_txt_encoding())
  35. return data_file.strip()
  36. @api.model
  37. def _txt_convert_amount(self, amount_str):
  38. if not amount_str:
  39. return 0.0
  40. if self.txt_map_id:
  41. thousands, decimal = self.txt_map_id._get_separators()
  42. else:
  43. thousands, decimal = ',', '.'
  44. valstr = re.sub(r'[^\d%s%s.-]' % (thousands, decimal), '', amount_str)
  45. valstrdot = valstr.replace(thousands, '')
  46. valstrdot = valstrdot.replace(decimal, '.')
  47. return float(valstrdot)
  48. @api.model
  49. def _check_xls(self, data_file):
  50. # Try if it is an Excel file
  51. headers = self.mapped('txt_map_id.map_line_ids.name')
  52. try:
  53. file_headers = []
  54. book = xlrd.open_workbook(file_contents=data_file)
  55. xl_sheet = book.sheet_by_index(0)
  56. row = xl_sheet.row(0) # 1st row
  57. for idx, cell_obj in enumerate(row):
  58. cell_type_str = xlrd.sheet.ctype_text.get(cell_obj.ctype, False)
  59. if cell_type_str:
  60. file_headers.append(cell_obj.value)
  61. else:
  62. return False
  63. if any(item not in file_headers for item in headers):
  64. raise UserError(
  65. _("Headers of file to import and Txt map lines does not "
  66. "match."))
  67. except xlrd.XLRDError as e:
  68. return False
  69. except Exception as e:
  70. return False
  71. return True
  72. @api.model
  73. def _check_txt(self, data_file):
  74. data_file = self._get_txt_str_data(data_file)
  75. if not self.txt_map_id:
  76. return False
  77. headers = self.mapped('txt_map_id.map_line_ids.name')
  78. file_headers = data_file.split('\n', 1)[0]
  79. if any(item not in file_headers for item in headers):
  80. raise UserError(
  81. _("Headers of file to import and Txt map lines does not "
  82. "match."))
  83. return True
  84. def _get_currency_fields(self):
  85. return ['amount', 'amount_currency']
  86. def _convert_txt_line_to_dict(self, idx, line):
  87. rline = dict()
  88. for item in range(len(line)):
  89. txt_map = self.mapped('txt_map_id.map_line_ids')[item]
  90. value = line[item]
  91. if not txt_map.field_to_assign:
  92. continue
  93. if txt_map.date_format:
  94. try:
  95. value = fields.Date.to_string(
  96. datetime.strptime(value, txt_map.date_format))
  97. except Exception:
  98. raise UserError(
  99. _("Date format of map file and Txt date does "
  100. "not match."))
  101. rline[txt_map.field_to_assign] = value
  102. for field in self._get_currency_fields():
  103. _logger.debug('Trying to convert %s to float' % rline[field])
  104. try:
  105. rline[field] = self._txt_convert_amount(rline[field])
  106. except Exception:
  107. raise UserError(
  108. _("Value '%s' for the field '%s' on line %d, "
  109. "cannot be converted to float")
  110. % (rline[field], field, idx))
  111. return rline
  112. def _parse_txt_file(self, data_file):
  113. data_file = self._get_txt_str_data(data_file)
  114. f = StringIO(data_file)
  115. f.seek(0)
  116. raw_lines = []
  117. if not self.txt_map_id.quotechar:
  118. reader = csv.reader(f,
  119. delimiter=self.txt_map_id.delimiter or False)
  120. else:
  121. reader = csv.reader(f,
  122. quotechar=self.txt_map_id.quotechar,
  123. delimiter=self.txt_map_id.delimiter or False)
  124. next(reader) # Drop header
  125. for idx, line in enumerate(reader):
  126. _logger.debug("Line %d: %s" % (idx, line))
  127. raw_lines.append(self._convert_txt_line_to_dict(idx, line))
  128. return raw_lines
  129. def _convert_xls_line_to_dict(self, row_idx, xl_sheet):
  130. rline = dict()
  131. for col_idx in range(0, xl_sheet.ncols): # Iterate through columns
  132. txt_map = self.mapped('txt_map_id.map_line_ids')[col_idx]
  133. cell_obj = xl_sheet.cell(row_idx, col_idx) # Get cell
  134. ctype = xl_sheet.cell(row_idx, col_idx).ctype
  135. value = cell_obj.value
  136. if not txt_map.field_to_assign:
  137. continue
  138. if ctype == xlrd.XL_CELL_DATE:
  139. ms_date_number = xl_sheet.cell(row_idx, col_idx).value
  140. try:
  141. year, month, day, hour, minute, \
  142. second = xlrd.xldate_as_tuple(
  143. ms_date_number, 0)
  144. except xlrd.XLDateError as e:
  145. raise UserError(
  146. _('An error was found translating a date '
  147. 'field from the file: %s') % e)
  148. value = dtm.date(year, month, day)
  149. value = value.strftime('%Y-%m-%d')
  150. rline[txt_map.field_to_assign] = value
  151. return rline
  152. def _parse_xls_file(self, data_file):
  153. try:
  154. raw_lines = []
  155. book = xlrd.open_workbook(file_contents=data_file)
  156. xl_sheet = book.sheet_by_index(0)
  157. for row_idx in range(1, xl_sheet.nrows):
  158. _logger.debug("Line %d" % row_idx)
  159. raw_lines.append(self._convert_xls_line_to_dict(
  160. row_idx, xl_sheet))
  161. except xlrd.XLRDError:
  162. return False
  163. except Exception as e:
  164. return False
  165. return raw_lines
  166. def _post_process_statement_line(self, raw_lines):
  167. """ Enter your additional logic here. """
  168. return raw_lines
  169. def _get_journal(self):
  170. journal_id = self.env.context.get('journal_id')
  171. if not journal_id:
  172. raise UserError(_('You must run this wizard from the journal'))
  173. return self.env['account.journal'].browse(journal_id)
  174. def _get_currency_id(self, fline):
  175. journal = self._get_journal()
  176. line_currency_name = fline.get('currency', False)
  177. currency = journal.currency_id or journal.company_id.currency_id
  178. if line_currency_name and line_currency_name != currency.name:
  179. currency = self.env['res.currency'].search(
  180. [('name', '=', fline['currency'])], limit=1)
  181. return currency.id
  182. return False
  183. @api.model
  184. def _get_partner_id(self, fline):
  185. partner_name = fline.get('partner_name', False)
  186. if partner_name:
  187. partner = self.env['res.partner'].search([
  188. ('name', '=ilike', partner_name)])
  189. if partner and len(partner) == 1:
  190. return partner.commercial_partner_id.id
  191. return None
  192. def _prepare_txt_statement_line(self, fline):
  193. currency_id = self._get_currency_id(fline)
  194. return {
  195. 'date': fline.get('date', False),
  196. 'name': fline.get('name', ''),
  197. 'ref': fline.get('ref', False),
  198. 'note': fline.get('Notes', False),
  199. 'amount': fline.get('amount', 0.0),
  200. 'currency_id': self._get_currency_id(fline),
  201. 'amount_currency': currency_id and fline.get(
  202. 'amount_currency', 0.0) or 0.0,
  203. 'partner_id': self._get_partner_id(fline),
  204. 'account_number': fline.get('account_number', False),
  205. }
  206. def _prepare_txt_statement(self, lines):
  207. balance_end_real = 0.0
  208. for line in lines:
  209. if 'amount' in line and line['amount']:
  210. balance_end_real += line['amount']
  211. return {
  212. 'name':
  213. _('%s Import %s > %s')
  214. % (self.txt_map_id.name,
  215. lines[0]['date'], lines[-1]['date']),
  216. 'date': lines[-1]['date'],
  217. 'balance_start': 0.0,
  218. 'balance_end_real': balance_end_real,
  219. }
  220. @api.model
  221. def _parse_file(self, data_file):
  222. """ Import a file in Txt CSV format """
  223. is_txt = False
  224. is_xls = self._check_xls(data_file)
  225. if not is_xls:
  226. is_txt = self._check_txt(data_file)
  227. if not is_txt and not is_xls:
  228. return super(AccountBankStatementImport, self)._parse_file(
  229. data_file)
  230. if is_txt:
  231. raw_lines = self._parse_txt_file(data_file)
  232. else:
  233. raw_lines = self._parse_xls_file(data_file)
  234. final_lines = self._post_process_statement_line(raw_lines)
  235. vals_bank_statement = self._prepare_txt_statement(final_lines)
  236. transactions = []
  237. for fline in final_lines:
  238. vals_line = self._prepare_txt_statement_line(fline)
  239. _logger.debug("vals_line = %s" % vals_line)
  240. transactions.append(vals_line)
  241. vals_bank_statement['transactions'] = transactions
  242. return None, None, [vals_bank_statement]
  243. @api.model
  244. def _complete_txt_statement_line(self, line):
  245. """ Enter additional logic here. """
  246. return None
  247. @api.model
  248. def _complete_stmts_vals(self, stmts_vals, journal_id, account_number):
  249. stmts_vals = super(AccountBankStatementImport, self). \
  250. _complete_stmts_vals(stmts_vals, journal_id, account_number)
  251. for line in stmts_vals[0]['transactions']:
  252. vals = self._complete_txt_statement_line(line)
  253. if vals:
  254. line.update(vals)
  255. return stmts_vals
  256. @api.model
  257. def default_get(self, fields):
  258. res = super(AccountBankStatementImport, self).default_get(fields)
  259. journal = self._get_journal()
  260. res['txt_map_id'] = journal.statement_import_txt_map_id.id
  261. return res