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.

292 lines
12 KiB

10 years ago
  1. # -*- coding: utf-8 -*-
  2. """Class to parse camt files."""
  3. ##############################################################################
  4. #
  5. # Copyright (C) 2013-2015 Therp BV <http://therp.nl>
  6. # Copyright 2017 Open Net Sàrl
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU Affero General Public License as published
  10. # by the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Affero General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Affero General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. ##############################################################################
  22. import re
  23. from copy import copy
  24. from datetime import datetime
  25. from lxml import etree
  26. from openerp import _
  27. from openerp.addons.account_bank_statement_import.parserlib import (
  28. BankStatement)
  29. class CamtParser(object):
  30. """Parser for camt bank statement import files."""
  31. def parse_amount(self, ns, node):
  32. """Parse element that contains Amount and CreditDebitIndicator."""
  33. if node is None:
  34. return 0.0
  35. sign = 1
  36. amount = 0.0
  37. sign_node = node.xpath('ns:CdtDbtInd', namespaces={'ns': ns})
  38. if sign_node and sign_node[0].text == 'DBIT':
  39. sign = -1
  40. amount_node = node.xpath('ns:Amt', namespaces={'ns': ns})
  41. if amount_node:
  42. amount = sign * float(amount_node[0].text)
  43. return amount
  44. def add_value_from_node(
  45. self, ns, node, xpath_str, obj, attr_name, join_str=None,
  46. default=None):
  47. """Add value to object from first or all nodes found with xpath.
  48. If xpath_str is a list (or iterable), it will be seen as a series
  49. of search path's in order of preference. The first item that results
  50. in a found node will be used to set a value."""
  51. if not isinstance(xpath_str, (list, tuple)):
  52. xpath_str = [xpath_str]
  53. for search_str in xpath_str:
  54. found_node = node.xpath(search_str, namespaces={'ns': ns})
  55. if found_node:
  56. if join_str is None:
  57. attr_value = found_node[0].text
  58. else:
  59. attr_value = join_str.join([x.text for x in found_node])
  60. setattr(obj, attr_name, attr_value)
  61. break
  62. else:
  63. if default:
  64. setattr(obj, attr_name, default)
  65. def parse_transaction_details(self, ns, node, transaction):
  66. """Parse TxDtls node."""
  67. # message
  68. self.add_value_from_node(
  69. ns,
  70. node,
  71. [
  72. './ns:RmtInf/ns:Ustrd',
  73. './ns:AddtlTxInf',
  74. './ns:AddtlNtryInf',
  75. './ns:RltdPties/ns:CdtrAcct/ns:Tp/ns:Prtry',
  76. './ns:RltdPties/ns:DbtrAcct/ns:Tp/ns:Prtry',
  77. ],
  78. transaction,
  79. 'message',
  80. join_str='\n',
  81. default=_('No description')
  82. )
  83. # eref
  84. self.add_value_from_node(
  85. ns, node, [
  86. './ns:RmtInf/ns:Strd/ns:CdtrRefInf/ns:Ref',
  87. './ns:Refs/ns:EndToEndId',
  88. ],
  89. transaction, 'eref'
  90. )
  91. amount = self.parse_amount(ns, node)
  92. if amount != 0.0:
  93. transaction['amount'] = amount
  94. # remote party values
  95. party_type = 'Dbtr'
  96. party_type_node = node.xpath(
  97. '../../ns:CdtDbtInd', namespaces={'ns': ns})
  98. if party_type_node and party_type_node[0].text != 'CRDT':
  99. party_type = 'Cdtr'
  100. party_node = node.xpath(
  101. './ns:RltdPties/ns:%s' % party_type, namespaces={'ns': ns})
  102. if party_node:
  103. self.add_value_from_node(
  104. ns, party_node[0], './ns:Nm', transaction, 'remote_owner')
  105. self.add_value_from_node(
  106. ns, party_node[0], './ns:PstlAdr/ns:Ctry', transaction,
  107. 'remote_owner_country'
  108. )
  109. address_node = party_node[0].xpath(
  110. './ns:PstlAdr/ns:AdrLine', namespaces={'ns': ns})
  111. if address_node:
  112. transaction.remote_owner_address = [address_node[0].text]
  113. # Get remote_account from iban or from domestic account:
  114. account_node = node.xpath(
  115. './ns:RltdPties/ns:%sAcct/ns:Id' % party_type,
  116. namespaces={'ns': ns}
  117. )
  118. if account_node:
  119. iban_node = account_node[0].xpath(
  120. './ns:IBAN', namespaces={'ns': ns})
  121. if iban_node:
  122. transaction.remote_account = iban_node[0].text
  123. bic_node = node.xpath(
  124. './ns:RltdAgts/ns:%sAgt/ns:FinInstnId/ns:BIC' % party_type,
  125. namespaces={'ns': ns}
  126. )
  127. if bic_node:
  128. transaction.remote_bank_bic = bic_node[0].text
  129. else:
  130. self.add_value_from_node(
  131. ns, account_node[0], './ns:Othr/ns:Id', transaction,
  132. 'remote_account'
  133. )
  134. def parse_entry(self, ns, node, transaction):
  135. """Parse an Ntry node and yield transactions."""
  136. self.add_value_from_node(
  137. ns, node, './ns:BkTxCd/ns:Prtry/ns:Cd', transaction,
  138. 'transfer_type'
  139. )
  140. self.add_value_from_node(
  141. ns, node, './ns:BookgDt/ns:Dt', transaction, 'date')
  142. self.add_value_from_node(
  143. ns, node, './ns:BookgDt/ns:Dt', transaction, 'execution_date')
  144. self.add_value_from_node(
  145. ns, node, './ns:ValDt/ns:Dt', transaction, 'value_date')
  146. amount = self.parse_amount(ns, node)
  147. if amount != 0.0:
  148. transaction['amount'] = amount
  149. self.add_value_from_node(
  150. ns, node, './ns:AddtlNtryInf', transaction, 'name')
  151. self.add_value_from_node(
  152. ns, node, [
  153. './ns:NtryDtls/ns:RmtInf/ns:Strd/ns:CdtrRefInf/ns:Ref',
  154. './ns:NtryDtls/ns:Btch/ns:PmtInfId',
  155. ],
  156. transaction, 'ref'
  157. )
  158. details_nodes = node.xpath(
  159. './ns:NtryDtls/ns:TxDtls', namespaces={'ns': ns})
  160. if len(details_nodes) == 0:
  161. yield transaction
  162. return
  163. transaction_base = transaction
  164. for i, dnode in enumerate(details_nodes):
  165. transaction = copy(transaction_base)
  166. self.parse_transaction_details(ns, dnode, transaction)
  167. # transactions['data'] should be a synthetic xml snippet which
  168. # contains only the TxDtls that's relevant.
  169. data = copy(node)
  170. for j, dnode in enumerate(data.xpath(
  171. './ns:NtryDtls/ns:TxDtls', namespaces={'ns': ns})):
  172. if j != i:
  173. dnode.getparent().remove(dnode)
  174. transaction['data'] = etree.tostring(data)
  175. yield transaction
  176. def get_balance_amounts(self, ns, node):
  177. """Return opening and closing balance.
  178. Depending on kind of balance and statement, the balance might be in a
  179. different kind of node:
  180. OPBD = OpeningBalance
  181. PRCD = PreviousClosingBalance
  182. ITBD = InterimBalance (first ITBD is start-, second is end-balance)
  183. CLBD = ClosingBalance
  184. """
  185. start_balance_node = None
  186. end_balance_node = None
  187. for node_name in ['OPBD', 'PRCD', 'CLBD', 'ITBD']:
  188. code_expr = (
  189. './ns:Bal/ns:Tp/ns:CdOrPrtry/ns:Cd[text()="%s"]/../../..' %
  190. node_name
  191. )
  192. balance_node = node.xpath(code_expr, namespaces={'ns': ns})
  193. if balance_node:
  194. if node_name in ['OPBD', 'PRCD']:
  195. start_balance_node = balance_node[0]
  196. elif node_name == 'CLBD':
  197. end_balance_node = balance_node[0]
  198. else:
  199. if not start_balance_node:
  200. start_balance_node = balance_node[0]
  201. if not end_balance_node:
  202. end_balance_node = balance_node[-1]
  203. return (
  204. self.parse_amount(ns, start_balance_node),
  205. self.parse_amount(ns, end_balance_node)
  206. )
  207. def parse_statement(self, ns, node):
  208. """Parse a single Stmt node."""
  209. statement = BankStatement()
  210. self.add_value_from_node(
  211. ns, node, [
  212. './ns:Acct/ns:Id/ns:IBAN',
  213. './ns:Acct/ns:Id/ns:Othr/ns:Id',
  214. ], statement, 'local_account'
  215. )
  216. self.add_value_from_node(
  217. ns, node, './ns:Id', statement, 'statement_id')
  218. self.add_value_from_node(
  219. ns, node, './ns:Acct/ns:Ccy', statement, 'local_currency')
  220. (statement.start_balance, statement.end_balance) = (
  221. self.get_balance_amounts(ns, node))
  222. entry_nodes = node.xpath('./ns:Ntry', namespaces={'ns': ns})
  223. transactions = []
  224. for entry_node in entry_nodes:
  225. transaction = statement.create_transaction()
  226. transactions.extend(self.parse_entry(ns, entry_node, transaction))
  227. statement['transactions'] = transactions
  228. if statement['transactions']:
  229. execution_date = statement['transactions'][0].execution_date[:10]
  230. statement.date = datetime.strptime(execution_date, "%Y-%m-%d")
  231. # Prepend date of first transaction to improve id uniquenes
  232. if execution_date not in statement.statement_id:
  233. statement.statement_id = "%s-%s" % (
  234. execution_date, statement.statement_id)
  235. return statement
  236. def check_version(self, ns, root):
  237. """Validate validity of camt file."""
  238. # Check wether it is camt at all:
  239. re_camt = re.compile(
  240. r'(^urn:iso:std:iso:20022:tech:xsd:camt.'
  241. r'|^ISO:camt.)'
  242. )
  243. if not re_camt.search(ns):
  244. raise ValueError('no camt: ' + ns)
  245. # Check wether version 052 or 053:
  246. re_camt_version = re.compile(
  247. r'(^urn:iso:std:iso:20022:tech:xsd:camt.053.'
  248. r'|^urn:iso:std:iso:20022:tech:xsd:camt.052.'
  249. r'|^ISO:camt.053.'
  250. r'|^ISO:camt.052.)'
  251. )
  252. if not re_camt_version.search(ns):
  253. raise ValueError('no camt 052 or 053: ' + ns)
  254. # Check GrpHdr element:
  255. root_0_0 = root[0][0].tag[len(ns) + 2:] # strip namespace
  256. if root_0_0 != 'GrpHdr':
  257. raise ValueError('expected GrpHdr, got: ' + root_0_0)
  258. def parse(self, data):
  259. """Parse a camt.052 or camt.053 file."""
  260. try:
  261. root = etree.fromstring(
  262. data, parser=etree.XMLParser(recover=True))
  263. except etree.XMLSyntaxError:
  264. # ABNAmro is known to mix up encodings
  265. root = etree.fromstring(
  266. data.decode('iso-8859-15').encode('utf-8'))
  267. if root is None:
  268. raise ValueError(
  269. 'Not a valid xml file, or not an xml file at all.')
  270. ns = root.tag[1:root.tag.index("}")]
  271. self.check_version(ns, root)
  272. statements = []
  273. for node in root[0][1:]:
  274. statement = self.parse_statement(ns, node)
  275. if len(statement['transactions']):
  276. statements.append(statement)
  277. return statements