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.

366 lines
16 KiB

  1. # -*- coding: utf-8 -*-
  2. """Framework for importing bank statement files."""
  3. import logging
  4. import base64
  5. from openerp import api, models, fields
  6. from openerp.tools.translate import _
  7. from openerp.exceptions import Warning
  8. _logger = logging.getLogger(__name__)
  9. class AccountBankStatementLine(models.Model):
  10. """Extend model account.bank.statement.line."""
  11. _inherit = "account.bank.statement.line"
  12. # Ensure transactions can be imported only once (if the import format
  13. # provides unique transaction ids)
  14. unique_import_id = fields.Char('Import ID', readonly=True, copy=False)
  15. _sql_constraints = [
  16. ('unique_import_id',
  17. 'unique (unique_import_id)',
  18. 'A bank account transactions can be imported only once !')
  19. ]
  20. class AccountBankStatementImport(models.TransientModel):
  21. """Extend model account.bank.statement."""
  22. _name = 'account.bank.statement.import'
  23. _description = 'Import Bank Statement'
  24. @api.model
  25. def _get_hide_journal_field(self):
  26. """ Return False if the journal_id can't be provided by the parsed
  27. file and must be provided by the wizard.
  28. See account_bank_statement_import_qif """
  29. return True
  30. journal_id = fields.Many2one(
  31. 'account.journal', string='Journal',
  32. help='Accounting journal related to the bank statement you\'re '
  33. 'importing. It has be be manually chosen for statement formats which '
  34. 'doesn\'t allow automatic journal detection (QIF for example).')
  35. hide_journal_field = fields.Boolean(
  36. string='Hide the journal field in the view',
  37. compute='_get_hide_journal_field')
  38. data_file = fields.Binary(
  39. 'Bank Statement File', required=True,
  40. help='Get you bank statements in electronic format from your bank '
  41. 'and select them here.')
  42. @api.multi
  43. def import_file(self):
  44. """ Process the file chosen in the wizard, create bank statement(s) and
  45. go to reconciliation."""
  46. self.ensure_one()
  47. data_file = base64.b64decode(self.data_file)
  48. statement_ids, notifications = self.with_context(
  49. active_id=self.id)._import_file(data_file)
  50. # dispatch to reconciliation interface
  51. action = self.env.ref(
  52. 'account.action_bank_reconcile_bank_statements')
  53. return {
  54. 'name': action.name,
  55. 'tag': action.tag,
  56. 'context': {
  57. 'statement_ids': statement_ids,
  58. 'notifications': notifications
  59. },
  60. 'type': 'ir.actions.client',
  61. }
  62. @api.model
  63. def _import_file(self, data_file):
  64. """ Create bank statement(s) from file."""
  65. # The appropriate implementation module returns the required data
  66. statement_ids = []
  67. notifications = []
  68. parse_result = self._parse_file(data_file)
  69. # Check for old version result, with separate currency and account
  70. if isinstance(parse_result, tuple) and len(parse_result) == 3:
  71. (currency_code, account_number, statements) = parse_result
  72. for stmt_vals in statements:
  73. stmt_vals['currency_code'] = currency_code
  74. stmt_vals['account_number'] = account_number
  75. else:
  76. statements = parse_result
  77. # Check raw data:
  78. self._check_parsed_data(statements)
  79. # Import all statements:
  80. for stmt_vals in statements:
  81. (statement_id, new_notifications) = (
  82. self._import_statement(stmt_vals))
  83. if statement_id:
  84. statement_ids.append(statement_id)
  85. notifications.append(new_notifications)
  86. if len(statement_ids) == 0:
  87. raise Warning(_('You have already imported that file.'))
  88. return statement_ids, notifications
  89. @api.model
  90. def _import_statement(self, stmt_vals):
  91. """Import a single bank-statement.
  92. Return ids of created statements and notifications.
  93. """
  94. currency_code = stmt_vals.pop('currency_code')
  95. account_number = stmt_vals.pop('account_number')
  96. # Try to find the bank account and currency in odoo
  97. currency_id = self._find_currency_id(currency_code)
  98. bank_account_id = self._find_bank_account_id(account_number)
  99. if not bank_account_id and account_number:
  100. raise Warning(_('Can not find the account number %s.') %
  101. account_number)
  102. # Find the bank journal
  103. journal_id = self._get_journal(currency_id, bank_account_id)
  104. # By now journal and account_number must be known
  105. if not journal_id:
  106. raise Warning(_('Can not determine journal for import.'))
  107. # Prepare statement data to be used for bank statements creation
  108. stmt_vals = self._complete_statement(
  109. stmt_vals, journal_id, account_number)
  110. # Create the bank stmt_vals
  111. return self._create_bank_statement(stmt_vals)
  112. @api.model
  113. def _parse_file(self, data_file):
  114. """ Each module adding a file support must extends this method. It
  115. processes the file if it can, returns super otherwise, resulting in a
  116. chain of responsability.
  117. This method parses the given file and returns the data required by
  118. the bank statement import process, as specified below.
  119. - bank statements data: list of dict containing (optional
  120. items marked by o) :
  121. -o currency code: string (e.g: 'EUR')
  122. The ISO 4217 currency code, case insensitive
  123. -o account number: string (e.g: 'BE1234567890')
  124. The number of the bank account which the statement
  125. belongs to
  126. - 'name': string (e.g: '000000123')
  127. - 'date': date (e.g: 2013-06-26)
  128. -o 'balance_start': float (e.g: 8368.56)
  129. -o 'balance_end_real': float (e.g: 8888.88)
  130. - 'transactions': list of dict containing :
  131. - 'name': string
  132. (e.g: 'KBC-INVESTERINGSKREDIET 787-5562831-01')
  133. - 'date': date
  134. - 'amount': float
  135. - 'unique_import_id': string
  136. -o 'account_number': string
  137. Will be used to find/create the res.partner.bank
  138. in odoo
  139. -o 'note': string
  140. -o 'partner_name': string
  141. -o 'ref': string
  142. """
  143. raise Warning(_(
  144. 'Could not make sense of the given file.\n'
  145. 'Did you install the module to support this type of file?'
  146. ))
  147. @api.model
  148. def _check_parsed_data(self, statements):
  149. """ Basic and structural verifications """
  150. if len(statements) == 0:
  151. raise Warning(_('This file doesn\'t contain any statement.'))
  152. for stmt_vals in statements:
  153. if 'transactions' in stmt_vals and stmt_vals['transactions']:
  154. return
  155. # If we get here, no transaction was found:
  156. raise Warning(_('This file doesn\'t contain any transaction.'))
  157. @api.model
  158. def _find_currency_id(self, currency_code):
  159. """ Get res.currency ID."""
  160. if currency_code:
  161. currency_ids = self.env['res.currency'].search(
  162. [('name', '=ilike', currency_code)])
  163. if currency_ids:
  164. return currency_ids[0].id
  165. else:
  166. raise Warning(_(
  167. 'Statement has invalid currency code %s') % currency_code)
  168. # if no currency_code is provided, we'll use the company currency
  169. return self.env.user.company_id.currency_id.id
  170. @api.model
  171. def _find_bank_account_id(self, account_number):
  172. """ Get res.partner.bank ID """
  173. bank_account_id = None
  174. if account_number and len(account_number) > 4:
  175. bank_account_ids = self.env['res.partner.bank'].search(
  176. [('acc_number', '=', account_number)], limit=1)
  177. if bank_account_ids:
  178. bank_account_id = bank_account_ids[0].id
  179. return bank_account_id
  180. @api.model
  181. def _get_journal(self, currency_id, bank_account_id):
  182. """ Find the journal """
  183. bank_model = self.env['res.partner.bank']
  184. # Find the journal from context, wizard or bank account
  185. journal_id = self.env.context.get('journal_id') or self.journal_id.id
  186. if bank_account_id:
  187. bank_account = bank_model.browse(bank_account_id)
  188. if journal_id:
  189. if (bank_account.journal_id.id and
  190. bank_account.journal_id.id != journal_id):
  191. raise Warning(
  192. _('The account of this statement is linked to '
  193. 'another journal.'))
  194. if not bank_account.journal_id.id:
  195. bank_model.write({'journal_id': journal_id})
  196. else:
  197. if bank_account.journal_id.id:
  198. journal_id = bank_account.journal_id.id
  199. # If importing into an existing journal, its currency must be the same
  200. # as the bank statement. When journal has no currency, currency must
  201. # be equal to company currency.
  202. if journal_id and currency_id:
  203. journal_obj = self.env['account.journal'].browse(journal_id)
  204. if journal_obj.currency:
  205. journal_currency_id = journal_obj.currency.id
  206. if currency_id != journal_currency_id:
  207. # ALso log message with id's for technical analysis:
  208. _logger.warn(
  209. _('Statement currency id is %d,'
  210. ' but journal currency id = %d.'),
  211. currency_id,
  212. journal_currency_id
  213. )
  214. raise Warning(_(
  215. 'The currency of the bank statement is not '
  216. 'the same as the currency of the journal !'
  217. ))
  218. else:
  219. company_currency_id = self.env.user.company_id.currency_id.id
  220. if currency_id != company_currency_id:
  221. # ALso log message with id's for technical analysis:
  222. _logger.warn(
  223. _('Statement currency id is %d,'
  224. ' but company currency id = %d.'),
  225. currency_id,
  226. company_currency_id
  227. )
  228. raise Warning(_(
  229. 'The currency of the bank statement is not '
  230. 'the same as the company currency !'
  231. ))
  232. return journal_id
  233. @api.model
  234. @api.returns('res.partner.bank')
  235. def _create_bank_account(
  236. self, account_number, company_id=False, currency_id=False):
  237. """Automagically create bank account, when not yet existing."""
  238. try:
  239. bank_type = self.env.ref('base.bank_normal')
  240. bank_code = bank_type.code
  241. except ValueError:
  242. bank_code = 'bank'
  243. vals_acc = {
  244. 'acc_number': account_number,
  245. 'state': bank_code,
  246. }
  247. # Odoo users bank accounts (which we import statement from) have
  248. # company_id and journal_id set while 'counterpart' bank accounts
  249. # (from which statement transactions originate) don't.
  250. # Warning : if company_id is set, the method post_write of class
  251. # bank will create a journal
  252. if company_id:
  253. vals = self.env['res.partner.bank'].onchange_company_id(company_id)
  254. vals_acc.update(vals.get('value', {}))
  255. vals_acc['company_id'] = company_id
  256. # When the journal is created at same time of the bank account, we need
  257. # to specify the currency to use for the account.account and
  258. # account.journal
  259. return self.env['res.partner.bank'].with_context(
  260. default_currency_id=currency_id,
  261. default_currency=currency_id).create(vals_acc)
  262. @api.model
  263. def _complete_statement(self, stmt_vals, journal_id, account_number):
  264. """Complete statement from information passed."""
  265. stmt_vals['journal_id'] = journal_id
  266. for line_vals in stmt_vals['transactions']:
  267. unique_import_id = line_vals.get('unique_import_id', False)
  268. if unique_import_id:
  269. line_vals['unique_import_id'] = (
  270. (account_number and account_number + '-' or '') +
  271. unique_import_id
  272. )
  273. if not line_vals.get('bank_account_id'):
  274. # Find the partner and his bank account or create the bank
  275. # account. The partner selected during the reconciliation
  276. # process will be linked to the bank when the statement is
  277. # closed.
  278. partner_id = False
  279. bank_account_id = False
  280. account_number = line_vals.get('account_number')
  281. if account_number:
  282. bank_model = self.env['res.partner.bank']
  283. banks = bank_model.search(
  284. [('acc_number', '=', account_number)], limit=1)
  285. if banks:
  286. bank_account_id = banks[0].id
  287. partner_id = banks[0].partner_id.id
  288. else:
  289. bank_obj = self._create_bank_account(account_number)
  290. bank_account_id = bank_obj and bank_obj.id or False
  291. line_vals['partner_id'] = partner_id
  292. line_vals['bank_account_id'] = bank_account_id
  293. return stmt_vals
  294. @api.model
  295. def _create_bank_statement(self, stmt_vals):
  296. """ Create bank statement from imported values, filtering out
  297. already imported transactions, and return data used by the
  298. reconciliation widget
  299. """
  300. bs_model = self.env['account.bank.statement']
  301. bsl_model = self.env['account.bank.statement.line']
  302. # Filter out already imported transactions and create statement
  303. ignored_line_ids = []
  304. filtered_st_lines = []
  305. for line_vals in stmt_vals['transactions']:
  306. unique_id = (
  307. 'unique_import_id' in line_vals and
  308. line_vals['unique_import_id']
  309. )
  310. if not unique_id or not bool(bsl_model.sudo().search(
  311. [('unique_import_id', '=', unique_id)], limit=1)):
  312. filtered_st_lines.append(line_vals)
  313. else:
  314. ignored_line_ids.append(unique_id)
  315. statement_id = False
  316. if len(filtered_st_lines) > 0:
  317. # Remove values that won't be used to create records
  318. stmt_vals.pop('transactions', None)
  319. for line_vals in filtered_st_lines:
  320. line_vals.pop('account_number', None)
  321. # Create the statement
  322. stmt_vals['line_ids'] = [
  323. [0, False, line] for line in filtered_st_lines]
  324. statement_id = bs_model.create(stmt_vals).id
  325. # Prepare import feedback
  326. notifications = []
  327. num_ignored = len(ignored_line_ids)
  328. if num_ignored > 0:
  329. notifications += [{
  330. 'type': 'warning',
  331. 'message':
  332. _("%d transactions had already been imported and "
  333. "were ignored.") % num_ignored
  334. if num_ignored > 1
  335. else _("1 transaction had already been imported and "
  336. "was ignored."),
  337. 'details': {
  338. 'name': _('Already imported items'),
  339. 'model': 'account.bank.statement.line',
  340. 'ids': bsl_model.search(
  341. [('unique_import_id', 'in', ignored_line_ids)]).ids}
  342. }]
  343. return statement_id, notifications