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.

270 lines
10 KiB

  1. # -*- coding: utf-8 -*-
  2. """Generic parser for MT940 files, base for customized versions per bank."""
  3. ##############################################################################
  4. #
  5. # OpenERP, Open Source Management Solution
  6. # This module copyright (C) 2014-2015 Therp BV <http://therp.nl>.
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU Affero General Public License as
  10. # published by the Free Software Foundation, either version 3 of the
  11. # License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Affero General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Affero General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. ##############################################################################
  22. import re
  23. import logging
  24. from datetime import datetime
  25. from openerp.addons.bank_statement_parse import parserlib
  26. def str2amount(sign, amount_str):
  27. """Convert sign (C or D) and amount in string to signed amount (float)."""
  28. factor = (1 if sign == 'C' else -1)
  29. return factor * float(amount_str.replace(',', '.'))
  30. def get_subfields(data, codewords):
  31. """Return dictionary with value array for each codeword in data.
  32. For instance:
  33. data =
  34. /BENM//NAME/Kosten/REMI/Periode 01-10-2013 t/m 31-12-2013/ISDT/20
  35. codewords = ['BENM', 'ADDR', 'NAME', 'CNTP', ISDT', 'REMI']
  36. Then return subfields = {
  37. 'BENM': [],
  38. 'NAME': ['Kosten'],
  39. 'REMI': ['Periode 01-10-2013 t', 'm 31-12-2013'],
  40. 'ISDT': ['20'],
  41. }
  42. """
  43. subfields = {}
  44. current_codeword = None
  45. for word in data.split('/'):
  46. if not word and not current_codeword:
  47. continue
  48. if word in codewords:
  49. current_codeword = word
  50. subfields[current_codeword] = []
  51. continue
  52. if current_codeword in subfields:
  53. subfields[current_codeword].append(word)
  54. return subfields
  55. def get_counterpart(transaction, subfield):
  56. """Get counterpart from transaction.
  57. Counterpart is often stored in subfield of tag 86. The subfield
  58. can be BENM, ORDP, CNTP"""
  59. if not subfield:
  60. return # subfield is empty
  61. if len(subfield) >= 1 and subfield[0]:
  62. transaction.remote_account = subfield[0]
  63. if len(subfield) >= 2 and subfield[1]:
  64. transaction.remote_bank_bic = subfield[1]
  65. if len(subfield) >= 3 and subfield[2]:
  66. transaction.remote_owner = subfield[2]
  67. if len(subfield) >= 4 and subfield[3]:
  68. transaction.remote_owner_city = subfield[3]
  69. def handle_common_subfields(transaction, subfields):
  70. """Deal with common functionality for tag 86 subfields."""
  71. # Get counterpart from CNTP, BENM or ORDP subfields:
  72. for counterpart_field in ['CNTP', 'BENM', 'ORDP']:
  73. if counterpart_field in subfields:
  74. get_counterpart(transaction, subfields[counterpart_field])
  75. # REMI: Remitter information (text entered by other party on trans.):
  76. if 'REMI' in subfields:
  77. transaction.message = (
  78. '/'.join(x for x in subfields['REMI'] if x))
  79. # Get transaction reference subfield (might vary):
  80. if transaction.eref in subfields:
  81. transaction.eref = ''.join(
  82. subfields[transaction.eref])
  83. class MT940(object):
  84. """Inherit this class in your account_banking.parsers.models.parser,
  85. define functions to handle the tags you need to handle and adjust static
  86. variables as needed.
  87. At least, you should override handle_tag_61 and handle_tag_86.
  88. Don't forget to call super.
  89. handle_tag_* functions receive the remainder of the the line (that is,
  90. without ':XX:') and are supposed to write into self.current_transaction
  91. """
  92. def __init__(self):
  93. """Initialize parser - override at least header_regex.
  94. This in fact uses the ING syntax, override in others."""
  95. self.mt940_type = 'General'
  96. self.header_lines = 3 # Number of lines to skip
  97. self.header_regex = '^0000 01INGBNL2AXXXX|^{1'
  98. self.footer_regex = '^-}$|^-XXX$' # Stop processing on seeing this
  99. self.tag_regex = '^:[0-9]{2}[A-Z]*:' # Start of new tag
  100. self.current_statement = None
  101. self.current_transaction = None
  102. self.statements = []
  103. def is_mt940(self, line):
  104. """determine if a line is the header of a statement"""
  105. if not bool(re.match(self.header_regex, line)):
  106. raise ValueError(
  107. 'File starting with %s does not seem to be a'
  108. ' valid %s MT940 format bank statement.' %
  109. (line[:12], self.mt940_type)
  110. )
  111. def parse(self, data):
  112. """Parse mt940 bank statement file contents."""
  113. self.is_mt940(data)
  114. iterator = data.replace('\r\n', '\n').split('\n').__iter__()
  115. line = None
  116. record_line = ''
  117. try:
  118. while True:
  119. if not self.current_statement:
  120. self.handle_header(line, iterator)
  121. line = iterator.next()
  122. if not self.is_tag(line) and not self.is_footer(line):
  123. record_line = self.append_continuation_line(
  124. record_line, line)
  125. continue
  126. if record_line:
  127. self.handle_record(record_line)
  128. if self.is_footer(line):
  129. self.handle_footer(line, iterator)
  130. record_line = ''
  131. continue
  132. record_line = line
  133. except StopIteration:
  134. pass
  135. if self.current_statement:
  136. if record_line:
  137. self.handle_record(record_line)
  138. record_line = ''
  139. self.statements.append(self.current_statement)
  140. self.current_statement = None
  141. return self.statements
  142. def append_continuation_line(self, line, continuation_line):
  143. """append a continuation line for a multiline record.
  144. Override and do data cleanups as necessary."""
  145. return line + continuation_line
  146. def create_statement(self):
  147. """create a BankStatement."""
  148. return parserlib.BankStatement()
  149. def create_transaction(self):
  150. """Create and return BankTransaction object."""
  151. return parserlib.BankTransaction()
  152. def is_footer(self, line):
  153. """determine if a line is the footer of a statement"""
  154. return line and bool(re.match(self.footer_regex, line))
  155. def is_tag(self, line):
  156. """determine if a line has a tag"""
  157. return line and bool(re.match(self.tag_regex, line))
  158. def handle_header(self, line, iterator):
  159. """skip header lines, create current statement"""
  160. for dummy_i in range(self.header_lines):
  161. iterator.next()
  162. self.current_statement = self.create_statement()
  163. def handle_footer(self, line, iterator):
  164. """add current statement to list, reset state"""
  165. self.statements.append(self.current_statement)
  166. self.current_statement = None
  167. def handle_record(self, line):
  168. """find a function to handle the record represented by line"""
  169. tag_match = re.match(self.tag_regex, line)
  170. tag = tag_match.group(0).strip(':')
  171. if not hasattr(self, 'handle_tag_%s' % tag):
  172. logging.error('Unknown tag %s', tag)
  173. logging.error(line)
  174. return
  175. handler = getattr(self, 'handle_tag_%s' % tag)
  176. handler(line[tag_match.end():])
  177. def handle_tag_20(self, data):
  178. """Contains unique ? message ID"""
  179. pass
  180. def handle_tag_25(self, data):
  181. """Handle tag 25: local bank account information."""
  182. data = data.replace('EUR', '').replace('.', '').strip()
  183. self.current_statement.local_account = data
  184. def handle_tag_28C(self, data):
  185. """Sequence number within batch - normally only zeroes."""
  186. pass
  187. def handle_tag_60F(self, data):
  188. """get start balance and currency"""
  189. # For the moment only first 60F record
  190. # The alternative would be to split the file and start a new
  191. # statement for each 20: tag encountered.
  192. stmt = self.current_statement
  193. if not stmt.local_currency:
  194. stmt.local_currency = data[7:10]
  195. stmt.start_balance = str2amount(data[0], data[10:])
  196. def handle_tag_61(self, data):
  197. """get transaction values"""
  198. transaction = self.create_transaction()
  199. self.current_statement.transactions.append(transaction)
  200. self.current_transaction = transaction
  201. transaction.execution_date = datetime.strptime(data[:6], '%y%m%d')
  202. transaction.value_date = datetime.strptime(data[:6], '%y%m%d')
  203. # ...and the rest already is highly bank dependent
  204. def handle_tag_62F(self, data):
  205. """Get ending balance, statement date and id.
  206. We use the date on the last 62F tag as statement date, as the date
  207. on the 60F record (previous end balance) might contain a date in
  208. a previous period.
  209. We generate the statement.id from the local_account and the end-date,
  210. this should normally be unique, provided there is a maximum of
  211. one statement per day.
  212. Depending on the bank, there might be multiple 62F tags in the import
  213. file. The last one counts.
  214. """
  215. stmt = self.current_statement
  216. stmt.end_balance = str2amount(data[0], data[10:])
  217. stmt.date = datetime.strptime(data[1:7], '%y%m%d')
  218. stmt.statement_id = '%s-%s' % (
  219. stmt.local_account,
  220. stmt.date.strftime('%Y-%m-%d'),
  221. )
  222. def handle_tag_64(self, data):
  223. """get current balance in currency"""
  224. pass
  225. def handle_tag_65(self, data):
  226. """get future balance in currency"""
  227. pass
  228. def handle_tag_86(self, data):
  229. """details for previous transaction, here most differences between
  230. banks occur"""
  231. pass