Trae Assistant commited on
Commit
92e639a
·
1 Parent(s): 91097d0

初始化并升级:错误处理、上传支持、中文优化

Browse files
Files changed (5) hide show
  1. Dockerfile +20 -0
  2. README.md +46 -6
  3. app.py +286 -0
  4. requirements.txt +5 -0
  5. templates/index.html +339 -0
Dockerfile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install dependencies
6
+ COPY requirements.txt .
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+
9
+ # Copy application code
10
+ COPY . .
11
+
12
+ # Create a non-root user
13
+ RUN useradd -m -u 1000 user
14
+ USER user
15
+ ENV HOME=/home/user \
16
+ PATH=/home/user/.local/bin:$PATH
17
+
18
+ EXPOSE 7860
19
+
20
+ CMD ["python", "app.py"]
README.md CHANGED
@@ -1,10 +1,50 @@
1
- ---
2
- title: Cloud Cost Optimizer
3
- emoji: 📉
4
- colorFrom: purple
5
- colorTo: gray
6
  sdk: docker
7
  pinned: false
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ title: 云成本精算师
2
+ emoji: 💰
3
+ colorFrom: blue
4
+ colorTo: green
 
5
  sdk: docker
6
  pinned: false
7
+ short_description: 模拟AWS账单分析、异常检测与成本优化建议
8
  ---
9
 
10
+ # 云成本精算师 (Cloud Cost Optimizer)
11
+
12
+ 这是一个模拟的云成本分析与优化平台 (FinOps Tool),旨在展示如何通过数据分析和算法来降低云基础设施的支出。
13
+
14
+ ## 核心功能
15
+
16
+ 1. **全景成本仪表盘**:实时查看总支出、月环比增长 (MoM) 及下月预测。
17
+ 2. **多维趋势分析**:基于 ECharts 的交互式堆叠柱状图,按服务拆分日成本。
18
+ 3. **智能异常检测**:自动识别超出 3-Sigma 阈值的异常消费突增 (Anomaly Detection)。
19
+ 4. **优化建议引擎**:模拟生成 RI (预留实例) 购买建议、闲置资源清理建议。
20
+
21
+ ## 技术栈
22
+
23
+ - **后端**: Python Flask, Pandas (数据处理), NumPy (统计计算)
24
+ - **前端**: Vue 3, Tailwind CSS, ECharts 5
25
+ - **数据**: 使用 Faker 和自定义算法生成高保真的模拟 AWS 账单数据 (EC2, RDS, S3, Lambda 等)
26
+
27
+ ## 如何运行
28
+
29
+ ### 本地运行
30
+
31
+ ```bash
32
+ pip install -r requirements.txt
33
+ python app.py
34
+ ```
35
+
36
+ 访问: http://localhost:7860
37
+
38
+ ### Docker 运行
39
+
40
+ ```bash
41
+ docker build -t cloud-cost-optimizer .
42
+ docker run -p 7860:7860 cloud-cost-optimizer
43
+ ```
44
+
45
+ ## 商业应用场景
46
+
47
+ 该项目演示了 FinOps SaaS 产品的核心逻辑,可扩展用于:
48
+ - 多云账单聚合 (AWS/Azure/GCP)
49
+ - 自动化成本异常告警
50
+ - 资源使用率分析与 Rightsizing 建议
app.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ import datetime
5
+ import pandas as pd
6
+ import numpy as np
7
+ from flask import Flask, render_template, jsonify, request
8
+ from faker import Faker
9
+
10
+ app = Flask(__name__)
11
+ fake = Faker()
12
+
13
+ # Configuration
14
+ app.config['JSON_AS_ASCII'] = False
15
+ app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024
16
+ app.jinja_env.variable_start_string = "[["
17
+ app.jinja_env.variable_end_string = "]]"
18
+
19
+ # Global Cache for simulated data
20
+ DATA_CACHE = None
21
+
22
+ class CostSimulator:
23
+ def __init__(self):
24
+ self.services = ['Amazon EC2', 'Amazon RDS', 'Amazon S3', 'AWS Lambda', 'Amazon CloudFront']
25
+ self.regions = ['us-east-1', 'us-west-2', 'eu-central-1', 'ap-northeast-1']
26
+ self.instance_types = ['t3.micro', 'm5.large', 'c5.xlarge', 'r5.2xlarge']
27
+
28
+ def generate_data(self, days=90):
29
+ """Generate simulated billing data for the last N days."""
30
+ data = []
31
+ end_date = datetime.date.today()
32
+ start_date = end_date - datetime.timedelta(days=days)
33
+
34
+ # Base resources (Long running)
35
+ resources = []
36
+ for _ in range(20):
37
+ resources.append({
38
+ 'id': fake.uuid4(),
39
+ 'service': random.choice(self.services),
40
+ 'region': random.choice(self.regions),
41
+ 'name': fake.hostname(),
42
+ 'tag_env': random.choice(['Production', 'Staging', 'Dev']),
43
+ 'base_cost': random.uniform(0.5, 50.0) # Daily cost
44
+ })
45
+
46
+ current_date = start_date
47
+ while current_date <= end_date:
48
+ # Add base resource costs
49
+ for res in resources:
50
+ daily_cost = res['base_cost'] * random.uniform(0.9, 1.1)
51
+
52
+ # Simulate a cost spike in the last 3 days for one specific resource
53
+ if current_date > end_date - datetime.timedelta(days=3) and res['service'] == 'AWS Lambda':
54
+ daily_cost *= random.uniform(5.0, 10.0) # Anomaly!
55
+
56
+ data.append({
57
+ 'date': current_date.strftime('%Y-%m-%d'),
58
+ 'resource_id': res['id'],
59
+ 'resource_name': res['name'],
60
+ 'service': res['service'],
61
+ 'region': res['region'],
62
+ 'environment': res['tag_env'],
63
+ 'cost': round(daily_cost, 4),
64
+ 'usage_amount': round(random.uniform(10, 1000), 2)
65
+ })
66
+
67
+ # Add some random transient costs (Spot instances, data transfer)
68
+ for _ in range(random.randint(5, 15)):
69
+ svc = random.choice(self.services)
70
+ data.append({
71
+ 'date': current_date.strftime('%Y-%m-%d'),
72
+ 'resource_id': fake.uuid4(),
73
+ 'resource_name': 'Transient-' + fake.word(),
74
+ 'service': svc,
75
+ 'region': random.choice(self.regions),
76
+ 'environment': 'Dev',
77
+ 'cost': round(random.uniform(0.1, 5.0), 4),
78
+ 'usage_amount': round(random.uniform(1, 100), 2)
79
+ })
80
+
81
+ current_date += datetime.timedelta(days=1)
82
+
83
+ return pd.DataFrame(data)
84
+
85
+ def get_data(refresh=False):
86
+ global DATA_CACHE
87
+ if DATA_CACHE is None or refresh:
88
+ sim = CostSimulator()
89
+ DATA_CACHE = sim.generate_data()
90
+ return DATA_CACHE
91
+
92
+ @app.route('/')
93
+ def index():
94
+ return render_template('index.html')
95
+
96
+ @app.route('/api/summary')
97
+ def api_summary():
98
+ df = get_data()
99
+
100
+ # Total Cost
101
+ total_cost = df['cost'].sum()
102
+
103
+ # This Month vs Last Month (Simulated logic using 30 day windows)
104
+ today = datetime.date.today()
105
+ last_30_start = (today - datetime.timedelta(days=30)).strftime('%Y-%m-%d')
106
+ prev_30_start = (today - datetime.timedelta(days=60)).strftime('%Y-%m-%d')
107
+
108
+ current_cost = df[df['date'] >= last_30_start]['cost'].sum()
109
+ prev_cost = df[(df['date'] >= prev_30_start) & (df['date'] < last_30_start)]['cost'].sum()
110
+
111
+ mom_change = 0
112
+ if prev_cost > 0:
113
+ mom_change = ((current_cost - prev_cost) / prev_cost) * 100
114
+
115
+ return jsonify({
116
+ 'total_cost': round(total_cost, 2),
117
+ 'current_month_cost': round(current_cost, 2),
118
+ 'mom_change': round(mom_change, 2),
119
+ 'forecast': round(current_cost * 1.05, 2) # Simple forecast
120
+ })
121
+
122
+ @app.route('/api/trend')
123
+ def api_trend():
124
+ df = get_data()
125
+ # Group by date and service
126
+ trend = df.groupby(['date', 'service'])['cost'].sum().reset_index()
127
+
128
+ # Pivot for ECharts
129
+ pivot = trend.pivot(index='date', columns='service', values='cost').fillna(0)
130
+
131
+ dates = pivot.index.tolist()
132
+ series = []
133
+ for column in pivot.columns:
134
+ series.append({
135
+ 'name': column,
136
+ 'type': 'bar',
137
+ 'stack': 'total',
138
+ 'data': pivot[column].round(2).tolist()
139
+ })
140
+
141
+ return jsonify({
142
+ 'dates': dates,
143
+ 'series': series
144
+ })
145
+
146
+ @app.route('/api/anomalies')
147
+ def api_anomalies():
148
+ df = get_data()
149
+ # Simple anomaly detection: Daily cost > Mean + 3*STD
150
+ daily_cost = df.groupby(['date', 'service'])['cost'].sum().reset_index()
151
+ anomalies = []
152
+
153
+ for service in df['service'].unique():
154
+ svc_data = daily_cost[daily_cost['service'] == service]
155
+ mean = svc_data['cost'].mean()
156
+ std = svc_data['cost'].std()
157
+ threshold = mean + 3 * std
158
+
159
+ outliers = svc_data[svc_data['cost'] > threshold]
160
+ for _, row in outliers.iterrows():
161
+ anomalies.append({
162
+ 'date': row['date'],
163
+ 'service': service,
164
+ 'cost': round(row['cost'], 2),
165
+ 'threshold': round(threshold, 2),
166
+ 'severity': 'Critical' if row['cost'] > mean * 2 else 'High'
167
+ })
168
+
169
+ return jsonify(sorted(anomalies, key=lambda x: x['date'], reverse=True))
170
+
171
+ @app.route('/api/recommendations')
172
+ def api_recommendations():
173
+ # Simulate logic: Find resources that are consistent but "expensive" -> Suggest RI
174
+ # Or find Dev resources running on weekends
175
+
176
+ recommendations = [
177
+ {
178
+ 'id': 1,
179
+ 'title': '购买 EC2 预留实例 (RI)',
180
+ 'description': '检测到 5 台 m5.large 实例长期运行,购买 1 年期全预付 RI 可节省 35%。',
181
+ 'potential_savings': 450.00,
182
+ 'effort': 'Medium',
183
+ 'category': 'Rate Optimization'
184
+ },
185
+ {
186
+ 'id': 2,
187
+ 'title': '清理未关联的弹性 IP',
188
+ 'description': '发现 3 个 EIP 未绑定到运行中的实例。',
189
+ 'potential_savings': 15.00,
190
+ 'effort': 'Low',
191
+ 'category': 'Waste'
192
+ },
193
+ {
194
+ 'id': 3,
195
+ 'title': 'S3 生命周期策略优化',
196
+ 'description': '2TB 的日志数据超过 90 天未访问,建议归档至 Glacier。',
197
+ 'potential_savings': 120.50,
198
+ 'effort': 'Medium',
199
+ 'category': 'Storage'
200
+ },
201
+ {
202
+ 'id': 4,
203
+ 'title': 'RDS 实例空闲检测',
204
+ 'description': 'db-staging-01 在过去 7 天 CPU 使用率低于 2%。',
205
+ 'potential_savings': 85.20,
206
+ 'effort': 'High',
207
+ 'category': 'Rightsizing'
208
+ }
209
+ ]
210
+ return jsonify(recommendations)
211
+
212
+ @app.route('/api/breakdown')
213
+ def api_breakdown():
214
+ df = get_data()
215
+ # Breakdown by Service
216
+ by_service = df.groupby('service')['cost'].sum().sort_values(ascending=False)
217
+ # Breakdown by Environment
218
+ by_env = df.groupby('environment')['cost'].sum().sort_values(ascending=False)
219
+
220
+ return jsonify({
221
+ 'service_breakdown': [{'name': k, 'value': round(v, 2)} for k, v in by_service.items()],
222
+ 'env_breakdown': [{'name': k, 'value': round(v, 2)} for k, v in by_env.items()]
223
+ })
224
+
225
+ def _ensure_schema(df: pd.DataFrame) -> pd.DataFrame:
226
+ required_cols = ['date', 'resource_id', 'resource_name', 'service', 'region', 'environment', 'cost', 'usage_amount']
227
+ for col in required_cols:
228
+ if col not in df.columns:
229
+ df[col] = None
230
+ df['date'] = df['date'].fillna(datetime.date.today().strftime('%Y-%m-%d')).astype(str)
231
+ df['resource_id'] = df['resource_id'].fillna(df['resource_name'].fillna('').astype(str) + '-' + pd.Series(range(len(df))).astype(str)).astype(str)
232
+ df['resource_name'] = df['resource_name'].fillna('Imported-' + pd.Series(range(len(df))).astype(str)).astype(str)
233
+ df['service'] = df['service'].fillna('Unknown Service').astype(str)
234
+ df['region'] = df['region'].fillna('us-east-1').astype(str)
235
+ df['environment'] = df['environment'].fillna('Dev').astype(str)
236
+ df['cost'] = pd.to_numeric(df['cost'], errors='coerce').fillna(0.0)
237
+ df['usage_amount'] = pd.to_numeric(df['usage_amount'], errors='coerce').fillna(0.0)
238
+ return df[required_cols]
239
+
240
+ @app.route('/api/upload', methods=['POST'])
241
+ def api_upload():
242
+ global DATA_CACHE
243
+ file = request.files.get('file')
244
+ if not file:
245
+ return jsonify({'status': 'error', 'message': '未收到文件'}), 400
246
+ filename = file.filename or 'uploaded'
247
+ try:
248
+ if filename.lower().endswith('.csv'):
249
+ chunks = pd.read_csv(file.stream, chunksize=100000, encoding='utf-8', on_bad_lines='skip')
250
+ df = pd.concat(list(chunks), ignore_index=True)
251
+ elif filename.lower().endswith('.json'):
252
+ payload = json.load(file.stream)
253
+ df = pd.DataFrame(payload if isinstance(payload, list) else [payload])
254
+ else:
255
+ tmp_path = os.path.join('/tmp', filename)
256
+ file.save(tmp_path)
257
+ return jsonify({'status': 'success', 'message': '二进制文件已保存', 'path': tmp_path})
258
+ df = _ensure_schema(df)
259
+ DATA_CACHE = df
260
+ return jsonify({'status': 'success', 'rows': int(len(df))})
261
+ except Exception as e:
262
+ return jsonify({'status': 'error', 'message': f'导入失败: {str(e)}'}), 500
263
+
264
+ def _is_api_request():
265
+ return request.path.startswith('/api/')
266
+
267
+ @app.errorhandler(404)
268
+ def handle_404(e):
269
+ if _is_api_request():
270
+ return jsonify({'status': 'error', 'message': '接口不存在'}), 404
271
+ return ('页面不存在 (404)', 404)
272
+
273
+ @app.errorhandler(500)
274
+ def handle_500(e):
275
+ if _is_api_request():
276
+ return jsonify({'status': 'error', 'message': '服务器内部错误'}), 500
277
+ return ('内部服务器错误,请稍后再试', 500)
278
+
279
+ @app.route('/api/refresh', methods=['POST'])
280
+ def api_refresh():
281
+ get_data(refresh=True)
282
+ return jsonify({'status': 'success'})
283
+
284
+ if __name__ == '__main__':
285
+ port = int(os.environ.get('PORT', 7860))
286
+ app.run(host='0.0.0.0', port=port)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Flask==3.0.0
2
+ pandas==2.1.4
3
+ numpy==1.26.3
4
+ gunicorn==21.2.0
5
+ faker==22.5.1
templates/index.html ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN" class="dark">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>云成本精算师 | Cloud Cost Optimizer</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
9
+ <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
10
+ <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
11
+ <script>
12
+ tailwind.config = {
13
+ darkMode: 'class',
14
+ theme: {
15
+ extend: {
16
+ colors: {
17
+ primary: '#3B82F6',
18
+ secondary: '#10B981',
19
+ dark: '#0F172A',
20
+ card: '#1E293B'
21
+ }
22
+ }
23
+ }
24
+ }
25
+ </script>
26
+ <style>
27
+ [v-cloak] { display: none; }
28
+ body { background-color: #0F172A; color: #E2E8F0; }
29
+ .chart-container { height: 350px; width: 100%; }
30
+ /* Custom scrollbar */
31
+ ::-webkit-scrollbar { width: 8px; }
32
+ ::-webkit-scrollbar-track { background: #1E293B; }
33
+ ::-webkit-scrollbar-thumb { background: #475569; border-radius: 4px; }
34
+ ::-webkit-scrollbar-thumb:hover { background: #64748B; }
35
+ </style>
36
+ </head>
37
+ <body class="antialiased min-h-screen">
38
+ <div id="app" v-cloak class="p-6 max-w-[1600px] mx-auto">
39
+ <!-- Header -->
40
+ <header class="flex justify-between items-center mb-8">
41
+ <div>
42
+ <h1 class="text-3xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-blue-400 to-teal-400">
43
+ 云成本精算师
44
+ </h1>
45
+ <p class="text-slate-400 mt-1 text-sm">FinOps 智能分析与优化平台</p>
46
+ </div>
47
+ <div class="flex gap-4">
48
+ <button @click="refreshData" :disabled="loading"
49
+ class="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-blue-600 rounded-lg transition-colors disabled:opacity-50">
50
+ <span v-if="loading" class="animate-spin">↻</span>
51
+ <span v-else>↻</span>
52
+ <span>生成新模拟数据</span>
53
+ </button>
54
+ <label class="flex items-center gap-2 px-4 py-2 bg-slate-700 hover:bg-slate-600 rounded-lg cursor-pointer">
55
+ <input id="fileInput" type="file" class="hidden" @change="onFileSelected">
56
+ <span>选择账单文件</span>
57
+ </label>
58
+ <button @click="uploadFile" :disabled="!selectedFile || loading"
59
+ class="flex items-center gap-2 px-4 py-2 bg-secondary hover:bg-emerald-600 rounded-lg transition-colors disabled:opacity-50">
60
+ <span>上传账单</span>
61
+ </button>
62
+ <span class="text-slate-400 text-sm self-center" v-if="uploadStatus">[[ uploadStatus ]]</span>
63
+ </div>
64
+ </header>
65
+
66
+ <!-- KPI Cards -->
67
+ <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
68
+ <div class="bg-card p-6 rounded-xl border border-slate-700/50 shadow-lg">
69
+ <div class="text-slate-400 text-sm mb-2">总支出 (近90天)</div>
70
+ <div class="text-3xl font-bold text-white">$[[ summary.total_cost ]]</div>
71
+ <div class="mt-2 text-xs text-slate-500">模拟 AWS 账单数据</div>
72
+ </div>
73
+ <div class="bg-card p-6 rounded-xl border border-slate-700/50 shadow-lg">
74
+ <div class="text-slate-400 text-sm mb-2">本月支出 (MTD)</div>
75
+ <div class="text-3xl font-bold text-white">$[[ summary.current_month_cost ]]</div>
76
+ <div class="mt-2 text-xs flex items-center" :class="summary.mom_change > 0 ? 'text-red-400' : 'text-green-400'">
77
+ <span v-if="summary.mom_change > 0">↑</span>
78
+ <span v-else>↓</span>
79
+ [[ Math.abs(summary.mom_change) ]]% 环比上月
80
+ </div>
81
+ </div>
82
+ <div class="bg-card p-6 rounded-xl border border-slate-700/50 shadow-lg">
83
+ <div class="text-slate-400 text-sm mb-2">下月预测</div>
84
+ <div class="text-3xl font-bold text-white">$[[ summary.forecast ]]</div>
85
+ <div class="mt-2 text-xs text-slate-500">基于线性趋势预测</div>
86
+ </div>
87
+ <div class="bg-card p-6 rounded-xl border border-slate-700/50 shadow-lg">
88
+ <div class="text-slate-400 text-sm mb-2">异常检测</div>
89
+ <div class="text-3xl font-bold" :class="anomalies.length > 0 ? 'text-red-500' : 'text-green-500'">
90
+ [[ anomalies.length ]]
91
+ </div>
92
+ <div class="mt-2 text-xs text-slate-500">过去 90 天内的突增</div>
93
+ </div>
94
+ </div>
95
+
96
+ <!-- Charts Section -->
97
+ <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
98
+ <!-- Main Trend Chart -->
99
+ <div class="lg:col-span-2 bg-card p-6 rounded-xl border border-slate-700/50 shadow-lg">
100
+ <h3 class="text-lg font-semibold mb-4 text-white">日成本趋势</h3>
101
+ <div id="trendChart" class="chart-container"></div>
102
+ </div>
103
+
104
+ <!-- Breakdown Chart -->
105
+ <div class="bg-card p-6 rounded-xl border border-slate-700/50 shadow-lg">
106
+ <h3 class="text-lg font-semibold mb-4 text-white">服务成本占比</h3>
107
+ <div id="pieChart" class="chart-container"></div>
108
+ </div>
109
+ </div>
110
+
111
+ <!-- Lower Section -->
112
+ <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
113
+ <!-- Anomalies List -->
114
+ <div class="bg-card p-6 rounded-xl border border-slate-700/50 shadow-lg flex flex-col h-full">
115
+ <h3 class="text-lg font-semibold mb-4 text-white flex items-center gap-2">
116
+ <span class="w-2 h-2 rounded-full bg-red-500"></span>
117
+ 异常成本预警
118
+ </h3>
119
+ <div class="overflow-y-auto flex-1 max-h-[400px]">
120
+ <table class="w-full text-left text-sm">
121
+ <thead class="bg-slate-800/50 text-slate-400 sticky top-0">
122
+ <tr>
123
+ <th class="p-3">日期</th>
124
+ <th class="p-3">服务</th>
125
+ <th class="p-3 text-right">花费</th>
126
+ <th class="p-3 text-right">阈值</th>
127
+ <th class="p-3 text-center">级别</th>
128
+ </tr>
129
+ </thead>
130
+ <tbody class="divide-y divide-slate-700/50">
131
+ <tr v-for="item in anomalies" :key="item.date + item.service" class="hover:bg-slate-700/20">
132
+ <td class="p-3 text-slate-300">[[ item.date ]]</td>
133
+ <td class="p-3 text-blue-400">[[ item.service ]]</td>
134
+ <td class="p-3 text-right font-mono text-white">$[[ item.cost ]]</td>
135
+ <td class="p-3 text-right font-mono text-slate-500">$[[ item.threshold ]]</td>
136
+ <td class="p-3 text-center">
137
+ <span class="px-2 py-1 rounded text-xs font-bold"
138
+ :class="item.severity === 'Critical' ? 'bg-red-500/20 text-red-400' : 'bg-orange-500/20 text-orange-400'">
139
+ [[ item.severity ]]
140
+ </span>
141
+ </td>
142
+ </tr>
143
+ <tr v-if="anomalies.length === 0">
144
+ <td colspan="5" class="p-8 text-center text-slate-500">无异常记录</td>
145
+ </tr>
146
+ </tbody>
147
+ </table>
148
+ </div>
149
+ </div>
150
+
151
+ <!-- Recommendations -->
152
+ <div class="bg-card p-6 rounded-xl border border-slate-700/50 shadow-lg flex flex-col h-full">
153
+ <h3 class="text-lg font-semibold mb-4 text-white flex items-center gap-2">
154
+ <span class="w-2 h-2 rounded-full bg-green-500"></span>
155
+ 优化建议
156
+ </h3>
157
+ <div class="space-y-4 overflow-y-auto flex-1 max-h-[400px]">
158
+ <div v-for="rec in recommendations" :key="rec.id"
159
+ class="p-4 rounded-lg bg-slate-800/50 border border-slate-700 hover:border-primary/50 transition-all">
160
+ <div class="flex justify-between items-start mb-2">
161
+ <h4 class="font-semibold text-white">[[ rec.title ]]</h4>
162
+ <span class="text-green-400 font-bold text-sm">节省 $[[ rec.potential_savings ]]/月</span>
163
+ </div>
164
+ <p class="text-slate-400 text-sm mb-3">[[ rec.description ]]</p>
165
+ <div class="flex gap-2 text-xs">
166
+ <span class="px-2 py-1 rounded bg-slate-700 text-slate-300">[[ rec.category ]]</span>
167
+ <span class="px-2 py-1 rounded bg-slate-700 text-slate-300">难度: [[ rec.effort ]]</span>
168
+ </div>
169
+ </div>
170
+ </div>
171
+ </div>
172
+ </div>
173
+ </div>
174
+
175
+ <script>
176
+ const { createApp, ref, onMounted } = Vue;
177
+
178
+ createApp({
179
+ delimiters: ['[[', ']]'],
180
+ setup() {
181
+ const loading = ref(false);
182
+ const summary = ref({ total_cost: 0, current_month_cost: 0, mom_change: 0, forecast: 0 });
183
+ const anomalies = ref([]);
184
+ const recommendations = ref([]);
185
+ const selectedFile = ref(null);
186
+ const uploadStatus = ref('');
187
+
188
+ let trendChart = null;
189
+ let pieChart = null;
190
+
191
+ const initCharts = () => {
192
+ trendChart = echarts.init(document.getElementById('trendChart'));
193
+ pieChart = echarts.init(document.getElementById('pieChart'));
194
+
195
+ window.addEventListener('resize', () => {
196
+ trendChart.resize();
197
+ pieChart.resize();
198
+ });
199
+ };
200
+
201
+ const fetchSummary = async () => {
202
+ const res = await axios.get('/api/summary');
203
+ summary.value = res.data;
204
+ };
205
+
206
+ const fetchTrend = async () => {
207
+ const res = await axios.get('/api/trend');
208
+ const option = {
209
+ backgroundColor: 'transparent',
210
+ tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
211
+ legend: { data: res.data.series.map(s => s.name), textStyle: { color: '#94a3b8' }, bottom: 0 },
212
+ grid: { left: '3%', right: '4%', bottom: '10%', containLabel: true },
213
+ xAxis: {
214
+ type: 'category',
215
+ data: res.data.dates,
216
+ axisLine: { lineStyle: { color: '#475569' } },
217
+ axisLabel: { color: '#94a3b8' }
218
+ },
219
+ yAxis: {
220
+ type: 'value',
221
+ axisLine: { show: false },
222
+ splitLine: { lineStyle: { color: '#334155' } },
223
+ axisLabel: { color: '#94a3b8', formatter: '${value}' }
224
+ },
225
+ series: res.data.series
226
+ };
227
+ trendChart.setOption(option);
228
+ };
229
+
230
+ const fetchBreakdown = async () => {
231
+ const res = await axios.get('/api/breakdown');
232
+ const option = {
233
+ backgroundColor: 'transparent',
234
+ tooltip: { trigger: 'item', formatter: '{b}: ${c} ({d}%)' },
235
+ legend: { orient: 'vertical', left: 'left', textStyle: { color: '#94a3b8' } },
236
+ series: [
237
+ {
238
+ name: 'Cost',
239
+ type: 'pie',
240
+ radius: ['50%', '70%'],
241
+ avoidLabelOverlap: false,
242
+ itemStyle: { borderRadius: 10, borderColor: '#1E293B', borderWidth: 2 },
243
+ label: { show: false },
244
+ labelLine: { show: false },
245
+ data: res.data.service_breakdown
246
+ }
247
+ ]
248
+ };
249
+ pieChart.setOption(option);
250
+ };
251
+
252
+ const fetchAnomalies = async () => {
253
+ const res = await axios.get('/api/anomalies');
254
+ anomalies.value = res.data;
255
+ };
256
+
257
+ const fetchRecommendations = async () => {
258
+ const res = await axios.get('/api/recommendations');
259
+ recommendations.value = res.data;
260
+ };
261
+
262
+ const loadAllData = async () => {
263
+ loading.value = true;
264
+ try {
265
+ await Promise.all([
266
+ fetchSummary(),
267
+ fetchTrend(),
268
+ fetchBreakdown(),
269
+ fetchAnomalies(),
270
+ fetchRecommendations()
271
+ ]);
272
+ } catch (e) {
273
+ console.error("Error loading data", e);
274
+ } finally {
275
+ loading.value = false;
276
+ }
277
+ };
278
+
279
+ const refreshData = async () => {
280
+ loading.value = true;
281
+ try {
282
+ await axios.post('/api/refresh');
283
+ await loadAllData();
284
+ } catch (e) {
285
+ console.error("Error refreshing data", e);
286
+ } finally {
287
+ loading.value = false;
288
+ }
289
+ };
290
+
291
+ const onFileSelected = (e) => {
292
+ selectedFile.value = e.target.files[0] || null;
293
+ uploadStatus.value = selectedFile.value ? `已选择:${selectedFile.value.name}` : '';
294
+ };
295
+
296
+ const uploadFile = async () => {
297
+ if (!selectedFile.value) return;
298
+ loading.value = true;
299
+ uploadStatus.value = '上传中...';
300
+ try {
301
+ const formData = new FormData();
302
+ formData.append('file', selectedFile.value);
303
+ const res = await axios.post('/api/upload', formData, {
304
+ headers: { 'Content-Type': 'multipart/form-data' },
305
+ maxContentLength: Infinity,
306
+ maxBodyLength: Infinity
307
+ });
308
+ uploadStatus.value = res.data.status === 'success'
309
+ ? `上传成功,行数:${res.data.rows || 0}`
310
+ : `上传失败:${res.data.message || '未知错误'}`;
311
+ await loadAllData();
312
+ } catch (e) {
313
+ uploadStatus.value = `上传失败:${e?.response?.data?.message || e.message}`;
314
+ } finally {
315
+ loading.value = false;
316
+ }
317
+ };
318
+
319
+ onMounted(() => {
320
+ initCharts();
321
+ loadAllData();
322
+ });
323
+
324
+ return {
325
+ loading,
326
+ summary,
327
+ anomalies,
328
+ recommendations,
329
+ refreshData,
330
+ selectedFile,
331
+ uploadStatus,
332
+ onFileSelected,
333
+ uploadFile
334
+ };
335
+ }
336
+ }).mount('#app');
337
+ </script>
338
+ </body>
339
+ </html>