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.

291 lines
11 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. def str2amount(sign, amount_str):
  25. """Convert sign (C or D) and amount in string to signed amount (float)."""
  26. factor = (1 if sign == 'C' else -1)
  27. return factor * float(amount_str.replace(',', '.'))
  28. def get_subfields(data, codewords):
  29. """Return dictionary with value array for each codeword in data.
  30. For instance:
  31. data =
  32. /BENM//NAME/Kosten/REMI/Periode 01-10-2013 t/m 31-12-2013/ISDT/20
  33. codewords = ['BENM', 'ADDR', 'NAME', 'CNTP', ISDT', 'REMI']
  34. Then return subfields = {
  35. 'BENM': [],
  36. 'NAME': ['Kosten'],
  37. 'REMI': ['Periode 01-10-2013 t', 'm 31-12-2013'],
  38. 'ISDT': ['20'],
  39. }
  40. """
  41. subfields = {}
  42. current_codeword = None
  43. for word in data.split('/'):
  44. if not word and not current_codeword:
  45. continue
  46. if word in codewords:
  47. current_codeword = word
  48. subfields[current_codeword] = []
  49. continue
  50. if current_codeword in subfields:
  51. subfields[current_codeword].append(word)
  52. return subfields
  53. def get_counterpart(transaction, subfield):
  54. """Get counterpart from transaction.
  55. Counterpart is often stored in subfield of tag 86. The subfield
  56. can be BENM, ORDP, CNTP"""
  57. if not subfield:
  58. return # subfield is empty
  59. if len(subfield) >= 1 and subfield[0]:
  60. transaction.update({'account_number': subfield[0]})
  61. if len(subfield) >= 2 and subfield[1]:
  62. transaction.update({'account_bic': subfield[1]})
  63. if len(subfield) >= 3 and subfield[2]:
  64. transaction.update({'partner_name': subfield[2]})
  65. def handle_common_subfields(transaction, subfields):
  66. """Deal with common functionality for tag 86 subfields."""
  67. # Get counterpart from CNTP, BENM or ORDP subfields:
  68. for counterpart_field in ['CNTP', 'BENM', 'ORDP']:
  69. if counterpart_field in subfields:
  70. get_counterpart(transaction, subfields[counterpart_field])
  71. if not transaction.get('name'):
  72. transaction['name'] = ''
  73. # REMI: Remitter information (text entered by other party on trans.):
  74. if 'REMI' in subfields:
  75. transaction['name'] += (
  76. subfields['REMI'][2]
  77. # this might look like
  78. # /REMI/USTD//<remittance info>/
  79. # or
  80. # /REMI/STRD/CUR/<betalingskenmerk>/
  81. if len(subfields['REMI']) >= 3 and subfields['REMI'][0] in [
  82. 'STRD', 'USTD'
  83. ]
  84. else
  85. '/'.join(x for x in subfields['REMI'] if x)
  86. )
  87. # EREF: End-to-end reference
  88. if 'EREF' in subfields:
  89. transaction['name'] += '/'.join(filter(bool, subfields['EREF']))
  90. # Get transaction reference subfield (might vary):
  91. if transaction.get('ref') in subfields:
  92. transaction['ref'] = ''.join(subfields[transaction['ref']])
  93. class MT940(object):
  94. """Inherit this class in your account_banking.parsers.models.parser,
  95. define functions to handle the tags you need to handle and adjust static
  96. variables as needed.
  97. At least, you should override handle_tag_61 and handle_tag_86.
  98. Don't forget to call super.
  99. handle_tag_* functions receive the remainder of the the line (that is,
  100. without ':XX:') and are supposed to write into self.current_transaction
  101. """
  102. def __init__(self):
  103. """Initialize parser - override at least header_regex.
  104. This in fact uses the ING syntax, override in others."""
  105. self.mt940_type = 'General'
  106. self.header_lines = 3 # Number of lines to skip
  107. self.header_regex = '^0000 01INGBNL2AXXXX|^{1' # Start of header
  108. self.footer_regex = '^-}$|^-XXX$' # Stop processing on seeing this
  109. self.tag_regex = '^:[0-9]{2}[A-Z]*:' # Start of new tag
  110. self.current_statement = None
  111. self.current_transaction = None
  112. self.statements = []
  113. self.currency_code = None
  114. self.account_number = None
  115. def is_mt940(self, line):
  116. """determine if a line is the header of a statement"""
  117. if not bool(re.match(self.header_regex, line)):
  118. raise ValueError(
  119. 'File starting with %s does not seem to be a'
  120. ' valid %s MT940 format bank statement.' %
  121. (line[:12], self.mt940_type)
  122. )
  123. def parse(self, data):
  124. """Parse mt940 bank statement file contents."""
  125. self.is_mt940(data)
  126. iterator = data.replace('\r\n', '\n').split('\n').__iter__()
  127. line = None
  128. record_line = ''
  129. try:
  130. while True:
  131. if not self.current_statement:
  132. self.handle_header(line, iterator)
  133. line = iterator.next()
  134. if not self.is_tag(line) and not self.is_footer(line):
  135. record_line = self.add_record_line(line, record_line)
  136. continue
  137. if record_line:
  138. self.handle_record(record_line)
  139. if self.is_footer(line):
  140. self.handle_footer(line, iterator)
  141. record_line = ''
  142. continue
  143. record_line = line
  144. except StopIteration:
  145. pass
  146. if self.current_statement:
  147. if record_line:
  148. self.handle_record(record_line)
  149. record_line = ''
  150. self.statements.append(self.current_statement)
  151. self.current_statement = None
  152. return self.currency_code, self.account_number, self.statements
  153. def add_record_line(self, line, record_line):
  154. record_line += line
  155. return record_line
  156. def is_footer(self, line):
  157. """determine if a line is the footer of a statement"""
  158. return line and bool(re.match(self.footer_regex, line))
  159. def is_tag(self, line):
  160. """determine if a line has a tag"""
  161. return line and bool(re.match(self.tag_regex, line))
  162. def handle_header(self, dummy_line, iterator):
  163. """skip header lines, create current statement"""
  164. for dummy_i in range(self.header_lines):
  165. iterator.next()
  166. self.current_statement = {
  167. 'name': None,
  168. 'date': None,
  169. 'balance_start': 0.0,
  170. 'balance_end_real': 0.0,
  171. 'transactions': []
  172. }
  173. def handle_footer(self, dummy_line, dummy_iterator):
  174. """add current statement to list, reset state"""
  175. self.statements.append(self.current_statement)
  176. self.current_statement = None
  177. def handle_record(self, line):
  178. """find a function to handle the record represented by line"""
  179. tag_match = re.match(self.tag_regex, line)
  180. tag = tag_match.group(0).strip(':')
  181. if not hasattr(self, 'handle_tag_%s' % tag): # pragma: no cover
  182. logging.error('Unknown tag %s', tag)
  183. logging.error(line)
  184. return
  185. handler = getattr(self, 'handle_tag_%s' % tag)
  186. handler(line[tag_match.end():])
  187. def handle_tag_20(self, data):
  188. """Contains unique ? message ID"""
  189. pass
  190. def handle_tag_25(self, data):
  191. """Handle tag 25: local bank account information."""
  192. data = data.replace('EUR', '').replace('.', '').strip()
  193. self.account_number = data
  194. def handle_tag_28C(self, data):
  195. """Sequence number within batch - normally only zeroes."""
  196. pass
  197. def handle_tag_60F(self, data):
  198. """get start balance and currency"""
  199. # For the moment only first 60F record
  200. # The alternative would be to split the file and start a new
  201. # statement for each 20: tag encountered.
  202. if not self.currency_code:
  203. self.currency_code = data[7:10]
  204. self.current_statement['balance_start'] = str2amount(
  205. data[0],
  206. data[10:]
  207. )
  208. def handle_tag_61(self, data):
  209. """get transaction values"""
  210. self.current_statement['transactions'].append({})
  211. self.current_transaction = self.current_statement['transactions'][-1]
  212. self.current_transaction['date'] = datetime.strptime(
  213. data[:6],
  214. '%y%m%d'
  215. )
  216. def handle_tag_62F(self, data):
  217. """Get ending balance, statement date and id.
  218. We use the date on the last 62F tag as statement date, as the date
  219. on the 60F record (previous end balance) might contain a date in
  220. a previous period.
  221. We generate the statement.id from the local_account and the end-date,
  222. this should normally be unique, provided there is a maximum of
  223. one statement per day.
  224. Depending on the bank, there might be multiple 62F tags in the import
  225. file. The last one counts.
  226. """
  227. self.current_statement['balance_end_real'] = str2amount(
  228. data[0],
  229. data[10:]
  230. )
  231. self.current_statement['date'] = datetime.strptime(data[1:7], '%y%m%d')
  232. # Only replace logically empty (only whitespace or zeroes) id's:
  233. # But do replace statement_id's added before (therefore starting
  234. # with local_account), because we need the date on the last 62F
  235. # record.
  236. statement_name = self.current_statement['name'] or ''
  237. test_empty_id = re.sub(r'[\s0]', '', statement_name)
  238. is_account_number = statement_name.startswith(self.account_number)
  239. if ((not test_empty_id) or is_account_number):
  240. self.current_statement['name'] = '%s-%s' % (
  241. self.account_number,
  242. self.current_statement['date'].strftime('%Y-%m-%d'),
  243. )
  244. def handle_tag_64(self, data):
  245. """get current balance in currency"""
  246. pass
  247. def handle_tag_65(self, data):
  248. """get future balance in currency"""
  249. pass
  250. def handle_tag_86(self, data):
  251. """details for previous transaction, here most differences between
  252. banks occur"""
  253. pass