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.

311 lines
12 KiB

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