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.

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