Skip to content

Commit c269ede

Browse files
authored
Merge pull request #179 from yjinjo/master
Add exchange currency function
2 parents 2bac3bf + e7f6510 commit c269ede

6 files changed

+87
-38
lines changed

src/spaceone/cost_analysis/connector/currency_connector.py

+19-27
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
_LOGGER = logging.getLogger(__name__)
1111

12-
EXCHANGE_CURRENCY_LIST = ["KRW", "USD", "JPY"]
12+
FROM_EXCHANGE_CURRENCIES = ["KRW", "USD", "JPY"]
1313

1414

1515
class CurrencyConnector(BaseConnector):
@@ -18,34 +18,26 @@ def __init__(self, *args, **kwargs):
1818
self.today = datetime.utcnow()
1919
self.today_date = self.today.strftime("%Y-%m-%d")
2020
self.two_weeks_ago = (self.today - timedelta(days=14)).strftime("%Y-%m-%d")
21+
self.currency_date = None
2122

22-
def add_exchange_rate(self, aggregated_cost_report: dict) -> dict:
23-
current_currency_dict = aggregated_cost_report.get("cost")
24-
cost = {}
23+
def add_currency_map_date(self, to_currency: str) -> tuple[dict, str]:
24+
currency_map = {}
25+
_currency_date = ""
2526

26-
for current_currency, current_cost in current_currency_dict.items():
27-
exchange_rate_cost = self._calculate_exchange_rate(
28-
current_currency, current_cost
29-
)
30-
cost.update({current_currency: exchange_rate_cost})
31-
32-
aggregated_cost_report.update({"cost": cost})
33-
return aggregated_cost_report
34-
35-
def _calculate_exchange_rate(self, from_currency: str, amount: float) -> float:
36-
exchange_rates = {}
37-
38-
for to_currency in EXCHANGE_CURRENCY_LIST:
27+
for from_currency in FROM_EXCHANGE_CURRENCIES:
3928
if from_currency == to_currency:
4029
exchange_rate = 1.0
4130
else:
42-
pair = f"{from_currency}/{to_currency}"
43-
exchange_rate_info = fdr.DataReader(
44-
pair, self.two_weeks_ago, self.today_date
45-
)["Close"].dropna()
46-
exchange_rate = exchange_rate_info.iloc[-1]
47-
48-
exchange_rates[to_currency] = exchange_rate
49-
50-
exchange_rate_cost = amount * exchange_rates[from_currency]
51-
return exchange_rate_cost
31+
pair = f"{to_currency}/{from_currency}"
32+
exchange_rate_info = (
33+
fdr.DataReader(pair, self.two_weeks_ago, self.today_date)
34+
.dropna()
35+
.reset_index()[["Date", "Close"]]
36+
)
37+
_currency_date, exchange_rate = exchange_rate_info.iloc[-1]
38+
currency_map[from_currency] = exchange_rate
39+
40+
if self.currency_date is None:
41+
self.currency_date = _currency_date
42+
43+
return currency_map, self.currency_date

src/spaceone/cost_analysis/manager/cost_report_manager.py

+17
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,20 @@ def list_cost_reports(self, query: dict) -> Tuple[QuerySet, int]:
4545

4646
def stat_cost_reports(self, query: dict) -> dict:
4747
return self.cost_report_model.stat(**query)
48+
49+
@staticmethod
50+
def get_exchange_currency(cost_info: dict, currency_map: dict) -> dict:
51+
from_currency = next(iter(cost_info.keys()))
52+
from_cost = cost_info.get(from_currency)
53+
54+
cost = {}
55+
for currency, ratio_cost in currency_map.items():
56+
cost[currency] = from_cost * ratio_cost
57+
58+
return cost
59+
60+
@staticmethod
61+
def get_currency_date(currency_date: str) -> str:
62+
currency_date = str(currency_date).split()[0]
63+
64+
return currency_date

src/spaceone/cost_analysis/manager/currency_manager.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,11 @@ class CurrencyManager(BaseManager):
1010
def __init__(self, *args, **kwargs):
1111
super().__init__(*args, **kwargs)
1212
self.currency_connector: CurrencyConnector = CurrencyConnector()
13+
self.currency_mapper = {}
1314

14-
def convert_exchange_rate(self, aggregated_cost_report: dict) -> dict:
15-
return self.currency_connector.add_exchange_rate(aggregated_cost_report)
15+
def get_currency_map_date(self, to_currency: str) -> tuple[dict, str]:
16+
currency_map, currency_date = self.currency_connector.add_currency_map_date(
17+
to_currency
18+
)
19+
20+
return currency_map, currency_date

src/spaceone/cost_analysis/service/cost_report_config_service.py

+13-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from spaceone.cost_analysis.manager.cost_report_config_manager import (
88
CostReportConfigManager,
99
)
10+
from spaceone.cost_analysis.manager.currency_manager import CurrencyManager
1011
from spaceone.cost_analysis.service.cost_report_serivce import CostReportService
1112
from spaceone.cost_analysis.service.cost_report_data_service import (
1213
CostReportDataService,
@@ -205,11 +206,22 @@ def delete(self, params: CostReportConfigDeleteRequest) -> None:
205206
def run(self, params: CostReportConfigRunRequest) -> None:
206207
"""RUN cost report config"""
207208

208-
# todo : apply currency manager
209209
cost_report_config_vo = self.cost_report_mgr.get_cost_report_config(
210210
params.domain_id, params.cost_report_config_id
211211
)
212+
213+
currency_mgr = CurrencyManager()
214+
215+
(
216+
currency_map,
217+
currency_date,
218+
) = currency_mgr.get_currency_map_date(cost_report_config_vo.currency)
219+
212220
cost_report_service = CostReportService()
221+
222+
cost_report_service.currency_map = currency_map
223+
cost_report_service.currency_date = currency_date
224+
213225
cost_report_service.create_cost_report(cost_report_config_vo)
214226

215227
@transaction(

src/spaceone/cost_analysis/service/cost_report_data_service.py

+11-3
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from spaceone.cost_analysis.manager.cost_report_config_manager import (
1212
CostReportConfigManager,
1313
)
14+
from spaceone.cost_analysis.manager.cost_report_manager import CostReportManager
1415
from spaceone.cost_analysis.manager.currency_manager import CurrencyManager
1516
from spaceone.cost_analysis.manager.data_source_manager import DataSourceManager
1617
from spaceone.cost_analysis.manager.identity_manager import IdentityManager
@@ -32,6 +33,8 @@ def __init__(self, *args, **kwargs):
3233
super().__init__(*args, **kwargs)
3334
self.cost_mgr = CostManager()
3435
self.cost_report_data_mgr = CostReportDataManager()
36+
self.currency_map: Union[dict, None] = None
37+
self.currency_date: Union[str, None] = None
3538

3639
@transaction(
3740
permission="cost-analysis:CostReportData.read",
@@ -238,9 +241,14 @@ def _aggregate_monthly_cost_report_data(
238241
aggregated_cost_report_data["domain_id"] = domain_id
239242
aggregated_cost_report_data["is_confirmed"] = is_confirmed
240243

241-
aggregated_cost_report_data["cost"] = currency_mgr.convert_exchange_rate(
242-
aggregated_cost_report_data
243-
).get("cost")
244+
aggregated_cost_report_data[
245+
"cost"
246+
] = CostReportManager.get_exchange_currency(
247+
aggregated_cost_report_data["cost"], self.currency_map
248+
)
249+
aggregated_cost_report_data[
250+
"currency_date"
251+
] = CostReportManager.get_currency_date(self.currency_date)
244252

245253
self.cost_report_data_mgr.create_cost_report_data(
246254
aggregated_cost_report_data

src/spaceone/cost_analysis/service/cost_report_serivce.py

+20-5
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,23 @@ def __init__(self, *args, **kwargs):
4343
self.cost_mgr = CostManager()
4444
self.cost_report_config_mgr = CostReportConfigManager()
4545
self.cost_report_mgr = CostReportManager()
46+
self.currency_map: Union[dict, None] = None
47+
self.currency_date: Union[str, None] = None
4648

4749
@transaction(exclude=["authentication", "authorization", "mutation"])
4850
def create_cost_report_by_cost_report_config(self, params: dict):
4951
"""Create cost report by cost report config"""
5052

51-
# todo: apply currency_manager
52-
53+
currency_mgr = CurrencyManager()
5354
for cost_report_config_vo in self._get_all_cost_report_configs():
55+
(
56+
currency_map,
57+
currency_date,
58+
) = currency_mgr.get_currency_map_date(cost_report_config_vo.currency)
59+
60+
self.currency_map = currency_map
61+
self.currency_date = currency_date
62+
5463
self.create_cost_report(cost_report_config_vo)
5564

5665
def send_cost_report_by_cost_report_config(self, params: dict):
@@ -302,15 +311,21 @@ def _aggregate_monthly_cost_report(
302311

303312
aggregated_cost_report_results = self._aggregate_result_by_currency(results)
304313

305-
currency_mgr = CurrencyManager()
306314
for aggregated_cost_report in aggregated_cost_report_results:
307-
aggregated_cost_report = currency_mgr.convert_exchange_rate(
308-
aggregated_cost_report
315+
aggregated_cost_report["cost"] = CostReportManager.get_exchange_currency(
316+
aggregated_cost_report["cost"], self.currency_map
309317
)
318+
319+
aggregated_cost_report[
320+
"currency_date"
321+
] = CostReportManager.get_currency_date(self.currency_date)
322+
310323
cost_report_vo = self.cost_report_mgr.create_cost_report(
311324
aggregated_cost_report
312325
)
313326
cost_report_data_svc = CostReportDataService()
327+
cost_report_data_svc.currency_map = self.currency_map
328+
cost_report_data_svc.currency_date = self.currency_date
314329
cost_report_data_svc.create_cost_report_data(cost_report_vo)
315330

316331
_LOGGER.debug(

0 commit comments

Comments
 (0)