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
11 KiB

9 years ago
  1. # -*- coding: utf-8 -*-
  2. """Class to parse camt files."""
  3. ##############################################################################
  4. #
  5. # Copyright (C) 2013-2015 Therp BV <http://therp.nl>
  6. # Copyright 2017 Open Net Sàrl
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU Affero General Public License as published
  10. # by the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Affero General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Affero General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. ##############################################################################
  22. import re
  23. from datetime import datetime
  24. from lxml import etree
  25. from openerp.addons.account_bank_statement_import.parserlib import (
  26. BankStatement)
  27. from copy import copy
  28. class CamtParser(object):
  29. """Parser for camt bank statement import files."""
  30. def parse_amount(self, ns, node):
  31. """Parse element that contains Amount and CreditDebitIndicator."""
  32. if node is None:
  33. return 0.0
  34. sign = 1
  35. amount = 0.0
  36. sign_node = node.xpath('ns:CdtDbtInd', namespaces={'ns': ns})
  37. if sign_node and sign_node[0].text == 'DBIT':
  38. sign = -1
  39. amount_node = node.xpath('ns:Amt', namespaces={'ns': ns})
  40. if amount_node:
  41. amount = sign * float(amount_node[0].text)
  42. return amount
  43. def add_value_from_node(
  44. self, ns, node, xpath_str, obj, attr_name, join_str=None):
  45. """Add value to object from first or all nodes found with xpath.
  46. If xpath_str is a list (or iterable), it will be seen as a series
  47. of search path's in order of preference. The first item that results
  48. in a found node will be used to set a value."""
  49. if not isinstance(xpath_str, (list, tuple)):
  50. xpath_str = [xpath_str]
  51. for search_str in xpath_str:
  52. found_node = node.xpath(search_str, namespaces={'ns': ns})
  53. if found_node:
  54. if join_str is None:
  55. attr_value = found_node[0].text
  56. else:
  57. attr_value = join_str.join([x.text for x in found_node])
  58. setattr(obj, attr_name, attr_value)
  59. break
  60. def parse_transaction_details(self, ns, node, transaction):
  61. """Parse TxDtls node."""
  62. # message
  63. self.add_value_from_node(
  64. ns, node, [
  65. './ns:RmtInf/ns:Ustrd',
  66. './ns:AddtlTxInf',
  67. './ns:AddtlNtryInf',
  68. ], transaction, 'message', join_str='\n')
  69. # eref
  70. self.add_value_from_node(
  71. ns, node, [
  72. './ns:RmtInf/ns:Strd/ns:CdtrRefInf/ns:Ref',
  73. './ns:Refs/ns:EndToEndId',
  74. ],
  75. transaction, 'eref'
  76. )
  77. amount = self.parse_amount(ns, node)
  78. if amount != 0.0:
  79. transaction['amount'] = amount
  80. # remote party values
  81. party_type = 'Dbtr'
  82. party_type_node = node.xpath(
  83. '../../ns:CdtDbtInd', namespaces={'ns': ns})
  84. if party_type_node and party_type_node[0].text != 'CRDT':
  85. party_type = 'Cdtr'
  86. party_node = node.xpath(
  87. './ns:RltdPties/ns:%s' % party_type, namespaces={'ns': ns})
  88. if party_node:
  89. self.add_value_from_node(
  90. ns, party_node[0], './ns:Nm', transaction, 'remote_owner')
  91. self.add_value_from_node(
  92. ns, party_node[0], './ns:PstlAdr/ns:Ctry', transaction,
  93. 'remote_owner_country'
  94. )
  95. address_node = party_node[0].xpath(
  96. './ns:PstlAdr/ns:AdrLine', namespaces={'ns': ns})
  97. if address_node:
  98. transaction.remote_owner_address = [address_node[0].text]
  99. # Get remote_account from iban or from domestic account:
  100. account_node = node.xpath(
  101. './ns:RltdPties/ns:%sAcct/ns:Id' % party_type,
  102. namespaces={'ns': ns}
  103. )
  104. if account_node:
  105. iban_node = account_node[0].xpath(
  106. './ns:IBAN', namespaces={'ns': ns})
  107. if iban_node:
  108. transaction.remote_account = iban_node[0].text
  109. bic_node = node.xpath(
  110. './ns:RltdAgts/ns:%sAgt/ns:FinInstnId/ns:BIC' % party_type,
  111. namespaces={'ns': ns}
  112. )
  113. if bic_node:
  114. transaction.remote_bank_bic = bic_node[0].text
  115. else:
  116. self.add_value_from_node(
  117. ns, account_node[0], './ns:Othr/ns:Id', transaction,
  118. 'remote_account'
  119. )
  120. def parse_entry(self, ns, node, transaction):
  121. """Parse an Ntry node and yield transactions."""
  122. self.add_value_from_node(
  123. ns, node, './ns:BkTxCd/ns:Prtry/ns:Cd', transaction,
  124. 'transfer_type'
  125. )
  126. self.add_value_from_node(
  127. ns, node, './ns:BookgDt/ns:Dt', transaction, 'date')
  128. self.add_value_from_node(
  129. ns, node, './ns:BookgDt/ns:Dt', transaction, 'execution_date')
  130. self.add_value_from_node(
  131. ns, node, './ns:ValDt/ns:Dt', transaction, 'value_date')
  132. amount = self.parse_amount(ns, node)
  133. if amount != 0.0:
  134. transaction['amount'] = amount
  135. self.add_value_from_node(
  136. ns, node, './ns:AddtlNtryInf', transaction, 'name')
  137. self.add_value_from_node(
  138. ns, node, [
  139. './ns:NtryDtls/ns:RmtInf/ns:Strd/ns:CdtrRefInf/ns:Ref',
  140. './ns:NtryDtls/ns:Btch/ns:PmtInfId',
  141. ],
  142. transaction, 'ref'
  143. )
  144. details_nodes = node.xpath(
  145. './ns:NtryDtls/ns:TxDtls', namespaces={'ns': ns})
  146. if len(details_nodes) == 0:
  147. yield transaction
  148. return
  149. transaction_base = transaction
  150. for i, dnode in enumerate(details_nodes):
  151. transaction = copy(transaction_base)
  152. self.parse_transaction_details(ns, dnode, transaction)
  153. # transactions['data'] should be a synthetic xml snippet which
  154. # contains only the TxDtls that's relevant.
  155. data = copy(node)
  156. for j, dnode in enumerate(data.xpath(
  157. './ns:NtryDtls/ns:TxDtls', namespaces={'ns': ns})):
  158. if j != i:
  159. dnode.getparent().remove(dnode)
  160. transaction['data'] = etree.tostring(data)
  161. yield transaction
  162. def get_balance_amounts(self, ns, node):
  163. """Return opening and closing balance.
  164. Depending on kind of balance and statement, the balance might be in a
  165. different kind of node:
  166. OPBD = OpeningBalance
  167. PRCD = PreviousClosingBalance
  168. ITBD = InterimBalance (first ITBD is start-, second is end-balance)
  169. CLBD = ClosingBalance
  170. """
  171. start_balance_node = None
  172. end_balance_node = None
  173. for node_name in ['OPBD', 'PRCD', 'CLBD', 'ITBD']:
  174. code_expr = (
  175. './ns:Bal/ns:Tp/ns:CdOrPrtry/ns:Cd[text()="%s"]/../../..' %
  176. node_name
  177. )
  178. balance_node = node.xpath(code_expr, namespaces={'ns': ns})
  179. if balance_node:
  180. if node_name in ['OPBD', 'PRCD']:
  181. start_balance_node = balance_node[0]
  182. elif node_name == 'CLBD':
  183. end_balance_node = balance_node[0]
  184. else:
  185. if not start_balance_node:
  186. start_balance_node = balance_node[0]
  187. if not end_balance_node:
  188. end_balance_node = balance_node[-1]
  189. return (
  190. self.parse_amount(ns, start_balance_node),
  191. self.parse_amount(ns, end_balance_node)
  192. )
  193. def parse_statement(self, ns, node):
  194. """Parse a single Stmt node."""
  195. statement = BankStatement()
  196. self.add_value_from_node(
  197. ns, node, [
  198. './ns:Acct/ns:Id/ns:IBAN',
  199. './ns:Acct/ns:Id/ns:Othr/ns:Id',
  200. ], statement, 'local_account'
  201. )
  202. self.add_value_from_node(
  203. ns, node, './ns:Id', statement, 'statement_id')
  204. self.add_value_from_node(
  205. ns, node, './ns:Acct/ns:Ccy', statement, 'local_currency')
  206. (statement.start_balance, statement.end_balance) = (
  207. self.get_balance_amounts(ns, node))
  208. entry_nodes = node.xpath('./ns:Ntry', namespaces={'ns': ns})
  209. transactions = []
  210. for entry_node in entry_nodes:
  211. transaction = statement.create_transaction()
  212. transactions.extend(self.parse_entry(ns, entry_node, transaction))
  213. statement['transactions'] = transactions
  214. if statement['transactions']:
  215. execution_date = statement['transactions'][0].execution_date
  216. statement.date = datetime.strptime(execution_date, "%Y-%m-%d")
  217. # Prepend date of first transaction to improve id uniquenes
  218. if execution_date not in statement.statement_id:
  219. statement.statement_id = "%s-%s" % (
  220. execution_date, statement.statement_id)
  221. return statement
  222. def check_version(self, ns, root):
  223. """Validate validity of camt file."""
  224. # Check wether it is camt at all:
  225. re_camt = re.compile(
  226. r'(^urn:iso:std:iso:20022:tech:xsd:camt.'
  227. r'|^ISO:camt.)'
  228. )
  229. if not re_camt.search(ns):
  230. raise ValueError('no camt: ' + ns)
  231. # Check wether version 052 or 053:
  232. re_camt_version = re.compile(
  233. r'(^urn:iso:std:iso:20022:tech:xsd:camt.053.'
  234. r'|^urn:iso:std:iso:20022:tech:xsd:camt.052.'
  235. r'|^ISO:camt.053.'
  236. r'|^ISO:camt.052.)'
  237. )
  238. if not re_camt_version.search(ns):
  239. raise ValueError('no camt 052 or 053: ' + ns)
  240. # Check GrpHdr element:
  241. root_0_0 = root[0][0].tag[len(ns) + 2:] # strip namespace
  242. if root_0_0 != 'GrpHdr':
  243. raise ValueError('expected GrpHdr, got: ' + root_0_0)
  244. def parse(self, data):
  245. """Parse a camt.052 or camt.053 file."""
  246. try:
  247. root = etree.fromstring(
  248. data, parser=etree.XMLParser(recover=True))
  249. except etree.XMLSyntaxError:
  250. # ABNAmro is known to mix up encodings
  251. root = etree.fromstring(
  252. data.decode('iso-8859-15').encode('utf-8'))
  253. if root is None:
  254. raise ValueError(
  255. 'Not a valid xml file, or not an xml file at all.')
  256. ns = root.tag[1:root.tag.index("}")]
  257. self.check_version(ns, root)
  258. statements = []
  259. for node in root[0][1:]:
  260. statement = self.parse_statement(ns, node)
  261. if len(statement['transactions']):
  262. statements.append(statement)
  263. return statements