Skip to content

Commit e78e742

Browse files
authored
Merge pull request #341 from ImMin5/master
Enhance budget notification logic
2 parents 1798d79 + 7107b02 commit e78e742

File tree

8 files changed

+36
-34
lines changed

8 files changed

+36
-34
lines changed

src/spaceone/cost_analysis/interface/task/v1/budget_update_scheduler.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,7 @@ def create_task(self) -> list:
4141
return tasks
4242

4343
def _create_budget_utilization_rate_update_task(self):
44-
from spaceone.core import model
4544

46-
model.init_all(False)
4745
current_day = datetime.now(timezone.utc).day
4846
if (
4947
current_day == self._budget_update_day

src/spaceone/cost_analysis/manager/budget_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def push_budget_job_task(params: dict) -> None:
8787
"locator": "SERVICE",
8888
"name": "BudgetService",
8989
"metadata": {"token": token},
90-
"method": "update_budget_utilization_rate",
90+
"method": "init_monthly_budget_info",
9191
"params": {"params": params},
9292
}
9393
],

src/spaceone/cost_analysis/manager/budget_usage_manager.py

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import logging
22
from datetime import datetime, timezone
3-
from typing import Union
4-
53
from dateutil.rrule import rrule, MONTHLY
64

75
from spaceone.core import config
@@ -105,12 +103,12 @@ def notify_budget_usage(self, budget_vo: Budget) -> None:
105103
budget_id = budget_vo.budget_id
106104
workspace_id = budget_vo.workspace_id
107105
domain_id = budget_vo.domain_id
108-
current_month = datetime.now(timezone.utc).strftime("%Y-%m")
109-
updated_plans = []
110-
is_changed = False
111106
notification = budget_vo.notification
112107

113108
plans = notification.plans or []
109+
current_month = datetime.now(timezone.utc).strftime("%Y-%m")
110+
updated_plans = []
111+
is_changed = False
114112

115113
for plan in plans:
116114

@@ -120,8 +118,10 @@ def notify_budget_usage(self, budget_vo: Budget) -> None:
120118
)
121119
continue
122120

123-
unit = plan.unit
124-
threshold = plan.threshold
121+
plan_info = plan.to_dict()
122+
123+
unit = plan_info["unit"]
124+
threshold = plan_info["threshold"]
125125
is_notify = False
126126

127127
if budget_vo.time_unit == "TOTAL":
@@ -157,6 +157,7 @@ def notify_budget_usage(self, budget_vo: Budget) -> None:
157157
continue
158158

159159
budget_percentage = budget_vo.utilization_rate
160+
total_budget_usage = round(total_budget_usage, 2)
160161

161162
if unit == "PERCENT":
162163
if budget_percentage > threshold:
@@ -166,28 +167,23 @@ def notify_budget_usage(self, budget_vo: Budget) -> None:
166167
_LOGGER.debug(
167168
f"[notify_budget_usage] notify event: {budget_id}, current month: {current_month} (plan: {plan.to_dict()})"
168169
)
169-
170170
try:
171171
self._notify_message(
172172
budget_vo,
173173
total_budget_usage,
174174
budget_percentage,
175175
threshold,
176176
)
177-
178-
updated_plans.append(
179-
{
180-
"threshold": threshold,
181-
"unit": unit,
182-
"notified": True,
183-
}
184-
)
177+
plan_info["notified"] = True
185178

186179
except Exception as e:
187180
_LOGGER.error(
188-
f"[notify_budget_usage] Failed to notify message ({budget_id}): {e}",
181+
f"[notify_budget_usage] Failed to notify message ({budget_id}): plan: {plan_info}, {e}",
189182
exc_info=True,
190183
)
184+
plan_info["notified"] = False
185+
finally:
186+
updated_plans.append(plan_info)
191187
else:
192188
if unit == "PERCENT":
193189
_LOGGER.debug(
@@ -200,7 +196,7 @@ def notify_budget_usage(self, budget_vo: Budget) -> None:
200196
f"(usage cost: {total_budget_usage}, threshold: {threshold})"
201197
)
202198

203-
updated_plans.append(plan.to_dict())
199+
updated_plans.append(plan_info)
204200

205201
if is_changed:
206202
notification.plans = updated_plans
@@ -216,9 +212,9 @@ def _notify_message(
216212
self,
217213
budget_vo: Budget,
218214
total_budget_usage: float,
219-
budget_percentage,
220-
threshold,
221-
):
215+
budget_percentage: float,
216+
threshold: int,
217+
) -> None:
222218

223219
if not self.email_mgr:
224220
self.email_mgr = EmailManager()

src/spaceone/cost_analysis/manager/email_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
},
3535
"ja": {
3636
"cost_report": "費用レポートが確認のために準備されました。",
37-
"budget_usage_alert": "",
3837
},
3938
}
4039

@@ -97,6 +96,7 @@ def send_budget_usage_alert_email(
9796
usage_rate=budget_percentage,
9897
today_date=today_date,
9998
budget_detail_link=console_link,
99+
currency=budget_vo.currency,
100100
)
101101

102102
subject = f"[{service_name}] {language_map_info['budget_usage_alert'].format(budget_name=budget_vo.name, threshold=threshold)}"

src/spaceone/cost_analysis/model/budget/database.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,6 @@ class Budget(MongoModel):
9090
"workspace_id",
9191
"project_id",
9292
"name",
93-
"budget_id",
9493
"time_unit",
9594
"service_account_id",
9695
],

src/spaceone/cost_analysis/service/budget_service.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -413,7 +413,7 @@ def stat(self, params: BudgetStatQueryRequest) -> dict:
413413

414414
@transaction(exclude=["authentication", "authorization", "mutation"])
415415
@check_required(["domain_id"])
416-
def update_budget_utilization_rate(self, params: dict) -> None:
416+
def init_monthly_budget_info(self, params: dict) -> None:
417417
"""
418418
Args:
419419
params (dict): {
@@ -432,17 +432,26 @@ def update_budget_utilization_rate(self, params: dict) -> None:
432432
{"k": "end", "v": current_month, "o": "gte"},
433433
]
434434
}
435-
_LOGGER.debug(f"[update_budget_utilization_rate] query_filter: {query_filter}")
435+
_LOGGER.debug(f"[init_monthly_budget_info] query_filter: {query_filter}")
436436
budget_vos, _ = self.budget_mgr.list_budgets(query_filter)
437437

438438
for budget_vo in budget_vos:
439+
utilization_rate = 0
439440
planned_limits = budget_vo.planned_limits or []
441+
notification = budget_vo.notification.to_dict() or {}
440442

441443
budget_limit = self._get_budget_limit_from_planned_limits(planned_limits)
442-
notification = self._reset_plans_from_notification(budget_vo.notification)
444+
notification = self._reset_plans_from_notification(notification)
445+
446+
budget_usage_vos = self.budget_usage_mgr.filter_budget_usages(
447+
domain_id=domain_id, budget_id=budget_vo.budget_id, date=current_month
448+
)
449+
450+
if budget_limit > 0 and (budget_usage_vo := budget_usage_vos[0]):
451+
utilization_rate = budget_usage_vo.cost / budget_limit * 100
443452

444453
update_params = {
445-
"utilization_rate": 0,
454+
"utilization_rate": utilization_rate,
446455
"limit": budget_limit,
447456
"notification": notification,
448457
}
@@ -462,8 +471,8 @@ def _check_time_period(start: str, end: str, budget_year: str = None) -> None:
462471
raise ERROR_INVALID_TIME_RANGE(start=start, end=end)
463472

464473
if budget_year:
465-
start_year = start[:4]
466-
end_year = end[:4]
474+
start_year = start.split("-")[0]
475+
end_year = end.split("-")[0]
467476
if start_year != budget_year or end_year != budget_year:
468477
raise ERROR_INVALID_PARAMETER(
469478
key="budget_year",

src/spaceone/cost_analysis/template/budget_usage_alert_en.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@
175175
• Budget Name: {{budget_name}}<br>
176176
• Budget Target: {{budget_target}}<br>
177177
• Budget Amount: {{budget_amount}} ({{budget_cycle}})<br>
178-
• Actual Cost: {{actual_cost}} ({{usage_rate}}%)<br>
178+
• Actual Cost: {{actual_cost}} {{currency}} ({{usage_rate}}%)<br>
179179
• Alert Date: {{today_date}}<br><br>
180180
</span>
181181
</div>

src/spaceone/cost_analysis/template/budget_usage_alert_ko.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@
175175
• 예산명: {{budget_name}}<br>
176176
• 예산 타겟: {{budget_target}}<br>
177177
• 예산: {{budget_amount}} ({{budget_cycle}})<br>
178-
• 실 사용 금액: {{actual_cost}} ({{usage_rate}}%)<br>
178+
• 실 사용 금액: {{actual_cost}} {{currency}} ({{usage_rate}}%)<br>
179179
• 알림 일자: {{today_date}}<br><br>
180180
</span>
181181
</div>

0 commit comments

Comments
 (0)