[IMP] account_bank_statement_import_online_qonto: black, isort, prettier

This commit is contained in:
Pedro M. Baeza
2022-04-10 15:56:13 +02:00
parent 70ed8e7e30
commit dba95fb13f
6 changed files with 182 additions and 159 deletions

View File

@@ -8,7 +8,5 @@
"license": "AGPL-3", "license": "AGPL-3",
"installable": True, "installable": True,
"depends": ["account_bank_statement_import_online"], "depends": ["account_bank_statement_import_online"],
"data": [ "data": ["view/online_bank_statement_provider.xml"],
"view/online_bank_statement_provider.xml"
],
} }

View File

@@ -1,43 +1,39 @@
# Copyright 2020 Florent de Labarre # Copyright 2020 Florent de Labarre
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import requests
import json import json
from datetime import datetime from datetime import datetime
import pytz
from odoo import api, models, _ import pytz
import requests
from odoo import _, api, models
from odoo.exceptions import UserError from odoo.exceptions import UserError
from odoo.addons.base.models.res_bank import sanitize_account_number from odoo.addons.base.models.res_bank import sanitize_account_number
QONTO_ENDPOINT = 'https://thirdparty.qonto.eu/v2' QONTO_ENDPOINT = "https://thirdparty.qonto.eu/v2"
class OnlineBankStatementProviderQonto(models.Model): class OnlineBankStatementProviderQonto(models.Model):
_inherit = 'online.bank.statement.provider' _inherit = "online.bank.statement.provider"
@api.model @api.model
def _get_available_services(self): def _get_available_services(self):
return super()._get_available_services() + [ return super()._get_available_services() + [
('qonto', 'Qonto.eu'), ("qonto", "Qonto.eu"),
] ]
def _obtain_statement_data(self, date_since, date_until): def _obtain_statement_data(self, date_since, date_until):
self.ensure_one() self.ensure_one()
if self.service != 'qonto': if self.service != "qonto":
return super()._obtain_statement_data( return super()._obtain_statement_data(date_since, date_until,)
date_since,
date_until,
)
return self._qonto_obtain_statement_data(date_since, date_until) return self._qonto_obtain_statement_data(date_since, date_until)
def _get_statement_date(self, date_since, date_until): def _get_statement_date(self, date_since, date_until):
self.ensure_one() self.ensure_one()
if self.service != 'qonto': if self.service != "qonto":
return super()._get_statement_date( return super()._get_statement_date(date_since, date_until,)
date_since, return date_since.astimezone(pytz.timezone("Europe/Paris")).date()
date_until,
)
return date_since.astimezone(pytz.timezone('Europe/Paris')).date()
######### #########
# qonto # # qonto #
@@ -46,85 +42,94 @@ class OnlineBankStatementProviderQonto(models.Model):
def _qonto_header(self): def _qonto_header(self):
self.ensure_one() self.ensure_one()
if self.username and self.password: if self.username and self.password:
return {'Authorization': '%s:%s' % (self.username, self.password)} return {"Authorization": "{}:{}".format(self.username, self.password)}
raise UserError(_('Please fill login and key')) raise UserError(_("Please fill login and key"))
def _qonto_get_slug(self): def _qonto_get_slug(self):
self.ensure_one() self.ensure_one()
url = QONTO_ENDPOINT + '/organizations/%7Bid%7D' url = QONTO_ENDPOINT + "/organizations/%7Bid%7D"
response = requests.get(url, verify=False, headers=self._qonto_header()) response = requests.get(url, verify=False, headers=self._qonto_header())
if response.status_code == 200: if response.status_code == 200:
data = json.loads(response.text) data = json.loads(response.text)
res = {} res = {}
for account in data.get('organization', {}).get('bank_accounts', []): for account in data.get("organization", {}).get("bank_accounts", []):
iban = sanitize_account_number(account.get('iban', '')) iban = sanitize_account_number(account.get("iban", ""))
res[iban] = account.get('slug') res[iban] = account.get("slug")
return res return res
raise UserError(_('%s \n\n %s') % (response.status_code, response.text)) raise UserError(_("%s \n\n %s") % (response.status_code, response.text))
def _qonto_obtain_transactions(self, slug, date_since, date_until): def _qonto_obtain_transactions(self, slug, date_since, date_until):
self.ensure_one() self.ensure_one()
url = QONTO_ENDPOINT + '/transactions' url = QONTO_ENDPOINT + "/transactions"
params = {'slug': slug, 'iban': self.account_number} params = {"slug": slug, "iban": self.account_number}
if date_since: if date_since:
params['settled_at_from'] = date_since.replace( params["settled_at_from"] = (
microsecond=0).isoformat() + 'Z' date_since.replace(microsecond=0).isoformat() + "Z"
)
if date_until: if date_until:
params['settled_at_to'] = date_until.replace( params["settled_at_to"] = (
microsecond=0).isoformat() + 'Z' date_until.replace(microsecond=0).isoformat() + "Z"
)
transactions = [] transactions = []
current_page = 1 current_page = 1
total_pages = 1 total_pages = 1
while current_page <= total_pages: while current_page <= total_pages:
params['current_page'] = current_page params["current_page"] = current_page
data = self._qonto_get_transactions(url, params) data = self._qonto_get_transactions(url, params)
transactions.extend(data.get('transactions', [])) transactions.extend(data.get("transactions", []))
total_pages = data['meta']['total_pages'] total_pages = data["meta"]["total_pages"]
current_page += 1 current_page += 1
return transactions return transactions
def _qonto_get_transactions(self, url, params): def _qonto_get_transactions(self, url, params):
response = requests.get(url, verify=False, params=params, response = requests.get(
headers=self._qonto_header()) url, verify=False, params=params, headers=self._qonto_header()
)
if response.status_code == 200: if response.status_code == 200:
return json.loads(response.text) return json.loads(response.text)
raise UserError(_('%s \n\n %s') % (response.status_code, response.text)) raise UserError(_("%s \n\n %s") % (response.status_code, response.text))
def _qonto_prepare_statement_line( def _qonto_prepare_statement_line(
self, transaction, sequence, journal_currency, currencies_code2id): self, transaction, sequence, journal_currency, currencies_code2id
date = datetime.strptime(transaction['settled_at'], '%Y-%m-%dT%H:%M:%S.%fZ') ):
side = 1 if transaction['side'] == 'credit' else -1 date = datetime.strptime(transaction["settled_at"], "%Y-%m-%dT%H:%M:%S.%fZ")
name = transaction['label'] or '/' side = 1 if transaction["side"] == "credit" else -1
if transaction['reference']: name = transaction["label"] or "/"
name = '%s %s' % (name, transaction['reference']) if transaction["reference"]:
name = "{} {}".format(name, transaction["reference"])
vals_line = { vals_line = {
'sequence': sequence, "sequence": sequence,
'date': date, "date": date,
'name': name, "name": name,
'ref': transaction['reference'], "ref": transaction["reference"],
'unique_import_id': transaction['transaction_id'], "unique_import_id": transaction["transaction_id"],
'amount': transaction['amount'] * side, "amount": transaction["amount"] * side,
} }
if not transaction['local_currency']: if not transaction["local_currency"]:
raise UserError(_( raise UserError(
_(
"Transaction ID %s has not local_currency. " "Transaction ID %s has not local_currency. "
"This should never happen.") % transaction['transaction_id']) "This should never happen."
if transaction['local_currency'] not in currencies_code2id: )
raise UserError(_( % transaction["transaction_id"]
"Currency %s used in transaction ID %s doesn't exist " )
"in Odoo.") % ( if transaction["local_currency"] not in currencies_code2id:
transaction['local_currency'], raise UserError(
transaction['transaction_id'])) _("Currency %s used in transaction ID %s doesn't exist " "in Odoo.")
% (transaction["local_currency"], transaction["transaction_id"])
)
line_currency_id = currencies_code2id[transaction['local_currency']] line_currency_id = currencies_code2id[transaction["local_currency"]]
if journal_currency.id != line_currency_id: if journal_currency.id != line_currency_id:
vals_line.update({ vals_line.update(
'currency_id': line_currency_id, {
'amount_currency': transaction['local_amount'] * side, "currency_id": line_currency_id,
}) "amount_currency": transaction["local_amount"] * side,
}
)
return vals_line return vals_line
def _qonto_obtain_statement_data(self, date_since, date_until): def _qonto_obtain_statement_data(self, date_since, date_until):
@@ -135,21 +140,23 @@ class OnlineBankStatementProviderQonto(models.Model):
slug = slugs.get(self.account_number) slug = slugs.get(self.account_number)
if not slug: if not slug:
raise UserError( raise UserError(
_('Qonto : wrong configuration, unknow account %s') _("Qonto : wrong configuration, unknow account %s")
% journal.bank_account_id.acc_number) % journal.bank_account_id.acc_number
)
transactions = self._qonto_obtain_transactions(slug, date_since, date_until) transactions = self._qonto_obtain_transactions(slug, date_since, date_until)
journal_currency = journal.currency_id or journal.company_id.currency_id journal_currency = journal.currency_id or journal.company_id.currency_id
all_currencies = self.env['res.currency'].search_read([], ['name']) all_currencies = self.env["res.currency"].search_read([], ["name"])
currencies_code2id = dict([(x['name'], x['id']) for x in all_currencies]) currencies_code2id = {x["name"]: x["id"] for x in all_currencies}
new_transactions = [] new_transactions = []
sequence = 0 sequence = 0
for transaction in transactions: for transaction in transactions:
sequence += 1 sequence += 1
vals_line = self._qonto_prepare_statement_line( vals_line = self._qonto_prepare_statement_line(
transaction, sequence, journal_currency, currencies_code2id) transaction, sequence, journal_currency, currencies_code2id
)
new_transactions.append(vals_line) new_transactions.append(vals_line)
if new_transactions: if new_transactions:

View File

@@ -7,55 +7,56 @@ from unittest import mock
from odoo import fields from odoo import fields
from odoo.tests import common from odoo.tests import common
_module_ns = 'odoo.addons.account_bank_statement_import_online_qonto' _module_ns = "odoo.addons.account_bank_statement_import_online_qonto"
_provider_class = ( _provider_class = (
_module_ns _module_ns
+ '.models.online_bank_statement_provider_qonto' + ".models.online_bank_statement_provider_qonto"
+ '.OnlineBankStatementProviderQonto' + ".OnlineBankStatementProviderQonto"
) )
class TestAccountBankAccountStatementImportOnlineQonto( class TestAccountBankAccountStatementImportOnlineQonto(common.TransactionCase):
common.TransactionCase
):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.now = fields.Datetime.now() self.now = fields.Datetime.now()
self.currency_eur = self.env.ref('base.EUR') self.currency_eur = self.env.ref("base.EUR")
self.currency_usd = self.env.ref('base.USD') self.currency_usd = self.env.ref("base.USD")
self.AccountJournal = self.env['account.journal'] self.AccountJournal = self.env["account.journal"]
self.ResPartnerBank = self.env['res.partner.bank'] self.ResPartnerBank = self.env["res.partner.bank"]
self.OnlineBankStatementProvider = self.env[ self.OnlineBankStatementProvider = self.env["online.bank.statement.provider"]
'online.bank.statement.provider' self.AccountBankStatement = self.env["account.bank.statement"]
] self.AccountBankStatementLine = self.env["account.bank.statement.line"]
self.AccountBankStatement = self.env['account.bank.statement']
self.AccountBankStatementLine = self.env['account.bank.statement.line']
self.bank_account = self.ResPartnerBank.create( self.bank_account = self.ResPartnerBank.create(
{'acc_number': 'FR0214508000302245362775K46', {
'partner_id': self.env.user.company_id.partner_id.id}) "acc_number": "FR0214508000302245362775K46",
self.journal = self.AccountJournal.create({ "partner_id": self.env.user.company_id.partner_id.id,
'name': 'Bank', }
'type': 'bank', )
'code': 'BANK', self.journal = self.AccountJournal.create(
'currency_id': self.currency_eur.id, {
'bank_statements_source': 'online', "name": "Bank",
'online_bank_statement_provider': 'qonto', "type": "bank",
'bank_account_id': self.bank_account.id, "code": "BANK",
}) "currency_id": self.currency_eur.id,
"bank_statements_source": "online",
"online_bank_statement_provider": "qonto",
"bank_account_id": self.bank_account.id,
}
)
self.provider = self.journal.online_bank_statement_provider_id self.provider = self.journal.online_bank_statement_provider_id
self.mock_slug = lambda: mock.patch( self.mock_slug = lambda: mock.patch(
_provider_class + '._qonto_get_slug', _provider_class + "._qonto_get_slug",
return_value={'FR0214508000302245362775K46': 'qonto-1234-bank-account-1'}, return_value={"FR0214508000302245362775K46": "qonto-1234-bank-account-1"},
) )
self.mock_transaction = lambda: mock.patch( self.mock_transaction = lambda: mock.patch(
_provider_class + '._qonto_get_transactions', _provider_class + "._qonto_get_transactions",
return_value={ return_value={
"transactions": [ "transactions": [
{"transaction_id": "qonto-1234-1-transaction-3", {
"transaction_id": "qonto-1234-1-transaction-3",
"amount": 1200.0, "amount": 1200.0,
"amount_cents": 120000, "amount_cents": 120000,
"attachment_ids": [], "attachment_ids": [],
@@ -78,9 +79,12 @@ class TestAccountBankAccountStatementImportOnlineQonto(
"initiator_id": None, "initiator_id": None,
"label_ids": [], "label_ids": [],
"attachment_lost": False, "attachment_lost": False,
"attachment_required": True}, "attachment_required": True,
{"transaction_id": "qonto-1234-1-transaction-2", },
"amount": 1128.36, "amount_cents": 112836, {
"transaction_id": "qonto-1234-1-transaction-2",
"amount": 1128.36,
"amount_cents": 112836,
"attachment_ids": [], "attachment_ids": [],
"local_amount": 1128.36, "local_amount": 1128.36,
"local_amount_cents": 112836, "local_amount_cents": 112836,
@@ -101,20 +105,24 @@ class TestAccountBankAccountStatementImportOnlineQonto(
"initiator_id": "9b783957-85a6-404a-8320-a298781cb5fa", "initiator_id": "9b783957-85a6-404a-8320-a298781cb5fa",
"label_ids": [], "label_ids": [],
"attachment_lost": False, "attachment_lost": False,
"attachment_required": True}], "attachment_required": True,
"meta": {"current_page": 1, },
],
"meta": {
"current_page": 1,
"next_page": None, "next_page": None,
"prev_page": None, "prev_page": None,
"total_pages": 1, "total_pages": 1,
"total_count": 2, "total_count": 2,
"per_page": 100}}, "per_page": 100,
},
},
) )
def test_qonto(self): def test_qonto(self):
with self.mock_transaction(), self.mock_slug(): with self.mock_transaction(), self.mock_slug():
lines, statement_values = self.provider._obtain_statement_data( lines, statement_values = self.provider._obtain_statement_data(
datetime(2020, 4, 15), datetime(2020, 4, 15), datetime(2020, 4, 17),
datetime(2020, 4, 17),
) )
self.assertEqual(len(lines), 2) self.assertEqual(len(lines), 2)

View File

@@ -3,7 +3,10 @@
<record model="ir.ui.view" id="online_bank_statement_provider_form"> <record model="ir.ui.view" id="online_bank_statement_provider_form">
<field name="name">online.bank.statement.provider.form</field> <field name="name">online.bank.statement.provider.form</field>
<field name="model">online.bank.statement.provider</field> <field name="model">online.bank.statement.provider</field>
<field name="inherit_id" ref="account_bank_statement_import_online.online_bank_statement_provider_form"/> <field
name="inherit_id"
ref="account_bank_statement_import_online.online_bank_statement_provider_form"
/>
<field name="arch" type="xml"> <field name="arch" type="xml">
<xpath expr="//page[@name='configuration']" position="inside"> <xpath expr="//page[@name='configuration']" position="inside">
<group name="qonto" attrs="{'invisible':[('service','!=','qonto')]}"> <group name="qonto" attrs="{'invisible':[('service','!=','qonto')]}">

View File

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

View File

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