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.

248 lines
9.6 KiB

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