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.

312 lines
12 KiB

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