import os import yaml import numpy as np import pandas as pd from environs import Env from render import Render from datetime import datetime, timedelta from utils import send_lark_message, summary, reason env = Env() env.read_env() def big_change_text(r: Render) -> str: text = '' if len(r.dataframe('big_contribution_projects')) > 0: text += '---\n' text += '\n# 变化较大的 Project\n' for _, prow in r.dataframe('big_contribution_projects').iterrows(): with r.context(project_id=prow.billing_project_id): text += f'- Project `{prow.billing_project_name}` 的日账单为 ${prow.today_project_cost_sum:,.2f},' text += f'比昨日(${prow.yesterday_project_cost_sum:,.2f}) ' text += f'${prow.today_project_cost_sum-prow.yesterday_project_cost_sum:+,.2f},' text += f'占总变化费用的 {prow.diff_ratio*100:.2f}%\n' text += '\n# 每个 project 变化原因\n' for _, prow in r.dataframe('big_contribution_projects').iterrows(): with r.context(project_id=prow.billing_project_id): text += f'\n## Project `{prow.billing_project_name}`\n' text += f'变化贡献最大的费用类目是:\n' for _, urow in r.dataframe('tenant_unit_contribution').iterrows(): text += f'- Cluster `{urow.billing_cluster_name}` 的费用类目 `{urow.billing_unit}` ' text += f'比昨日 ${urow.today_cost-urow.yesterday_cost:+,.2f},占该租户变化费用的 {urow.diff_ratio*100:.2f}%\n' return text if __name__ == '__main__': r = Render(os.path.join(os.path.dirname(__file__), 'daily.yaml'), env.str("TRINO_HOST")) with open(os.path.join(os.path.dirname(__file__), 'tenants.yaml'), "r") as stream: tenants = yaml.safe_load(stream) for tenant in tenants: with r.context(tenant_id=tenant['id'], today=(datetime.now() - timedelta(days=4)).strftime('%Y-%m-%d')): text = '' text += f'{r.ctx["today"]},{tenant["name"]}({tenant["id"]}) 的日账单为 ${r.today_cost_sum:,.2f},' text += f'比前一日(${r.yesterday_cost_sum:,.2f})' text += f'${r.today_cost_sum-r.yesterday_cost_sum:+,.2f},' text += f'变化 {(r.today_cost_sum-r.yesterday_cost_sum)/r.yesterday_cost_sum*100:+.2f}%。\n' if np.abs((r.today_cost_sum-r.yesterday_cost_sum)/r.yesterday_cost_sum) < 0.05: text += f'{r.ctx["today"]} 整体日账单变化波动很小。\n' else: text += big_change_text(r) send_lark_message( env, '# 租户日账单\n\n' + summary(env, text) + '\n\n# 账单详情\n\n' + text, tenant['chat_id'], ) if np.abs((r.today_cost_sum-r.yesterday_cost_sum)/r.yesterday_cost_sum) >= 0.05: send_lark_message( env, reason(env, text, tenant['id'], r.ctx["today"]), tenant['chat_id'], )