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.

280 lines
10 KiB

9 years ago
  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.account_bank_statement_import.parserlib import (
  25. BankStatement)
  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. if not transaction.message:
  76. transaction.message = ''
  77. # REMI: Remitter information (text entered by other party on trans.):
  78. if 'REMI' in subfields:
  79. transaction.message += (
  80. subfields['REMI'][2]
  81. # this might look like
  82. # /REMI/USTD//<remittance info>/
  83. # or
  84. # /REMI/STRD/CUR/<betalingskenmerk>/
  85. if len(subfields['REMI']) >= 3 and subfields['REMI'][0] in [
  86. 'STRD', 'USTD'
  87. ]
  88. else
  89. '/'.join(x for x in subfields['REMI'] if x)
  90. )
  91. # EREF: End-to-end reference
  92. if 'EREF' in subfields:
  93. transaction.message += '/'.join(filter(bool, subfields['EREF']))
  94. # Get transaction reference subfield (might vary):
  95. if transaction.eref in subfields:
  96. transaction.eref = ''.join(subfields[transaction.eref])
  97. class MT940(object):
  98. """Inherit this class in your account_banking.parsers.models.parser,
  99. define functions to handle the tags you need to handle and adjust static
  100. variables as needed.
  101. At least, you should override handle_tag_61 and handle_tag_86.
  102. Don't forget to call super.
  103. handle_tag_* functions receive the remainder of the the line (that is,
  104. without ':XX:') and are supposed to write into self.current_transaction
  105. """
  106. def __init__(self):
  107. """Initialize parser - override at least header_regex.
  108. This in fact uses the ING syntax, override in others."""
  109. self.mt940_type = 'General'
  110. self.header_lines = 3 # Number of lines to skip
  111. self.header_regex = '^0000 01INGBNL2AXXXX|^{1' # Start of header
  112. self.footer_regex = '^-}$|^-XXX$' # Stop processing on seeing this
  113. self.tag_regex = '^:[0-9]{2}[A-Z]*:' # Start of new tag
  114. self.current_statement = None
  115. self.current_transaction = None
  116. self.statements = []
  117. def is_mt940(self, line):
  118. """determine if a line is the header of a statement"""
  119. if not bool(re.match(self.header_regex, line)):
  120. raise ValueError(
  121. 'File starting with %s does not seem to be a'
  122. ' valid %s MT940 format bank statement.' %
  123. (line[:12], self.mt940_type)
  124. )
  125. def parse(self, data):
  126. """Parse mt940 bank statement file contents."""
  127. self.is_mt940(data)
  128. iterator = data.replace('\r\n', '\n').split('\n').__iter__()
  129. line = None
  130. record_line = ''
  131. try:
  132. while True:
  133. if not self.current_statement:
  134. self.handle_header(line, iterator)
  135. line = iterator.next()
  136. if not self.is_tag(line) and not self.is_footer(line):
  137. record_line = self.add_record_line(line, record_line)
  138. continue
  139. if record_line:
  140. self.handle_record(record_line)
  141. if self.is_footer(line):
  142. self.handle_footer(line, iterator)
  143. record_line = ''
  144. continue
  145. record_line = line
  146. except StopIteration:
  147. pass
  148. if self.current_statement:
  149. if record_line:
  150. self.handle_record(record_line)
  151. record_line = ''
  152. self.statements.append(self.current_statement)
  153. self.current_statement = None
  154. return self.statements
  155. def add_record_line(self, line, record_line):
  156. record_line += line
  157. return record_line
  158. def is_footer(self, line):
  159. """determine if a line is the footer of a statement"""
  160. return line and bool(re.match(self.footer_regex, line))
  161. def is_tag(self, line):
  162. """determine if a line has a tag"""
  163. return line and bool(re.match(self.tag_regex, line))
  164. def handle_header(self, dummy_line, iterator):
  165. """skip header lines, create current statement"""
  166. for dummy_i in range(self.header_lines):
  167. iterator.next()
  168. self.current_statement = BankStatement()
  169. def handle_footer(self, dummy_line, dummy_iterator):
  170. """add current statement to list, reset state"""
  171. self.statements.append(self.current_statement)
  172. self.current_statement = None
  173. def handle_record(self, line):
  174. """find a function to handle the record represented by line"""
  175. tag_match = re.match(self.tag_regex, line)
  176. tag = tag_match.group(0).strip(':')
  177. if not hasattr(self, 'handle_tag_%s' % tag):
  178. logging.error('Unknown tag %s', tag)
  179. logging.error(line)
  180. return
  181. handler = getattr(self, 'handle_tag_%s' % tag)
  182. handler(line[tag_match.end():])
  183. def handle_tag_20(self, data):
  184. """Contains unique ? message ID"""
  185. pass
  186. def handle_tag_25(self, data):
  187. """Handle tag 25: local bank account information."""
  188. data = data.replace('EUR', '').replace('.', '').strip()
  189. self.current_statement.local_account = data
  190. def handle_tag_28C(self, data):
  191. """Sequence number within batch - normally only zeroes."""
  192. pass
  193. def handle_tag_60F(self, data):
  194. """get start balance and currency"""
  195. # For the moment only first 60F record
  196. # The alternative would be to split the file and start a new
  197. # statement for each 20: tag encountered.
  198. stmt = self.current_statement
  199. if not stmt.local_currency:
  200. stmt.local_currency = data[7:10]
  201. stmt.start_balance = str2amount(data[0], data[10:])
  202. def handle_tag_61(self, data):
  203. """get transaction values"""
  204. transaction = self.current_statement.create_transaction()
  205. self.current_transaction = transaction
  206. transaction.execution_date = datetime.strptime(data[:6], '%y%m%d')
  207. transaction.value_date = datetime.strptime(data[:6], '%y%m%d')
  208. # ...and the rest already is highly bank dependent
  209. def handle_tag_62F(self, data):
  210. """Get ending balance, statement date and id.
  211. We use the date on the last 62F tag as statement date, as the date
  212. on the 60F record (previous end balance) might contain a date in
  213. a previous period.
  214. We generate the statement.id from the local_account and the end-date,
  215. this should normally be unique, provided there is a maximum of
  216. one statement per day.
  217. Depending on the bank, there might be multiple 62F tags in the import
  218. file. The last one counts.
  219. """
  220. stmt = self.current_statement
  221. stmt.end_balance = str2amount(data[0], data[10:])
  222. stmt.date = datetime.strptime(data[1:7], '%y%m%d')
  223. # Only replace logically empty (only whitespace or zeroes) id's:
  224. # But do replace statement_id's added before (therefore starting
  225. # with local_account), because we need the date on the last 62F
  226. # record.
  227. test_empty_id = re.sub(r'[\s0]', '', stmt.statement_id)
  228. if ((not test_empty_id) or
  229. (stmt.statement_id.startswith(stmt.local_account))):
  230. stmt.statement_id = '%s-%s' % (
  231. stmt.local_account,
  232. stmt.date.strftime('%Y-%m-%d'),
  233. )
  234. def handle_tag_64(self, data):
  235. """get current balance in currency"""
  236. pass
  237. def handle_tag_65(self, data):
  238. """get future balance in currency"""
  239. pass
  240. def handle_tag_86(self, data):
  241. """details for previous transaction, here most differences between
  242. banks occur"""
  243. pass