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.

242 lines
9.6 KiB

  1. # -*- coding: utf-8 -*-
  2. """Class to parse camt files."""
  3. ##############################################################################
  4. #
  5. # Copyright (C) 2013-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 published
  9. # by the Free Software Foundation, either version 3 of the License, or
  10. # (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. from datetime import datetime
  23. from lxml import etree
  24. from openerp.addons.bank_statement_parse.parserlib import (
  25. BankStatement,
  26. BankTransaction
  27. )
  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 transaction details (message, party, account...)."""
  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')
  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. # remote party values
  78. party_type = 'Dbtr'
  79. party_type_node = node.xpath(
  80. '../../ns:CdtDbtInd', namespaces={'ns': ns})
  81. if party_type_node and party_type_node[0].text != 'CRDT':
  82. party_type = 'Cdtr'
  83. party_node = node.xpath(
  84. './ns:RltdPties/ns:%s' % party_type, namespaces={'ns': ns})
  85. if party_node:
  86. self.add_value_from_node(
  87. ns, party_node[0], './ns:Nm', transaction, 'remote_owner')
  88. self.add_value_from_node(
  89. ns, party_node[0], './ns:PstlAdr/ns:Ctry', transaction,
  90. 'remote_owner_country'
  91. )
  92. address_node = party_node[0].xpath(
  93. './ns:PstlAdr/ns:AdrLine', namespaces={'ns': ns})
  94. if address_node:
  95. transaction.remote_owner_address = [address_node[0].text]
  96. # Get remote_account from iban or from domestic account:
  97. account_node = node.xpath(
  98. './ns:RltdPties/ns:%sAcct/ns:Id' % party_type,
  99. namespaces={'ns': ns}
  100. )
  101. if account_node:
  102. iban_node = account_node[0].xpath(
  103. './ns:IBAN', namespaces={'ns': ns})
  104. if iban_node:
  105. transaction.remote_account = iban_node[0].text
  106. bic_node = node.xpath(
  107. './ns:RltdAgts/ns:%sAgt/ns:FinInstnId/ns:BIC' % party_type,
  108. namespaces={'ns': ns}
  109. )
  110. if bic_node:
  111. transaction.remote_bank_bic = bic_node[0].text
  112. else:
  113. self.add_value_from_node(
  114. ns, account_node[0], './ns:Othr/ns:Id', transaction,
  115. 'remote_account'
  116. )
  117. def parse_transaction(self, ns, node):
  118. """Parse transaction (entry) node."""
  119. transaction = BankTransaction()
  120. self.add_value_from_node(
  121. ns, node, './ns:BkTxCd/ns:Prtry/ns:Cd', transaction,
  122. 'transfer_type'
  123. )
  124. self.add_value_from_node(
  125. ns, node, './ns:BookgDt/ns:Dt', transaction, 'execution_date')
  126. self.add_value_from_node(
  127. ns, node, './ns:ValDt/ns:Dt', transaction, 'value_date')
  128. transaction.transferred_amount = self.parse_amount(ns, node)
  129. details_node = node.xpath(
  130. './ns:NtryDtls/ns:TxDtls', namespaces={'ns': ns})
  131. if details_node:
  132. self.parse_transaction_details(ns, details_node[0], transaction)
  133. transaction.data = etree.tostring(node)
  134. return transaction
  135. def get_balance_amounts(self, ns, node):
  136. """Return opening and closing balance.
  137. Depending on kind of balance and statement, the balance might be in a
  138. different kind of node:
  139. OPBD = OpeningBalance
  140. PRCD = PreviousClosingBalance
  141. ITBD = InterimBalance (first ITBD is start-, second is end-balance)
  142. CLBD = ClosingBalance
  143. """
  144. start_balance_node = None
  145. end_balance_node = None
  146. for node_name in ['OPBD', 'PRCD', 'CLBD', 'ITBD']:
  147. code_expr = (
  148. './ns:Bal/ns:Tp/ns:CdOrPrtry/ns:Cd[text()="%s"]/../../..' %
  149. node_name
  150. )
  151. balance_node = node.xpath(code_expr, namespaces={'ns': ns})
  152. if balance_node:
  153. if node_name in ['OPBD', 'PRCD']:
  154. start_balance_node = balance_node[0]
  155. elif node_name == 'CLBD':
  156. end_balance_node = balance_node[0]
  157. else:
  158. if not start_balance_node:
  159. start_balance_node = balance_node[0]
  160. if not end_balance_node:
  161. end_balance_node = balance_node[-1]
  162. return (
  163. self.parse_amount(ns, start_balance_node),
  164. self.parse_amount(ns, end_balance_node)
  165. )
  166. def parse_statement(self, ns, node):
  167. """Parse a single Stmt node."""
  168. statement = BankStatement()
  169. self.add_value_from_node(
  170. ns, node, [
  171. './ns:Acct/ns:Id/ns:IBAN',
  172. './ns:Acct/ns:Id/ns:Othr/ns:Id',
  173. ], statement, 'local_account'
  174. )
  175. self.add_value_from_node(
  176. ns, node, './ns:Id', statement, 'statement_id')
  177. self.add_value_from_node(
  178. ns, node, './ns:Acct/ns:Ccy', statement, 'local_currency')
  179. (statement.start_balance, statement.end_balance) = (
  180. self.get_balance_amounts(ns, node))
  181. transaction_nodes = node.xpath('./ns:Ntry', namespaces={'ns': ns})
  182. for entry_node in transaction_nodes:
  183. transaction = self.parse_transaction(ns, entry_node)
  184. statement.transactions.append(transaction)
  185. if statement.transactions:
  186. statement.date = datetime.strptime(
  187. statement.transactions[0].execution_date, "%Y-%m-%d")
  188. return statement
  189. def check_version(self, ns, root):
  190. """Validate validity of camt file."""
  191. # Check wether it is camt at all:
  192. re_camt = re.compile(
  193. r'(^urn:iso:std:iso:20022:tech:xsd:camt.'
  194. r'|^ISO:camt.)'
  195. )
  196. if not re_camt.search(ns):
  197. raise ValueError('no camt: ' + ns)
  198. # Check wether version 052 or 053:
  199. re_camt_version = re.compile(
  200. r'(^urn:iso:std:iso:20022:tech:xsd:camt.053.'
  201. r'|^urn:iso:std:iso:20022:tech:xsd:camt.052.'
  202. r'|^ISO:camt.053.'
  203. r'|^ISO:camt.052.)'
  204. )
  205. if not re_camt_version.search(ns):
  206. raise ValueError('no camt 052 or 053: ' + ns)
  207. # Check GrpHdr element:
  208. root_0_0 = root[0][0].tag[len(ns) + 2:] # strip namespace
  209. if root_0_0 != 'GrpHdr':
  210. raise ValueError('expected GrpHdr, got: ' + root_0_0)
  211. def parse(self, data):
  212. """Parse a camt.052 or camt.053 file."""
  213. try:
  214. root = etree.fromstring(
  215. data, parser=etree.XMLParser(recover=True))
  216. except etree.XMLSyntaxError:
  217. # ABNAmro is known to mix up encodings
  218. root = etree.fromstring(
  219. data.decode('iso-8859-15').encode('utf-8'))
  220. if root is None:
  221. raise ValueError(
  222. 'Not a valid xml file, or not an xml file at all.')
  223. ns = root.tag[1:root.tag.index("}")]
  224. self.check_version(ns, root)
  225. statements = []
  226. for node in root[0][1:]:
  227. statement = self.parse_statement(ns, node)
  228. if len(statement.transactions):
  229. statements.append(statement)
  230. return statements