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

7 years ago
  1. """Class to parse camt files."""
  2. # © 2013-2016 Therp BV <http://therp.nl>
  3. # Copyright 2017 Open Net Sàrl
  4. # License AGPL-3.0 or later (http://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. """Parser for camt bank statement import files."""
  10. _name = '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 sign_node and sign_node[0].text == 'DBIT':
  19. sign = -1
  20. amount_node = node.xpath('ns:Amt', namespaces={'ns': ns})
  21. if amount_node:
  22. amount = sign * float(amount_node[0].text)
  23. return amount
  24. def add_value_from_node(
  25. self, ns, node, xpath_str, obj, attr_name, join_str=None):
  26. """Add value to object from first or all nodes found with xpath.
  27. If xpath_str is a list (or iterable), it will be seen as a series
  28. of search path's in order of preference. The first item that results
  29. in a found node will be used to set a value."""
  30. if not isinstance(xpath_str, (list, tuple)):
  31. xpath_str = [xpath_str]
  32. for search_str in xpath_str:
  33. found_node = node.xpath(search_str, namespaces={'ns': ns})
  34. if found_node:
  35. if join_str is None:
  36. attr_value = found_node[0].text
  37. else:
  38. attr_value = join_str.join([x.text for x in found_node])
  39. obj[attr_name] = attr_value
  40. break
  41. def parse_transaction_details(self, ns, node, transaction):
  42. """Parse TxDtls node."""
  43. # message
  44. self.add_value_from_node(
  45. ns, node, [
  46. './ns:RmtInf/ns:Ustrd',
  47. './ns:AddtlNtryInf',
  48. './ns:Refs/ns:InstrId',
  49. ], transaction, 'note', join_str='\n')
  50. # name
  51. self.add_value_from_node(
  52. ns, node, [
  53. './ns:AddtlTxInf',
  54. ], transaction, 'name', join_str='\n')
  55. # eref
  56. self.add_value_from_node(
  57. ns, node, [
  58. './ns:RmtInf/ns:Strd/ns:CdtrRefInf/ns:Ref',
  59. './ns:Refs/ns:EndToEndId',
  60. './ns:Ntry/ns:AcctSvcrRef'
  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. # Get remote_account from iban or from domestic account:
  79. account_node = node.xpath(
  80. './ns:RltdPties/ns:%sAcct/ns:Id' % party_type,
  81. namespaces={'ns': ns}
  82. )
  83. if account_node:
  84. iban_node = account_node[0].xpath(
  85. './ns:IBAN', namespaces={'ns': ns})
  86. if iban_node:
  87. transaction['account_number'] = iban_node[0].text
  88. else:
  89. self.add_value_from_node(
  90. ns, account_node[0], './ns:Othr/ns:Id', transaction,
  91. 'account_number'
  92. )
  93. def parse_entry(self, ns, node):
  94. """Parse an Ntry node and yield transactions"""
  95. transaction = {'name': '/', 'amount': 0} # fallback defaults
  96. self.add_value_from_node(
  97. ns, node, './ns:BookgDt/ns:Dt', transaction, 'date')
  98. amount = self.parse_amount(ns, node)
  99. if amount != 0.0:
  100. transaction['amount'] = amount
  101. self.add_value_from_node(
  102. ns, node, './ns:AddtlNtryInf', transaction, 'name')
  103. self.add_value_from_node(
  104. ns, node, [
  105. './ns:NtryDtls/ns:RmtInf/ns:Strd/ns:CdtrRefInf/ns:Ref',
  106. './ns:NtryDtls/ns:Btch/ns:PmtInfId',
  107. './ns:NtryDtls/ns:TxDtls/ns:Refs/ns:AcctSvcrRef'
  108. ],
  109. transaction, 'ref'
  110. )
  111. details_nodes = node.xpath(
  112. './ns:NtryDtls/ns:TxDtls', namespaces={'ns': ns})
  113. if len(details_nodes) == 0:
  114. yield transaction
  115. return
  116. transaction_base = transaction
  117. for node in details_nodes:
  118. transaction = transaction_base.copy()
  119. self.parse_transaction_details(ns, node, transaction)
  120. yield transaction
  121. def get_balance_amounts(self, ns, node):
  122. """Return opening and closing balance.
  123. Depending on kind of balance and statement, the balance might be in a
  124. different kind of node:
  125. OPBD = OpeningBalance
  126. PRCD = PreviousClosingBalance
  127. ITBD = InterimBalance (first ITBD is start-, second is end-balance)
  128. CLBD = ClosingBalance
  129. """
  130. start_balance_node = None
  131. end_balance_node = None
  132. for node_name in ['OPBD', 'PRCD', 'CLBD', 'ITBD']:
  133. code_expr = (
  134. './ns:Bal/ns:Tp/ns:CdOrPrtry/ns:Cd[text()="%s"]/../../..' %
  135. node_name
  136. )
  137. balance_node = node.xpath(code_expr, namespaces={'ns': ns})
  138. if balance_node:
  139. if node_name in ['OPBD', 'PRCD']:
  140. start_balance_node = balance_node[0]
  141. elif node_name == 'CLBD':
  142. end_balance_node = balance_node[0]
  143. else:
  144. if not start_balance_node:
  145. start_balance_node = balance_node[0]
  146. if not end_balance_node:
  147. end_balance_node = balance_node[-1]
  148. return (
  149. self.parse_amount(ns, start_balance_node),
  150. self.parse_amount(ns, end_balance_node)
  151. )
  152. def parse_statement(self, ns, node):
  153. """Parse a single Stmt node."""
  154. result = {}
  155. self.add_value_from_node(
  156. ns, node, [
  157. './ns:Acct/ns:Id/ns:IBAN',
  158. './ns:Acct/ns:Id/ns:Othr/ns:Id',
  159. ], result, 'account_number'
  160. )
  161. self.add_value_from_node(
  162. ns, node, './ns:Id', result, 'name')
  163. self.add_value_from_node(
  164. ns, node, './ns:Acct/ns:Ccy', result, 'currency')
  165. result['balance_start'], result['balance_end_real'] = (
  166. self.get_balance_amounts(ns, node))
  167. entry_nodes = node.xpath('./ns:Ntry', namespaces={'ns': ns})
  168. transactions = []
  169. for entry_node in entry_nodes:
  170. transactions.extend(self.parse_entry(ns, entry_node))
  171. result['transactions'] = transactions
  172. result['date'] = None
  173. if 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 whether 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 whether 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