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.

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