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.

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