Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions altinkaya_reports/report/account_invoice_report.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from odoo import models, fields, api, tools

from datetime import datetime

class AccountInvoice(models.Model):
_inherit = 'account.invoice'
Expand Down Expand Up @@ -28,15 +28,17 @@ class AccountInvoiceReport(models.Model):
source_id = fields.Many2one('utm.source', string='Marketing Source', readonly=True)
campaign_id = fields.Many2one('utm.campaign', string='Marketing Campaign', readonly=True)
month_nr = fields.Char('Ay No', readonly=True)
customer_create_date = fields.Date(string='Customer Create Date', readonly=True)
medium_id = fields.Many2one('utm.medium', string='Marketing Medium', readonly=True)

def _select(self):
return super(AccountInvoiceReport, self)._select() + \
", sub.state_id, sub.total_tax as total_tax, sub.price_total_usd as price_total_usd, sub.price_average_usd as price_average_usd, sub.source_id as source_id, sub.campaign_id as campaign_id, sub.month_nr as month_nr"
", sub.state_id, sub.total_tax as total_tax, sub.price_total_usd as price_total_usd, sub.price_average_usd as price_average_usd, sub.source_id as source_id, sub.campaign_id as campaign_id, sub.month_nr as month_nr, sub.customer_create_date as customer_create_date, sub.medium_id as medium_id"

def _sub_select(self):
return super(AccountInvoiceReport, self)._sub_select() + \
""", coalesce(partner.state_id, partner_ai.state_id) AS state_id,
partner.source_id,partner.campaign_id,
partner.source_id,partner.campaign_id,partner.medium_id,
to_char(ai.date_invoice, 'MM') AS month_nr,
SUM(ail.price_subtotal_signed * invoice_type.sign * ai.usd_rate) AS price_total_usd,
ail.kdv_amount as total_tax,
Expand All @@ -47,5 +49,5 @@ def _sub_select(self):
END AS price_average_usd"""

def _group_by(self):
return super(AccountInvoiceReport, self)._group_by() + ", coalesce(partner.state_id, partner_ai.state_id),partner.source_id,partner.campaign_id,month_nr"
return super(AccountInvoiceReport, self)._group_by() + ", coalesce(partner.state_id, partner_ai.state_id),partner.source_id,partner.campaign_id,partner.medium_id,month_nr"

75 changes: 75 additions & 0 deletions currency_rate_update_tcmb/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
============================
Currency Rate Update: TCMB.gov.tr
============================

.. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! 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%2Fcurrency-lightgray.png?logo=github
:target: https://github.com/OCA/currency/tree/12.0/currency_rate_update_tcmb
:alt: OCA/currency
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/currency-12-0/currency-12-0-currency_rate_update_tcmb
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runbot-Try%20me-875A7B.png
:target: https://runbot.odoo-community.org/runbot/259/12.0
:alt: Try me on Runbot

|badge1| |badge2| |badge3| |badge4| |badge5|

This module adds `TCMB.gov.tr <https://tcmb.gov.tr/>`_ as currency rate provider. Central Bank of the Republic of Turkey.


**Table of contents**

.. contents::
:local:


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

Bugs are tracked on `GitHub Issues <https://github.com/OCA/currency/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/currency/issues/new?body=module:%20currency_rate_update_tcmb%0Aversion:%2012.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
~~~~~~~

* Yiğit Budak <[email protected]>

Contributors
~~~~~~~~~~~~

* Alexey Pelykh <[email protected]>

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.

This module is part of the `OCA/currency <https://github.com/OCA/currency/tree/12.0/currency_rate_update_xe>`_ project on GitHub.

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
3 changes: 3 additions & 0 deletions currency_rate_update_tcmb/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).

from . import models
23 changes: 23 additions & 0 deletions currency_rate_update_tcmb/__manifest__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Copyright 2020 Yiğit Budak (https://github.com/yibudak)
# Copyright 2019 Brainbean Apps (https://brainbeanapps.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).

{
'name': 'Currency Rate Update: Turkish Central Bank',
'version': '12.0.1.0.0',
'category': 'Financial Management/Configuration',
'summary': 'Update exchange rates using TCMB.gov.tr',
'author':
'Yiğit Budak, '
'Odoo Community Association (OCA)',
'Brainbean Apps'
'license': 'AGPL-3',
'installable': True,
'application': False,
'depends': [
'currency_rate_update',
],
'data': [
'views/res_currency_rate_provider.xml',
],
}
3 changes: 3 additions & 0 deletions currency_rate_update_tcmb/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).

from . import res_currency_rate_provider_TCMB
140 changes: 140 additions & 0 deletions currency_rate_update_tcmb/models/res_currency_rate_provider_TCMB.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# Copyright 2021 Yiğit Budak (https://github.com/yibudak)
# -*- coding: utf-8 -*-

from datetime import datetime, timedelta, date
from odoo import models, fields, api
from odoo.tools.translate import _
import logging
from lxml.etree import fromstring
import requests

_logger = logging.getLogger(__name__)

TCMB_RATE_TYPES = [
"ForexBuying",
"ForexSelling",
"BanknoteBuying",
"BanknoteSelling",
]

class ResCurrencyRateProviderTCMB(models.Model):
_inherit = 'res.currency.rate.provider'

service = fields.Selection(
selection_add=[('TCMB', 'Central Bank of the Republic of Turkey')],
default="TCMB"
)
service_rate_type = fields.Selection([
('ForexBuying', _('Forex Buy')),
('ForexSelling', _('Forex Sell')),
('BanknoteBuying', _('Banknote Buy')),
('BanknoteSelling', _('Banknote Sell'))
], string='Service Rate Type', default="ForexBuying", required=True)

@api.multi
def _get_supported_currencies(self):
self.ensure_one()
if self.service != 'TCMB':
return super()._get_supported_currencies()

# List of currencies obrained from:
# http://www.tcmb.gov.tr/kurlar/today.xml
return \
[
'USD', 'AUD', 'DKK', 'EUR', 'GBP', 'CHF', 'SEK', 'CAD',
'KWD', 'NOK', 'SAR', 'JPY', 'BGN', 'RON', 'RUB', 'IRR',
'CNY', 'PKR', 'QAR', 'XDR', 'TRY'
]

@api.multi
def _obtain_rates(self, base_currency, currencies, date_from, date_to):
self.ensure_one()
if self.service != 'TCMB':
return super()._obtain_rates(base_currency, currencies, date_from, date_to)

invert_calculation = False
if base_currency != 'TRY':
invert_calculation = True
if base_currency not in currencies:
currencies.append(base_currency)

if 'TRY' in currencies:
currencies.remove('TRY')

def daterange(start_date, end_date):
for n in range(int((end_date - start_date).days)):
yield start_date + timedelta(n)

result = {}
if date_from == date_to and date_from == date.today():
url = 'https://www.tcmb.gov.tr/kurlar/today.xml'
try:
rate_date = date.today().strftime('%Y-%m-%d')
currency_data = self.get_tcmb_currency_data(url, currencies)
result[rate_date] = currency_data
self._action_log_update(rate_date)
except Exception:
_logger.error(_('No currency rate on %s' % (date_from.strftime("%Y-%m-%d"))))
else:
latest_data = None
for single_date in daterange(date_from, date_to):
year = str(single_date.year)
month = '{:02d}'.format(single_date.month)
day = '{:02d}'.format(single_date.day)
url = "https://www.tcmb.gov.tr/kurlar/%s%s/%s%s%s.xml" % (year, month, day, month, year)
try:
rate_date = (single_date + timedelta(days=1)).strftime('%Y-%m-%d')
currency_data = self.get_tcmb_currency_data(url, currencies)
result[rate_date] = currency_data # bir gun oncesinin kurunu al
latest_data = currency_data
self._action_log_update(rate_date)
except Exception:
_logger.error(_('No currency rate on %s' % (single_date.strftime("%Y-%m-%d"))))
rate_date = (single_date + timedelta(days=1)).strftime('%Y-%m-%d')
if latest_data:
result[rate_date] = latest_data # bir gun oncesinin kurunu al
self._action_log_update(rate_date)
continue

content = result
if invert_calculation:
for k in content.keys():
base_rate = float(content[k][base_currency])
for rate in content[k].keys():
content[k][rate] = str(float(content[k][rate]) / base_rate)
content[k]['TRY'] = str(1.0 / base_rate)
return content

def rate_retrieve(self, dom, currency, rate_type):
res = {}
xpath_currency_rate = "./Currency[@Kod='%s']/%s" % (currency.upper(), rate_type)
res['rate_currency'] = float(
dom.findall(xpath_currency_rate)[0].text
)
xpath_rate_ref = "./Currency[@Kod='%s']/Unit" % currency.upper()
res['rate_ref'] = float(dom.findall(xpath_rate_ref)[0].text)
return res

def get_tcmb_currency_data(self, url, currencies):
response = requests.get(url).text
dom = fromstring(response.encode('utf-8'))

_logger.debug("TCMB sent a valid XML file")
currency_data = {}
for currency in currencies:
currency_data[currency] = {}
for rate_type in TCMB_RATE_TYPES:
curr_data = self.rate_retrieve(dom, currency, rate_type)
currency_data[currency][rate_type] = curr_data['rate_ref'] / (curr_data['rate_currency'] or 1.0)

return currency_data

def _action_log_update(self, rate_date):
self.env['mail.message'].create({
'email_from': 'Administrator',
'author_id': 2,
'model': 'res.currency.rate.provider',
'subtype_id': self.env.ref('mail.mt_comment').id,
'body': "%s Currency Rate Updated at %s" % (rate_date, datetime.now()),
'res_id': self.id,
})
2 changes: 2 additions & 0 deletions currency_rate_update_tcmb/readme/CONTRIBUTORS.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
* Yiğit Budak <[email protected]>
* Alexey Pelykh <[email protected]>
4 changes: 4 additions & 0 deletions currency_rate_update_tcmb/readme/DESCRIPTION.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
This module adds `TCMB.gov.tr <https://tcmb.gov.tr/>`_ as currency rate provider. Central Bank of the Republic of Turkey.



Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading