Skip to content

Commit

Permalink
Merge pull request #165 from yjinjo/master
Browse files Browse the repository at this point in the history
Add exchange rate
  • Loading branch information
yjinjo authored Jan 26, 2024
2 parents 4409e4b + b1192d5 commit b6c2cb3
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 5 deletions.
4 changes: 3 additions & 1 deletion pkg/pip_requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
spaceone-api
pandas
numpy
jinja2
jinja2
finance-datareader
plotly
51 changes: 51 additions & 0 deletions src/spaceone/cost_analysis/connector/currency_connector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import logging
import FinanceDataReader as fdr

from datetime import datetime, timedelta

from spaceone.core.connector import BaseConnector

__all__ = ["CurrencyConnector"]

_LOGGER = logging.getLogger(__name__)

EXCHANGE_CURRENCY_LIST = ["KRW", "USD", "JPY"]


class CurrencyConnector(BaseConnector):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.today = datetime.utcnow()
self.today_date = self.today.strftime("%Y-%m-%d")
self.two_weeks_ago = (self.today - timedelta(days=14)).strftime("%Y-%m-%d")

def add_exchange_rate(self, aggregated_cost_report: dict) -> dict:
current_currency_dict = aggregated_cost_report.get("cost")
cost = {}

for current_currency, current_cost in current_currency_dict.items():
exchange_rate_cost = self._calculate_exchange_rate(
current_currency, current_cost
)
cost.update({current_currency: exchange_rate_cost})

aggregated_cost_report.update({"cost": cost})
return aggregated_cost_report

def _calculate_exchange_rate(self, from_currency: str, amount: float) -> float:
exchange_rates = {}

for to_currency in EXCHANGE_CURRENCY_LIST:
if from_currency == to_currency:
exchange_rate = 1.0
else:
pair = f"{from_currency}/{to_currency}"
exchange_rate_info = fdr.DataReader(
pair, self.two_weeks_ago, self.today_date
)["Close"].dropna()
exchange_rate = exchange_rate_info.iloc[-1]

exchange_rates[to_currency] = exchange_rate

exchange_rate_cost = amount * exchange_rates[from_currency]
return exchange_rate_cost
15 changes: 15 additions & 0 deletions src/spaceone/cost_analysis/manager/currency_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import logging

from spaceone.core.manager import BaseManager
from spaceone.cost_analysis.connector.currency_connector import CurrencyConnector

_LOGGER = logging.getLogger(__name__)


class CurrencyManager(BaseManager):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.currency_connector: CurrencyConnector = CurrencyConnector()

def convert_exchange_rate(self, aggregated_cost_report: dict) -> dict:
return self.currency_connector.add_exchange_rate(aggregated_cost_report)
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from spaceone.cost_analysis.manager.cost_report_config_manager import (
CostReportConfigManager,
)
from spaceone.cost_analysis.manager.currency_manager import CurrencyManager
from spaceone.cost_analysis.manager.data_source_manager import DataSourceManager
from spaceone.cost_analysis.manager.identity_manager import IdentityManager
from spaceone.cost_analysis.model.cost_report_data.request import *
Expand Down Expand Up @@ -224,6 +225,7 @@ def _aggregate_monthly_cost_report_data(
)

results = response.get("results", [])
currency_mgr = CurrencyManager()
for aggregated_cost_report in results:
ag_cost_report_currency = data_source_currency_map.get(
aggregated_cost_report.pop("data_source_id")
Expand All @@ -249,13 +251,16 @@ def _aggregate_monthly_cost_report_data(
aggregated_cost_report["service_account_id"], "Unknown"
)

aggregated_cost_report["bank_name"] = "Yahoo! Finance" # todo : replace
aggregated_cost_report[
"cost_report_config_id"
] = cost_report_config_vo.cost_report_config_id
aggregated_cost_report["domain_id"] = domain_id
aggregated_cost_report["is_confirmed"] = is_confirmed

aggregated_cost_report["cost"] = currency_mgr.convert_exchange_rate(
aggregated_cost_report
).get("cost")

self.cost_report_data_mgr.create_cost_report_data(aggregated_cost_report)

_LOGGER.debug(
Expand Down
13 changes: 10 additions & 3 deletions src/spaceone/cost_analysis/service/cost_report_serivce.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from mongoengine import QuerySet
from spaceone.core import config
from spaceone.core.service import *

from spaceone.cost_analysis.model.cost_report.database import CostReport
from spaceone.cost_analysis.model.cost_report_config.database import CostReportConfig
from spaceone.cost_analysis.model.cost_report.request import *
Expand All @@ -19,6 +20,7 @@
)
from spaceone.cost_analysis.manager.cost_manager import CostManager
from spaceone.cost_analysis.manager.cost_report_manager import CostReportManager
from spaceone.cost_analysis.manager.currency_manager import CurrencyManager
from spaceone.cost_analysis.manager.data_source_manager import DataSourceManager
from spaceone.cost_analysis.manager.email_manager import EmailManager
from spaceone.cost_analysis.manager.identity_manager import IdentityManager
Expand Down Expand Up @@ -273,12 +275,16 @@ def _aggregate_monthly_cost_report(

aggregated_cost_report_results = self._aggregate_result_by_currency(results)

currency_mgr = CurrencyManager()
for aggregated_cost_report in aggregated_cost_report_results:
# todo: apply currency cost
aggregated_cost_report = currency_mgr.convert_exchange_rate(
aggregated_cost_report
)
self.cost_report_mgr.create_cost_report(aggregated_cost_report)

_LOGGER.debug(
f"[aggregate_monthly_cost_report] create cost report ({report_month}) (count = {len(aggregated_cost_report_results)})"
f"[aggregate_monthly_cost_report] create cost report ({report_month}) \
(count = {len(aggregated_cost_report_results)})"
)
self._delete_old_cost_reports(report_month, domain_id)

Expand Down Expand Up @@ -358,7 +364,8 @@ def send_cost_report(self, cost_report_vo: CostReport) -> None:
user_id, email, cost_report_link, language, cost_report_vo
)
_LOGGER.debug(
f"[send_cost_report] send cost report ({workspace_id}/{cost_report_vo.cost_report_id}) to {users_info.get('total_count', 0)} users"
f"[send_cost_report] send cost report ({workspace_id}/{cost_report_vo.cost_report_id}) to \
{users_info.get('total_count', 0)} users"
)

def _get_console_cost_report_url(
Expand Down

0 comments on commit b6c2cb3

Please sign in to comment.