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.

268 lines
9.9 KiB

10 years ago
  1. # -*- coding: utf-8 -*-
  2. """Generic parser for MT940 files, base for customized versions per bank."""
  3. # Copyright 2014-2018 Therp BV <https://therp.nl>.
  4. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  5. import re
  6. import logging
  7. from datetime import datetime
  8. from openerp.addons.account_bank_statement_import.parserlib import (
  9. BankStatement)
  10. def str2amount(sign, amount_str):
  11. """Convert sign (C or D) and amount in string to signed amount (float)."""
  12. factor = (1 if sign == 'C' else -1)
  13. return factor * float(amount_str.replace(',', '.'))
  14. def get_subfields(data, codewords):
  15. """Return dictionary with value array for each codeword in data.
  16. For instance:
  17. data =
  18. /BENM//NAME/Kosten/REMI/Periode 01-10-2013 t/m 31-12-2013/ISDT/20
  19. codewords = ['BENM', 'ADDR', 'NAME', 'CNTP', ISDT', 'REMI']
  20. Then return subfields = {
  21. 'BENM': [],
  22. 'NAME': ['Kosten'],
  23. 'REMI': ['Periode 01-10-2013 t', 'm 31-12-2013'],
  24. 'ISDT': ['20'],
  25. }
  26. """
  27. subfields = {}
  28. current_codeword = None
  29. for word in data.split('/'):
  30. if not word and not current_codeword:
  31. continue
  32. if word in codewords:
  33. current_codeword = word
  34. subfields[current_codeword] = []
  35. continue
  36. if current_codeword in subfields:
  37. subfields[current_codeword].append(word)
  38. return subfields
  39. def get_counterpart(transaction, subfield):
  40. """Get counterpart from transaction.
  41. Counterpart is often stored in subfield of tag 86. The subfield
  42. can be BENM, ORDP, CNTP"""
  43. if not subfield:
  44. return # subfield is empty
  45. if len(subfield) >= 1 and subfield[0]:
  46. transaction.remote_account = subfield[0]
  47. if len(subfield) >= 2 and subfield[1]:
  48. transaction.remote_bank_bic = subfield[1]
  49. if len(subfield) >= 3 and subfield[2]:
  50. transaction.remote_owner = subfield[2]
  51. if len(subfield) >= 4 and subfield[3]:
  52. transaction.remote_owner_city = subfield[3]
  53. def handle_common_subfields(transaction, subfields):
  54. """Deal with common functionality for tag 86 subfields.
  55. transaction.eref is filled from 61 record with information on subfield
  56. that contains the actual reference in 86 record. So transaction.eref
  57. is used for a dual purpose!
  58. """
  59. # Get counterpart from CNTP, BENM or ORDP subfields:
  60. for counterpart_field in ['CNTP', 'BENM', 'ORDP']:
  61. if counterpart_field in subfields:
  62. get_counterpart(transaction, subfields[counterpart_field])
  63. if not transaction.message:
  64. transaction.message = ''
  65. # REMI: Remitter information (text entered by other party on trans.):
  66. if 'REMI' in subfields:
  67. transaction.message += (
  68. subfields['REMI'][2]
  69. # this might look like
  70. # /REMI/USTD//<remittance info>/
  71. # or
  72. # /REMI/STRD/CUR/<betalingskenmerk>/
  73. if len(subfields['REMI']) >= 3 and subfields['REMI'][0] in [
  74. 'STRD', 'USTD'
  75. ]
  76. else
  77. '/'.join(x for x in subfields['REMI'] if x)
  78. )
  79. # EREF: End-to-end reference
  80. # Get transaction reference subfield (might vary):
  81. transaction.eref = transaction.eref or 'EREF'
  82. if transaction.eref in subfields:
  83. transaction.eref = ''.join(subfields[transaction.eref])
  84. class MT940(object):
  85. """Inherit this class in your account_banking.parsers.models.parser,
  86. define functions to handle the tags you need to handle and adjust static
  87. variables as needed.
  88. At least, you should override handle_tag_61 and handle_tag_86.
  89. Don't forget to call super.
  90. handle_tag_* functions receive the remainder of the the line (that is,
  91. without ':XX:') and are supposed to write into self.current_transaction
  92. """
  93. def __init__(self):
  94. """Initialize parser - override at least header_regex.
  95. This in fact uses the ING syntax, override in others."""
  96. self.mt940_type = 'General'
  97. self.header_lines = 3 # Number of lines to skip
  98. self.header_regex = '^0000 01INGBNL2AXXXX|^{1' # Start of header
  99. self.footer_regex = '^-}$|^-XXX$' # Stop processing on seeing this
  100. self.tag_regex = '^:[0-9]{2}[A-Z]*:' # Start of new tag
  101. self.current_statement = None
  102. self.current_transaction = None
  103. self.statements = []
  104. def is_mt940(self, line):
  105. """determine if a line is the header of a statement"""
  106. if not bool(re.match(self.header_regex, line)):
  107. raise ValueError(
  108. 'File starting with %s does not seem to be a'
  109. ' valid %s MT940 format bank statement.' %
  110. (line[:12], self.mt940_type)
  111. )
  112. def parse(self, data):
  113. """Parse mt940 bank statement file contents."""
  114. self.is_mt940(data)
  115. iterator = data.replace('\r\n', '\n').split('\n').__iter__()
  116. line = None
  117. record_line = ''
  118. try:
  119. while True:
  120. if not self.current_statement:
  121. self.handle_header(line, iterator)
  122. line = iterator.next()
  123. if not self.is_tag(line) and not self.is_footer(line):
  124. record_line = self.add_record_line(line, record_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 add_record_line(self, line, record_line):
  143. record_line += line
  144. return record_line
  145. def is_footer(self, line):
  146. """determine if a line is the footer of a statement"""
  147. return line and bool(re.match(self.footer_regex, line))
  148. def is_tag(self, line):
  149. """determine if a line has a tag"""
  150. return line and bool(re.match(self.tag_regex, line))
  151. def handle_header(self, dummy_line, iterator):
  152. """skip header lines, create current statement"""
  153. for dummy_i in range(self.header_lines):
  154. iterator.next()
  155. self.current_statement = BankStatement()
  156. def handle_footer(self, dummy_line, dummy_iterator):
  157. """add current statement to list, reset state"""
  158. self.statements.append(self.current_statement)
  159. self.current_statement = None
  160. def handle_record(self, line):
  161. """find a function to handle the record represented by line"""
  162. tag_match = re.match(self.tag_regex, line)
  163. tag = tag_match.group(0).strip(':')
  164. if not hasattr(self, 'handle_tag_%s' % tag):
  165. logging.error('Unknown tag %s', tag)
  166. logging.error(line)
  167. return
  168. handler = getattr(self, 'handle_tag_%s' % tag)
  169. handler(line[tag_match.end():])
  170. def handle_tag_20(self, data):
  171. """Contains unique ? message ID"""
  172. pass
  173. def handle_tag_25(self, data):
  174. """Handle tag 25: local bank account information."""
  175. data = data.replace('EUR', '').replace('.', '').strip()
  176. self.current_statement.local_account = data
  177. def handle_tag_28C(self, data):
  178. """Sequence number within batch - normally only zeroes."""
  179. pass
  180. def handle_tag_60F(self, data):
  181. """get start balance and currency"""
  182. # For the moment only first 60F record
  183. # The alternative would be to split the file and start a new
  184. # statement for each 20: tag encountered.
  185. stmt = self.current_statement
  186. if not stmt.local_currency:
  187. stmt.local_currency = data[7:10]
  188. stmt.start_balance = str2amount(data[0], data[10:])
  189. def handle_tag_61(self, data):
  190. """get transaction values"""
  191. transaction = self.current_statement.create_transaction()
  192. self.current_transaction = transaction
  193. transaction.execution_date = datetime.strptime(data[:6], '%y%m%d')
  194. transaction.value_date = datetime.strptime(data[:6], '%y%m%d')
  195. # ...and the rest already is highly bank dependent
  196. def handle_tag_62F(self, data):
  197. """Get ending balance, statement date and id.
  198. We use the date on the last 62F tag as statement date, as the date
  199. on the 60F record (previous end balance) might contain a date in
  200. a previous period.
  201. We generate the statement.id from the local_account and the end-date,
  202. this should normally be unique, provided there is a maximum of
  203. one statement per day.
  204. Depending on the bank, there might be multiple 62F tags in the import
  205. file. The last one counts.
  206. """
  207. stmt = self.current_statement
  208. stmt.end_balance = str2amount(data[0], data[10:])
  209. stmt.date = datetime.strptime(data[1:7], '%y%m%d')
  210. # Only replace logically empty (only whitespace or zeroes) id's:
  211. # But do replace statement_id's added before (therefore starting
  212. # with local_account), because we need the date on the last 62F
  213. # record.
  214. test_empty_id = re.sub(r'[\s0]', '', stmt.statement_id)
  215. if ((not test_empty_id) or
  216. (stmt.statement_id.startswith(stmt.local_account))):
  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