Skip to content

Commit

Permalink
Merge pull request #1 from akretion/10.0-mig-currency_rate_update-sma…
Browse files Browse the repository at this point in the history
…ll_mig_improvements

10.0 Improve your PR to port currency_rate_update to v10
  • Loading branch information
nikiwaibel committed Dec 6, 2016
2 parents 39c116a + 945d00c commit 46cc038
Show file tree
Hide file tree
Showing 17 changed files with 245 additions and 237 deletions.
27 changes: 12 additions & 15 deletions currency_rate_update/README.rst
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
.. image:: https://img.shields.io/badge/licence-AGPL--3-blue.svg
:alt: License
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
:alt: License: AGPL-3

====================
Currency Rate Update
====================

Import exchange rates from the Internet.
Download exchange rates automatically from the Internet.

The module is able to use the following sources:

Expand Down Expand Up @@ -38,13 +40,11 @@ The module is able to use the following sources:
Configuration
=============

The update can be set under the company form.
You can set for each services which currency you want to update.
The logs of the update are visible under the service note.
You can active or deactivate the update.
The module uses internal ir-cron feature from Odoo, so the job is
launched once the server starts if the 'first execute date' is before
the current day.
To configure the module, go to *Accounting > Configuration > Multi-currencies > Rate Auto-download* and create one or several services to download rates from the Internet.

Then, go to the page *Accounting > Configuration > Settings* and, in the section *Multi Currencies*, make sure that the option *Automatic Currency Rates Download* is enabled.

In developper mode, in the menu *Settings > Technical > Scheduled Actions*, make sure that the action *Currency Rate Update* is active. If you want to run it immediately, use the button *Run Manually*.

Usage
=====
Expand Down Expand Up @@ -72,15 +72,13 @@ Roadmap:
* Updated daily from Citibank N.A., source in EUR. Information may be delayed.
This is parsed from an HTML page, so it may be broken at anytime.


Bug Tracker
===========

Bugs are tracked on `GitHub Issues <https://github.com/OCA/account-financial-tools/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.


Credits
=======

Expand Down Expand Up @@ -108,18 +106,17 @@ Contributors
* Daniel Dico <ddico@oerp.ca> (BOC)
* Dmytro Katyukha <firemage.dima@gmail.com>


Maintainer
----------

.. image:: http://odoo-community.org/logo.png
.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: http://odoo-community.org
:target: https://odoo-community.org

This module is maintained by the OCA.

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.

To contribute to this module, please visit http://odoo-community.org.
To contribute to this module, please visit https://odoo-community.org.
4 changes: 3 additions & 1 deletion currency_rate_update/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
from . import model
# -*- coding: utf-8 -*-

from . import models
from .services.currency_getter_interface import CurrencyGetterInterface
8 changes: 3 additions & 5 deletions currency_rate_update/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,11 @@
"account", # Added to ensure account security groups are present
],
"data": [
"view/service_cron_data.xml",
"view/currency_rate_update.xml",
"view/company_view.xml",
"data/cron.xml",
"views/currency_rate_update.xml",
"views/account_config_settings.xml",
"security/rule.xml",
"security/ir.model.access.csv",
],
"images": [],
"demo": [],
'installable': True
}
File renamed without changes.
2 changes: 0 additions & 2 deletions currency_rate_update/model/__init__.py

This file was deleted.

27 changes: 0 additions & 27 deletions currency_rate_update/model/company.py

This file was deleted.

5 changes: 5 additions & 0 deletions currency_rate_update/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# -*- coding: utf-8 -*-

from . import currency_rate_update
from . import company
from . import account_config_settings
12 changes: 12 additions & 0 deletions currency_rate_update/models/account_config_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# -*- coding: utf-8 -*-
# © 2016 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from odoo import models, fields


class AccountConfigSettings(models.TransientModel):
_inherit = 'account.config.settings'

auto_currency_up = fields.Boolean(
related='company_id.auto_currency_up')
14 changes: 14 additions & 0 deletions currency_rate_update/models/company.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-
# © 2009-2016 Camptocamp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import models, fields


class ResCompany(models.Model):
_inherit = "res.company"

# Activate the currency update
auto_currency_up = fields.Boolean(
string='Automatic Currency Rates Download', default=True,
help="Automatic download of currency rates for this company")
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
from dateutil.relativedelta import relativedelta

from odoo import models, fields, api, _
from odoo import exceptions
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_compare


from ..services.currency_getter_interface import CurrencyGetterType

Expand All @@ -29,17 +31,20 @@ class CurrencyRateUpdateService(models.Model):
_name = "currency.rate.update.service"
_description = "Currency Rate Update"

@api.one
@api.multi
@api.constrains('max_delta_days')
def _check_max_delta_days(self):
if self.max_delta_days < 0:
raise exceptions.Warning(_('Max delta days must be >= 0'))
for srv in self:
if srv.max_delta_days < 0:
raise ValidationError(_(
'Max delta days must be >= 0'))

@api.one
@api.multi
@api.constrains('interval_number')
def _check_interval_number(self):
if self.interval_number < 0:
raise exceptions.Warning(_('Interval number must be >= 0'))
for srv in self:
if srv.interval_number < 0:
raise ValidationError(_('Interval number must be >= 0'))

@api.onchange('interval_number')
def _onchange_interval_number(self):
Expand Down Expand Up @@ -74,6 +79,10 @@ def _selection_service(self, *a, **k):
'service_id',
'currency_id',
string='Currencies available')
# I can't just put readonly=True in the field above because I need
# it as r+w for the on_change to work
currency_list_readonly = fields.Many2many(
related='currency_list', readonly=True)
# List of currency to update
currency_to_update = fields.Many2many('res.currency',
'res_currency_auto_update_rel',
Expand All @@ -83,7 +92,7 @@ def _selection_service(self, *a, **k):
'this service')
# Link with company
company_id = fields.Many2one(
'res.company', 'Company',
'res.company', 'Company', required=True,
default=lambda self: self.env['res.company']._company_default_get(
'currency.rate.update.service'))
# Note fileds that will be used as a logger
Expand All @@ -92,7 +101,7 @@ def _selection_service(self, *a, **k):
string='Max delta days', default=4, required=True,
help="If the time delta between the rate date given by the "
"webservice and the current date exceeds this value, "
"then the currency rate is not updated in OpenERP.")
"then the currency rate is not updated in Odoo.")
interval_type = fields.Selection([
('days', 'Day(s)'),
('weeks', 'Week(s)'),
Expand All @@ -107,81 +116,87 @@ def _selection_service(self, *a, **k):
_('You can use a service only one time per '
'company !'))]

@api.one
@api.multi
def refresh_currency(self):
"""Refresh the currencies rates !!for all companies now"""
_logger.info(
'Starting to refresh currencies with service %s (company: %s)',
self.service, self.company_id.name)
rate_obj = self.env['res.currency.rate']
company = self.company_id
# The multi company currency can be set or no so we handle
# The two case
if company.auto_currency_up:
main_currency = self.company_id.currency_id
if not main_currency:
raise exceptions.Warning(_('There is no main '
'currency defined!'))
if main_currency.rate != 1:
raise exceptions.Warning(_('Base currency rate should '
'be 1.00!'))
note = self.note or ''
try:
# We initalize the class that will handle the request
# and return a dict of rate
getter = CurrencyGetterType.get(self.service)
curr_to_fetch = [x.name for x in self.currency_to_update]
res, log_info = getter.get_updated_currency(
curr_to_fetch,
main_currency.name,
self.max_delta_days
for srv in self:
_logger.info(
'Starting to refresh currencies with service %s (company: %s)',
srv.service, srv.company_id.name)
company = srv.company_id
# The multi company currency can be set or no so we handle
# The two case
if company.auto_currency_up:
main_currency = company.currency_id
# No need to test if main_currency exists, because it is a
# required field
if float_compare(
main_currency.rate, 1,
precision_rounding=main_currency.rounding):
raise UserError(_(
"In company '%s', the rate of the main currency (%s) "
"must be 1.00 (current rate: %s).") % (
company.name,
main_currency.name,
main_currency.rate))
note = srv.note or ''
try:
# We initalize the class that will handle the request
# and return a dict of rate
getter = CurrencyGetterType.get(srv.service)
curr_to_fetch = [x.name for x in srv.currency_to_update]
res, log_info = getter.get_updated_currency(
curr_to_fetch,
main_currency.name,
srv.max_delta_days
)
rate_name = \
fields.Datetime.to_string(datetime.utcnow().replace(
hour=0, minute=0, second=0, microsecond=0))
for curr in srv.currency_to_update:
if curr == main_currency:
continue
do_create = True
for rate in curr.rate_ids:
if rate.name == rate_name:
rate.rate = res[curr.name]
do_create = False
break
if do_create:
vals = {
'currency_id': curr.id,
'rate': res[curr.name],
'name': rate_name
}
rate_obj.create(vals)
_logger.info(
'Updated currency %s via service %s',
curr.name, srv.service)

# Show the most recent note at the top
msg = '%s \n%s currency updated. %s' % (
log_info or '',
fields.Datetime.to_string(datetime.today()),
note
)
srv.write({'note': msg})
except Exception as exc:
error_msg = '\n%s ERROR: %s %s' % (
fields.Datetime.to_string(datetime.today()),
repr(exc),
note
)
rate_name = \
fields.Datetime.to_string(datetime.utcnow().replace(
hour=0, minute=0, second=0, microsecond=0))
for curr in self.currency_to_update:
if curr.id == main_currency.id:
continue
do_create = True
for rate in curr.rate_ids:
if rate.name == rate_name:
rate.rate = res[curr.name]
do_create = False
break
if do_create:
vals = {
'currency_id': curr.id,
'rate': res[curr.name],
'name': rate_name
}
rate_obj.create(vals)
_logger.info(
'Updated currency %s via service %s',
curr.name, self.service)

# Show the most recent note at the top
msg = '%s \n%s currency updated. %s' % (
log_info or '',
fields.Datetime.to_string(datetime.today()),
note
)
self.write({'note': msg})
except Exception as exc:
error_msg = '\n%s ERROR : %s %s' % (
fields.Datetime.to_string(datetime.today()),
repr(exc),
note
)
_logger.error(repr(exc))
self.write({'note': error_msg})
if self._context.get('cron', False):
midnight = time(0, 0)
next_run = (datetime.combine(
fields.Date.from_string(self.next_run),
midnight) +
_intervalTypes[str(self.interval_type)]
(self.interval_number)).date()
self.next_run = next_run
_logger.error(repr(exc))
srv.write({'note': error_msg})
if self._context.get('cron'):
midnight = time(0, 0)
next_run = (datetime.combine(
fields.Date.from_string(srv.next_run),
midnight) +
_intervalTypes[str(srv.interval_type)]
(srv.interval_number)).date()
srv.next_run = next_run
return True

@api.multi
Expand Down
Loading

0 comments on commit 46cc038

Please sign in to comment.