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.

255 lines
9.9 KiB

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