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