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.

422 lines
18 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, RedirectWarning
  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(
  138. _('Can not determine journal for import'
  139. ' for account number %s and currency %s.') %
  140. (account_number, currency_code)
  141. )
  142. # Prepare statement data to be used for bank statements creation
  143. stmt_vals = self._complete_statement(
  144. stmt_vals, journal_id, account_number)
  145. # Create the bank stmt_vals
  146. return self._create_bank_statement(stmt_vals)
  147. @api.model
  148. def _parse_file(self, data_file):
  149. # pylint: disable=no-self-use
  150. # pylint: disable=unused-argument
  151. """ Each module adding a file support must extends this method. It
  152. processes the file if it can, returns super otherwise, resulting in a
  153. chain of responsability.
  154. This method parses the given file and returns the data required by
  155. the bank statement import process, as specified below.
  156. - bank statements data: list of dict containing (optional
  157. items marked by o) :
  158. -o currency code: string (e.g: 'EUR')
  159. The ISO 4217 currency code, case insensitive
  160. -o account number: string (e.g: 'BE1234567890')
  161. The number of the bank account which the statement
  162. belongs to
  163. - 'name': string (e.g: '000000123')
  164. - 'date': date (e.g: 2013-06-26)
  165. -o 'balance_start': float (e.g: 8368.56)
  166. -o 'balance_end_real': float (e.g: 8888.88)
  167. - 'transactions': list of dict containing :
  168. - 'name': string
  169. (e.g: 'KBC-INVESTERINGSKREDIET 787-5562831-01')
  170. - 'date': date
  171. - 'amount': float
  172. - 'unique_import_id': string
  173. -o 'account_number': string
  174. Will be used to find/create the res.partner.bank
  175. in odoo
  176. -o 'note': string
  177. -o 'partner_name': string
  178. -o 'ref': string
  179. """
  180. raise UserError(_(
  181. 'Could not make sense of the given file.\n'
  182. 'Did you install the module to support this type of file?'
  183. ))
  184. @api.model
  185. def _check_parsed_data(self, statements):
  186. # pylint: disable=no-self-use
  187. """ Basic and structural verifications """
  188. if len(statements) == 0:
  189. raise UserError(_('This file doesn\'t contain any statement.'))
  190. for stmt_vals in statements:
  191. if 'transactions' in stmt_vals and stmt_vals['transactions']:
  192. return
  193. # If we get here, no transaction was found:
  194. raise UserError(_('This file doesn\'t contain any transaction.'))
  195. @api.model
  196. def _find_currency_id(self, currency_code):
  197. """ Get res.currency ID."""
  198. if currency_code:
  199. currency_ids = self.env['res.currency'].search(
  200. [('name', '=ilike', currency_code)])
  201. if currency_ids:
  202. return currency_ids[0].id
  203. else:
  204. raise UserError(_(
  205. 'Statement has invalid currency code %s') % currency_code)
  206. # if no currency_code is provided, we'll use the company currency
  207. return self.env.user.company_id.currency_id.id
  208. @api.model
  209. def _find_bank_account_id(self, account_number):
  210. """ Get res.partner.bank ID """
  211. bank_account_id = None
  212. if account_number and len(account_number) > 4:
  213. bank_account_ids = self.env['res.partner.bank'].search(
  214. [('acc_number', '=', account_number)], limit=1)
  215. if bank_account_ids:
  216. bank_account_id = bank_account_ids[0].id
  217. return bank_account_id
  218. @api.model
  219. def _get_journal(self, currency_id, bank_account_id):
  220. """ Find the journal """
  221. bank_model = self.env['res.partner.bank']
  222. # Find the journal from context, wizard or bank account
  223. journal_id = self.env.context.get('journal_id') or self.journal_id.id
  224. currency = self.env['res.currency'].browse(currency_id)
  225. if bank_account_id:
  226. bank_account = bank_model.browse(bank_account_id)
  227. if journal_id:
  228. if (bank_account.journal_id.id and
  229. bank_account.journal_id.id != journal_id):
  230. raise UserError(
  231. _('The account of this statement is linked to '
  232. 'another journal.'))
  233. if not bank_account.journal_id.id:
  234. bank_model.write({'journal_id': journal_id})
  235. else:
  236. if bank_account.journal_id.id:
  237. journal_id = bank_account.journal_id.id
  238. # If importing into an existing journal, its currency must be the same
  239. # as the bank statement. When journal has no currency, currency must
  240. # be equal to company currency.
  241. if journal_id and currency_id:
  242. journal_obj = self.env['account.journal'].browse(journal_id)
  243. if journal_obj.currency:
  244. journal_currency_id = journal_obj.currency.id
  245. if currency_id != journal_currency_id:
  246. # ALso log message with id's for technical analysis:
  247. _logger.warn(
  248. _('Statement currency id is %d,'
  249. ' but journal currency id = %d.'),
  250. currency_id,
  251. journal_currency_id
  252. )
  253. raise UserError(_(
  254. 'The currency of the bank statement (%s) is not '
  255. 'the same as the currency of the journal %s (%s) !'
  256. ) % (
  257. currency.name,
  258. journal_obj.name,
  259. journal_obj.currency.name))
  260. else:
  261. company_currency = self.env.user.company_id.currency_id
  262. if currency_id != company_currency.id:
  263. # ALso log message with id's for technical analysis:
  264. _logger.warn(
  265. _('Statement currency id is %d,'
  266. ' but company currency id = %d.'),
  267. currency_id,
  268. company_currency.id
  269. )
  270. raise UserError(_(
  271. 'The currency of the bank statement (%s) is not '
  272. 'the same as the company currency (%s) !'
  273. ) % (currency.name, company_currency.name))
  274. return journal_id
  275. @api.model
  276. @api.returns('res.partner.bank')
  277. def _create_bank_account(
  278. self, account_number, company_id=False, currency_id=False):
  279. """Automagically create bank account, when not yet existing."""
  280. try:
  281. bank_type = self.env.ref('base.bank_normal')
  282. bank_code = bank_type.code
  283. except ValueError:
  284. bank_code = 'bank'
  285. vals_acc = {
  286. 'acc_number': account_number,
  287. 'state': bank_code,
  288. }
  289. # Odoo users bank accounts (which we import statement from) have
  290. # company_id and journal_id set while 'counterpart' bank accounts
  291. # (from which statement transactions originate) don't.
  292. # Warning : if company_id is set, the method post_write of class
  293. # bank will create a journal
  294. if company_id:
  295. vals = self.env['res.partner.bank'].onchange_company_id(company_id)
  296. vals_acc.update(vals.get('value', {}))
  297. vals_acc['company_id'] = company_id
  298. # When the journal is created at same time of the bank account, we need
  299. # to specify the currency to use for the account.account and
  300. # account.journal
  301. return self.env['res.partner.bank'].with_context(
  302. default_currency_id=currency_id,
  303. default_currency=currency_id).create(vals_acc)
  304. @api.model
  305. def _complete_statement(self, stmt_vals, journal_id, account_number):
  306. """Complete statement from information passed."""
  307. stmt_vals['journal_id'] = journal_id
  308. for line_vals in stmt_vals['transactions']:
  309. unique_import_id = line_vals.get('unique_import_id', False)
  310. if unique_import_id:
  311. line_vals['unique_import_id'] = (
  312. (account_number and account_number + '-' or '') +
  313. unique_import_id
  314. )
  315. if not line_vals.get('bank_account_id'):
  316. # Find the partner and his bank account or create the bank
  317. # account. The partner selected during the reconciliation
  318. # process will be linked to the bank when the statement is
  319. # closed.
  320. partner_id = False
  321. bank_account_id = False
  322. partner_account_number = line_vals.get('account_number')
  323. if partner_account_number:
  324. bank_model = self.env['res.partner.bank']
  325. banks = bank_model.search(
  326. [('acc_number', '=', partner_account_number)], limit=1)
  327. if banks:
  328. bank_account_id = banks[0].id
  329. partner_id = banks[0].partner_id.id
  330. else:
  331. bank_obj = self._create_bank_account(
  332. partner_account_number)
  333. bank_account_id = bank_obj and bank_obj.id or False
  334. line_vals['partner_id'] = partner_id
  335. line_vals['bank_account_id'] = bank_account_id
  336. if 'date' in stmt_vals and 'period_id' not in stmt_vals:
  337. # if the parser found a date but didn't set a period for this date,
  338. # do this now
  339. try:
  340. stmt_vals['period_id'] =\
  341. self.env['account.period']\
  342. .with_context(account_period_prefer_normal=True)\
  343. .find(dt=stmt_vals['date']).id
  344. except RedirectWarning:
  345. # if there's no period for the date, ignore resulting exception
  346. pass
  347. return stmt_vals
  348. @api.model
  349. def _create_bank_statement(self, stmt_vals):
  350. """ Create bank statement from imported values, filtering out
  351. already imported transactions, and return data used by the
  352. reconciliation widget
  353. """
  354. bs_model = self.env['account.bank.statement']
  355. bsl_model = self.env['account.bank.statement.line']
  356. # Filter out already imported transactions and create statement
  357. ignored_line_ids = []
  358. filtered_st_lines = []
  359. for line_vals in stmt_vals['transactions']:
  360. unique_id = (
  361. 'unique_import_id' in line_vals and
  362. line_vals['unique_import_id']
  363. )
  364. if not unique_id or not bool(bsl_model.sudo().search(
  365. [('unique_import_id', '=', unique_id)], limit=1)):
  366. filtered_st_lines.append(line_vals)
  367. else:
  368. ignored_line_ids.append(unique_id)
  369. statement_id = False
  370. if len(filtered_st_lines) > 0:
  371. # Remove values that won't be used to create records
  372. stmt_vals.pop('transactions', None)
  373. for line_vals in filtered_st_lines:
  374. line_vals.pop('account_number', None)
  375. # Create the statement
  376. stmt_vals['line_ids'] = [
  377. [0, False, line] for line in filtered_st_lines]
  378. statement_id = bs_model.create(stmt_vals).id
  379. # Prepare import feedback
  380. notifications = []
  381. num_ignored = len(ignored_line_ids)
  382. if num_ignored > 0:
  383. notifications += [{
  384. 'type': 'warning',
  385. 'message':
  386. _("%d transactions had already been imported and "
  387. "were ignored.") % num_ignored
  388. if num_ignored > 1
  389. else _("1 transaction had already been imported and "
  390. "was ignored."),
  391. 'details': {
  392. 'name': _('Already imported items'),
  393. 'model': 'account.bank.statement.line',
  394. 'ids': bsl_model.search(
  395. [('unique_import_id', 'in', ignored_line_ids)]).ids}
  396. }]
  397. return statement_id, notifications