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.

403 lines
17 KiB

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