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.

269 lines
10 KiB

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