Merge PR #601 into 14.0

Signed-off-by alexey-pelykh
This commit is contained in:
OCA-git-bot
2024-02-12 14:19:48 +00:00
20 changed files with 3012 additions and 0 deletions

View File

@@ -0,0 +1,125 @@
===================================================
Online Bank Statements: Wise.com (TransferWise.com)
===================================================
.. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
:target: https://odoo-community.org/page/development-status
:alt: Beta
.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
:alt: License: AGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fbank--statement--import-lightgray.png?logo=github
:target: https://github.com/OCA/bank-statement-import/tree/13.0/account_bank_statement_import_online_transferwise
:alt: OCA/bank-statement-import
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/bank-statement-import-13-0/bank-statement-import-13-0-account_bank_statement_import_online_transferwise
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runbot-Try%20me-875A7B.png
:target: https://runbot.odoo-community.org/runbot/174/13.0
:alt: Try me on Runbot
|badge1| |badge2| |badge3| |badge4| |badge5|
This module provides online bank statements from
`Wise.com <https://wise.com/>`__.
(formely `TransferWise.com <https://transferwise.com/>`__).
**Table of contents**
.. contents::
:local:
Configuration
=============
To configure online bank statements provider:
#. Go to *Invoicing > Configuration > Bank Accounts*
#. Open bank account to configure and edit it
#. Set *Bank Feeds* to *Online*
#. Select *Wise.com (TransferWise.com)* as online bank statements provider in
*Online Bank Statements (OCA)* section
#. Save the bank account
#. Click on provider and configure provider-specific settings.
or, alternatively:
#. Go to *Invoicing > Overview*
#. Open settings of the corresponding journal account
#. Switch to *Bank Account* tab
#. Set *Bank Feeds* to *Online*
#. Select *Wise.com (TransferWise.com)* as online bank statements provider in
*Online Bank Statements (OCA)* section
#. Save the bank account
#. Click on provider and configure provider-specific settings.
Usage
=====
To pull historical bank statements:
#. Go to *Invoicing > Configuration > Bank Accounts*
#. Select specific bank accounts
#. Launch *Actions > Online Bank Statements Pull Wizard*
#. Configure date interval and click *Pull*
To configure Strong Customer Authentication:
#. Go to provider-specific settings and either press *Generate Key* or paste
manually-generate private and public keys
#. Navigate to `Wise.com <https://wise.com/public-keys/>`__ and register the public key.
Bug Tracker
===========
Bugs are tracked on `GitHub Issues <https://github.com/OCA/bank-statement-import/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us smashing it by providing a detailed and welcomed
`feedback <https://github.com/OCA/bank-statement-import/issues/new?body=module:%20account_bank_statement_import_online_transferwise%0Aversion:%2013.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
Do not contact contributors directly about support or help with technical issues.
Credits
=======
Authors
~~~~~~~
* CorporateHub
Contributors
~~~~~~~~~~~~
* `CorporateHub <https://corporatehub.eu/>`__
* Alexey Pelykh <alexey.pelykh@corphub.eu>
Maintainers
~~~~~~~~~~~
This module is maintained by the OCA.
.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: https://odoo-community.org
OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.
.. |maintainer-alexey-pelykh| image:: https://github.com/alexey-pelykh.png?size=40px
:target: https://github.com/alexey-pelykh
:alt: alexey-pelykh
Current `maintainer <https://odoo-community.org/page/maintainer-role>`__:
|maintainer-alexey-pelykh|
This module is part of the `OCA/bank-statement-import <https://github.com/OCA/bank-statement-import/tree/13.0/account_bank_statement_import_online_transferwise>`_ project on GitHub.
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

View File

@@ -0,0 +1,3 @@
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from . import models

View File

@@ -0,0 +1,18 @@
# Copyright 2019 Brainbean Apps (https://brainbeanapps.com)
# Copyright 2020-2021 CorporateHub (https://corporatehub.eu)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Online Bank Statements: Wise.com (TransferWise.com)",
"version": "14.0.1.0.0",
"author": "CorporateHub, Odoo Community Association (OCA)",
"maintainers": ["alexey-pelykh"],
"website": "https://github.com/OCA/bank-statement-import",
"license": "AGPL-3",
"category": "Accounting",
"summary": "Online bank statements for Wise.com (TransferWise.com)",
"depends": ["account_statement_import_online", "web_widget_dropdown_dynamic"],
"external_dependencies": {"python": ["cryptography"]},
"data": ["views/online_bank_statement_provider.xml"],
"installable": True,
}

View File

@@ -0,0 +1,95 @@
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * account_bank_statement_import_online_transferwise
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 13.0\n"
"Report-Msgid-Bugs-To: \n"
"Last-Translator: \n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: \n"
#. module: account_bank_statement_import_online_transferwise
#: model_terms:ir.ui.view,arch_db:account_bank_statement_import_online_transferwise.online_bank_statement_provider_form
msgid "API base"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: model_terms:ir.ui.view,arch_db:account_bank_statement_import_online_transferwise.online_bank_statement_provider_form
msgid "API key"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: code:addons/account_bank_statement_import_online_transferwise/models/online_bank_statement_provider_transferwise.py:0
#, python-format
msgid "Ending balance unavailable"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: code:addons/account_bank_statement_import_online_transferwise/models/online_bank_statement_provider_transferwise.py:0
#, python-format
msgid "Fee for %s"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: model_terms:ir.ui.view,arch_db:account_bank_statement_import_online_transferwise.online_bank_statement_provider_form
msgid "Generate Key"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: code:addons/account_bank_statement_import_online_transferwise/models/online_bank_statement_provider_transferwise.py:0
#, python-format
msgid "No API key specified!"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: model:ir.model,name:account_bank_statement_import_online_transferwise.model_online_bank_statement_provider
msgid "Online Bank Statement Provider"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: model:ir.model.fields,field_description:account_bank_statement_import_online_transferwise.field_online_bank_statement_provider__transferwise_profile
msgid "Origin"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: model_terms:ir.ui.view,arch_db:account_bank_statement_import_online_transferwise.online_bank_statement_provider_form
msgid "Private key"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: model_terms:ir.ui.view,arch_db:account_bank_statement_import_online_transferwise.online_bank_statement_provider_form
msgid "Profile"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: model_terms:ir.ui.view,arch_db:account_bank_statement_import_online_transferwise.online_bank_statement_provider_form
msgid "Public key"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: model_terms:ir.ui.view,arch_db:account_bank_statement_import_online_transferwise.online_bank_statement_provider_form
msgid "Strong Customer Authentication"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: code:addons/account_bank_statement_import_online_transferwise/models/online_bank_statement_provider_transferwise.py:0
#, python-format
msgid "Strong Customer Authentication is not configured"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: code:addons/account_bank_statement_import_online_transferwise/models/online_bank_statement_provider_transferwise.py:0
#, python-format
msgid "Transaction fee for %s"
msgstr ""
#. module: account_bank_statement_import_online_transferwise
#: code:addons/account_bank_statement_import_online_transferwise/models/online_bank_statement_provider_transferwise.py:0
#, python-format
msgid "Unable to parse key"
msgstr ""

View File

@@ -0,0 +1,61 @@
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * account_bank_statement_import_online_transferwise
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 12.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2021-01-22 22:44+0000\n"
"Last-Translator: Bosd <c5e2fd43-d292-4c90-9d1f-74ff3436329a@anonaddy.me>\n"
"Language-Team: none\n"
"Language: nl\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 4.3.2\n"
#. module: account_bank_statement_import_online_transferwise
#: model_terms:ir.ui.view,arch_db:account_bank_statement_import_online_transferwise.online_bank_statement_provider_form
msgid "API base"
msgstr "API base"
#. module: account_bank_statement_import_online_transferwise
#: model_terms:ir.ui.view,arch_db:account_bank_statement_import_online_transferwise.online_bank_statement_provider_form
msgid "API key"
msgstr "API Sleutel"
#. module: account_bank_statement_import_online_transferwise
#: code:addons/account_bank_statement_import_online_transferwise/models/online_bank_statement_provider_transferwise.py:131
#, python-format
msgid "Ending balance unavailable"
msgstr "Eindbalans is niet beschikbaar"
#. module: account_bank_statement_import_online_transferwise
#: code:addons/account_bank_statement_import_online_transferwise/models/online_bank_statement_provider_transferwise.py:250
#, fuzzy, python-format
msgid "Fee for %s"
msgstr "Transactievergoeding voor %s"
#. module: account_bank_statement_import_online_transferwise
#: code:addons/account_bank_statement_import_online_transferwise/models/online_bank_statement_provider_transferwise.py:281
#, python-format
msgid "No API key specified!"
msgstr "Geen API sleutel ingegeven!"
#. module: account_bank_statement_import_online_transferwise
#: model:ir.model,name:account_bank_statement_import_online_transferwise.model_online_bank_statement_provider
msgid "Online Bank Statement Provider"
msgstr "Online Bankafschrift Provider"
#. module: account_bank_statement_import_online_transferwise
#: model_terms:ir.ui.view,arch_db:account_bank_statement_import_online_transferwise.online_bank_statement_provider_form
msgid "Profile"
msgstr "Profiel"
#. module: account_bank_statement_import_online_transferwise
#: code:addons/account_bank_statement_import_online_transferwise/models/online_bank_statement_provider_transferwise.py:255
#, python-format
msgid "Transaction fee for %s"
msgstr "Transactievergoeding voor %s"

View File

@@ -0,0 +1,3 @@
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from . import online_bank_statement_provider_transferwise

View File

@@ -0,0 +1,369 @@
# Copyright 2019 Brainbean Apps (https://brainbeanapps.com)
# Copyright 2020-2021 CorporateHub (https://corporatehub.eu)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import itertools
import json
import logging
import urllib.parse
import urllib.request
from base64 import b64encode
from decimal import Decimal
from urllib.error import HTTPError
import dateutil.parser
import pytz
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from dateutil.relativedelta import relativedelta
from odoo import _, api, fields, models
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
TRANSFERWISE_API_BASE = "https://api.transferwise.com"
class OnlineBankStatementProviderTransferwise(models.Model):
_inherit = "online.bank.statement.provider"
# NOTE: This is needed to workaround possible multiple 'origin' fields
# present in the same view, resulting in wrong field view configuraion
# if more than one is widget="dynamic_dropdown"
transferwise_profile = fields.Char(
related="origin",
readonly=False,
)
@api.model
def values_transferwise_profile(self):
api_base = self.env.context.get("api_base") or TRANSFERWISE_API_BASE
api_key = self.env.context.get("api_key")
if not api_key:
return []
try:
url = api_base + "/v1/profiles"
data = self._transferwise_retrieve(url, api_key)
except BaseException:
_logger.warning("Unable to get profiles", exc_info=True)
return []
return list(
map(
lambda entry: (
str(entry["id"]),
"%s %s (personal)"
% (
entry["details"]["firstName"],
entry["details"]["lastName"],
)
if entry["type"] == "personal"
else entry["details"]["name"],
),
data,
)
)
@api.model
def _get_available_services(self):
return super()._get_available_services() + [
("transferwise", "Wise.com (TransferWise.com)"),
]
def _obtain_statement_data(self, date_since, date_until):
self.ensure_one()
if self.service != "transferwise":
return super()._obtain_statement_data(
date_since,
date_until,
) # pragma: no cover
api_base = self.api_base or TRANSFERWISE_API_BASE
api_key = self.password
private_key = self.certificate_private_key
if private_key:
private_key = serialization.load_pem_private_key(
private_key.encode(),
password=None,
backend=default_backend(),
)
currency = (self.currency_id or self.company_id.currency_id).name
if date_since.tzinfo:
date_since = date_since.astimezone(pytz.utc).replace(tzinfo=None)
if date_until.tzinfo:
date_until = date_until.astimezone(pytz.utc).replace(tzinfo=None)
# Get corresponding balance by currency
url = api_base + "/v1/borderless-accounts?profileId={}".format(self.origin)
data = self._transferwise_retrieve(url, api_key, private_key)
if not data:
return None
borderless_account = data[0]["id"]
balance = list(
filter(lambda balance: balance["currency"] == currency, data[0]["balances"])
)
if not balance:
return None
# Notes on /statement endpoint:
# - intervalStart <= date < intervalEnd
# Get starting balance
starting_balance_timestamp = date_since.isoformat() + "Z"
url = api_base + (
"/v3/profiles/%s/borderless-accounts/%s/statement.json"
+ "?currency=%s&intervalStart=%s&intervalEnd=%s&type=COMPACT"
) % (
self.origin,
borderless_account,
currency,
starting_balance_timestamp,
starting_balance_timestamp,
)
data = self._transferwise_retrieve(url, api_key, private_key)
balance_start = data["endOfStatementBalance"]["value"]
# Get statements, using 469 days (around 1 year 3 month) as step.
interval_step = relativedelta(days=469)
interval_start = date_since
interval_end = date_until
transactions = []
balance_end = None
while interval_start < interval_end:
url = api_base + (
"/v3/profiles/%s/borderless-accounts/%s/statement.json"
+ "?currency=%s&intervalStart=%s&intervalEnd=%s&type=COMPACT"
) % (
self.origin,
borderless_account,
currency,
interval_start.isoformat() + "Z",
min(interval_start + interval_step, interval_end).isoformat() + "Z",
)
data = self._transferwise_retrieve(url, api_key, private_key)
transactions += data["transactions"]
balance_end = data["endOfStatementBalance"]["value"]
interval_start += interval_step
if balance_end is None:
raise UserError(_("Ending balance unavailable"))
# Normalize transactions' date, sort by it, and get lines
transactions = map(
lambda transaction: self._transferwise_preparse_transaction(transaction),
transactions,
)
lines = list(
itertools.chain.from_iterable(
map(
lambda x: self._transferwise_transaction_to_lines(x),
sorted(transactions, key=lambda transaction: transaction["date"]),
)
)
)
return lines, {"balance_start": balance_start, "balance_end_real": balance_end}
@api.model
def _transferwise_preparse_transaction(self, transaction):
transaction["date"] = dateutil.parser.parse(transaction["date"]).replace(
tzinfo=None
)
return transaction
@api.model
def _transferwise_transaction_to_lines(self, transaction):
transaction_type = transaction["type"]
reference_number = transaction["referenceNumber"]
details = transaction.get("details", {})
exchange_details = transaction.get("exchangeDetails")
recipient = details.get("recipient")
total_fees = transaction.get("totalFees")
date = transaction["date"]
payment_reference = details.get("paymentReference")
description = details.get("description")
pay_ref = reference_number
if description:
pay_ref = "{}: {}".format(pay_ref, description)
amount = transaction["amount"]
amount_value = amount.get("value", 0)
fees_value = total_fees.get("value", Decimal())
if transaction_type == "CREDIT" and details.get("type") == "MONEY_ADDED":
fees_value = fees_value.copy_negate()
else:
fees_value = fees_value.copy_sign(amount_value)
amount_value -= fees_value
unique_import_id = "{}-{}-{}".format(
transaction_type,
reference_number,
int(date.timestamp()),
)
line = {
"name": payment_reference or description or "",
"amount": str(amount_value),
"date": date,
"payment_ref": pay_ref,
"unique_import_id": unique_import_id,
}
if recipient:
if "name" in recipient:
line.update({"partner_name": recipient["name"]})
if "bankAccount" in recipient:
line.update({"account_number": recipient["bankAccount"]})
elif "merchant" in details:
merchant = details["merchant"]
if "name" in merchant:
line.update({"partner_name": merchant["name"]})
else:
if "senderName" in details:
line.update({"partner_name": details["senderName"]})
if "senderAccount" in details:
line.update({"account_number": details["senderAccount"]})
if exchange_details:
to_amount = exchange_details["toAmount"]
from_amount = exchange_details["fromAmount"]
other_amount_value = (
to_amount["value"]
if to_amount["currency"] != amount["currency"]
else from_amount["value"]
)
other_currency_name = (
to_amount["currency"]
if to_amount["currency"] != amount["currency"]
else from_amount["currency"]
)
other_amount_value = other_amount_value.copy_abs()
if amount_value.is_signed():
other_amount_value = other_amount_value.copy_negate()
other_currency = self.env["res.currency"].search(
[("name", "=", other_currency_name)], limit=1
)
if other_amount_value and other_currency:
line.update(
{
"amount_currency": str(other_amount_value),
"currency_id": other_currency.id,
}
)
lines = [line]
if fees_value:
lines += [
{
"name": _("Fee for %s") % reference_number,
"amount": str(fees_value),
"date": date,
"partner_name": "Wise (former TransferWise)",
"unique_import_id": "%s-FEE" % unique_import_id,
"payment_ref": _("Transaction fee for %s") % reference_number,
}
]
return lines
@api.model
def _transferwise_validate(self, content):
content = json.loads(content, parse_float=Decimal)
if "error" in content and content["error"]:
raise UserError(
content["error_description"]
if "error_description" in content
else "Unknown error"
)
return content
@api.model
def _transferwise_retrieve(self, url, api_key, private_key=None):
try:
with self._transferwise_urlopen(url, api_key) as response:
content = response.read().decode(
response.headers.get_content_charset() or "utf-8"
)
except HTTPError as e:
if e.code != 403 or e.headers.get("X-2FA-Approval-Result") != "REJECTED":
raise e
if not private_key:
raise UserError(_("Strong Customer Authentication is not configured"))
one_time_token = e.headers["X-2FA-Approval"]
signature = private_key.sign(
one_time_token.encode(),
padding.PKCS1v15(),
hashes.SHA256(),
)
with self._transferwise_urlopen(
url,
api_key,
one_time_token,
b64encode(signature).decode(),
) as response:
content = response.read().decode(
response.headers.get_content_charset() or "utf-8"
)
return self._transferwise_validate(content)
@api.model
def _transferwise_urlopen(self, url, api_key, ott=None, signature=None):
if not api_key:
raise UserError(_("No API key specified!"))
request = urllib.request.Request(url)
request.add_header("Authorization", "Bearer %s" % api_key)
if ott and signature:
request.add_header("X-2FA-Approval", ott)
request.add_header("X-Signature", signature)
return urllib.request.urlopen(request)
@api.onchange("certificate_private_key", "service")
def _onchange_transferwise_certificate_private_key(self):
if self.service != "transferwise":
return
self.certificate_public_key = False
if not self.certificate_private_key:
return
try:
private_key = serialization.load_pem_private_key(
self.certificate_private_key.encode(),
password=None,
backend=default_backend(),
)
self.certificate_public_key = (
private_key.public_key()
.public_bytes(
serialization.Encoding.PEM,
serialization.PublicFormat.PKCS1,
)
.decode()
)
except BaseException:
_logger.warning("Unable to parse key", exc_info=True)
raise UserError(_("Unable to parse key"))
def _transferwise_generate_key(self):
self.ensure_one()
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend(),
)
self.certificate_private_key = private_key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL, # a.k.a. PKCS#1
serialization.NoEncryption(),
).decode()
self.certificate_public_key = (
private_key.public_key()
.public_bytes(
serialization.Encoding.PEM,
serialization.PublicFormat.PKCS1,
)
.decode()
)
def button_transferwise_generate_key(self):
for provider in self:
provider._transferwise_generate_key()

View File

@@ -0,0 +1,20 @@
To configure online bank statements provider:
#. Go to *Invoicing > Configuration > Bank Accounts*
#. Open bank account to configure and edit it
#. Set *Bank Feeds* to *Online*
#. Select *Wise.com (TransferWise.com)* as online bank statements provider in
*Online Bank Statements (OCA)* section
#. Save the bank account
#. Click on provider and configure provider-specific settings.
or, alternatively:
#. Go to *Invoicing > Overview*
#. Open settings of the corresponding journal account
#. Switch to *Bank Account* tab
#. Set *Bank Feeds* to *Online*
#. Select *Wise.com (TransferWise.com)* as online bank statements provider in
*Online Bank Statements (OCA)* section
#. Save the bank account
#. Click on provider and configure provider-specific settings.

View File

@@ -0,0 +1,3 @@
* `CorporateHub <https://corporatehub.eu/>`__
* Alexey Pelykh <alexey.pelykh@corphub.eu>

View File

@@ -0,0 +1,3 @@
This module provides online bank statements from
`Wise.com <https://wise.com/>`__.
(formely `TransferWise.com <https://transferwise.com/>`__).

View File

@@ -0,0 +1,12 @@
To pull historical bank statements:
#. Go to *Invoicing > Configuration > Bank Accounts*
#. Select specific bank accounts
#. Launch *Actions > Online Bank Statements Pull Wizard*
#. Configure date interval and click *Pull*
To configure Strong Customer Authentication:
#. Go to provider-specific settings and either press *Generate Key* or paste
manually-generate private and public keys
#. Navigate to `Wise.com <https://wise.com/public-keys/>`__ and register the public key.

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

View File

@@ -0,0 +1,466 @@
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.15.1: http://docutils.sourceforge.net/" />
<title>Online Bank Statements: Wise.com (TransferWise.com)</title>
<style type="text/css">
/*
:Author: David Goodger (goodger@python.org)
:Id: $Id: html4css1.css 7952 2016-07-26 18:15:59Z milde $
:Copyright: This stylesheet has been placed in the public domain.
Default cascading style sheet for the HTML output of Docutils.
See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
customize this style sheet.
*/
/* used to remove borders from tables and images */
.borderless, table.borderless td, table.borderless th {
border: 0 }
table.borderless td, table.borderless th {
/* Override padding for "table.docutils td" with "! important".
The right padding separates the table cells. */
padding: 0 0.5em 0 0 ! important }
.first {
/* Override more specific margin styles with "! important". */
margin-top: 0 ! important }
.last, .with-subtitle {
margin-bottom: 0 ! important }
.hidden {
display: none }
.subscript {
vertical-align: sub;
font-size: smaller }
.superscript {
vertical-align: super;
font-size: smaller }
a.toc-backref {
text-decoration: none ;
color: black }
blockquote.epigraph {
margin: 2em 5em ; }
dl.docutils dd {
margin-bottom: 0.5em }
object[type="image/svg+xml"], object[type="application/x-shockwave-flash"] {
overflow: hidden;
}
/* Uncomment (and remove this text!) to get bold-faced definition list terms
dl.docutils dt {
font-weight: bold }
*/
div.abstract {
margin: 2em 5em }
div.abstract p.topic-title {
font-weight: bold ;
text-align: center }
div.admonition, div.attention, div.caution, div.danger, div.error,
div.hint, div.important, div.note, div.tip, div.warning {
margin: 2em ;
border: medium outset ;
padding: 1em }
div.admonition p.admonition-title, div.hint p.admonition-title,
div.important p.admonition-title, div.note p.admonition-title,
div.tip p.admonition-title {
font-weight: bold ;
font-family: sans-serif }
div.attention p.admonition-title, div.caution p.admonition-title,
div.danger p.admonition-title, div.error p.admonition-title,
div.warning p.admonition-title, .code .error {
color: red ;
font-weight: bold ;
font-family: sans-serif }
/* Uncomment (and remove this text!) to get reduced vertical space in
compound paragraphs.
div.compound .compound-first, div.compound .compound-middle {
margin-bottom: 0.5em }
div.compound .compound-last, div.compound .compound-middle {
margin-top: 0.5em }
*/
div.dedication {
margin: 2em 5em ;
text-align: center ;
font-style: italic }
div.dedication p.topic-title {
font-weight: bold ;
font-style: normal }
div.figure {
margin-left: 2em ;
margin-right: 2em }
div.footer, div.header {
clear: both;
font-size: smaller }
div.line-block {
display: block ;
margin-top: 1em ;
margin-bottom: 1em }
div.line-block div.line-block {
margin-top: 0 ;
margin-bottom: 0 ;
margin-left: 1.5em }
div.sidebar {
margin: 0 0 0.5em 1em ;
border: medium outset ;
padding: 1em ;
background-color: #ffffee ;
width: 40% ;
float: right ;
clear: right }
div.sidebar p.rubric {
font-family: sans-serif ;
font-size: medium }
div.system-messages {
margin: 5em }
div.system-messages h1 {
color: red }
div.system-message {
border: medium outset ;
padding: 1em }
div.system-message p.system-message-title {
color: red ;
font-weight: bold }
div.topic {
margin: 2em }
h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
margin-top: 0.4em }
h1.title {
text-align: center }
h2.subtitle {
text-align: center }
hr.docutils {
width: 75% }
img.align-left, .figure.align-left, object.align-left, table.align-left {
clear: left ;
float: left ;
margin-right: 1em }
img.align-right, .figure.align-right, object.align-right, table.align-right {
clear: right ;
float: right ;
margin-left: 1em }
img.align-center, .figure.align-center, object.align-center {
display: block;
margin-left: auto;
margin-right: auto;
}
table.align-center {
margin-left: auto;
margin-right: auto;
}
.align-left {
text-align: left }
.align-center {
clear: both ;
text-align: center }
.align-right {
text-align: right }
/* reset inner alignment in figures */
div.align-right {
text-align: inherit }
/* div.align-center * { */
/* text-align: left } */
.align-top {
vertical-align: top }
.align-middle {
vertical-align: middle }
.align-bottom {
vertical-align: bottom }
ol.simple, ul.simple {
margin-bottom: 1em }
ol.arabic {
list-style: decimal }
ol.loweralpha {
list-style: lower-alpha }
ol.upperalpha {
list-style: upper-alpha }
ol.lowerroman {
list-style: lower-roman }
ol.upperroman {
list-style: upper-roman }
p.attribution {
text-align: right ;
margin-left: 50% }
p.caption {
font-style: italic }
p.credits {
font-style: italic ;
font-size: smaller }
p.label {
white-space: nowrap }
p.rubric {
font-weight: bold ;
font-size: larger ;
color: maroon ;
text-align: center }
p.sidebar-title {
font-family: sans-serif ;
font-weight: bold ;
font-size: larger }
p.sidebar-subtitle {
font-family: sans-serif ;
font-weight: bold }
p.topic-title {
font-weight: bold }
pre.address {
margin-bottom: 0 ;
margin-top: 0 ;
font: inherit }
pre.literal-block, pre.doctest-block, pre.math, pre.code {
margin-left: 2em ;
margin-right: 2em }
pre.code .ln { color: grey; } /* line numbers */
pre.code, code { background-color: #eeeeee }
pre.code .comment, code .comment { color: #5C6576 }
pre.code .keyword, code .keyword { color: #3B0D06; font-weight: bold }
pre.code .literal.string, code .literal.string { color: #0C5404 }
pre.code .name.builtin, code .name.builtin { color: #352B84 }
pre.code .deleted, code .deleted { background-color: #DEB0A1}
pre.code .inserted, code .inserted { background-color: #A3D289}
span.classifier {
font-family: sans-serif ;
font-style: oblique }
span.classifier-delimiter {
font-family: sans-serif ;
font-weight: bold }
span.interpreted {
font-family: sans-serif }
span.option {
white-space: nowrap }
span.pre {
white-space: pre }
span.problematic {
color: red }
span.section-subtitle {
/* font-size relative to parent (h1..h6 element) */
font-size: 80% }
table.citation {
border-left: solid 1px gray;
margin-left: 1px }
table.docinfo {
margin: 2em 4em }
table.docutils {
margin-top: 0.5em ;
margin-bottom: 0.5em }
table.footnote {
border-left: solid 1px black;
margin-left: 1px }
table.docutils td, table.docutils th,
table.docinfo td, table.docinfo th {
padding-left: 0.5em ;
padding-right: 0.5em ;
vertical-align: top }
table.docutils th.field-name, table.docinfo th.docinfo-name {
font-weight: bold ;
text-align: left ;
white-space: nowrap ;
padding-left: 0 }
/* "booktabs" style (no vertical lines) */
table.docutils.booktabs {
border: 0px;
border-top: 2px solid;
border-bottom: 2px solid;
border-collapse: collapse;
}
table.docutils.booktabs * {
border: 0px;
}
table.docutils.booktabs th {
border-bottom: thin solid;
text-align: left;
}
h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
font-size: 100% }
ul.auto-toc {
list-style-type: none }
</style>
</head>
<body>
<div class="document" id="online-bank-statements-wise-com-transferwise-com">
<h1 class="title">Online Bank Statements: Wise.com (TransferWise.com)</h1>
<!-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -->
<p><a class="reference external" href="https://odoo-community.org/page/development-status"><img alt="Beta" src="https://img.shields.io/badge/maturity-Beta-yellow.png" /></a> <a class="reference external" href="http://www.gnu.org/licenses/agpl-3.0-standalone.html"><img alt="License: AGPL-3" src="https://img.shields.io/badge/licence-AGPL--3-blue.png" /></a> <a class="reference external" href="https://github.com/OCA/bank-statement-import/tree/13.0/account_bank_statement_import_online_transferwise"><img alt="OCA/bank-statement-import" src="https://img.shields.io/badge/github-OCA%2Fbank--statement--import-lightgray.png?logo=github" /></a> <a class="reference external" href="https://translation.odoo-community.org/projects/bank-statement-import-13-0/bank-statement-import-13-0-account_bank_statement_import_online_transferwise"><img alt="Translate me on Weblate" src="https://img.shields.io/badge/weblate-Translate%20me-F47D42.png" /></a> <a class="reference external" href="https://runbot.odoo-community.org/runbot/174/13.0"><img alt="Try me on Runbot" src="https://img.shields.io/badge/runbot-Try%20me-875A7B.png" /></a></p>
<p>This module provides online bank statements from
<a class="reference external" href="https://wise.com/">Wise.com</a>.
(formely <a class="reference external" href="https://transferwise.com/">TransferWise.com</a>).</p>
<p><strong>Table of contents</strong></p>
<div class="contents local topic" id="contents">
<ul class="simple">
<li><a class="reference internal" href="#configuration" id="id1">Configuration</a></li>
<li><a class="reference internal" href="#usage" id="id2">Usage</a></li>
<li><a class="reference internal" href="#bug-tracker" id="id3">Bug Tracker</a></li>
<li><a class="reference internal" href="#credits" id="id4">Credits</a><ul>
<li><a class="reference internal" href="#authors" id="id5">Authors</a></li>
<li><a class="reference internal" href="#contributors" id="id6">Contributors</a></li>
<li><a class="reference internal" href="#maintainers" id="id7">Maintainers</a></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="configuration">
<h1><a class="toc-backref" href="#id1">Configuration</a></h1>
<p>To configure online bank statements provider:</p>
<ol class="arabic simple">
<li>Go to <em>Invoicing &gt; Configuration &gt; Bank Accounts</em></li>
<li>Open bank account to configure and edit it</li>
<li>Set <em>Bank Feeds</em> to <em>Online</em></li>
<li>Select <em>Wise.com (TransferWise.com)</em> as online bank statements provider in
<em>Online Bank Statements (OCA)</em> section</li>
<li>Save the bank account</li>
<li>Click on provider and configure provider-specific settings.</li>
</ol>
<p>or, alternatively:</p>
<ol class="arabic simple">
<li>Go to <em>Invoicing &gt; Overview</em></li>
<li>Open settings of the corresponding journal account</li>
<li>Switch to <em>Bank Account</em> tab</li>
<li>Set <em>Bank Feeds</em> to <em>Online</em></li>
<li>Select <em>Wise.com (TransferWise.com)</em> as online bank statements provider in
<em>Online Bank Statements (OCA)</em> section</li>
<li>Save the bank account</li>
<li>Click on provider and configure provider-specific settings.</li>
</ol>
</div>
<div class="section" id="usage">
<h1><a class="toc-backref" href="#id2">Usage</a></h1>
<p>To pull historical bank statements:</p>
<ol class="arabic simple">
<li>Go to <em>Invoicing &gt; Configuration &gt; Bank Accounts</em></li>
<li>Select specific bank accounts</li>
<li>Launch <em>Actions &gt; Online Bank Statements Pull Wizard</em></li>
<li>Configure date interval and click <em>Pull</em></li>
</ol>
<p>To configure Strong Customer Authentication:</p>
<p>#. Go to provider-specific settings and either press <em>Generate Key</em> or paste
manually-generate private and public keys
#. Navigate to <a class="reference external" href="https://wise.com/public-keys/">Wise.com</a> and register the public key.</p>
</div>
<div class="section" id="bug-tracker">
<h1><a class="toc-backref" href="#id3">Bug Tracker</a></h1>
<p>Bugs are tracked on <a class="reference external" href="https://github.com/OCA/bank-statement-import/issues">GitHub Issues</a>.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us smashing it by providing a detailed and welcomed
<a class="reference external" href="https://github.com/OCA/bank-statement-import/issues/new?body=module:%20account_bank_statement_import_online_transferwise%0Aversion:%2013.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**">feedback</a>.</p>
<p>Do not contact contributors directly about support or help with technical issues.</p>
</div>
<div class="section" id="credits">
<h1><a class="toc-backref" href="#id4">Credits</a></h1>
<div class="section" id="authors">
<h2><a class="toc-backref" href="#id5">Authors</a></h2>
<ul class="simple">
<li>CorporateHub</li>
</ul>
</div>
<div class="section" id="contributors">
<h2><a class="toc-backref" href="#id6">Contributors</a></h2>
<ul class="simple">
<li><a class="reference external" href="https://corporatehub.eu/">CorporateHub</a><ul>
<li>Alexey Pelykh &lt;<a class="reference external" href="mailto:alexey.pelykh&#64;corphub.eu">alexey.pelykh&#64;corphub.eu</a>&gt;</li>
</ul>
</li>
</ul>
</div>
<div class="section" id="maintainers">
<h2><a class="toc-backref" href="#id7">Maintainers</a></h2>
<p>This module is maintained by the OCA.</p>
<a class="reference external image-reference" href="https://odoo-community.org"><img alt="Odoo Community Association" src="https://odoo-community.org/logo.png" /></a>
<p>OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.</p>
<p>Current <a class="reference external" href="https://odoo-community.org/page/maintainer-role">maintainer</a>:</p>
<p><a class="reference external" href="https://github.com/alexey-pelykh"><img alt="alexey-pelykh" src="https://github.com/alexey-pelykh.png?size=40px" /></a></p>
<p>This module is part of the <a class="reference external" href="https://github.com/OCA/bank-statement-import/tree/13.0/account_bank_statement_import_online_transferwise">OCA/bank-statement-import</a> project on GitHub.</p>
<p>You are welcome to contribute. To learn how please visit <a class="reference external" href="https://odoo-community.org/page/Contribute">https://odoo-community.org/page/Contribute</a>.</p>
</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,3 @@
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from . import test_account_statement_import_online_transferwise

View File

@@ -0,0 +1,881 @@
# Copyright 2019 Brainbean Apps (https://brainbeanapps.com)
# Copyright 2020-2021 CorporateHub (https://corporatehub.eu)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import json
from datetime import datetime
from decimal import Decimal
from unittest import mock
from urllib.error import HTTPError
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.tests import common
_module_ns = "odoo.addons.account_bank_statement_import_online_transferwise"
_provider_class = (
_module_ns
+ ".models.online_bank_statement_provider_transferwise"
+ ".OnlineBankStatementProviderTransferwise"
)
class MockedResponse:
class Headers(dict):
def get_content_charset(self):
return None
def __init__(self, data=None, exception=None):
self.data = data
self.exception = exception
self.headers = MockedResponse.Headers()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
# pylint: disable=method-required-super
def read(self):
if self.exception is not None:
raise self.exception()
return self.data
class TestAccountBankAccountStatementImportOnlineTransferwise(common.TransactionCase):
def setUp(self):
super().setUp()
self.now = fields.Datetime.now()
self.currency_eur = self.env.ref("base.EUR")
self.currency_usd = self.env.ref("base.USD")
self.AccountJournal = self.env["account.journal"]
self.OnlineBankStatementProvider = self.env["online.bank.statement.provider"]
self.AccountBankStatement = self.env["account.bank.statement"]
self.AccountBankStatementLine = self.env["account.bank.statement.line"]
Provider = self.OnlineBankStatementProvider
self.transferwise_parse_transaction = lambda payload: (
Provider._transferwise_transaction_to_lines(
Provider._transferwise_preparse_transaction(
json.loads(
payload,
parse_float=Decimal,
)
)
)
)
self.response_balance = MockedResponse(
data=b"""[
{
"id": 42,
"balances": [
{
"currency": "EUR"
}
]
}
]"""
)
self.response_ott = MockedResponse(
exception=lambda: HTTPError(
"https://wise.com/",
403,
"403",
{"X-2FA-Approval-Result": "REJECTED", "X-2FA-Approval": "0123456789"},
None,
)
)
self.response_transactions = MockedResponse(
data=b"""{
"transactions": [],
"endOfStatementBalance": {
"value": 42.00,
"currency": "EUR"
}
}"""
)
def test_values_transferwise_profile(self):
mocked_response = json.loads(
"""[
{
"id": 1234567890,
"type": "personal",
"details": {
"firstName": "Alexey",
"lastName": "Pelykh"
}
},
{
"id": 1234567891,
"type": "business",
"details": {
"name": "Brainbean Apps OÜ"
}
}
]""",
parse_float=Decimal,
)
values_transferwise_profile = []
with mock.patch(
_provider_class + "._transferwise_retrieve",
return_value=mocked_response,
):
values_transferwise_profile = self.OnlineBankStatementProvider.with_context(
{"api_base": "https://example.com", "api_key": "dummy"}
).values_transferwise_profile()
self.assertEqual(
values_transferwise_profile,
[
("1234567890", "Alexey Pelykh (personal)"),
("1234567891", "Brainbean Apps OÜ"),
],
)
def test_values_transferwise_profile_no_key(self):
values_transferwise_profile = self.OnlineBankStatementProvider.with_context(
{"api_base": "https://example.com"}
).values_transferwise_profile()
self.assertEqual(values_transferwise_profile, [])
def test_values_transferwise_profile_error(self):
values_transferwise_profile = []
with mock.patch(
_provider_class + "._transferwise_retrieve",
side_effect=lambda: Exception(),
):
values_transferwise_profile = self.OnlineBankStatementProvider.with_context(
{"api_base": "https://example.com", "api_key": "dummy"}
).values_transferwise_profile()
self.assertEqual(values_transferwise_profile, [])
def test_pull(self):
journal = self.AccountJournal.create(
{
"name": "Bank",
"type": "bank",
"code": "BANK",
"currency_id": self.currency_eur.id,
"bank_statements_source": "online",
"online_bank_statement_provider": "transferwise",
}
)
provider = journal.online_bank_statement_provider_id
provider.origin = "1234567891"
def mock_response(url, api_key, private_key=None):
if "/borderless-accounts?profileId=1234567891" in url:
payload = """[
{
"id": 42,
"balances": [
{
"currency": "EUR"
}
]
}
]"""
elif "/borderless-accounts/42/statement.json" in url:
payload = """{
"transactions": [],
"endOfStatementBalance": {
"value": 42.00,
"currency": "EUR"
}
}"""
return json.loads(payload, parse_float=Decimal)
with mock.patch(
_provider_class + "._transferwise_retrieve",
side_effect=mock_response,
):
data = provider._obtain_statement_data(
self.now - relativedelta(hours=1),
self.now,
)
self.assertEqual(len(data[0]), 0)
self.assertEqual(data[1]["balance_start"], 42.0)
self.assertEqual(data[1]["balance_end_real"], 42.0)
def test_pull_no_data(self):
journal = self.AccountJournal.create(
{
"name": "Bank",
"type": "bank",
"code": "BANK",
"currency_id": self.currency_eur.id,
"bank_statements_source": "online",
"online_bank_statement_provider": "transferwise",
}
)
provider = journal.online_bank_statement_provider_id
provider.origin = "1234567891"
provider.password = "API_KEY"
with mock.patch(
_provider_class + "._transferwise_retrieve",
return_value=[],
):
data = provider._obtain_statement_data(
self.now - relativedelta(hours=1),
self.now,
)
self.assertFalse(data)
def test_update_public_key(self):
journal = self.AccountJournal.create(
{
"name": "Bank",
"type": "bank",
"code": "BANK",
"currency_id": self.currency_eur.id,
"bank_statements_source": "online",
"online_bank_statement_provider": "transferwise",
}
)
provider = journal.online_bank_statement_provider_id
provider.origin = "1234567891"
provider.password = "API_KEY"
with common.Form(provider) as provider_form:
provider_form.certificate_private_key = """
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAxC7aYWigCwPIB4mfyLpsALYPnqDm3/IC8I/3GdEwfK8eqXoF
sU1BHnVytFycBDEObmJ2Acpxe8Dk61FnbWPrrl6rXVnXfIRqfFl94TvgwFsuwG7u
8crncD6gPfe1QGkEykHcfBURr74OcSE8590ngNJcKMGvac0cuyZ2/NEszTw7EFJg
obpMWjp0m5ItgZ/UNsPLR/D4gFE9vZz7a4+FYQMa9Wbv+xaVxUS6z9rQCJfUQx7N
iih4etIvAafbfAnX6rFv8PwPzz+XvexPWWJxnbS4iV1LN2atrPDxqw73g5hc3W88
a0V2AVubtxhw9L2VK1VmRb/gnqsZpRXhDPSUIwIDAQABAoIBAQCMvnRLV80hudfC
mJh6YEvlgrfX/OVFmpFDVnVXHz2i5dugiHsXBS6HlIjzHlGLrEoHJTo19K/PscZJ
kEAcOYg2s5JLSY4PtcvTZDyr3tJSDdiPk8Z2zzOU0kkRy+lLyUv3cqKknlTu+PHR
daAFVCLoB4K4dqPKyq0nEuRgYgy7O42SPBY5DHgWYBKqkYGlTu+ImwpDD9unbv3e
mwvdcBCp9hAlYAArc1Ip/6aUkZdKxJYgVhovruaH309yuOmBfAEgguhsy3vR18t5
IZXbAF3C6iXCQXi8l+S1NUu8XWPLEavldb+ZA2hI2L+NPSBVIYqhI4jDiI7lfs1c
HE8BRsRpAoGBAO6BnK3qD8sRvg6JsrBhppoIGsudOdpZ/KVp9ZpYCBJNJmfrkqLR
bWx1KF2UjAoYUmaKDTS2GP8JQd7X2n4T5LX8q+7iG9/wzdSWZYZuBOnjvWlNyJu4
OiUKX4aEgdvZHiuEIin5xTP98/c5LTZXwM3bq8IrOXEz8LBLLPrTCGRvAoGBANKS
i3cn1jtVirJWbvhSIjjqhpfuZN0361FB6j1Aho+7z0WVd4NQjPQqA6cAqnWoa/kj
cX0X8Ncu5eHqf6CuW+HsQda3yp3bvCXi1Yc2nKBTHnWtMm721O4ZW6rbaALzBZYW
qeJr0m9pNlfCAL0INTcy7IVAtqcCJ/7CEN6Hjm2NAoGAIGSgKArDLFxziLvw9f29
R+xT31WyVtKj+r9iaR0Ns5ag4bpgBxcUmodq/RLA1lopTt3vHzqgOHtEZATDGx6O
kJ0JqP8ys/6bpgTrMw/cQPv6bMPwvB2QYBmBkd6LWJWrgFOI5FSVEROrv+cXGetf
N1ZfhJakTZi1VuxO5p4k5KcCgYAZS9OHR/jbfeZAkFOabzt/POVYYSIq1SnmxBVg
sFy57aTzxgXqd4XHWzi/GjxgEBCQiGp8zaB4KUEih6o3YlrVZC1wnvmvRxNuNbbT
HINqWzHgjyLs46gmxlMVzm/LUuiL5EMaWTuZeLk3h63RB6hk7jAtvd1zaLXnS+b8
5Kn+jQKBgQCDeMO6rvB2rbfqSbHvPPuTru1sPIsJBKm1YZpXTFI+VMjwtk7+meYb
UQnfZ1t5rjp9q4LEcRYuSa+PfifIkM6p+wMHVQhtltUCzXWWRYkLkmQrBWKu+qiP
edF6byMgXSzgOWYuRPXwmHpBQV0GiexQUAxVyUzaVWfil69LaFfXaw==
-----END RSA PRIVATE KEY-----
"""
self.assertTrue(provider.certificate_public_key)
def test_sca(self):
journal = self.AccountJournal.create(
{
"name": "Bank",
"type": "bank",
"code": "BANK",
"currency_id": self.currency_eur.id,
"bank_statements_source": "online",
"online_bank_statement_provider": "transferwise",
}
)
provider = journal.online_bank_statement_provider_id
provider.origin = "1234567891"
provider.password = "API_KEY"
provider.button_transferwise_generate_key()
with mock.patch(
"urllib.request.urlopen",
side_effect=[
self.response_balance,
self.response_ott,
self.response_transactions,
self.response_transactions,
self.response_transactions,
],
):
data = provider._obtain_statement_data(
self.now - relativedelta(hours=1),
self.now,
)
self.assertEqual(len(data[0]), 0)
self.assertEqual(data[1]["balance_start"], 42.0)
self.assertEqual(data[1]["balance_end_real"], 42.0)
def test_transaction_parse_1(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "CREDIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": 0.42,
"currency": "EUR"
},
"totalFees": {
"value": 0.00,
"currency": "EUR"
},
"details": {
"type": "DEPOSIT",
"description": "Received money from SENDER with reference REF-XYZ",
"senderName": "SENDER",
"senderAccount": "XX00 0000 0000 0000",
"paymentReference": "REF-XYZ"
},
"exchangeDetails": null,
"runningBalance": {
"value": 0.42,
"currency": "EUR"
},
"referenceNumber": "TRANSFER-123456789"
}"""
)
self.assertEqual(len(lines), 1)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"amount": "0.42",
"name": "REF-XYZ",
"note": (
"TRANSFER-123456789: Received money from SENDER with reference"
" REF-XYZ"
),
"partner_name": "SENDER",
"account_number": "XX00 0000 0000 0000",
"unique_import_id": "CREDIT-TRANSFER-123456789-946684800",
},
)
def test_transaction_parse_2(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "DEBIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": -200.60,
"currency": "EUR"
},
"totalFees": {
"value": 0.60,
"currency": "EUR"
},
"details": {
"type": "TRANSFER",
"description": "Sent money to John Doe",
"recipient": {
"name": "John Doe",
"bankAccount": "XX00 0000 0000 0000"
},
"paymentReference": "INVOICE 42-01"
},
"exchangeDetails": null,
"runningBalance": {
"value": 100.42,
"currency": "EUR"
},
"referenceNumber": "TRANSFER-123456789"
}"""
)
self.assertEqual(len(lines), 2)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"amount": "-200.00",
"name": "INVOICE 42-01",
"note": "TRANSFER-123456789: Sent money to John Doe",
"partner_name": "John Doe",
"account_number": "XX00 0000 0000 0000",
"unique_import_id": "DEBIT-TRANSFER-123456789-946684800",
},
)
self.assertEqual(
lines[1],
{
"date": datetime(2000, 1, 1),
"amount": "-0.60",
"name": "Fee for TRANSFER-123456789",
"note": "Transaction fee for TRANSFER-123456789",
"partner_name": "Wise (former TransferWise)",
"unique_import_id": "DEBIT-TRANSFER-123456789-946684800-FEE",
},
)
def test_transaction_parse_3(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "DEBIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": -123.45,
"currency": "USD"
},
"totalFees": {
"value": 0.00,
"currency": "USD"
},
"details": {
"type": "CARD",
"description":
"Card transaction of 1234.56 USD issued by Paypal *XX CITY",
"amount": {
"value": 1234.56,
"currency": "USD"
},
"category": "Professional Services not elsewh",
"merchant": {
"name": "Paypal *XX",
"firstLine": null,
"postCode": "12345",
"city": "CITY",
"state": null,
"country": "GB",
"category": "Professional Services not elsewh"
}
},
"exchangeDetails": null,
"runningBalance": {
"value": 0.00,
"currency": "USD"
},
"referenceNumber": "CARD-123456789"
}"""
)
self.assertEqual(len(lines), 1)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"amount": "-123.45",
"name": ("Card transaction of 1234.56 USD issued by Paypal *XX CITY"),
"note": (
"CARD-123456789: Card transaction of 1234.56 USD issued by "
"Paypal *XX CITY"
),
"partner_name": "Paypal *XX",
"unique_import_id": "DEBIT-CARD-123456789-946684800",
},
)
def test_transaction_parse_4(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "DEBIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": -456.78,
"currency": "EUR"
},
"totalFees": {
"value": 1.23,
"currency": "EUR"
},
"details": {
"type": "CARD",
"description":
"Card transaction of 1234.56 USD issued by Paypal *XX CITY",
"amount": {
"value": 1234.56,
"currency": "USD"
},
"category": "Professional Services not elsewh",
"merchant": {
"name": "Paypal *XX",
"firstLine": null,
"postCode": "12345",
"city": "CITY",
"state": null,
"country": "GB",
"category": "Professional Services not elsewh"
}
},
"exchangeDetails": {
"toAmount": {
"value": 567.89,
"currency": "USD"
},
"fromAmount": {
"value": 456.78,
"currency": "EUR"
},
"rate": 1.12260
},
"runningBalance": {
"value": 0.00,
"currency": "EUR"
},
"referenceNumber": "CARD-123456789"
}"""
)
self.assertEqual(len(lines), 2)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"amount": "-455.55",
"name": ("Card transaction of 1234.56 USD issued by Paypal *XX CITY"),
"note": (
"CARD-123456789: Card transaction of 1234.56 USD issued by"
" Paypal *XX CITY"
),
"partner_name": "Paypal *XX",
"unique_import_id": "DEBIT-CARD-123456789-946684800",
"amount_currency": "-567.89",
"currency_id": self.currency_usd.id,
},
)
self.assertEqual(
lines[1],
{
"date": datetime(2000, 1, 1),
"amount": "-1.23",
"name": "Fee for CARD-123456789",
"note": "Transaction fee for CARD-123456789",
"partner_name": "Wise (former TransferWise)",
"unique_import_id": "DEBIT-CARD-123456789-946684800-FEE",
},
)
def test_transaction_parse_5(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "DEBIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": -270.55,
"currency": "EUR"
},
"totalFees": {
"value": 5.21,
"currency": "EUR"
},
"details": {
"type": "TRANSFER",
"description": "Sent money to Jane Doe",
"recipient": {
"name": "Jane Doe",
"bankAccount": "(ADBCDEF) 0000000000000000"
},
"paymentReference": "Invoice A from DD MMM YYYY"
},
"exchangeDetails": {
"toAmount": {
"value": 297.00,
"currency": "USD"
},
"fromAmount": {
"value": 265.34,
"currency": "EUR"
},
"rate": 1.11930
},
"runningBalance": {
"value": 2360.43,
"currency": "EUR"
},
"referenceNumber": "TRANSFER-123456789"
}"""
)
self.assertEqual(len(lines), 2)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"name": "Invoice A from DD MMM YYYY",
"note": "TRANSFER-123456789: Sent money to Jane Doe",
"partner_name": "Jane Doe",
"account_number": "(ADBCDEF) 0000000000000000",
"amount": "-265.34",
"amount_currency": "-297.00",
"currency_id": self.currency_usd.id,
"unique_import_id": "DEBIT-TRANSFER-123456789-946684800",
},
)
self.assertEqual(
lines[1],
{
"date": datetime(2000, 1, 1),
"name": "Fee for TRANSFER-123456789",
"note": "Transaction fee for TRANSFER-123456789",
"partner_name": "Wise (former TransferWise)",
"amount": "-5.21",
"unique_import_id": "DEBIT-TRANSFER-123456789-946684800-FEE",
},
)
def test_transaction_parse_6(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "CREDIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": 5000.00,
"currency": "EUR"
},
"totalFees": {
"value": 0.00,
"currency": "EUR"
},
"details": {
"type": "MONEY_ADDED",
"description": "Topped up balance"
},
"exchangeDetails": null,
"runningBalance": {
"value": 7071.13,
"currency": "EUR"
},
"referenceNumber": "TRANSFER-123456789"
}"""
)
self.assertEqual(len(lines), 1)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"name": "Topped up balance",
"note": "TRANSFER-123456789: Topped up balance",
"amount": "5000.00",
"unique_import_id": "CREDIT-TRANSFER-123456789-946684800",
},
)
def test_transaction_parse_7(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "CREDIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": 6.93,
"currency": "EUR"
},
"totalFees": {
"value": 0.00,
"currency": "EUR"
},
"details": {
"type": "CONVERSION",
"description": "Converted 7.93 USD to 6.93 EUR",
"sourceAmount": {
"value": 7.93,
"currency": "USD"
},
"targetAmount": {
"value": 6.93,
"currency": "EUR"
},
"rate": 0.87944162
},
"exchangeDetails": {
"toAmount": {
"value": 6.93,
"currency": "EUR"
},
"fromAmount": {
"value": 7.93,
"currency": "USD"
},
"rate": 0.87944
},
"runningBalance": {
"value": 255.00,
"currency": "EUR"
},
"referenceNumber": "BALANCE-123456789"
}"""
)
self.assertEqual(len(lines), 1)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"name": "Converted 7.93 USD to 6.93 EUR",
"note": "BALANCE-123456789: Converted 7.93 USD to 6.93 EUR",
"amount": "6.93",
"amount_currency": "7.93",
"currency_id": self.currency_usd.id,
"unique_import_id": "CREDIT-BALANCE-123456789-946684800",
},
)
def test_transaction_parse_8(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "DEBIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": -7.93,
"currency": "USD"
},
"totalFees": {
"value": 0.05,
"currency": "USD"
},
"details": {
"type": "CONVERSION",
"description": "Converted 7.93 USD to 6.93 EUR",
"sourceAmount": {
"value": 7.93,
"currency": "USD"
},
"targetAmount": {
"value": 6.93,
"currency": "EUR"
},
"rate": 0.87944162
},
"exchangeDetails": {
"toAmount": {
"value": 6.93,
"currency": "EUR"
},
"fromAmount": {
"value": 7.93,
"currency": "USD"
},
"rate": 0.87944
},
"runningBalance": {
"value": 0.00,
"currency": "USD"
},
"referenceNumber": "BALANCE-123456789"
}"""
)
self.assertEqual(len(lines), 2)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"name": "Converted 7.93 USD to 6.93 EUR",
"note": "BALANCE-123456789: Converted 7.93 USD to 6.93 EUR",
"amount": "-7.88",
"amount_currency": "-6.93",
"currency_id": self.currency_eur.id,
"unique_import_id": "DEBIT-BALANCE-123456789-946684800",
},
)
self.assertEqual(
lines[1],
{
"date": datetime(2000, 1, 1),
"name": "Fee for BALANCE-123456789",
"note": "Transaction fee for BALANCE-123456789",
"amount": "-0.05",
"partner_name": "Wise (former TransferWise)",
"unique_import_id": "DEBIT-BALANCE-123456789-946684800-FEE",
},
)
def test_transaction_parse_9(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "CREDIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": 25.00,
"currency": "USD"
},
"totalFees": {
"value": 0.68,
"currency": "USD"
},
"details": {
"type": "MONEY_ADDED",
"description": "Topped up balance"
},
"exchangeDetails": null,
"runningBalance": {
"value": 25.68,
"currency": "USD"
},
"referenceNumber": "TRANSFER-123456789"
}"""
)
self.assertEqual(len(lines), 2)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"name": "Topped up balance",
"note": "TRANSFER-123456789: Topped up balance",
"amount": "25.68",
"unique_import_id": "CREDIT-TRANSFER-123456789-946684800",
},
)
self.assertEqual(
lines[1],
{
"date": datetime(2000, 1, 1),
"name": "Fee for TRANSFER-123456789",
"note": "Transaction fee for TRANSFER-123456789",
"amount": "-0.68",
"partner_name": "Wise (former TransferWise)",
"unique_import_id": "CREDIT-TRANSFER-123456789-946684800-FEE",
},
)
def test_transaction_parse_10(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "CREDIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": 1804.33,
"currency": "USD"
},
"totalFees": {
"value": 4.33,
"currency": "USD"
},
"details": {
"type": "TRANSFER",
"description": "Sent money to Acme Inc.",
"recipient": {
"name": "Acme Inc."
}
},
"exchangeDetails": null,
"runningBalance": {
"value": 1804.33,
"currency": "USD"
},
"referenceNumber": "TRANSFER-123456789"
}"""
)
self.assertEqual(len(lines), 2)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"name": "Sent money to Acme Inc.",
"note": "TRANSFER-123456789: Sent money to Acme Inc.",
"partner_name": "Acme Inc.",
"amount": "1800.00",
"unique_import_id": "CREDIT-TRANSFER-123456789-946684800",
},
)
self.assertEqual(
lines[1],
{
"date": datetime(2000, 1, 1),
"name": "Fee for TRANSFER-123456789",
"note": "Transaction fee for TRANSFER-123456789",
"amount": "4.33",
"partner_name": "Wise (former TransferWise)",
"unique_import_id": "CREDIT-TRANSFER-123456789-946684800-FEE",
},
)

View File

@@ -0,0 +1,881 @@
# Copyright 2019 Brainbean Apps (https://brainbeanapps.com)
# Copyright 2020-2021 CorporateHub (https://corporatehub.eu)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import json
from datetime import datetime
from decimal import Decimal
from unittest import mock
from urllib.error import HTTPError
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.tests import common
_module_ns = "odoo.addons.account_statement_import_online_wise"
_provider_class = (
_module_ns
+ ".models.online_bank_statement_provider_transferwise"
+ ".OnlineBankStatementProviderTransferwise"
)
class MockedResponse:
class Headers(dict):
def get_content_charset(self):
return None
def __init__(self, data=None, exception=None):
self.data = data
self.exception = exception
self.headers = MockedResponse.Headers()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
# pylint: disable=method-required-super
def read(self):
if self.exception is not None:
raise self.exception()
return self.data
class TestAccountBankAccountStatementImportOnlineTransferwise(common.TransactionCase):
def setUp(self):
super().setUp()
self.now = fields.Datetime.now()
self.currency_eur = self.env.ref("base.EUR")
self.currency_usd = self.env.ref("base.USD")
self.AccountJournal = self.env["account.journal"]
self.OnlineBankStatementProvider = self.env["online.bank.statement.provider"]
self.AccountBankStatement = self.env["account.bank.statement"]
self.AccountBankStatementLine = self.env["account.bank.statement.line"]
Provider = self.OnlineBankStatementProvider
self.transferwise_parse_transaction = lambda payload: (
Provider._transferwise_transaction_to_lines(
Provider._transferwise_preparse_transaction(
json.loads(
payload,
parse_float=Decimal,
)
)
)
)
self.response_balance = MockedResponse(
data=b"""[
{
"id": 42,
"balances": [
{
"currency": "EUR"
}
]
}
]"""
)
self.response_ott = MockedResponse(
exception=lambda: HTTPError(
"https://wise.com/",
403,
"403",
{"X-2FA-Approval-Result": "REJECTED", "X-2FA-Approval": "0123456789"},
None,
)
)
self.response_transactions = MockedResponse(
data=b"""{
"transactions": [],
"endOfStatementBalance": {
"value": 42.00,
"currency": "EUR"
}
}"""
)
def test_values_transferwise_profile(self):
mocked_response = json.loads(
"""[
{
"id": 1234567890,
"type": "personal",
"details": {
"firstName": "Alexey",
"lastName": "Pelykh"
}
},
{
"id": 1234567891,
"type": "business",
"details": {
"name": "Brainbean Apps OÜ"
}
}
]""",
parse_float=Decimal,
)
values_transferwise_profile = []
with mock.patch(
_provider_class + "._transferwise_retrieve",
return_value=mocked_response,
):
values_transferwise_profile = self.OnlineBankStatementProvider.with_context(
{"api_base": "https://example.com", "api_key": "dummy"}
).values_transferwise_profile()
self.assertEqual(
values_transferwise_profile,
[
("1234567890", "Alexey Pelykh (personal)"),
("1234567891", "Brainbean Apps OÜ"),
],
)
def test_values_transferwise_profile_no_key(self):
values_transferwise_profile = self.OnlineBankStatementProvider.with_context(
{"api_base": "https://example.com"}
).values_transferwise_profile()
self.assertEqual(values_transferwise_profile, [])
def test_values_transferwise_profile_error(self):
values_transferwise_profile = []
with mock.patch(
_provider_class + "._transferwise_retrieve",
side_effect=lambda: Exception(),
):
values_transferwise_profile = self.OnlineBankStatementProvider.with_context(
{"api_base": "https://example.com", "api_key": "dummy"}
).values_transferwise_profile()
self.assertEqual(values_transferwise_profile, [])
def test_pull(self):
journal = self.AccountJournal.create(
{
"name": "Bank",
"type": "bank",
"code": "BANK",
"currency_id": self.currency_eur.id,
"bank_statements_source": "online",
"online_bank_statement_provider": "transferwise",
}
)
provider = journal.online_bank_statement_provider_id
provider.origin = "1234567891"
def mock_response(url, api_key, private_key=None):
if "/borderless-accounts?profileId=1234567891" in url:
payload = """[
{
"id": 42,
"balances": [
{
"currency": "EUR"
}
]
}
]"""
elif "/borderless-accounts/42/statement.json" in url:
payload = """{
"transactions": [],
"endOfStatementBalance": {
"value": 42.00,
"currency": "EUR"
}
}"""
return json.loads(payload, parse_float=Decimal)
with mock.patch(
_provider_class + "._transferwise_retrieve",
side_effect=mock_response,
):
data = provider._obtain_statement_data(
self.now - relativedelta(hours=1),
self.now,
)
self.assertEqual(len(data[0]), 0)
self.assertEqual(data[1]["balance_start"], 42.0)
self.assertEqual(data[1]["balance_end_real"], 42.0)
def test_pull_no_data(self):
journal = self.AccountJournal.create(
{
"name": "Bank",
"type": "bank",
"code": "BANK",
"currency_id": self.currency_eur.id,
"bank_statements_source": "online",
"online_bank_statement_provider": "transferwise",
}
)
provider = journal.online_bank_statement_provider_id
provider.origin = "1234567891"
provider.password = "API_KEY"
with mock.patch(
_provider_class + "._transferwise_retrieve",
return_value=[],
):
data = provider._obtain_statement_data(
self.now - relativedelta(hours=1),
self.now,
)
self.assertFalse(data)
def test_update_public_key(self):
journal = self.AccountJournal.create(
{
"name": "Bank",
"type": "bank",
"code": "BANK",
"currency_id": self.currency_eur.id,
"bank_statements_source": "online",
"online_bank_statement_provider": "transferwise",
}
)
provider = journal.online_bank_statement_provider_id
provider.origin = "1234567891"
provider.password = "API_KEY"
with common.Form(provider) as provider_form:
provider_form.certificate_private_key = """
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAxC7aYWigCwPIB4mfyLpsALYPnqDm3/IC8I/3GdEwfK8eqXoF
sU1BHnVytFycBDEObmJ2Acpxe8Dk61FnbWPrrl6rXVnXfIRqfFl94TvgwFsuwG7u
8crncD6gPfe1QGkEykHcfBURr74OcSE8590ngNJcKMGvac0cuyZ2/NEszTw7EFJg
obpMWjp0m5ItgZ/UNsPLR/D4gFE9vZz7a4+FYQMa9Wbv+xaVxUS6z9rQCJfUQx7N
iih4etIvAafbfAnX6rFv8PwPzz+XvexPWWJxnbS4iV1LN2atrPDxqw73g5hc3W88
a0V2AVubtxhw9L2VK1VmRb/gnqsZpRXhDPSUIwIDAQABAoIBAQCMvnRLV80hudfC
mJh6YEvlgrfX/OVFmpFDVnVXHz2i5dugiHsXBS6HlIjzHlGLrEoHJTo19K/PscZJ
kEAcOYg2s5JLSY4PtcvTZDyr3tJSDdiPk8Z2zzOU0kkRy+lLyUv3cqKknlTu+PHR
daAFVCLoB4K4dqPKyq0nEuRgYgy7O42SPBY5DHgWYBKqkYGlTu+ImwpDD9unbv3e
mwvdcBCp9hAlYAArc1Ip/6aUkZdKxJYgVhovruaH309yuOmBfAEgguhsy3vR18t5
IZXbAF3C6iXCQXi8l+S1NUu8XWPLEavldb+ZA2hI2L+NPSBVIYqhI4jDiI7lfs1c
HE8BRsRpAoGBAO6BnK3qD8sRvg6JsrBhppoIGsudOdpZ/KVp9ZpYCBJNJmfrkqLR
bWx1KF2UjAoYUmaKDTS2GP8JQd7X2n4T5LX8q+7iG9/wzdSWZYZuBOnjvWlNyJu4
OiUKX4aEgdvZHiuEIin5xTP98/c5LTZXwM3bq8IrOXEz8LBLLPrTCGRvAoGBANKS
i3cn1jtVirJWbvhSIjjqhpfuZN0361FB6j1Aho+7z0WVd4NQjPQqA6cAqnWoa/kj
cX0X8Ncu5eHqf6CuW+HsQda3yp3bvCXi1Yc2nKBTHnWtMm721O4ZW6rbaALzBZYW
qeJr0m9pNlfCAL0INTcy7IVAtqcCJ/7CEN6Hjm2NAoGAIGSgKArDLFxziLvw9f29
R+xT31WyVtKj+r9iaR0Ns5ag4bpgBxcUmodq/RLA1lopTt3vHzqgOHtEZATDGx6O
kJ0JqP8ys/6bpgTrMw/cQPv6bMPwvB2QYBmBkd6LWJWrgFOI5FSVEROrv+cXGetf
N1ZfhJakTZi1VuxO5p4k5KcCgYAZS9OHR/jbfeZAkFOabzt/POVYYSIq1SnmxBVg
sFy57aTzxgXqd4XHWzi/GjxgEBCQiGp8zaB4KUEih6o3YlrVZC1wnvmvRxNuNbbT
HINqWzHgjyLs46gmxlMVzm/LUuiL5EMaWTuZeLk3h63RB6hk7jAtvd1zaLXnS+b8
5Kn+jQKBgQCDeMO6rvB2rbfqSbHvPPuTru1sPIsJBKm1YZpXTFI+VMjwtk7+meYb
UQnfZ1t5rjp9q4LEcRYuSa+PfifIkM6p+wMHVQhtltUCzXWWRYkLkmQrBWKu+qiP
edF6byMgXSzgOWYuRPXwmHpBQV0GiexQUAxVyUzaVWfil69LaFfXaw==
-----END RSA PRIVATE KEY-----
"""
self.assertTrue(provider.certificate_public_key)
def test_sca(self):
journal = self.AccountJournal.create(
{
"name": "Bank",
"type": "bank",
"code": "BANK",
"currency_id": self.currency_eur.id,
"bank_statements_source": "online",
"online_bank_statement_provider": "transferwise",
}
)
provider = journal.online_bank_statement_provider_id
provider.origin = "1234567891"
provider.password = "API_KEY"
provider.button_transferwise_generate_key()
with mock.patch(
"urllib.request.urlopen",
side_effect=[
self.response_balance,
self.response_ott,
self.response_transactions,
self.response_transactions,
self.response_transactions,
],
):
data = provider._obtain_statement_data(
self.now - relativedelta(hours=1),
self.now,
)
self.assertEqual(len(data[0]), 0)
self.assertEqual(data[1]["balance_start"], 42.0)
self.assertEqual(data[1]["balance_end_real"], 42.0)
def test_transaction_parse_1(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "CREDIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": 0.42,
"currency": "EUR"
},
"totalFees": {
"value": 0.00,
"currency": "EUR"
},
"details": {
"type": "DEPOSIT",
"description": "Received money from SENDER with reference REF-XYZ",
"senderName": "SENDER",
"senderAccount": "XX00 0000 0000 0000",
"paymentReference": "REF-XYZ"
},
"exchangeDetails": null,
"runningBalance": {
"value": 0.42,
"currency": "EUR"
},
"referenceNumber": "TRANSFER-123456789"
}"""
)
self.assertEqual(len(lines), 1)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"amount": "0.42",
"name": "REF-XYZ",
"payment_ref": (
"TRANSFER-123456789: Received money from SENDER with reference"
" REF-XYZ"
),
"partner_name": "SENDER",
"account_number": "XX00 0000 0000 0000",
"unique_import_id": "CREDIT-TRANSFER-123456789-946684800",
},
)
def test_transaction_parse_2(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "DEBIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": -200.60,
"currency": "EUR"
},
"totalFees": {
"value": 0.60,
"currency": "EUR"
},
"details": {
"type": "TRANSFER",
"description": "Sent money to John Doe",
"recipient": {
"name": "John Doe",
"bankAccount": "XX00 0000 0000 0000"
},
"paymentReference": "INVOICE 42-01"
},
"exchangeDetails": null,
"runningBalance": {
"value": 100.42,
"currency": "EUR"
},
"referenceNumber": "TRANSFER-123456789"
}"""
)
self.assertEqual(len(lines), 2)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"amount": "-200.00",
"name": "INVOICE 42-01",
"payment_ref": "TRANSFER-123456789: Sent money to John Doe",
"partner_name": "John Doe",
"account_number": "XX00 0000 0000 0000",
"unique_import_id": "DEBIT-TRANSFER-123456789-946684800",
},
)
self.assertEqual(
lines[1],
{
"date": datetime(2000, 1, 1),
"amount": "-0.60",
"name": "Fee for TRANSFER-123456789",
"payment_ref": "Transaction fee for TRANSFER-123456789",
"partner_name": "Wise (former TransferWise)",
"unique_import_id": "DEBIT-TRANSFER-123456789-946684800-FEE",
},
)
def test_transaction_parse_3(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "DEBIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": -123.45,
"currency": "USD"
},
"totalFees": {
"value": 0.00,
"currency": "USD"
},
"details": {
"type": "CARD",
"description":
"Card transaction of 1234.56 USD issued by Paypal *XX CITY",
"amount": {
"value": 1234.56,
"currency": "USD"
},
"category": "Professional Services not elsewh",
"merchant": {
"name": "Paypal *XX",
"firstLine": null,
"postCode": "12345",
"city": "CITY",
"state": null,
"country": "GB",
"category": "Professional Services not elsewh"
}
},
"exchangeDetails": null,
"runningBalance": {
"value": 0.00,
"currency": "USD"
},
"referenceNumber": "CARD-123456789"
}"""
)
self.assertEqual(len(lines), 1)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"amount": "-123.45",
"name": ("Card transaction of 1234.56 USD issued by Paypal *XX CITY"),
"payment_ref": (
"CARD-123456789: Card transaction of 1234.56 USD issued by "
"Paypal *XX CITY"
),
"partner_name": "Paypal *XX",
"unique_import_id": "DEBIT-CARD-123456789-946684800",
},
)
def test_transaction_parse_4(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "DEBIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": -456.78,
"currency": "EUR"
},
"totalFees": {
"value": 1.23,
"currency": "EUR"
},
"details": {
"type": "CARD",
"description":
"Card transaction of 1234.56 USD issued by Paypal *XX CITY",
"amount": {
"value": 1234.56,
"currency": "USD"
},
"category": "Professional Services not elsewh",
"merchant": {
"name": "Paypal *XX",
"firstLine": null,
"postCode": "12345",
"city": "CITY",
"state": null,
"country": "GB",
"category": "Professional Services not elsewh"
}
},
"exchangeDetails": {
"toAmount": {
"value": 567.89,
"currency": "USD"
},
"fromAmount": {
"value": 456.78,
"currency": "EUR"
},
"rate": 1.12260
},
"runningBalance": {
"value": 0.00,
"currency": "EUR"
},
"referenceNumber": "CARD-123456789"
}"""
)
self.assertEqual(len(lines), 2)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"amount": "-455.55",
"name": ("Card transaction of 1234.56 USD issued by Paypal *XX CITY"),
"payment_ref": (
"CARD-123456789: Card transaction of 1234.56 USD issued by"
" Paypal *XX CITY"
),
"partner_name": "Paypal *XX",
"unique_import_id": "DEBIT-CARD-123456789-946684800",
"amount_currency": "-567.89",
"currency_id": self.currency_usd.id,
},
)
self.assertEqual(
lines[1],
{
"date": datetime(2000, 1, 1),
"amount": "-1.23",
"name": "Fee for CARD-123456789",
"payment_ref": "Transaction fee for CARD-123456789",
"partner_name": "Wise (former TransferWise)",
"unique_import_id": "DEBIT-CARD-123456789-946684800-FEE",
},
)
def test_transaction_parse_5(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "DEBIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": -270.55,
"currency": "EUR"
},
"totalFees": {
"value": 5.21,
"currency": "EUR"
},
"details": {
"type": "TRANSFER",
"description": "Sent money to Jane Doe",
"recipient": {
"name": "Jane Doe",
"bankAccount": "(ADBCDEF) 0000000000000000"
},
"paymentReference": "Invoice A from DD MMM YYYY"
},
"exchangeDetails": {
"toAmount": {
"value": 297.00,
"currency": "USD"
},
"fromAmount": {
"value": 265.34,
"currency": "EUR"
},
"rate": 1.11930
},
"runningBalance": {
"value": 2360.43,
"currency": "EUR"
},
"referenceNumber": "TRANSFER-123456789"
}"""
)
self.assertEqual(len(lines), 2)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"name": "Invoice A from DD MMM YYYY",
"payment_ref": "TRANSFER-123456789: Sent money to Jane Doe",
"partner_name": "Jane Doe",
"account_number": "(ADBCDEF) 0000000000000000",
"amount": "-265.34",
"amount_currency": "-297.00",
"currency_id": self.currency_usd.id,
"unique_import_id": "DEBIT-TRANSFER-123456789-946684800",
},
)
self.assertEqual(
lines[1],
{
"date": datetime(2000, 1, 1),
"name": "Fee for TRANSFER-123456789",
"payment_ref": "Transaction fee for TRANSFER-123456789",
"partner_name": "Wise (former TransferWise)",
"amount": "-5.21",
"unique_import_id": "DEBIT-TRANSFER-123456789-946684800-FEE",
},
)
def test_transaction_parse_6(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "CREDIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": 5000.00,
"currency": "EUR"
},
"totalFees": {
"value": 0.00,
"currency": "EUR"
},
"details": {
"type": "MONEY_ADDED",
"description": "Topped up balance"
},
"exchangeDetails": null,
"runningBalance": {
"value": 7071.13,
"currency": "EUR"
},
"referenceNumber": "TRANSFER-123456789"
}"""
)
self.assertEqual(len(lines), 1)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"name": "Topped up balance",
"payment_ref": "TRANSFER-123456789: Topped up balance",
"amount": "5000.00",
"unique_import_id": "CREDIT-TRANSFER-123456789-946684800",
},
)
def test_transaction_parse_7(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "CREDIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": 6.93,
"currency": "EUR"
},
"totalFees": {
"value": 0.00,
"currency": "EUR"
},
"details": {
"type": "CONVERSION",
"description": "Converted 7.93 USD to 6.93 EUR",
"sourceAmount": {
"value": 7.93,
"currency": "USD"
},
"targetAmount": {
"value": 6.93,
"currency": "EUR"
},
"rate": 0.87944162
},
"exchangeDetails": {
"toAmount": {
"value": 6.93,
"currency": "EUR"
},
"fromAmount": {
"value": 7.93,
"currency": "USD"
},
"rate": 0.87944
},
"runningBalance": {
"value": 255.00,
"currency": "EUR"
},
"referenceNumber": "BALANCE-123456789"
}"""
)
self.assertEqual(len(lines), 1)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"name": "Converted 7.93 USD to 6.93 EUR",
"payment_ref": "BALANCE-123456789: Converted 7.93 USD to 6.93 EUR",
"amount": "6.93",
"amount_currency": "7.93",
"currency_id": self.currency_usd.id,
"unique_import_id": "CREDIT-BALANCE-123456789-946684800",
},
)
def test_transaction_parse_8(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "DEBIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": -7.93,
"currency": "USD"
},
"totalFees": {
"value": 0.05,
"currency": "USD"
},
"details": {
"type": "CONVERSION",
"description": "Converted 7.93 USD to 6.93 EUR",
"sourceAmount": {
"value": 7.93,
"currency": "USD"
},
"targetAmount": {
"value": 6.93,
"currency": "EUR"
},
"rate": 0.87944162
},
"exchangeDetails": {
"toAmount": {
"value": 6.93,
"currency": "EUR"
},
"fromAmount": {
"value": 7.93,
"currency": "USD"
},
"rate": 0.87944
},
"runningBalance": {
"value": 0.00,
"currency": "USD"
},
"referenceNumber": "BALANCE-123456789"
}"""
)
self.assertEqual(len(lines), 2)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"name": "Converted 7.93 USD to 6.93 EUR",
"payment_ref": "BALANCE-123456789: Converted 7.93 USD to 6.93 EUR",
"amount": "-7.88",
"amount_currency": "-6.93",
"currency_id": self.currency_eur.id,
"unique_import_id": "DEBIT-BALANCE-123456789-946684800",
},
)
self.assertEqual(
lines[1],
{
"date": datetime(2000, 1, 1),
"name": "Fee for BALANCE-123456789",
"payment_ref": "Transaction fee for BALANCE-123456789",
"amount": "-0.05",
"partner_name": "Wise (former TransferWise)",
"unique_import_id": "DEBIT-BALANCE-123456789-946684800-FEE",
},
)
def test_transaction_parse_9(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "CREDIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": 25.00,
"currency": "USD"
},
"totalFees": {
"value": 0.68,
"currency": "USD"
},
"details": {
"type": "MONEY_ADDED",
"description": "Topped up balance"
},
"exchangeDetails": null,
"runningBalance": {
"value": 25.68,
"currency": "USD"
},
"referenceNumber": "TRANSFER-123456789"
}"""
)
self.assertEqual(len(lines), 2)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"name": "Topped up balance",
"payment_ref": "TRANSFER-123456789: Topped up balance",
"amount": "25.68",
"unique_import_id": "CREDIT-TRANSFER-123456789-946684800",
},
)
self.assertEqual(
lines[1],
{
"date": datetime(2000, 1, 1),
"name": "Fee for TRANSFER-123456789",
"payment_ref": "Transaction fee for TRANSFER-123456789",
"amount": "-0.68",
"partner_name": "Wise (former TransferWise)",
"unique_import_id": "CREDIT-TRANSFER-123456789-946684800-FEE",
},
)
def test_transaction_parse_10(self):
lines = self.transferwise_parse_transaction(
"""{
"type": "CREDIT",
"date": "2000-01-01T00:00:00.000Z",
"amount": {
"value": 1804.33,
"currency": "USD"
},
"totalFees": {
"value": 4.33,
"currency": "USD"
},
"details": {
"type": "TRANSFER",
"description": "Sent money to Acme Inc.",
"recipient": {
"name": "Acme Inc."
}
},
"exchangeDetails": null,
"runningBalance": {
"value": 1804.33,
"currency": "USD"
},
"referenceNumber": "TRANSFER-123456789"
}"""
)
self.assertEqual(len(lines), 2)
self.assertEqual(
lines[0],
{
"date": datetime(2000, 1, 1),
"name": "Sent money to Acme Inc.",
"payment_ref": "TRANSFER-123456789: Sent money to Acme Inc.",
"partner_name": "Acme Inc.",
"amount": "1800.00",
"unique_import_id": "CREDIT-TRANSFER-123456789-946684800",
},
)
self.assertEqual(
lines[1],
{
"date": datetime(2000, 1, 1),
"name": "Fee for TRANSFER-123456789",
"payment_ref": "Transaction fee for TRANSFER-123456789",
"amount": "4.33",
"partner_name": "Wise (former TransferWise)",
"unique_import_id": "CREDIT-TRANSFER-123456789-946684800-FEE",
},
)

View File

@@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8" ?>
<!--
Copyright 2019 Brainbean Apps (https://brainbeanapps.com)
Copyright 2021 CorporateHub (https://corporatehub.eu)
License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
-->
<odoo>
<record model="ir.ui.view" id="online_bank_statement_provider_form">
<field name="name">online.bank.statement.provider.form</field>
<field name="model">online.bank.statement.provider</field>
<field
name="inherit_id"
ref="account_statement_import_online.online_bank_statement_provider_form"
/>
<field name="arch" type="xml">
<xpath expr="//sheet" position="inside">
<group attrs="{'invisible': [('service', '!=', 'transferwise')]}">
<group>
<field
name="api_base"
string="API base"
groups="base.group_no_one"
/>
<field
name="password"
string="API key"
password="True"
attrs="{'required': [('service', '=', 'transferwise')]}"
/>
</group>
<group>
<field
name="transferwise_profile"
string="Profile"
attrs="{'required': [('service', '=', 'transferwise')]}"
widget="dynamic_dropdown"
values="values_transferwise_profile"
context="{'api_key': password, 'api_base': api_base}"
/>
</group>
<group string="Strong Customer Authentication" colspan="4">
<field
name="certificate_private_key"
string="Private key"
password="True"
/>
<field name="certificate_public_key" string="Public key" />
<div col="2" colspan="2">
<button
name="button_transferwise_generate_key"
title="Generate Key"
type="object"
class="oe_edit_only"
/>
</div>
</group>
</group>
</xpath>
</field>
</record>
</odoo>

View File

@@ -1,4 +1,5 @@
# generated from manifests external_dependencies # generated from manifests external_dependencies
chardet chardet
cryptography
ofxparse ofxparse
xlrd xlrd

View File

@@ -0,0 +1 @@
../../../../account_statement_import_online_wise

View File

@@ -0,0 +1,6 @@
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)