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.

276 lines
10 KiB

10 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 += 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 is_footer(self, line):
  156. """determine if a line is the footer of a statement"""
  157. return line and bool(re.match(self.footer_regex, line))
  158. def is_tag(self, line):
  159. """determine if a line has a tag"""
  160. return line and bool(re.match(self.tag_regex, line))
  161. def handle_header(self, dummy_line, iterator):
  162. """skip header lines, create current statement"""
  163. for dummy_i in range(self.header_lines):
  164. iterator.next()
  165. self.current_statement = BankStatement()
  166. def handle_footer(self, dummy_line, dummy_iterator):
  167. """add current statement to list, reset state"""
  168. self.statements.append(self.current_statement)
  169. self.current_statement = None
  170. def handle_record(self, line):
  171. """find a function to handle the record represented by line"""
  172. tag_match = re.match(self.tag_regex, line)
  173. tag = tag_match.group(0).strip(':')
  174. if not hasattr(self, 'handle_tag_%s' % tag):
  175. logging.error('Unknown tag %s', tag)
  176. logging.error(line)
  177. return
  178. handler = getattr(self, 'handle_tag_%s' % tag)
  179. handler(line[tag_match.end():])
  180. def handle_tag_20(self, data):
  181. """Contains unique ? message ID"""
  182. pass
  183. def handle_tag_25(self, data):
  184. """Handle tag 25: local bank account information."""
  185. data = data.replace('EUR', '').replace('.', '').strip()
  186. self.current_statement.local_account = data
  187. def handle_tag_28C(self, data):
  188. """Sequence number within batch - normally only zeroes."""
  189. pass
  190. def handle_tag_60F(self, data):
  191. """get start balance and currency"""
  192. # For the moment only first 60F record
  193. # The alternative would be to split the file and start a new
  194. # statement for each 20: tag encountered.
  195. stmt = self.current_statement
  196. if not stmt.local_currency:
  197. stmt.local_currency = data[7:10]
  198. stmt.start_balance = str2amount(data[0], data[10:])
  199. def handle_tag_61(self, data):
  200. """get transaction values"""
  201. transaction = self.current_statement.create_transaction()
  202. self.current_transaction = transaction
  203. transaction.execution_date = datetime.strptime(data[:6], '%y%m%d')
  204. transaction.value_date = datetime.strptime(data[:6], '%y%m%d')
  205. # ...and the rest already is highly bank dependent
  206. def handle_tag_62F(self, data):
  207. """Get ending balance, statement date and id.
  208. We use the date on the last 62F tag as statement date, as the date
  209. on the 60F record (previous end balance) might contain a date in
  210. a previous period.
  211. We generate the statement.id from the local_account and the end-date,
  212. this should normally be unique, provided there is a maximum of
  213. one statement per day.
  214. Depending on the bank, there might be multiple 62F tags in the import
  215. file. The last one counts.
  216. """
  217. stmt = self.current_statement
  218. stmt.end_balance = str2amount(data[0], data[10:])
  219. stmt.date = datetime.strptime(data[1:7], '%y%m%d')
  220. # Only replace logically empty (only whitespace or zeroes) id's:
  221. # But do replace statement_id's added before (therefore starting
  222. # with local_account), because we need the date on the last 62F
  223. # record.
  224. test_empty_id = re.sub(r'[\s0]', '', stmt.statement_id)
  225. if ((not test_empty_id) or
  226. (stmt.statement_id.startswith(stmt.local_account))):
  227. stmt.statement_id = '%s-%s' % (
  228. stmt.local_account,
  229. stmt.date.strftime('%Y-%m-%d'),
  230. )
  231. def handle_tag_64(self, data):
  232. """get current balance in currency"""
  233. pass
  234. def handle_tag_65(self, data):
  235. """get future balance in currency"""
  236. pass
  237. def handle_tag_86(self, data):
  238. """details for previous transaction, here most differences between
  239. banks occur"""
  240. pass