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.

241 lines
9.2 KiB

8 years ago
  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 odoo 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. './ns:Ntry/ns:AcctSvcrRef'
  62. ],
  63. transaction, 'ref'
  64. )
  65. amount = self.parse_amount(ns, node)
  66. if amount != 0.0:
  67. transaction['amount'] = amount
  68. # remote party values
  69. party_type = 'Dbtr'
  70. party_type_node = node.xpath(
  71. '../../ns:CdtDbtInd', namespaces={'ns': ns})
  72. if party_type_node and party_type_node[0].text != 'CRDT':
  73. party_type = 'Cdtr'
  74. party_node = node.xpath(
  75. './ns:RltdPties/ns:%s' % party_type, namespaces={'ns': ns})
  76. if party_node:
  77. self.add_value_from_node(
  78. ns, party_node[0], './ns:Nm', transaction, 'partner_name')
  79. # Get remote_account from iban or from domestic account:
  80. account_node = node.xpath(
  81. './ns:RltdPties/ns:%sAcct/ns:Id' % party_type,
  82. namespaces={'ns': ns}
  83. )
  84. if account_node:
  85. iban_node = account_node[0].xpath(
  86. './ns:IBAN', namespaces={'ns': ns})
  87. if iban_node:
  88. transaction['account_number'] = iban_node[0].text
  89. else:
  90. self.add_value_from_node(
  91. ns, account_node[0], './ns:Othr/ns:Id', transaction,
  92. 'account_number'
  93. )
  94. def parse_entry(self, ns, node):
  95. """Parse an Ntry node and yield transactions"""
  96. transaction = {'name': '/', 'amount': 0} # fallback defaults
  97. self.add_value_from_node(
  98. ns, node, './ns:BookgDt/ns:Dt', transaction, 'date')
  99. amount = self.parse_amount(ns, node)
  100. if amount != 0.0:
  101. transaction['amount'] = amount
  102. self.add_value_from_node(
  103. ns, node, './ns:AddtlNtryInf', transaction, 'name')
  104. self.add_value_from_node(
  105. ns, node, [
  106. './ns:NtryDtls/ns:RmtInf/ns:Strd/ns:CdtrRefInf/ns:Ref',
  107. './ns:NtryDtls/ns:Btch/ns:PmtInfId',
  108. './ns:NtryDtls/ns:TxDtls/ns:Refs/ns:AcctSvcrRef'
  109. ],
  110. transaction, 'ref'
  111. )
  112. details_nodes = node.xpath(
  113. './ns:NtryDtls/ns:TxDtls', namespaces={'ns': ns})
  114. if len(details_nodes) == 0:
  115. yield transaction
  116. return
  117. transaction_base = transaction
  118. for node in details_nodes:
  119. transaction = transaction_base.copy()
  120. self.parse_transaction_details(ns, node, transaction)
  121. yield transaction
  122. def get_balance_amounts(self, ns, node):
  123. """Return opening and closing balance.
  124. Depending on kind of balance and statement, the balance might be in a
  125. different kind of node:
  126. OPBD = OpeningBalance
  127. PRCD = PreviousClosingBalance
  128. ITBD = InterimBalance (first ITBD is start-, second is end-balance)
  129. CLBD = ClosingBalance
  130. """
  131. start_balance_node = None
  132. end_balance_node = None
  133. for node_name in ['OPBD', 'PRCD', 'CLBD', 'ITBD']:
  134. code_expr = (
  135. './ns:Bal/ns:Tp/ns:CdOrPrtry/ns:Cd[text()="%s"]/../../..' %
  136. node_name
  137. )
  138. balance_node = node.xpath(code_expr, namespaces={'ns': ns})
  139. if balance_node:
  140. if node_name in ['OPBD', 'PRCD']:
  141. start_balance_node = balance_node[0]
  142. elif node_name == 'CLBD':
  143. end_balance_node = balance_node[0]
  144. else:
  145. if not start_balance_node:
  146. start_balance_node = balance_node[0]
  147. if not end_balance_node:
  148. end_balance_node = balance_node[-1]
  149. return (
  150. self.parse_amount(ns, start_balance_node),
  151. self.parse_amount(ns, end_balance_node)
  152. )
  153. def parse_statement(self, ns, node):
  154. """Parse a single Stmt node."""
  155. result = {}
  156. self.add_value_from_node(
  157. ns, node, [
  158. './ns:Acct/ns:Id/ns:IBAN',
  159. './ns:Acct/ns:Id/ns:Othr/ns:Id',
  160. ], result, 'account_number'
  161. )
  162. self.add_value_from_node(
  163. ns, node, './ns:Id', result, 'name')
  164. self.add_value_from_node(
  165. ns, node, './ns:Acct/ns:Ccy', result, 'currency')
  166. result['balance_start'], result['balance_end_real'] = (
  167. self.get_balance_amounts(ns, node))
  168. entry_nodes = node.xpath('./ns:Ntry', namespaces={'ns': ns})
  169. transactions = []
  170. for entry_node in entry_nodes:
  171. transactions.extend(self.parse_entry(ns, entry_node))
  172. result['transactions'] = transactions
  173. result['date'] = sorted(transactions,
  174. key=lambda x: x['date'],
  175. reverse=True
  176. )[0]['date']
  177. return result
  178. def check_version(self, ns, root):
  179. """Validate validity of camt file."""
  180. # Check wether it is camt at all:
  181. re_camt = re.compile(
  182. r'(^urn:iso:std:iso:20022:tech:xsd:camt.'
  183. r'|^ISO:camt.)'
  184. )
  185. if not re_camt.search(ns):
  186. raise ValueError('no camt: ' + ns)
  187. # Check wether version 052 ,053 or 054:
  188. re_camt_version = re.compile(
  189. r'(^urn:iso:std:iso:20022:tech:xsd:camt.054.'
  190. r'|^urn:iso:std:iso:20022:tech:xsd:camt.053.'
  191. r'|^urn:iso:std:iso:20022:tech:xsd:camt.052.'
  192. r'|^ISO:camt.054.'
  193. r'|^ISO:camt.053.'
  194. r'|^ISO:camt.052.)'
  195. )
  196. if not re_camt_version.search(ns):
  197. raise ValueError('no camt 052 or 053 or 054: ' + ns)
  198. # Check GrpHdr element:
  199. root_0_0 = root[0][0].tag[len(ns) + 2:] # strip namespace
  200. if root_0_0 != 'GrpHdr':
  201. raise ValueError('expected GrpHdr, got: ' + root_0_0)
  202. def parse(self, data):
  203. """Parse a camt.052 or camt.053 or camt.054 file."""
  204. try:
  205. root = etree.fromstring(
  206. data, parser=etree.XMLParser(recover=True))
  207. except etree.XMLSyntaxError:
  208. # ABNAmro is known to mix up encodings
  209. root = etree.fromstring(
  210. data.decode('iso-8859-15').encode('utf-8'))
  211. if root is None:
  212. raise ValueError(
  213. 'Not a valid xml file, or not an xml file at all.')
  214. ns = root.tag[1:root.tag.index("}")]
  215. self.check_version(ns, root)
  216. statements = []
  217. currency = None
  218. account_number = None
  219. for node in root[0][1:]:
  220. statement = self.parse_statement(ns, node)
  221. if len(statement['transactions']):
  222. if 'currency' in statement:
  223. currency = statement.pop('currency')
  224. if 'account_number' in statement:
  225. account_number = statement.pop('account_number')
  226. statements.append(statement)
  227. return currency, account_number, statements