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.

238 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 BankStatement
  25. class CamtParser(object):
  26. """Parser for camt bank statement import files."""
  27. def parse_amount(self, ns, node):
  28. """Parse element that contains Amount and CreditDebitIndicator."""
  29. if node is None:
  30. return 0.0
  31. sign = 1
  32. amount = 0.0
  33. sign_node = node.xpath('ns:CdtDbtInd', namespaces={'ns': ns})
  34. if sign_node and sign_node[0].text == 'DBIT':
  35. sign = -1
  36. amount_node = node.xpath('ns:Amt', namespaces={'ns': ns})
  37. if amount_node:
  38. amount = sign * float(amount_node[0].text)
  39. return amount
  40. def add_value_from_node(
  41. self, ns, node, xpath_str, obj, attr_name, join_str=None):
  42. """Add value to object from first or all nodes found with xpath.
  43. If xpath_str is a list (or iterable), it will be seen as a series
  44. of search path's in order of preference. The first item that results
  45. in a found node will be used to set a value."""
  46. if not isinstance(xpath_str, (list, tuple)):
  47. xpath_str = [xpath_str]
  48. for search_str in xpath_str:
  49. found_node = node.xpath(search_str, namespaces={'ns': ns})
  50. if found_node:
  51. if join_str is None:
  52. attr_value = found_node[0].text
  53. else:
  54. attr_value = join_str.join([x.text for x in found_node])
  55. setattr(obj, attr_name, attr_value)
  56. break
  57. def parse_transaction_details(self, ns, node, transaction):
  58. """Parse transaction details (message, party, account...)."""
  59. # message
  60. self.add_value_from_node(
  61. ns, node, [
  62. './ns:RmtInf/ns:Ustrd',
  63. './ns:AddtlTxInf',
  64. './ns:AddtlNtryInf',
  65. ], transaction, 'message')
  66. # eref
  67. self.add_value_from_node(
  68. ns, node, [
  69. './ns:RmtInf/ns:Strd/ns:CdtrRefInf/ns:Ref',
  70. './ns:Refs/ns:EndToEndId',
  71. ],
  72. transaction, 'eref'
  73. )
  74. # remote party values
  75. party_type = 'Dbtr'
  76. party_type_node = node.xpath(
  77. '../../ns:CdtDbtInd', namespaces={'ns': ns})
  78. if party_type_node and party_type_node[0].text != 'CRDT':
  79. party_type = 'Cdtr'
  80. party_node = node.xpath(
  81. './ns:RltdPties/ns:%s' % party_type, namespaces={'ns': ns})
  82. if party_node:
  83. self.add_value_from_node(
  84. ns, party_node[0], './ns:Nm', transaction, 'remote_owner')
  85. self.add_value_from_node(
  86. ns, party_node[0], './ns:PstlAdr/ns:Ctry', transaction,
  87. 'remote_owner_country'
  88. )
  89. address_node = party_node[0].xpath(
  90. './ns:PstlAdr/ns:AdrLine', namespaces={'ns': ns})
  91. if address_node:
  92. transaction.remote_owner_address = [address_node[0].text]
  93. # Get remote_account from iban or from domestic account:
  94. account_node = node.xpath(
  95. './ns:RltdPties/ns:%sAcct/ns:Id' % party_type,
  96. namespaces={'ns': ns}
  97. )
  98. if account_node:
  99. iban_node = account_node[0].xpath(
  100. './ns:IBAN', namespaces={'ns': ns})
  101. if iban_node:
  102. transaction.remote_account = iban_node[0].text
  103. bic_node = node.xpath(
  104. './ns:RltdAgts/ns:%sAgt/ns:FinInstnId/ns:BIC' % party_type,
  105. namespaces={'ns': ns}
  106. )
  107. if bic_node:
  108. transaction.remote_bank_bic = bic_node[0].text
  109. else:
  110. self.add_value_from_node(
  111. ns, account_node[0], './ns:Othr/ns:Id', transaction,
  112. 'remote_account'
  113. )
  114. def parse_transaction(self, ns, node, transaction):
  115. """Parse transaction (entry) node."""
  116. self.add_value_from_node(
  117. ns, node, './ns:BkTxCd/ns:Prtry/ns:Cd', transaction,
  118. 'transfer_type'
  119. )
  120. self.add_value_from_node(
  121. ns, node, './ns:BookgDt/ns:Dt', transaction, 'execution_date')
  122. self.add_value_from_node(
  123. ns, node, './ns:ValDt/ns:Dt', transaction, 'value_date')
  124. transaction.transferred_amount = self.parse_amount(ns, node)
  125. details_node = node.xpath(
  126. './ns:NtryDtls/ns:TxDtls', namespaces={'ns': ns})
  127. if details_node:
  128. self.parse_transaction_details(ns, details_node[0], transaction)
  129. transaction.data = etree.tostring(node)
  130. return transaction
  131. def get_balance_amounts(self, ns, node):
  132. """Return opening and closing balance.
  133. Depending on kind of balance and statement, the balance might be in a
  134. different kind of node:
  135. OPBD = OpeningBalance
  136. PRCD = PreviousClosingBalance
  137. ITBD = InterimBalance (first ITBD is start-, second is end-balance)
  138. CLBD = ClosingBalance
  139. """
  140. start_balance_node = None
  141. end_balance_node = None
  142. for node_name in ['OPBD', 'PRCD', 'CLBD', 'ITBD']:
  143. code_expr = (
  144. './ns:Bal/ns:Tp/ns:CdOrPrtry/ns:Cd[text()="%s"]/../../..' %
  145. node_name
  146. )
  147. balance_node = node.xpath(code_expr, namespaces={'ns': ns})
  148. if balance_node:
  149. if node_name in ['OPBD', 'PRCD']:
  150. start_balance_node = balance_node[0]
  151. elif node_name == 'CLBD':
  152. end_balance_node = balance_node[0]
  153. else:
  154. if not start_balance_node:
  155. start_balance_node = balance_node[0]
  156. if not end_balance_node:
  157. end_balance_node = balance_node[-1]
  158. return (
  159. self.parse_amount(ns, start_balance_node),
  160. self.parse_amount(ns, end_balance_node)
  161. )
  162. def parse_statement(self, ns, node):
  163. """Parse a single Stmt node."""
  164. statement = BankStatement()
  165. self.add_value_from_node(
  166. ns, node, [
  167. './ns:Acct/ns:Id/ns:IBAN',
  168. './ns:Acct/ns:Id/ns:Othr/ns:Id',
  169. ], statement, 'local_account'
  170. )
  171. self.add_value_from_node(
  172. ns, node, './ns:Id', statement, 'statement_id')
  173. self.add_value_from_node(
  174. ns, node, './ns:Acct/ns:Ccy', statement, 'local_currency')
  175. (statement.start_balance, statement.end_balance) = (
  176. self.get_balance_amounts(ns, node))
  177. transaction_nodes = node.xpath('./ns:Ntry', namespaces={'ns': ns})
  178. for entry_node in transaction_nodes:
  179. transaction = statement.create_transaction()
  180. self.parse_transaction(ns, entry_node, transaction)
  181. if statement['transactions']:
  182. statement.date = datetime.strptime(
  183. statement['transactions'][0].execution_date, "%Y-%m-%d")
  184. return statement
  185. def check_version(self, ns, root):
  186. """Validate validity of camt file."""
  187. # Check wether it is camt at all:
  188. re_camt = re.compile(
  189. r'(^urn:iso:std:iso:20022:tech:xsd:camt.'
  190. r'|^ISO:camt.)'
  191. )
  192. if not re_camt.search(ns):
  193. raise ValueError('no camt: ' + ns)
  194. # Check wether version 052 or 053:
  195. re_camt_version = re.compile(
  196. r'(^urn:iso:std:iso:20022:tech:xsd:camt.053.'
  197. r'|^urn:iso:std:iso:20022:tech:xsd:camt.052.'
  198. r'|^ISO:camt.053.'
  199. r'|^ISO:camt.052.)'
  200. )
  201. if not re_camt_version.search(ns):
  202. raise ValueError('no camt 052 or 053: ' + ns)
  203. # Check GrpHdr element:
  204. root_0_0 = root[0][0].tag[len(ns) + 2:] # strip namespace
  205. if root_0_0 != 'GrpHdr':
  206. raise ValueError('expected GrpHdr, got: ' + root_0_0)
  207. def parse(self, data):
  208. """Parse a camt.052 or camt.053 file."""
  209. try:
  210. root = etree.fromstring(
  211. data, parser=etree.XMLParser(recover=True))
  212. except etree.XMLSyntaxError:
  213. # ABNAmro is known to mix up encodings
  214. root = etree.fromstring(
  215. data.decode('iso-8859-15').encode('utf-8'))
  216. if root is None:
  217. raise ValueError(
  218. 'Not a valid xml file, or not an xml file at all.')
  219. ns = root.tag[1:root.tag.index("}")]
  220. self.check_version(ns, root)
  221. statements = []
  222. for node in root[0][1:]:
  223. statement = self.parse_statement(ns, node)
  224. if len(statement['transactions']):
  225. statements.append(statement)
  226. return statements