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.

77 lines
2.4 KiB

  1. # -*- coding: utf-8 -*-
  2. import logging
  3. import StringIO
  4. from odoo import api, models, _
  5. from odoo.exceptions import UserError
  6. _logger = logging.getLogger(__name__)
  7. try:
  8. from ofxparse import OfxParser
  9. except ImportError:
  10. _logger.debug("ofxparse not found.")
  11. OfxParser = None
  12. class AccountBankStatementImport(models.TransientModel):
  13. _inherit = 'account.bank.statement.import'
  14. @api.model
  15. def _check_ofx(self, data_file):
  16. if not OfxParser:
  17. return False
  18. try:
  19. ofx = OfxParser.parse(StringIO.StringIO(data_file))
  20. except Exception as e:
  21. _logger.debug(e)
  22. return False
  23. return ofx
  24. @api.model
  25. def _prepare_ofx_transaction_line(self, transaction):
  26. # Since ofxparse doesn't provide account numbers,
  27. # we cannot provide the key 'bank_account_id',
  28. # nor the key 'account_number'
  29. # If you read odoo10/addons/account_bank_statement_import/
  30. # account_bank_statement_import.py, it's the only 2 keys
  31. # we can provide to match a partner.
  32. vals = {
  33. 'date': transaction.date,
  34. 'name': transaction.payee + (
  35. transaction.memo and ': ' + transaction.memo or ''),
  36. 'ref': transaction.id,
  37. 'amount': float(transaction.amount),
  38. 'unique_import_id': transaction.id,
  39. }
  40. return vals
  41. def _parse_file(self, data_file):
  42. ofx = self._check_ofx(data_file)
  43. if not ofx:
  44. return super(AccountBankStatementImport, self)._parse_file(
  45. data_file)
  46. transactions = []
  47. total_amt = 0.00
  48. try:
  49. for transaction in ofx.account.statement.transactions:
  50. vals = self._prepare_ofx_transaction_line(transaction)
  51. if vals:
  52. transactions.append(vals)
  53. total_amt += vals['amount']
  54. except Exception, e:
  55. raise UserError(_(
  56. "The following problem occurred during import. "
  57. "The file might not be valid.\n\n %s") % e.message)
  58. balance = float(ofx.account.statement.balance)
  59. vals_bank_statement = {
  60. 'name': ofx.account.number,
  61. 'transactions': transactions,
  62. 'balance_start': balance - total_amt,
  63. 'balance_end_real': balance,
  64. }
  65. return ofx.account.statement.currency, ofx.account.number, [
  66. vals_bank_statement]