yangtb24 commited on
Commit
931e053
·
verified ·
1 Parent(s): 5bd5ccf

Upload 7 files

Browse files
Files changed (7) hide show
  1. api_client.py +123 -0
  2. app.py +162 -374
  3. config.py +24 -0
  4. data_manager.py +211 -0
  5. scheduler_jobs.py +89 -0
  6. templates/account_statements.html +423 -0
  7. templates/dashboard.html +152 -235
api_client.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ from datetime import datetime
4
+ import pytz
5
+ import config
6
+
7
+ shanghai_tz = pytz.timezone(config.SHANGHAI_TZ_STR)
8
+
9
+ def api_login(email, password):
10
+ payload = {"email": email, "password": password}
11
+ try:
12
+ response = requests.post(config.LOGIN_URL, json=payload, timeout=10)
13
+ response.raise_for_status()
14
+ data = response.json()
15
+ cookies = response.cookies
16
+ jwt_token = cookies.get("jwt_token")
17
+
18
+ if data.get("code") == 0 and jwt_token:
19
+ return jwt_token, None
20
+ else:
21
+ error_message = data.get('message', "未知登录错误")
22
+ if data.get("code") == 0 and not jwt_token:
23
+ error_message = "响应成功但未返回 jwt_token。"
24
+ return None, f"{error_message} (Code: {data.get('code')})"
25
+ except requests.exceptions.Timeout:
26
+ return None, "登录请求超时。"
27
+ except requests.exceptions.RequestException as e:
28
+ return None, f"登录请求错误: {str(e)}"
29
+ except json.JSONDecodeError:
30
+ return None, "登录响应不是有效的 JSON。"
31
+
32
+ def get_api_profile(email, token):
33
+ if not token:
34
+ return None, "Token 为空,无法获取 Profile。"
35
+
36
+ cookies = {"jwt_token": token}
37
+ try:
38
+ response = requests.get(config.PROFILE_URL, cookies=cookies, timeout=10)
39
+ response.raise_for_status()
40
+ profile_data = response.json()
41
+ if profile_data.get("code") == 0 and profile_data.get("data"):
42
+ return profile_data.get("data"), None
43
+ else:
44
+ error_message = profile_data.get('message', "未知 Profile 错误")
45
+ if profile_data.get("code") == 0 and not profile_data.get("data"):
46
+ error_message = "响应成功但未返回 Profile 数据。"
47
+ return None, f"{error_message} (Code: {profile_data.get('code')})"
48
+ except requests.exceptions.Timeout:
49
+ return None, "获取 Profile 请求超时。"
50
+ except requests.exceptions.RequestException as e:
51
+ return None, f"获取 Profile 请求错误: {str(e)}"
52
+ except json.JSONDecodeError:
53
+ return None, "Profile 响应不是有效的 JSON。"
54
+
55
+ def get_api_card_info(email, token):
56
+ if not token:
57
+ return None, "Token 为空,无法获取卡片信息。"
58
+
59
+ cookies = {"jwt_token": token}
60
+ print(f"[{datetime.now(shanghai_tz)}] 尝试为账户 {email} 获取卡片信息...")
61
+ try:
62
+ response = requests.get(config.CARD_INFO_URL, cookies=cookies, timeout=10)
63
+ response.raise_for_status()
64
+ card_data = response.json()
65
+ if card_data.get("code") == 0 and "items" in card_data.get("data", {}):
66
+ items = card_data["data"]["items"]
67
+ if items:
68
+ item = items[0]
69
+ provider_bin = None
70
+ if item.get("provider"):
71
+ parts = item["provider"].split('_')
72
+ if len(parts) > 1 and parts[-1].isdigit():
73
+ provider_bin = parts[-1]
74
+
75
+ processed_card_info = {
76
+ "provider_bin": provider_bin,
77
+ "card_last_four_digits": item.get("card_last_four_digits"),
78
+ "consumption_limit": item.get("consumption_limit"),
79
+ "status": item.get("status"),
80
+ "name": item.get("name"),
81
+ "available_balance": item.get("available_balance")
82
+ }
83
+ return processed_card_info, None
84
+ else:
85
+ return None, None
86
+ elif card_data.get("code") == 0 and not card_data.get("data", {}).get("items"):
87
+ return None, None
88
+ else:
89
+ error_message = card_data.get('message', "未知卡片信息错误")
90
+ if card_data.get("code") == 0 and not card_data.get("data"):
91
+ error_message = "响应成功但未返回卡片数据。"
92
+ return None, f"{error_message} (Code: {card_data.get('code')})"
93
+ except requests.exceptions.Timeout:
94
+ return None, "获取卡片信息请求超时。"
95
+ except requests.exceptions.RequestException as e:
96
+ return None, f"获取卡片信息请求错误: {str(e)}"
97
+ except json.JSONDecodeError:
98
+ return None, "卡片信息响应不是有效的 JSON。"
99
+
100
+ def get_statement_records(token, page=1, size=10):
101
+ if not token:
102
+ return None, "Token 为空,无法获取账单记录。"
103
+
104
+ cookies = {"jwt_token": token}
105
+ payload = {"page": page, "size": size}
106
+ statement_url = f"{config.BASE_API_URL}/user/statement/record"
107
+
108
+ try:
109
+ response = requests.post(statement_url, json=payload, cookies=cookies, timeout=20)
110
+ response.raise_for_status()
111
+ data = response.json()
112
+
113
+ if data.get("code") == 0:
114
+ return data, None
115
+ else:
116
+ error_message = data.get('message', "获取账单记录时发生未知错误")
117
+ return None, f"{error_message} (Code: {data.get('code')})"
118
+ except requests.exceptions.Timeout:
119
+ return None, "获取账单记录请求超时。"
120
+ except requests.exceptions.RequestException as e:
121
+ return None, f"获取账单记录请求错误: {str(e)}"
122
+ except json.JSONDecodeError:
123
+ return None, "账单记录响应不是有效的 JSON。"
app.py CHANGED
@@ -1,329 +1,14 @@
1
  import os
2
- import json
3
- import threading
4
- from datetime import datetime, timezone, timedelta
5
- from flask import Flask, request, jsonify, render_template_string, redirect, url_for, session
 
6
  import requests
7
- from apscheduler.schedulers.background import BackgroundScheduler
8
- import pytz
9
- from dotenv import load_dotenv
10
-
11
- load_dotenv()
12
 
13
  app = Flask(__name__)
14
- app.secret_key = os.getenv("SECRET_KEY")
15
- if not app.secret_key:
16
- print("警告: SECRET_KEY 环境变量未设置。将使用默认的、不安全的密钥。请在生产环境中设置一个安全的 SECRET_KEY。")
17
- app.secret_key = "dev_secret_key_for_testing_only_change_me"
18
- app.permanent_session_lifetime = timedelta(days=30)
19
-
20
- LOGIN_URL = "https://api-card.infini.money/user/login"
21
- PROFILE_URL = "https://api-card.infini.money/user/profile"
22
- CARD_INFO_URL = "https://api-card.infini.money/card/info"
23
- FRONTEND_PASSWORD = os.getenv("PASSWORD")
24
- ACCOUNTS_JSON = os.getenv("ACCOUNTS")
25
-
26
- accounts_data = {}
27
- shanghai_tz = pytz.timezone('Asia/Shanghai')
28
- scheduler = BackgroundScheduler(daemon=True, timezone=shanghai_tz)
29
- data_lock = threading.Lock()
30
-
31
- def parse_accounts():
32
- global accounts_data
33
- if not ACCOUNTS_JSON:
34
- print("错误: ACCOUNTS 环境变量未设置。")
35
- return False
36
- try:
37
- accounts_list = json.loads(ACCOUNTS_JSON)
38
- if not isinstance(accounts_list, list):
39
- print("错误: ACCOUNTS 环境变量必须是一个 JSON 数组。")
40
- return False
41
-
42
- temp_accounts_data = {}
43
- for acc in accounts_list:
44
- if isinstance(acc, dict) and "email" in acc and "password" in acc:
45
- temp_accounts_data[acc["email"]] = {
46
- "password": acc["password"],
47
- "token": None,
48
- "profile": None,
49
- "last_login_success": None,
50
- "last_profile_success": None,
51
- "last_login_attempt": None,
52
- "last_profile_attempt": None,
53
- "login_error": None,
54
- "profile_error": None,
55
- "cards_info": None,
56
- "last_card_info_success": None,
57
- "last_card_info_attempt": None,
58
- "card_info_error": None,
59
- }
60
- else:
61
- print(f"警告: ACCOUNTS 中的条目格式不正确: {acc}")
62
-
63
- with data_lock:
64
- accounts_data = temp_accounts_data
65
- print(f"成功加载 {len(accounts_data)} 个账户。")
66
- return True
67
- except json.JSONDecodeError:
68
- print("错误: ACCOUNTS 环境变量不是有效的 JSON 格式。")
69
- return False
70
-
71
- def api_login(email, password):
72
- payload = {"email": email, "password": password}
73
- try:
74
- response = requests.post(LOGIN_URL, json=payload, timeout=10)
75
- response.raise_for_status()
76
- data = response.json()
77
- cookies = response.cookies
78
- jwt_token = cookies.get("jwt_token")
79
-
80
- if data.get("code") == 0 and jwt_token:
81
- return jwt_token, None
82
- else:
83
- error_message = data.get('message', "未知登录错误")
84
- if data.get("code") == 0 and not jwt_token:
85
- error_message = "响应成功但未返回 jwt_token。"
86
- return None, f"{error_message} (Code: {data.get('code')})"
87
- except requests.exceptions.Timeout:
88
- return None, "登录请求超时。"
89
- except requests.exceptions.RequestException as e:
90
- return None, f"登录请求错误: {str(e)}"
91
- except json.JSONDecodeError:
92
- return None, "登录响应不是有效的 JSON。"
93
-
94
- def get_api_profile(email, token):
95
- if not token:
96
- return None, "Token 为空,无法获取 Profile。"
97
-
98
- cookies = {"jwt_token": token}
99
- try:
100
- response = requests.get(PROFILE_URL, cookies=cookies, timeout=10)
101
- response.raise_for_status()
102
- profile_data = response.json()
103
- if profile_data.get("code") == 0 and profile_data.get("data"):
104
- return profile_data.get("data"), None
105
- else:
106
- error_message = profile_data.get('message', "未知 Profile 错误")
107
- if profile_data.get("code") == 0 and not profile_data.get("data"):
108
- error_message = "响应成功但未返回 Profile 数据。"
109
- return None, f"{error_message} (Code: {profile_data.get('code')})"
110
- except requests.exceptions.Timeout:
111
- return None, "获取 Profile 请求超时。"
112
- except requests.exceptions.RequestException as e:
113
- return None, f"获取 Profile 请求错误: {str(e)}"
114
- except json.JSONDecodeError:
115
- return None, "Profile 响��不是有效的 JSON。"
116
-
117
- def get_api_card_info(email, token):
118
- if not token:
119
- return None, "Token 为空,无法获取卡片信息。"
120
-
121
- cookies = {"jwt_token": token}
122
- print(f"[{datetime.now(shanghai_tz)}] 尝试为账户 {email} 获取卡片信息...")
123
- try:
124
- response = requests.get(CARD_INFO_URL, cookies=cookies, timeout=10)
125
- response.raise_for_status()
126
- card_data = response.json()
127
- if card_data.get("code") == 0 and "items" in card_data.get("data", {}):
128
- items = card_data["data"]["items"]
129
- if items:
130
- item = items[0]
131
- provider_bin = None
132
- if item.get("provider"):
133
- parts = item["provider"].split('_')
134
- if len(parts) > 1 and parts[-1].isdigit():
135
- provider_bin = parts[-1]
136
-
137
- processed_card_info = {
138
- "provider_bin": provider_bin,
139
- "card_last_four_digits": item.get("card_last_four_digits"),
140
- "consumption_limit": item.get("consumption_limit"),
141
- "status": item.get("status"),
142
- "name": item.get("name"),
143
- "available_balance": item.get("available_balance")
144
- }
145
- return processed_card_info, None
146
- else:
147
- return None, None
148
- elif card_data.get("code") == 0 and not card_data.get("data", {}).get("items"):
149
- return None, None
150
- else:
151
- error_message = card_data.get('message', "未知卡片信息错误")
152
- if card_data.get("code") == 0 and not card_data.get("data"):
153
- error_message = "响应成功但未返回卡片数据。"
154
- return None, f"{error_message} (Code: {card_data.get('code')})"
155
- except requests.exceptions.Timeout:
156
- return None, "获取卡片信息请求超时。"
157
- except requests.exceptions.RequestException as e:
158
- return None, f"获取卡片信息请求错误: {str(e)}"
159
- except json.JSONDecodeError:
160
- return None, "卡片信息响应不是有效的 JSON。"
161
-
162
- def login_and_store_token(email):
163
- global accounts_data
164
- with data_lock:
165
- account_info = accounts_data.get(email)
166
- if not account_info:
167
- print(f"错误: 账户 {email} 未找到。")
168
- return
169
-
170
- password = account_info["password"]
171
- print(f"[{datetime.now(shanghai_tz)}] 尝试为账户 {email} 登录...")
172
-
173
- token, error = api_login(email, password)
174
-
175
- with data_lock:
176
- accounts_data[email]["last_login_attempt"] = datetime.now(shanghai_tz)
177
- if token:
178
- accounts_data[email]["token"] = token
179
- accounts_data[email]["last_login_success"] = True
180
- accounts_data[email]["login_error"] = None
181
- print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 登录成功。")
182
- else:
183
- accounts_data[email]["token"] = None
184
- accounts_data[email]["last_login_success"] = False
185
- accounts_data[email]["login_error"] = error
186
- print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 登录失败: {error}")
187
-
188
- def fetch_and_store_profile(email):
189
- global accounts_data
190
- with data_lock:
191
- account_info = accounts_data.get(email)
192
- if not account_info:
193
- print(f"错误: 账户 {email} 未找到 (fetch_and_store_profile)。")
194
- return
195
- token = account_info.get("token")
196
-
197
- # 以下所有逻辑都应在 fetch_and_store_profile 函数内部
198
- if not token:
199
- print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 没有有效的 token,跳过获取 Profile。")
200
- with data_lock:
201
- accounts_data[email]["last_profile_attempt"] = datetime.now(shanghai_tz)
202
- accounts_data[email]["last_profile_success"] = False
203
- accounts_data[email]["profile_error"] = "无有效 Token"
204
- accounts_data[email]["profile"] = None
205
- # 由于没有token,卡片信息也无法获取
206
- accounts_data[email]["last_card_info_attempt"] = datetime.now(shanghai_tz)
207
- accounts_data[email]["cards_info"] = None
208
- accounts_data[email]["last_card_info_success"] = False
209
- accounts_data[email]["card_info_error"] = "因 Token 为空未尝试"
210
- return
211
-
212
- print(f"[{datetime.now(shanghai_tz)}] 尝试为账户 {email} 获取 Profile...")
213
- profile, error = get_api_profile(email, token)
214
-
215
- profile_fetch_successful_this_attempt = False
216
- with data_lock:
217
- accounts_data[email]["last_profile_attempt"] = datetime.now(shanghai_tz)
218
- if profile:
219
- accounts_data[email]["profile"] = profile
220
- accounts_data[email]["last_profile_success"] = True
221
- accounts_data[email]["profile_error"] = None
222
- profile_fetch_successful_this_attempt = True
223
- print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 获取 Profile 成功。")
224
- else:
225
- accounts_data[email]["profile"] = None
226
- accounts_data[email]["last_profile_success"] = False
227
- accounts_data[email]["profile_error"] = error
228
- print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 获取 Profile 失败: {error}")
229
- if error and ("token" in error.lower() or "auth" in error.lower() or "登录" in error.lower()):
230
- print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 获取 Profile 失败,疑似 Token 失效,将尝试重新登录。")
231
- accounts_data[email]["token"] = None # 清除失效的token
232
- # 如果获取 profile 失败,则不应继续获取卡片信息
233
- accounts_data[email]["last_card_info_attempt"] = datetime.now(shanghai_tz)
234
- accounts_data[email]["cards_info"] = None
235
- accounts_data[email]["last_card_info_success"] = False
236
- accounts_data[email]["card_info_error"] = "因 Profile 获取失败未尝试"
237
- return # 确保在这里返回,不再执行后续的卡片信息获取
238
-
239
- # 只有当 profile 获取成功时才继续获取卡片信息
240
- if profile_fetch_successful_this_attempt:
241
- # 重新从 data_lock 内获取 token,因为它可能在上面被清除了
242
- current_token_for_cards = None
243
- with data_lock:
244
- # 确保在访问 token 前,account_info 仍然有效且 email 存在
245
- if email in accounts_data:
246
- current_token_for_cards = accounts_data[email].get("token")
247
- else: # 理论上不应该发生,但作为防御性编程
248
- print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 在获取卡片信息前数据结构异常,跳过。")
249
- return
250
-
251
-
252
- if not current_token_for_cards:
253
- print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 在获取卡片信息前发现 Token 已失效或被清除,跳过。")
254
- with data_lock:
255
- if email in accounts_data: # 再次检查
256
- accounts_data[email]["last_card_info_attempt"] = datetime.now(shanghai_tz)
257
- accounts_data[email]["cards_info"] = None
258
- accounts_data[email]["last_card_info_success"] = False
259
- accounts_data[email]["card_info_error"] = "因 Token 失效未尝试"
260
- return
261
-
262
- print(f"[{datetime.now(shanghai_tz)}] Profile 获取成功,继续为账户 {email} 获取卡片信息...")
263
- cards_info, card_error = get_api_card_info(email, current_token_for_cards)
264
-
265
- with data_lock:
266
- if email in accounts_data: # 再次检查
267
- accounts_data[email]["last_card_info_attempt"] = datetime.now(shanghai_tz)
268
- if cards_info:
269
- accounts_data[email]["cards_info"] = cards_info
270
- accounts_data[email]["last_card_info_success"] = True
271
- accounts_data[email]["card_info_error"] = None
272
- print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 获取卡片信息成功。")
273
- elif card_error: # API 调用有错误
274
- accounts_data[email]["cards_info"] = None
275
- accounts_data[email]["last_card_info_success"] = False
276
- accounts_data[email]["card_info_error"] = card_error
277
- print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 获取卡片信息失败: {card_error}")
278
- else: # API 调用成功,但没有卡片数据
279
- accounts_data[email]["cards_info"] = None
280
- accounts_data[email]["last_card_info_success"] = True # 标记为成功,因为API调用是成功的
281
- accounts_data[email]["card_info_error"] = None # 没有错误
282
- print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 获取卡片信息成功,但无卡片数据。")
283
- # else 分支(profile_fetch_successful_this_attempt 为 False)已在上面处理 profile 获取失败的情况并返回
284
-
285
- def initial_login_all_accounts():
286
- print("程序启动,开始为所有账户执行初始登录...")
287
- threads = []
288
- with data_lock:
289
- emails_to_login = list(accounts_data.keys())
290
-
291
- for email in emails_to_login:
292
- thread = threading.Thread(target=login_and_store_token, args=(email,))
293
- threads.append(thread)
294
- thread.start()
295
- for thread in threads:
296
- thread.join()
297
- print("所有账户初始登录尝试完成。")
298
-
299
- def scheduled_login_all_accounts():
300
- print(f"[{datetime.now(shanghai_tz)}] 定时任务:开始为所有账户重新登录...")
301
- threads = []
302
- with data_lock:
303
- emails_to_login = list(accounts_data.keys())
304
-
305
- for email in emails_to_login:
306
- thread = threading.Thread(target=login_and_store_token, args=(email,))
307
- threads.append(thread)
308
- thread.start()
309
- for thread in threads:
310
- thread.join()
311
- print(f"[{datetime.now(shanghai_tz)}] 定时任务:所有账户重新登录尝试完成。")
312
- scheduled_fetch_all_profiles()
313
-
314
- def scheduled_fetch_all_profiles():
315
- print(f"[{datetime.now(shanghai_tz)}] 定时任务:开始为所有账户获取 Profile...")
316
- threads = []
317
- with data_lock:
318
- emails_to_fetch = list(accounts_data.keys())
319
-
320
- for email in emails_to_fetch:
321
- thread = threading.Thread(target=fetch_and_store_profile, args=(email,))
322
- threads.append(thread)
323
- thread.start()
324
- for thread in threads:
325
- thread.join()
326
- print(f"[{datetime.now(shanghai_tz)}] 定时任务:所有账户获取 Profile 尝试完成。")
327
 
328
  LOGIN_FORM_HTML = """
329
  <!DOCTYPE html>
@@ -421,7 +106,7 @@ LOGIN_FORM_HTML = """
421
 
422
  @app.route('/', methods=['GET', 'POST'])
423
  def login_frontend():
424
- if not FRONTEND_PASSWORD:
425
  return "错误: 前端密码 (PASSWORD 环境变量) 未设置。", 500
426
 
427
  if 'logged_in' in session and session['logged_in']:
@@ -430,8 +115,27 @@ def login_frontend():
430
  error = None
431
  if request.method == 'POST':
432
  entered_password = request.form.get('password')
433
- if entered_password == FRONTEND_PASSWORD:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
  session['logged_in'] = True
 
435
  session.permanent = True
436
  return redirect(url_for('dashboard'))
437
  else:
@@ -444,6 +148,17 @@ def dashboard():
444
  return redirect(url_for('login_frontend'))
445
  return render_template_string(open('templates/dashboard.html', encoding='utf-8').read())
446
 
 
 
 
 
 
 
 
 
 
 
 
447
  @app.route('/logout')
448
  def logout():
449
  session.pop('logged_in', None)
@@ -454,68 +169,141 @@ def get_all_data():
454
  if not ('logged_in' in session and session['logged_in']):
455
  return jsonify({"error": "未授权访问"}), 401
456
 
457
- with data_lock:
458
- display_data = {}
459
- for email, data in accounts_data.items():
460
- display_data[email] = {
461
- "profile": data.get("profile"),
462
- "last_login_success": data.get("last_login_success"),
463
- "last_profile_success": data.get("last_profile_success"),
464
- "last_login_attempt": data.get("last_login_attempt").isoformat() if data.get("last_login_attempt") else None,
465
- "last_profile_attempt": data.get("last_profile_attempt").isoformat() if data.get("last_profile_attempt") else None,
466
- "login_error": data.get("login_error"),
467
- "profile_error": data.get("profile_error"),
468
- "token_present": bool(data.get("token")),
469
- "cards_info": data.get("cards_info"),
470
- "last_card_info_success": data.get("last_card_info_success"),
471
- "last_card_info_attempt": data.get("last_card_info_attempt").isoformat() if data.get("last_card_info_attempt") else None,
472
- "card_info_error": data.get("card_info_error")
473
- }
474
  return jsonify(display_data)
475
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476
  @app.route('/api/refresh', methods=['POST'])
477
  def manual_refresh_all_data():
478
  if not ('logged_in' in session and session['logged_in']):
479
  return jsonify({"error": "未授权访问"}), 401
480
 
481
- print(f"[{datetime.now(shanghai_tz)}] 手动触发数据刷新...")
482
- threading.Thread(target=scheduled_login_all_accounts).start()
483
  return jsonify({"message": "刷新任务已启动,请稍后查看数据。"}), 202
484
 
485
  if __name__ == '__main__':
486
- if not FRONTEND_PASSWORD:
487
- print("警告: PASSWORD 环境变量未设置,前端将无法登录。")
488
- if not parse_accounts():
489
- print("由于账户加载失败,程序将退出。请检查 ACCOUNTS 环境变量。")
490
- else:
491
- initial_login_all_accounts()
492
- scheduled_fetch_all_profiles()
493
-
494
- scheduler.add_job(scheduled_login_all_accounts, 'interval', days=3, id='job_login_all')
495
- scheduler.add_job(scheduled_fetch_all_profiles, 'interval', minutes=30, id='job_fetch_profiles')
496
-
497
- try:
498
- scheduler.start()
499
- print("定时任务已启动。")
500
- print(f"APScheduler jobs: {scheduler.get_jobs()}")
501
- except Exception as e:
502
- print(f"启动 APScheduler 失败: {e}")
503
 
 
504
  is_hf_space = os.getenv("SPACE_ID") is not None
505
  if not is_hf_space:
506
- app.run(host='0.0.0.0', port=7860, debug=True)
 
 
 
 
 
 
507
 
508
  else:
509
- if FRONTEND_PASSWORD and parse_accounts():
510
- initial_login_all_accounts()
511
- scheduled_fetch_all_profiles()
512
- if not scheduler.running:
513
- scheduler.add_job(scheduled_login_all_accounts, 'interval', days=3, id='job_login_all_gunicorn')
514
- scheduler.add_job(scheduled_fetch_all_profiles, 'interval', minutes=30, id='job_fetch_profiles_gunicorn')
515
- try:
516
- scheduler.start()
517
- print("APScheduler (Gunicorn) jobs started.")
518
- except Exception as e:
519
- print(f"Failed to start APScheduler (Gunicorn): {e}")
520
- else:
521
- print("Gunicorn: 未能正确初始化账户或密码未设置。")
 
1
  import os
2
+ from flask import Flask, request, jsonify, render_template_string, redirect, url_for, session, render_template
3
+ import config
4
+ import data_manager
5
+ import scheduler_jobs
6
+ import api_client
7
  import requests
 
 
 
 
 
8
 
9
  app = Flask(__name__)
10
+ app.secret_key = config.SECRET_KEY
11
+ app.permanent_session_lifetime = config.PERMANENT_SESSION_LIFETIME
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  LOGIN_FORM_HTML = """
14
  <!DOCTYPE html>
 
106
 
107
  @app.route('/', methods=['GET', 'POST'])
108
  def login_frontend():
109
+ if not config.FRONTEND_PASSWORD:
110
  return "错误: 前端密码 (PASSWORD 环境变量) 未设置。", 500
111
 
112
  if 'logged_in' in session and session['logged_in']:
 
115
  error = None
116
  if request.method == 'POST':
117
  entered_password = request.form.get('password')
118
+ if entered_password == config.FRONTEND_PASSWORD:
119
+ accounts_list = data_manager.get_accounts_from_config()
120
+ if not accounts_list:
121
+ error = "配置错误:未找到账户信息。"
122
+ return render_template_string(LOGIN_FORM_HTML, error=error)
123
+
124
+ first_account_email = accounts_list[0]['email']
125
+ first_account_password = accounts_list[0]['password']
126
+
127
+ jwt_token, login_api_error = api_client.api_login(first_account_email, first_account_password)
128
+
129
+ if login_api_error:
130
+ error = f"API 登录失败: {login_api_error}"
131
+ return render_template_string(LOGIN_FORM_HTML, error=error)
132
+
133
+ if not jwt_token:
134
+ error = "API 登录成功但未能获取 Token。"
135
+ return render_template_string(LOGIN_FORM_HTML, error=error)
136
+
137
  session['logged_in'] = True
138
+ session['jwt_token'] = jwt_token
139
  session.permanent = True
140
  return redirect(url_for('dashboard'))
141
  else:
 
148
  return redirect(url_for('login_frontend'))
149
  return render_template_string(open('templates/dashboard.html', encoding='utf-8').read())
150
 
151
+ @app.route('/dashboard/statements')
152
+ def account_statements_page():
153
+ if not ('logged_in' in session and session['logged_in']):
154
+ return redirect(url_for('login_frontend'))
155
+
156
+ account_email_param = request.args.get('email')
157
+ if not account_email_param:
158
+ return redirect(url_for('dashboard'))
159
+
160
+ return render_template('account_statements.html', account_email=account_email_param)
161
+
162
  @app.route('/logout')
163
  def logout():
164
  session.pop('logged_in', None)
 
169
  if not ('logged_in' in session and session['logged_in']):
170
  return jsonify({"error": "未授权访问"}), 401
171
 
172
+ display_data = data_manager.get_accounts_data_for_display()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  return jsonify(display_data)
174
 
175
+ @app.route('/api/account_statements', methods=['GET'])
176
+ def get_account_statements():
177
+ if not ('logged_in' in session and session['logged_in']):
178
+ return jsonify({"error": "未授权访问"}), 401
179
+
180
+ email_param = request.args.get('email')
181
+ if not email_param:
182
+ return jsonify({"error": "缺少 'email' 参数"}), 400
183
+
184
+ page = request.args.get('page', 1, type=int)
185
+ size = request.args.get('size', 10000, type=int)
186
+
187
+ token_to_use = None
188
+ target_account_password = None
189
+
190
+ all_accounts = data_manager.get_accounts_from_config()
191
+ for acc in all_accounts:
192
+ if acc.get('email') == email_param:
193
+ target_account_password = acc.get('password')
194
+ break
195
+
196
+ if not target_account_password:
197
+ return jsonify({"error": f"未找到账户 {email_param} 的配置信息或密码。"}), 404
198
+
199
+ print(f"为特定账户 {email_param} 获取账单,尝试重新登录获取专属 token...")
200
+ specific_token, login_error = api_client.api_login(email_param, target_account_password)
201
+
202
+ if login_error:
203
+ print(f"为账户 {email_param} 获取专属 token 失败: {login_error}")
204
+ return jsonify({"error": f"为账户 {email_param} 获取账单时登录失败: {login_error}"}), 500
205
+
206
+ if not specific_token:
207
+ return jsonify({"error": f"为账户 {email_param} 获取账单时未能获取专属 API token。"}), 500
208
+
209
+ token_to_use = specific_token
210
+ print(f"成功获取账户 {email_param} 的专属 token,将用于获取账单。")
211
+
212
+ statement_data, error = api_client.get_statement_records(token_to_use, page, size)
213
+
214
+ if error:
215
+ return jsonify({"error": f"获取账户 {email_param} 的账单失败: {error}"}), 500
216
+
217
+ return jsonify(statement_data)
218
+
219
+ @app.route('/api/account_summary_statistics', methods=['GET'])
220
+ def get_account_summary_statistics():
221
+ if not ('logged_in' in session and session['logged_in']):
222
+ return jsonify({"error": "未授权访问"}), 401
223
+
224
+ email_param = request.args.get('email')
225
+ if not email_param:
226
+ return jsonify({"error": "缺少 'email' 参数"}), 400
227
+
228
+ target_account_password = None
229
+ all_accounts = data_manager.get_accounts_from_config()
230
+ for acc in all_accounts:
231
+ if acc.get('email') == email_param:
232
+ target_account_password = acc.get('password')
233
+ break
234
+
235
+ if not target_account_password:
236
+ return jsonify({"error": f"未找到账户 {email_param} 的配置信息或密码。"}), 404
237
+
238
+ print(f"为特定账户 {email_param} 获取统计摘要,尝试重新登录获取专属 token...")
239
+ specific_token, login_error = api_client.api_login(email_param, target_account_password)
240
+
241
+ if login_error:
242
+ print(f"为账户 {email_param} 获取专属 token 失败: {login_error}")
243
+ return jsonify({"error": f"为账户 {email_param} 获取统计摘要时登录失败: {login_error}"}), 500
244
+
245
+ if not specific_token:
246
+ return jsonify({"error": f"为账户 {email_param} 获取统计摘要时未能获取专属 API token。"}), 500
247
+
248
+ token_to_use = specific_token
249
+ print(f"成功获取账户 {email_param} 的专属 token,将用于获取统计摘要。")
250
+
251
+ external_api_url = "https://api-card.infini.money/user/statement/statistics"
252
+ headers = {
253
+ "Authorization": f"Bearer {token_to_use}",
254
+ "User-Agent": "InfiniDashboard/1.0"
255
+ }
256
+
257
+ try:
258
+ response = requests.get(external_api_url, headers=headers, timeout=10)
259
+ response.raise_for_status()
260
+
261
+ api_response_data = response.json()
262
+
263
+ return jsonify(api_response_data)
264
+
265
+ except requests.exceptions.HTTPError as http_err:
266
+ print(f"HTTP error occurred while fetching statistics for {email_param}: {http_err}")
267
+ try:
268
+ error_content = http_err.response.json()
269
+ return jsonify({"error": f"获取统计摘要失败 (API错误): {error_content.get('message', str(http_err))}", "details": error_content}), http_err.response.status_code
270
+ except:
271
+ return jsonify({"error": f"获取统计摘要失败: {str(http_err)}"}), getattr(http_err.response, 'status_code', 500)
272
+ except requests.exceptions.RequestException as req_err:
273
+ print(f"Request error occurred while fetching statistics for {email_param}: {req_err}")
274
+ return jsonify({"error": f"获取统计摘要时发生网络请求错误: {str(req_err)}"}), 503
275
+ except Exception as e:
276
+ print(f"An unexpected error occurred while fetching statistics for {email_param}: {e}")
277
+ return jsonify({"error": f"获取统计摘要时发生未知错误: {str(e)}"}), 500
278
+
279
+
280
  @app.route('/api/refresh', methods=['POST'])
281
  def manual_refresh_all_data():
282
  if not ('logged_in' in session and session['logged_in']):
283
  return jsonify({"error": "未授权访问"}), 401
284
 
285
+ scheduler_jobs.manual_refresh_all_data_job()
 
286
  return jsonify({"message": "刷新任务已启动,请稍后查看数据。"}), 202
287
 
288
  if __name__ == '__main__':
289
+ if not config.FRONTEND_PASSWORD:
290
+ print("警告: PASSWORD 环境变量未设置,前端将无法登录。程序将尝试继续,但部分功能可能受限。")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
 
292
+ if scheduler_jobs.initialize_scheduler(is_gunicorn=False):
293
  is_hf_space = os.getenv("SPACE_ID") is not None
294
  if not is_hf_space:
295
+ print("在本地环境运行 Flask 开发服务器...")
296
+ app.run(host='0.0.0.0', port=int(os.getenv("PORT", 7860)), debug=False)
297
+ else:
298
+ print("检测到在 Hugging Face Space 环境中运行。假定由 Gunicorn 等 WSGI 服务器启动。")
299
+ else:
300
+ print("定时任务初始化失败,程序退出。")
301
+
302
 
303
  else:
304
+ print("在 Gunicorn 环境下初始化应用...")
305
+ if not config.FRONTEND_PASSWORD:
306
+ print("Gunicorn警告: PASSWORD 环境变量未设置,前端将无法登录。")
307
+
308
+ if not scheduler_jobs.initialize_scheduler(is_gunicorn=True):
309
+ print("Gunicorn: 定时任务初始化失败。")
 
 
 
 
 
 
 
config.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from datetime import timedelta
4
+
5
+ load_dotenv()
6
+
7
+ SECRET_KEY = os.getenv("SECRET_KEY", "dev_secret_key_for_testing_only_change_me")
8
+ PERMANENT_SESSION_LIFETIME = timedelta(days=30)
9
+
10
+ LOGIN_URL = "https://api-card.infini.money/user/login"
11
+ PROFILE_URL = "https://api-card.infini.money/user/profile"
12
+ CARD_INFO_URL = "https://api-card.infini.money/card/info"
13
+ BASE_API_URL = "https://api-card.infini.money"
14
+
15
+ FRONTEND_PASSWORD = os.getenv("PASSWORD")
16
+ ACCOUNTS_JSON = os.getenv("ACCOUNTS")
17
+
18
+ SHANGHAI_TZ_STR = 'Asia/Shanghai'
19
+
20
+ if not os.getenv("SECRET_KEY"):
21
+ print("警告: SECRET_KEY 环境变量未设置。将使用默认的、不安全的密钥。请在生产环境中设置一个安全的 SECRET_KEY。")
22
+
23
+ if not FRONTEND_PASSWORD:
24
+ print("警告: PASSWORD 环境变量未设置,前端将无法登录。")
data_manager.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import threading
3
+ from datetime import datetime
4
+ import pytz
5
+ import config
6
+ import api_client
7
+
8
+ accounts_data = {}
9
+ data_lock = threading.Lock()
10
+ shanghai_tz = pytz.timezone(config.SHANGHAI_TZ_STR)
11
+
12
+ def parse_accounts():
13
+ global accounts_data
14
+ if not config.ACCOUNTS_JSON:
15
+ print("错误: ACCOUNTS 环境变量未设置。")
16
+ return False
17
+ try:
18
+ accounts_list = json.loads(config.ACCOUNTS_JSON)
19
+ if not isinstance(accounts_list, list):
20
+ print("错误: ACCOUNTS 环境变量必须是一个 JSON 数组。")
21
+ return False
22
+
23
+ temp_accounts_data = {}
24
+ for acc in accounts_list:
25
+ if isinstance(acc, dict) and "email" in acc and "password" in acc:
26
+ temp_accounts_data[acc["email"]] = {
27
+ "password": acc["password"],
28
+ "token": None,
29
+ "profile": None,
30
+ "last_login_success": None,
31
+ "last_profile_success": None,
32
+ "last_login_attempt": None,
33
+ "last_profile_attempt": None,
34
+ "login_error": None,
35
+ "profile_error": None,
36
+ "cards_info": None,
37
+ "last_card_info_success": None,
38
+ "last_card_info_attempt": None,
39
+ "card_info_error": None,
40
+ }
41
+ else:
42
+ print(f"警告: ACCOUNTS 中的条目格式不正确: {acc}")
43
+
44
+ with data_lock:
45
+ accounts_data = temp_accounts_data
46
+ print(f"成功加载 {len(accounts_data)} 个账户。")
47
+ return True
48
+ except json.JSONDecodeError:
49
+ print("错误: ACCOUNTS 环境变量不是有效的 JSON 格式。")
50
+ return False
51
+
52
+ def login_and_store_token(email):
53
+ global accounts_data
54
+ with data_lock:
55
+ account_info = accounts_data.get(email)
56
+ if not account_info:
57
+ print(f"错误: 账户 {email} 未找到。")
58
+ return
59
+
60
+ password = account_info["password"]
61
+ print(f"[{datetime.now(shanghai_tz)}] 尝试为账户 {email} 登录...")
62
+
63
+ token, error = api_client.api_login(email, password)
64
+
65
+ with data_lock:
66
+ accounts_data[email]["last_login_attempt"] = datetime.now(shanghai_tz)
67
+ if token:
68
+ accounts_data[email]["token"] = token
69
+ accounts_data[email]["last_login_success"] = True
70
+ accounts_data[email]["login_error"] = None
71
+ print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 登录成功。")
72
+ else:
73
+ accounts_data[email]["token"] = None
74
+ accounts_data[email]["last_login_success"] = False
75
+ accounts_data[email]["login_error"] = error
76
+ print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 登录失败: {error}")
77
+
78
+ def fetch_and_store_profile(email):
79
+ global accounts_data
80
+ with data_lock:
81
+ account_info = accounts_data.get(email)
82
+ if not account_info:
83
+ print(f"错误: 账户 {email} 未找到 (fetch_and_store_profile)。")
84
+ return
85
+ token = account_info.get("token")
86
+
87
+ if not token:
88
+ print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 没有有效的 token,跳过获取 Profile。")
89
+ with data_lock:
90
+ accounts_data[email]["last_profile_attempt"] = datetime.now(shanghai_tz)
91
+ accounts_data[email]["last_profile_success"] = False
92
+ accounts_data[email]["profile_error"] = "无有效 Token"
93
+ accounts_data[email]["profile"] = None
94
+ accounts_data[email]["last_card_info_attempt"] = datetime.now(shanghai_tz)
95
+ accounts_data[email]["cards_info"] = None
96
+ accounts_data[email]["last_card_info_success"] = False
97
+ accounts_data[email]["card_info_error"] = "因 Token 为空未尝试"
98
+ return
99
+
100
+ print(f"[{datetime.now(shanghai_tz)}] 尝试为账户 {email} 获取 Profile...")
101
+ profile, error = api_client.get_api_profile(email, token)
102
+
103
+ profile_fetch_successful_this_attempt = False
104
+ with data_lock:
105
+ accounts_data[email]["last_profile_attempt"] = datetime.now(shanghai_tz)
106
+ if profile:
107
+ accounts_data[email]["profile"] = profile
108
+ accounts_data[email]["last_profile_success"] = True
109
+ accounts_data[email]["profile_error"] = None
110
+ profile_fetch_successful_this_attempt = True
111
+ print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 获取 Profile 成功。")
112
+ else:
113
+ accounts_data[email]["profile"] = None
114
+ accounts_data[email]["last_profile_success"] = False
115
+ accounts_data[email]["profile_error"] = error
116
+ print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 获取 Profile 失败: {error}")
117
+ if error and ("token" in error.lower() or "auth" in error.lower() or "登录" in error.lower()):
118
+ print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 获取 Profile 失败,疑似 Token 失效,将尝试重新登录。")
119
+ accounts_data[email]["token"] = None
120
+ accounts_data[email]["last_card_info_attempt"] = datetime.now(shanghai_tz)
121
+ accounts_data[email]["cards_info"] = None
122
+ accounts_data[email]["last_card_info_success"] = False
123
+ accounts_data[email]["card_info_error"] = "因 Profile 获取失败未尝试"
124
+ return
125
+
126
+ if profile_fetch_successful_this_attempt:
127
+ current_token_for_cards = None
128
+ with data_lock:
129
+ if email in accounts_data:
130
+ current_token_for_cards = accounts_data[email].get("token")
131
+ else:
132
+ print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 在获取卡片信息前数据结构异常,跳过。")
133
+ return
134
+
135
+
136
+ if not current_token_for_cards:
137
+ print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 在获取卡片信息前发现 Token 已失效或被清除,跳过。")
138
+ with data_lock:
139
+ if email in accounts_data:
140
+ accounts_data[email]["last_card_info_attempt"] = datetime.now(shanghai_tz)
141
+ accounts_data[email]["cards_info"] = None
142
+ accounts_data[email]["last_card_info_success"] = False
143
+ accounts_data[email]["card_info_error"] = "因 Token 失效未尝试"
144
+ return
145
+
146
+ print(f"[{datetime.now(shanghai_tz)}] Profile 获取成功,继续为账户 {email} 获取卡片信息...")
147
+ cards_info, card_error = api_client.get_api_card_info(email, current_token_for_cards)
148
+
149
+ with data_lock:
150
+ if email in accounts_data:
151
+ accounts_data[email]["last_card_info_attempt"] = datetime.now(shanghai_tz)
152
+ if cards_info:
153
+ accounts_data[email]["cards_info"] = cards_info
154
+ accounts_data[email]["last_card_info_success"] = True
155
+ accounts_data[email]["card_info_error"] = None
156
+ print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 获取卡片信息成功。")
157
+ elif card_error:
158
+ accounts_data[email]["cards_info"] = None
159
+ accounts_data[email]["last_card_info_success"] = False
160
+ accounts_data[email]["card_info_error"] = card_error
161
+ print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 获取卡片信息失败: {card_error}")
162
+ else: # No error, but no card_info (e.g. no cards for the account)
163
+ accounts_data[email]["cards_info"] = None
164
+ accounts_data[email]["last_card_info_success"] = True # Success in fetching, just no data
165
+ accounts_data[email]["card_info_error"] = None
166
+ print(f"[{datetime.now(shanghai_tz)}] 账户 {email} 获取卡片信息成功,但无卡片数据。")
167
+
168
+ def get_accounts_data_for_display():
169
+ with data_lock:
170
+ display_data = {}
171
+ for email, data in accounts_data.items():
172
+ display_data[email] = {
173
+ "profile": data.get("profile"),
174
+ "last_login_success": data.get("last_login_success"),
175
+ "last_profile_success": data.get("last_profile_success"),
176
+ "last_login_attempt": data.get("last_login_attempt").isoformat() if data.get("last_login_attempt") else None,
177
+ "last_profile_attempt": data.get("last_profile_attempt").isoformat() if data.get("last_profile_attempt") else None,
178
+ "login_error": data.get("login_error"),
179
+ "profile_error": data.get("profile_error"),
180
+ "token_present": bool(data.get("token")),
181
+ "cards_info": data.get("cards_info"),
182
+ "last_card_info_success": data.get("last_card_info_success"),
183
+ "last_card_info_attempt": data.get("last_card_info_attempt").isoformat() if data.get("last_card_info_attempt") else None,
184
+ "card_info_error": data.get("card_info_error")
185
+ }
186
+ return display_data
187
+
188
+ def get_all_account_emails():
189
+ with data_lock:
190
+ return list(accounts_data.keys())
191
+
192
+ def get_accounts_from_config():
193
+ if not config.ACCOUNTS_JSON:
194
+ print("错误: ACCOUNTS 环境变量未设置 (get_accounts_from_config)。")
195
+ return []
196
+ try:
197
+ accounts_list = json.loads(config.ACCOUNTS_JSON)
198
+ if not isinstance(accounts_list, list):
199
+ print("错误: ACCOUNTS 环境变量必须是一个 JSON 数组 (get_accounts_from_config)。")
200
+ return []
201
+
202
+ valid_accounts = []
203
+ for acc in accounts_list:
204
+ if isinstance(acc, dict) and "email" in acc and "password" in acc:
205
+ valid_accounts.append({"email": acc["email"], "password": acc["password"]})
206
+ else:
207
+ print(f"警告: ACCOUNTS 中的条目格式不正确,已跳过: {acc} (get_accounts_from_config)")
208
+ return valid_accounts
209
+ except json.JSONDecodeError:
210
+ print("错误: ACCOUNTS 环境变量不是有效的 JSON 格式 (get_accounts_from_config)。")
211
+ return []
scheduler_jobs.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import threading
3
+ from datetime import datetime, timedelta
4
+ from apscheduler.schedulers.background import BackgroundScheduler
5
+ import pytz
6
+ import config
7
+ import data_manager
8
+
9
+ shanghai_tz = pytz.timezone(config.SHANGHAI_TZ_STR)
10
+ scheduler = BackgroundScheduler(daemon=True, timezone=shanghai_tz)
11
+
12
+ def initial_login_all_accounts_job():
13
+ print("程序启动,开始为所有账户执行初始登录...")
14
+ threads = []
15
+ emails_to_login = data_manager.get_all_account_emails()
16
+
17
+ for email in emails_to_login:
18
+ thread = threading.Thread(target=data_manager.login_and_store_token, args=(email,))
19
+ threads.append(thread)
20
+ thread.start()
21
+ for thread in threads:
22
+ thread.join()
23
+ print("所有账户初始登录尝试完成。")
24
+
25
+ def scheduled_login_all_accounts_job():
26
+ print(f"[{datetime.now(shanghai_tz)}] 定时任务:开始为所有账户重新登录...")
27
+ threads = []
28
+ emails_to_login = data_manager.get_all_account_emails()
29
+
30
+ for email in emails_to_login:
31
+ thread = threading.Thread(target=data_manager.login_and_store_token, args=(email,))
32
+ threads.append(thread)
33
+ thread.start()
34
+ for thread in threads:
35
+ thread.join()
36
+ print(f"[{datetime.now(shanghai_tz)}] 定时任务:所有账户重新登录尝试完成。")
37
+ scheduled_fetch_all_profiles_job()
38
+
39
+ def scheduled_fetch_all_profiles_job():
40
+ print(f"[{datetime.now(shanghai_tz)}] 定时任务:开始为所有账户获取 Profile...")
41
+ threads = []
42
+ emails_to_fetch = data_manager.get_all_account_emails()
43
+
44
+ for email in emails_to_fetch:
45
+ thread = threading.Thread(target=data_manager.fetch_and_store_profile, args=(email,))
46
+ threads.append(thread)
47
+ thread.start()
48
+ for thread in threads:
49
+ thread.join()
50
+ print(f"[{datetime.now(shanghai_tz)}] 定时任务:所有账户获取 Profile 尝试完成。")
51
+
52
+ def manual_refresh_all_data_job():
53
+ print(f"[{datetime.now(shanghai_tz)}] 手动触发数据刷新...")
54
+ threading.Thread(target=scheduled_fetch_all_profiles_job).start()
55
+
56
+
57
+ def initialize_scheduler(is_gunicorn=False):
58
+ if not data_manager.parse_accounts():
59
+ print("由于账户加载失败,定时任务无法初始化。请检查 ACCOUNTS 环境变量。")
60
+ return False
61
+
62
+ initial_login_all_accounts_job()
63
+ scheduled_fetch_all_profiles_job()
64
+
65
+ login_job_id = 'job_login_all_gunicorn' if is_gunicorn else 'job_login_all'
66
+ profile_job_id = 'job_fetch_profiles_gunicorn' if is_gunicorn else 'job_fetch_profiles'
67
+
68
+ if scheduler.get_job(login_job_id):
69
+ scheduler.remove_job(login_job_id)
70
+ if scheduler.get_job(profile_job_id):
71
+ scheduler.remove_job(profile_job_id)
72
+
73
+ run_date_login = datetime.now(shanghai_tz) + timedelta(days=3)
74
+ run_date_profile = datetime.now(shanghai_tz) + timedelta(minutes=30)
75
+
76
+ scheduler.add_job(scheduled_login_all_accounts_job, 'interval', days=3, id=login_job_id, next_run_time=run_date_login)
77
+ scheduler.add_job(scheduled_fetch_all_profiles_job, 'interval', minutes=30, id=profile_job_id, next_run_time=run_date_profile)
78
+
79
+ try:
80
+ if not scheduler.running:
81
+ scheduler.start()
82
+ print(f"定时任务已启动 ({'Gunicorn' if is_gunicorn else 'Local'})。")
83
+ else:
84
+ print(f"定时任务已在运行中 ({'Gunicorn' if is_gunicorn else 'Local'})。")
85
+ print(f"APScheduler jobs: {scheduler.get_jobs()}")
86
+ return True
87
+ except Exception as e:
88
+ print(f"启动 APScheduler 失败 ({'Gunicorn' if is_gunicorn else 'Local'}): {e}")
89
+ return False
templates/account_statements.html ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>账户账单详情</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com">
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
9
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
10
+ <style>
11
+ :root {
12
+ --bg-color: #ffffff;
13
+ --text-color: #111827;
14
+ --secondary-text-color: #6b7280;
15
+ --border-color: #e5e7eb;
16
+ --card-bg-color: #ffffff;
17
+ --accent-color: #000000;
18
+ --error-color: #ef4444;
19
+ --success-color: #10b981;
20
+ --info-color: #3b82f6;
21
+ --income-color: #22c55e;
22
+ --expense-color: #ef4444;
23
+ --summary-bar-bg: #f9fafb;
24
+ }
25
+ body {
26
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
27
+ margin: 0;
28
+ background-color: var(--summary-bar-bg);
29
+ color: var(--text-color);
30
+ line-height: 1.6;
31
+ -webkit-font-smoothing: antialiased;
32
+ -moz-osx-font-smoothing: grayscale;
33
+ }
34
+ .container {
35
+ max-width: 1200px;
36
+ margin: 0 auto;
37
+ padding: 32px 20px;
38
+ }
39
+ header {
40
+ display: flex;
41
+ justify-content: space-between;
42
+ align-items: center;
43
+ margin-bottom: 16px;
44
+ padding-bottom: 24px;
45
+ border-bottom: 1px solid var(--border-color);
46
+ }
47
+ header h1 {
48
+ margin: 0;
49
+ font-size: 28px;
50
+ color: var(--text-color);
51
+ font-weight: 700;
52
+ }
53
+ .header-actions {
54
+ display: flex;
55
+ align-items: center;
56
+ }
57
+ .header-actions .back-link {
58
+ padding: 8px 16px;
59
+ background-color: var(--bg-color);
60
+ color: var(--secondary-text-color);
61
+ border: 1px solid var(--border-color);
62
+ border-radius: 6px;
63
+ cursor: pointer;
64
+ font-size: 14px;
65
+ font-weight: 500;
66
+ text-decoration: none;
67
+ transition: background-color 0.2s ease, border-color 0.2s ease;
68
+ }
69
+ .header-actions .back-link:hover {
70
+ background-color: #f3f4f6;
71
+ border-color: #d1d5db;
72
+ text-decoration: none;
73
+ }
74
+
75
+ #account-summary-bar {
76
+ display: grid;
77
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
78
+ gap: 20px;
79
+ background-color: var(--card-bg-color);
80
+ padding: 20px;
81
+ border-radius: 8px;
82
+ margin-bottom: 30px;
83
+ border: 1px solid var(--border-color);
84
+ box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
85
+ }
86
+ .summary-item {
87
+ text-align: left;
88
+ }
89
+ .summary-label {
90
+ display: block;
91
+ font-size: 0.875em;
92
+ color: var(--secondary-text-color);
93
+ margin-bottom: 4px;
94
+ font-weight: 500;
95
+ }
96
+ .summary-value {
97
+ display: block;
98
+ font-size: 1.5em;
99
+ color: var(--text-color);
100
+ font-weight: 600;
101
+ }
102
+
103
+ .statement-card-item {
104
+ background-color: var(--card-bg-color);
105
+ border-radius: 8px;
106
+ border: 1px solid var(--border-color);
107
+ box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
108
+ margin-bottom: 12px;
109
+ cursor: pointer;
110
+ transition: box-shadow 0.2s ease, transform 0.2s ease;
111
+ }
112
+ .statement-card-item:hover {
113
+ box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06);
114
+ transform: translateY(-2px);
115
+ }
116
+ .statement-card-item .card-summary {
117
+ padding: 16px 20px;
118
+ display: flex;
119
+ justify-content: space-between;
120
+ align-items: center;
121
+ }
122
+ .statement-card-item .summary-left { display: flex; align-items: center; gap: 12px; }
123
+ .statement-card-item .change-type-icon {
124
+ width: 32px; height: 32px; border-radius: 50%; display: flex;
125
+ align-items: center; justify-content: center; font-weight: 600; color: white;
126
+ }
127
+ .statement-card-item .summary-info .description { font-weight: 500; color: var(--text-color); }
128
+ .statement-card-item .summary-info .timestamp { font-size: 0.875em; color: var(--secondary-text-color); }
129
+ .statement-card-item .summary-right .amount { font-weight: 600; font-size: 1.1em; }
130
+ .statement-card-item .amount.positive { color: var(--income-color); }
131
+ .statement-card-item .amount.negative { color: var(--expense-color); }
132
+ .statement-card-item .amount.neutral { color: var(--text-color); }
133
+ .statement-card-item .card-details {
134
+ padding: 0 20px 16px 20px;
135
+ border-top: 1px solid var(--border-color);
136
+ margin-top: 12px;
137
+ display: none;
138
+ }
139
+ .statement-card-item .details-grid {
140
+ display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
141
+ gap: 12px 20px; margin-top: 12px;
142
+ }
143
+ .statement-card-item .detail-item { font-size: 0.9em; }
144
+ .statement-card-item .detail-item strong { color: var(--secondary-text-color); font-weight: 500; margin-right: 8px; display: inline-block; min-width: 80px;}
145
+ .statement-card-item .detail-item span { color: var(--text-color); word-break: break-all; }
146
+ .statement-card-item .metadata-title { font-weight: 600; margin-top: 16px; margin-bottom: 8px; font-size: 0.95em; color: var(--text-color); }
147
+ .statement-card-item .metadata-item { font-size: 0.85em; padding-left: 10px; border-left: 2px solid var(--border-color); margin-bottom: 4px; }
148
+ .statement-card-item .metadata-item strong { min-width: 70px; }
149
+
150
+ #statements-loading-indicator {
151
+ text-align: center; padding: 40px; font-size: 1em; color: var(--secondary-text-color); display: none; width: 100%;
152
+ }
153
+ #statements-loading-indicator::before {
154
+ content: ''; display: inline-block; width: 24px; height: 24px;
155
+ border: 3px solid rgba(0,0,0, 0.1); border-radius: 50%;
156
+ border-top-color: var(--text-color); animation: spin 0.8s linear infinite;
157
+ margin-right: 12px; position: relative; top: 4px;
158
+ }
159
+ @keyframes spin { to { transform: rotate(360deg); } }
160
+ #pagination-controls {
161
+ margin-top: 20px;
162
+ text-align: center;
163
+ }
164
+ #pagination-controls button {
165
+ padding: 8px 16px;
166
+ margin: 0 5px;
167
+ border: 1px solid var(--border-color);
168
+ background-color: var(--card-bg-color);
169
+ color: var(--text-color);
170
+ border-radius: 6px;
171
+ cursor: pointer;
172
+ }
173
+ #pagination-controls button:disabled {
174
+ opacity: 0.5;
175
+ cursor: not-allowed;
176
+ }
177
+ #pagination-controls button:hover:not(:disabled) {
178
+ border-color: var(--accent-color);
179
+ }
180
+ </style>
181
+ </head>
182
+ <body>
183
+ <div class="container">
184
+ <header>
185
+ <h1>账户账单详情</h1>
186
+ <div class="header-actions">
187
+ <a href="{{ url_for('dashboard') }}" class="back-link">&larr; 返回仪表盘</a>
188
+ </div>
189
+ </header>
190
+
191
+ <div id="account-summary-bar">
192
+ <div class="summary-item">
193
+ <span class="summary-label">总收入</span>
194
+ <span class="summary-value" id="summary-total-income">--.-- USD</span>
195
+ </div>
196
+ <div class="summary-item">
197
+ <span class="summary-label">总支出</span>
198
+ <span class="summary-value" id="summary-total-expense">--.-- USD</span>
199
+ </div>
200
+ <div class="summary-item">
201
+ <span class="summary-label">总结余</span>
202
+ <span class="summary-value" id="summary-total-balance">--.-- USD</span>
203
+ </div>
204
+ </div>
205
+
206
+ <div id="statements-loading-indicator">正在加载账单...</div>
207
+ <div id="statement-records-container">
208
+ </div>
209
+ <div id="pagination-controls">
210
+ <button id="prev-page-btn" disabled>上一页</button>
211
+ <span id="page-info">第 1 页</span>
212
+ <button id="next-page-btn" disabled>下一页</button>
213
+ </div>
214
+ </div>
215
+
216
+ <script>
217
+ const accountEmail = "{{ account_email }}";
218
+ const recordsContainer = document.getElementById('statement-records-container');
219
+ const loadingIndicator = document.getElementById('statements-loading-indicator');
220
+ const prevPageBtn = document.getElementById('prev-page-btn');
221
+ const nextPageBtn = document.getElementById('next-page-btn');
222
+ const pageInfoElem = document.getElementById('page-info');
223
+
224
+ const summaryTotalIncomeElem = document.getElementById('summary-total-income');
225
+ const summaryTotalExpenseElem = document.getElementById('summary-total-expense');
226
+ const summaryTotalBalanceElem = document.getElementById('summary-total-balance');
227
+
228
+ let currentPage = 1;
229
+ const pageSize = 20;
230
+ let totalRecords = 0;
231
+
232
+ function formatStatementTimestamp(unixTimestamp) {
233
+ if (!unixTimestamp) return 'N/A';
234
+ const date = new Date(unixTimestamp * 1000);
235
+ return date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
236
+ }
237
+
238
+ function getChangeTypeDetails(type) {
239
+ const types = {
240
+ 1: { text: "充值", icon: "➕", color: "#22c55e" }, 2: { text: "提现", icon: "➖", color: "#ef4444" },
241
+ 3: { text: "接收", icon: "➡️", color: "#3b82f6" }, 4: { text: "发送", icon: "⬅️", color: "#f97316" },
242
+ 5: { text: "消费", icon: "💳", color: "#ef4444" }, 6: { text: "收益", icon: "💰", color: "#10b981" },
243
+ 7: { text: "提出", icon: "🔄", color: "#6366f1" }, 8: { text: "开卡", icon: "🚫", color: "#6b7280" },
244
+ 14: { text: "红包", icon: "🧧", color: "#f43f5e" }
245
+ };
246
+ return types[type] || { text: `类型 ${type}`, icon: "❓", color: "#6b7280" };
247
+ }
248
+
249
+ function formatMetadata(metadata) {
250
+ if (typeof metadata !== 'object' || metadata === null || Object.keys(metadata).length === 0) {
251
+ return '<p class="detail-item"><strong>元数据:</strong> <span>无</span></p>';
252
+ }
253
+ let html = '<div class="metadata-title">元数据:</div>';
254
+ for (const key in metadata) {
255
+ html += `<div class="metadata-item"><strong>${key}:</strong> <span>${typeof metadata[key] === 'object' ? JSON.stringify(metadata[key]) : metadata[key]}</span></div>`;
256
+ }
257
+ return html;
258
+ }
259
+
260
+ function renderStatementRecords(apiResponse) {
261
+ recordsContainer.innerHTML = '';
262
+ loadingIndicator.style.display = 'none';
263
+
264
+ if (!apiResponse || !apiResponse.data || !apiResponse.data.items) {
265
+ recordsContainer.innerHTML = '<p>无法加载账单数据或无记录。</p>';
266
+ updatePaginationControls(0);
267
+ return;
268
+ }
269
+ const items = apiResponse.data.items;
270
+ totalRecords = apiResponse.data.total || items.length;
271
+
272
+ if (items.length === 0) {
273
+ recordsContainer.innerHTML = '<p>该账户暂无账单记录。</p>';
274
+ updatePaginationControls(0);
275
+ return;
276
+ }
277
+
278
+ items.forEach(item => {
279
+ const statementItemCard = document.createElement('div');
280
+ statementItemCard.classList.add('statement-card-item');
281
+ const changeTypeDetails = getChangeTypeDetails(item.change_type);
282
+ const amountClass = item.change > 0 ? 'positive' : (item.change < 0 ? 'negative' : 'neutral');
283
+ const formattedAmount = `${item.change >= 0 ? '+' : ''}${parseFloat(item.change).toFixed(item.field === "RED_PACKET_BALANCE" || item.field === "AVAILABLE_BALANCE" ? 5 : 2)}`;
284
+
285
+ statementItemCard.innerHTML = `
286
+ <div class="card-summary">
287
+ <div class="summary-left">
288
+ <div class="change-type-icon" style="background-color: ${changeTypeDetails.color};">${changeTypeDetails.icon}</div>
289
+ <div class="summary-info">
290
+ <div class="description">${changeTypeDetails.text} - ${item.field === "AVAILABLE_BALANCE" ? "可用余额" : (item.field === "RED_PACKET_BALANCE" ? "红包余额" : item.field)}</div>
291
+ <div class="timestamp">${formatStatementTimestamp(item.created_at)}</div>
292
+ </div>
293
+ </div>
294
+ <div class="summary-right"><span class="amount ${amountClass}">${formattedAmount}</span></div>
295
+ </div>
296
+ <div class="card-details">
297
+ <div class="details-grid">
298
+ <p class="detail-item"><strong>ID:</strong> <span>${item.id}</span></p>
299
+ <p class="detail-item"><strong>交易ID:</strong> <span>${item.tx_id}</span></p>
300
+ <p class="detail-item"><strong>字段:</strong> <span>${item.field}</span></p>
301
+ <p class="detail-item"><strong>变动类型:</strong> <span>${changeTypeDetails.text} (${item.change_type})</span></p>
302
+ <p class="detail-item"><strong>变动额:</strong> <span class="${amountClass}">${formattedAmount}</span></p>
303
+ <p class="detail-item"><strong>状态:</strong> <span>${item.status === 1 ? '成功' : '处理中/失败'}</span></p>
304
+ <p class="detail-item"><strong>变动前余额:</strong> <span>${parseFloat(item.pre_balance).toFixed(5)}</span></p>
305
+ <p class="detail-item"><strong>变动后余额:</strong> <span>${parseFloat(item.balance).toFixed(5)}</span></p>
306
+ </div>
307
+ ${formatMetadata(item.metadata)}
308
+ </div>
309
+ `;
310
+ statementItemCard.querySelector('.card-summary').addEventListener('click', () => {
311
+ const details = statementItemCard.querySelector('.card-details');
312
+ details.style.display = details.style.display === 'none' || details.style.display === '' ? 'block' : 'none';
313
+ });
314
+ recordsContainer.appendChild(statementItemCard);
315
+ });
316
+ updatePaginationControls(totalRecords);
317
+ }
318
+
319
+ function updatePaginationControls(total) {
320
+ const totalPages = Math.ceil(total / pageSize);
321
+ pageInfoElem.textContent = `第 ${currentPage} / ${totalPages} 页 (共 ${total} 条)`;
322
+ prevPageBtn.disabled = currentPage === 1;
323
+ nextPageBtn.disabled = currentPage === totalPages || totalPages === 0;
324
+ }
325
+
326
+ async function fetchStatementsForPage(page) {
327
+ loadingIndicator.style.display = 'block';
328
+ recordsContainer.innerHTML = '';
329
+ try {
330
+ const response = await fetch(`/api/account_statements?email=${encodeURIComponent(accountEmail)}&page=${page}&size=${pageSize}`);
331
+ if (response.status === 401) { window.location.href = '/'; return; }
332
+ if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
333
+
334
+ const statementData = await response.json();
335
+ if (statementData.error) {
336
+ recordsContainer.innerHTML = `<p style="color: var(--error-color);">获取账单失败: ${statementData.error}</p>`;
337
+ } else {
338
+ renderStatementRecords(statementData);
339
+ }
340
+ } catch (error) {
341
+ console.error(`Error fetching statements for ${accountEmail} page ${page}:`, error);
342
+ recordsContainer.innerHTML = `<p style="color: var(--error-color);">获取账单时发生网络错误。</p>`;
343
+ }
344
+ }
345
+
346
+ prevPageBtn.addEventListener('click', () => {
347
+ if (currentPage > 1) {
348
+ currentPage--;
349
+ fetchStatementsForPage(currentPage);
350
+ }
351
+ });
352
+
353
+ nextPageBtn.addEventListener('click', () => {
354
+ const totalPages = Math.ceil(totalRecords / pageSize);
355
+ if (currentPage < totalPages) {
356
+ currentPage++;
357
+ fetchStatementsForPage(currentPage);
358
+ }
359
+ });
360
+
361
+ document.addEventListener('DOMContentLoaded', function() {
362
+ if (accountEmail) {
363
+ fetchAccountStatistics();
364
+ fetchStatementsForPage(currentPage);
365
+ } else {
366
+ recordsContainer.innerHTML = "<p>未指定账户信息。</p>";
367
+ loadingIndicator.style.display = 'none';
368
+ summaryTotalIncomeElem.textContent = 'N/A';
369
+ summaryTotalExpenseElem.textContent = 'N/A';
370
+ summaryTotalBalanceElem.textContent = 'N/A';
371
+ }
372
+ });
373
+
374
+ async function fetchAccountStatistics() {
375
+ if (!accountEmail) return;
376
+
377
+ try {
378
+ const response = await fetch(`/api/account_summary_statistics?email=${encodeURIComponent(accountEmail)}`);
379
+
380
+ if (response.status === 401) {
381
+ console.warn('Unauthorized access to statistics API via backend. User might need to log in.');
382
+ summaryTotalIncomeElem.textContent = '认证失败';
383
+ summaryTotalExpenseElem.textContent = '认证失败';
384
+ summaryTotalBalanceElem.textContent = '认证失败';
385
+ return;
386
+ }
387
+
388
+ if (!response.ok) {
389
+ let errorMsg = `HTTP error! status: ${response.status}`;
390
+ try {
391
+ const errData = await response.json();
392
+ errorMsg = errData.error || errData.message || errorMsg;
393
+ } catch (e) { }
394
+ throw new Error(errorMsg);
395
+ }
396
+
397
+ const statsData = await response.json();
398
+
399
+ if (statsData.error) {
400
+ console.error('Backend failed to get statistics:', statsData.error);
401
+ summaryTotalIncomeElem.textContent = '加载失败';
402
+ summaryTotalExpenseElem.textContent = '加载失败';
403
+ summaryTotalBalanceElem.textContent = '加载失败';
404
+ } else if (statsData.code === 0 && statsData.data) {
405
+ summaryTotalIncomeElem.textContent = `${parseFloat(statsData.data.income || 0).toFixed(2)} USD`;
406
+ summaryTotalExpenseElem.textContent = `${parseFloat(statsData.data.expense || 0).toFixed(2)} USD`;
407
+ summaryTotalBalanceElem.textContent = `${parseFloat(statsData.data.balance || 0).toFixed(2)} USD`;
408
+ } else {
409
+ console.error('Received unexpected statistics data structure from backend:', statsData);
410
+ summaryTotalIncomeElem.textContent = '数据格式错误';
411
+ summaryTotalExpenseElem.textContent = '数据格式错误';
412
+ summaryTotalBalanceElem.textContent = '数据格式错误';
413
+ }
414
+ } catch (error) {
415
+ console.error('Error fetching account statistics via backend:', error);
416
+ summaryTotalIncomeElem.textContent = '网络错误';
417
+ summaryTotalExpenseElem.textContent = '网络错误';
418
+ summaryTotalBalanceElem.textContent = '网络错误';
419
+ }
420
+ }
421
+ </script>
422
+ </body>
423
+ </html>
templates/dashboard.html CHANGED
@@ -10,20 +10,20 @@
10
  <style>
11
  :root {
12
  --bg-color: #ffffff;
13
- --text-color: #000000;
14
- --secondary-text-color: #666666;
15
- --border-color: #e0e0e0;
16
  --card-bg-color: #ffffff;
17
  --accent-color: #000000;
18
- --error-color: #ff0000;
19
- --success-color: #000000;
20
- --summary-bar-bg: #fafafa;
21
  }
22
 
23
  body {
24
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
25
  margin: 0;
26
- background-color: var(--bg-color);
27
  color: var(--text-color);
28
  line-height: 1.6;
29
  -webkit-font-smoothing: antialiased;
@@ -32,188 +32,163 @@
32
  .container {
33
  max-width: 1200px;
34
  margin: 0 auto;
35
- padding: 40px 20px;
36
  }
37
  header {
38
  display: flex;
39
- flex-direction: column;
40
- align-items: flex-start;
41
- margin-bottom: 20px;
42
- padding-bottom: 20px;
43
- border-bottom: 1px solid var(--border-color);
44
  }
45
  header h1 {
46
- margin: 0 0 10px 0;
47
- font-size: 32px;
48
  color: var(--text-color);
49
  font-weight: 700;
50
  }
51
-
52
- .top-controls-container {
53
- display: flex;
54
- justify-content: space-between;
55
- align-items: center;
56
- width: 100%;
57
- margin-bottom: 20px;
58
- padding-top: 10px;
 
 
 
59
  }
60
-
61
- #last-updated {
62
- font-size: 0.9em;
63
- color: var(--secondary-text-color);
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  }
65
-
66
  #summary-bar {
67
- display: flex;
68
- justify-content: space-between;
69
- align-items: center;
70
- background-color: var(--card-bg-color);
71
  padding: 20px;
72
  border-radius: 8px;
73
- margin-bottom: 30px;
74
  border: 1px solid var(--border-color);
75
- box-shadow: 0 1px 3px rgba(0,0,0,0.04), 0 1px 2px rgba(0,0,0,0.06);
76
  }
77
  .summary-item {
78
- text-align: center;
79
- flex-grow: 1;
80
- padding: 0 10px;
81
- }
82
- .summary-item:not(:last-child) {
83
- border-right: 1px solid var(--border-color);
84
  }
85
  .summary-label {
86
  display: block;
87
- font-size: 0.9em;
88
  color: var(--secondary-text-color);
89
- margin-bottom: 5px;
90
  font-weight: 500;
91
  }
92
  .summary-value {
93
  display: block;
94
- font-size: 1.4em;
95
  color: var(--text-color);
96
  font-weight: 600;
97
  }
98
 
99
-
100
-
101
- .actions {
102
- display: flex;
103
- }
104
- .actions button {
105
- padding: 9px 18px;
106
- background-color: var(--accent-color);
107
- color: var(--bg-color);
108
- border: 1px solid var(--accent-color);
109
- border-radius: 6px;
110
- cursor: pointer;
111
- font-size: 14px;
112
- font-weight: 500;
113
- margin-left: 12px;
114
- transition: background-color 0.2s ease, border-color 0.2s ease, color 0.2s ease;
115
- }
116
- .actions button:hover {
117
- background-color: #333333;
118
- border-color: #333333;
119
- }
120
- .actions button#logout-btn {
121
- background-color: var(--bg-color);
122
- color: var(--secondary-text-color);
123
- border: 1px solid var(--border-color);
124
- }
125
- .actions button#logout-btn:hover {
126
- background-color: #f7f7f7;
127
- border-color: #cccccc;
128
- color: var(--text-color);
129
- }
130
-
131
  #account-cards-container {
132
  display: grid;
133
- grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
134
- gap: 20px;
 
 
 
 
 
 
135
  }
136
-
137
  .account-card {
138
- padding: 20px;
 
139
  background-color: var(--card-bg-color);
140
  border-radius: 8px;
141
  border: 1px solid var(--border-color);
142
- box-shadow: 0 1px 3px rgba(0,0,0,0.04), 0 1px 2px rgba(0,0,0,0.06);
143
  transition: box-shadow 0.2s ease, transform 0.2s ease;
 
 
 
144
  }
145
- .account-card:hover {
146
- box-shadow: 0 4px 12px rgba(0,0,0,0.08), 0 2px 6px rgba(0,0,0,0.08);
147
- transform: translateY(-1px);
 
 
 
148
  }
149
-
150
  .account-info h3 {
151
  margin-top: 0;
152
- font-size: 16px;
153
  color: var(--text-color);
154
  border-bottom: 1px solid var(--border-color);
155
  padding-bottom: 12px;
156
  margin-bottom: 12px;
157
- font-weight: 600;
158
  }
159
- .account-info p { margin: 10px 0; font-size: 14px; color: var(--secondary-text-color); }
160
- .account-info p strong {
161
- color: var(--text-color);
162
- min-width: 130px;
163
  display: inline-block;
164
  font-weight: 500;
165
  }
166
  .account-info .highlight-balance {
167
- font-weight: 700;
168
- font-size: 1.1em;
169
- color: var(--text-color);
170
  }
171
  .status-ok { color: var(--success-color); font-weight: 500; }
172
  .status-error { color: var(--error-color); font-weight: 500; }
173
  .error-details {
174
- font-size: 0.9em;
175
  color: var(--error-color);
176
- margin-left: 0;
177
  white-space: pre-wrap;
178
- background-color: rgba(255,0,0,0.05);
179
- padding: 8px 10px;
180
  border-radius: 4px;
181
- margin-top: 5px;
182
- border: 1px solid rgba(255,0,0,0.1);
183
  }
184
  .account-info .card-details-integrated {
185
  margin-top: 15px;
186
  padding-top: 15px;
187
  border-top: 1px solid var(--border-color);
188
  }
189
- .account-info .card-details-integrated p {
190
- margin: 8px 0;
191
- font-size: 14px;
192
- }
193
- .account-info .card-details-integrated p strong {
194
- min-width: 100px;
195
- }
196
-
197
  #loading-indicator {
198
  text-align: center;
199
- padding: 50px;
200
- font-size: 16px;
201
  color: var(--secondary-text-color);
202
  display: none;
203
  width: 100%;
204
  }
205
  #loading-indicator::before {
206
- content: '';
207
- display: inline-block;
208
- width: 28px;
209
- height: 28px;
210
- border: 3px solid rgba(0,0,0, 0.1);
211
- border-radius: 50%;
212
- border-top-color: var(--text-color);
213
- animation: spin 0.8s linear infinite;
214
- margin-right: 15px;
215
- position: relative;
216
- top: 6px;
217
  }
218
  @keyframes spin { to { transform: rotate(360deg); } }
219
  </style>
@@ -222,15 +197,13 @@
222
  <div class="container">
223
  <header>
224
  <h1>账户仪表盘</h1>
225
- </header>
226
-
227
- <div class="top-controls-container">
228
- <div id="last-updated">最后更新时间: N/A</div>
229
- <div class="actions">
230
  <button id="refresh-btn">刷新数据</button>
231
  <button id="logout-btn">登出</button>
232
  </div>
233
- </div>
 
 
234
 
235
  <div id="summary-bar">
236
  <div class="summary-item">
@@ -247,7 +220,7 @@
247
  </div>
248
  </div>
249
 
250
- <div id="loading-indicator">正在加载数据...</div>
251
  <div id="account-cards-container">
252
  </div>
253
  </div>
@@ -255,37 +228,32 @@
255
  <script>
256
  document.addEventListener('DOMContentLoaded', function() {
257
  const accountCardsContainer = document.getElementById('account-cards-container');
258
- const loadingIndicator = document.getElementById('loading-indicator');
259
  const refreshButton = document.getElementById('refresh-btn');
260
  const logoutButton = document.getElementById('logout-btn');
261
- const lastUpdatedElem = document.getElementById('last-updated');
262
  const totalAccountsValueElem = document.getElementById('total-accounts-value');
263
  const totalBalanceValueElem = document.getElementById('total-balance-value');
264
  const totalDailyConsumptionValueElem = document.getElementById('total-daily-consumption-value');
265
 
 
266
 
267
- let autoRefreshInterval;
268
-
269
- function formatDateTime(isoString) {
270
  if (!isoString) return 'N/A';
271
  try {
272
- // 强制使用 UTC+8 (Asia/Shanghai) 时区
273
  return new Date(isoString).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
274
- } catch (e) {
275
- return 'Invalid Date';
276
- }
277
  }
278
-
279
- function displayData(data) {
280
  accountCardsContainer.innerHTML = '';
281
- loadingIndicator.style.display = 'none';
282
 
283
  const numAccounts = Object.keys(data).length;
284
  totalAccountsValueElem.textContent = numAccounts;
285
  const currentTime = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
286
  lastUpdatedElem.textContent = `最后更新时间: ${currentTime}`;
287
 
288
-
289
  if (numAccounts === 0) {
290
  accountCardsContainer.innerHTML = '<p style="text-align:center; color: #888; grid-column: 1 / -1;">没有可显示的账户数据。</p>';
291
  totalBalanceValueElem.textContent = '$0.00';
@@ -295,56 +263,38 @@
295
 
296
  let totalAvailableBalance = 0;
297
  let totalDailyConsumption = 0;
298
- let foundBalance = false;
299
- let foundConsumption = false;
300
 
301
  for (const email in data) {
302
  const account = data[email];
303
  if (account.cards_info && account.cards_info.available_balance) {
304
- const balance = parseFloat(account.cards_info.available_balance);
305
- if (!isNaN(balance)) {
306
- totalAvailableBalance += balance;
307
- foundBalance = true;
308
- }
309
  }
310
  if (account.profile && account.profile.daily_consumption) {
311
- const consumption = parseFloat(String(account.profile.daily_consumption).replace('$', ''));
312
- if (!isNaN(consumption)) {
313
- totalDailyConsumption += consumption;
314
- foundConsumption = true;
315
- }
316
  }
317
 
 
 
 
 
318
  const accountCard = document.createElement('div');
319
  accountCard.classList.add('account-card');
320
-
321
- let contentHTML = `<div class="account-info"><h3>${email}</h3>`;
322
 
 
323
  contentHTML += `<p><strong>Token 状态:</strong> ${account.token_present ? '<span class="status-ok">存在</span>' : '<span class="status-error">不存在</span>'}</p>`;
 
 
 
 
 
324
 
325
- contentHTML += `<p><strong>最后登录:</strong> ${formatDateTime(account.last_login_attempt)} - ${account.last_login_success === true ? '<span class="status-ok">成功</span>' : (account.last_login_success === false ? '<span class="status-error">失败</span>' : 'N/A')}</p>`;
326
- if (account.login_error) {
327
- contentHTML += `<p class="error-details">登录错误: ${account.login_error}</p>`;
328
- }
329
 
330
- contentHTML += `<p><strong>最后 Profile 获取:</strong> ${formatDateTime(account.last_profile_attempt)} - ${account.last_profile_success === true ? '<span class="status-ok">成功</span>' : (account.last_profile_success === false ? '<span class="status-error">失败</span>' : 'N/A')}</p>`;
331
- if (account.profile_error) {
332
- contentHTML += `<p class="error-details">Profile 错误: ${account.profile_error}</p>`;
333
- }
334
-
335
-
336
- contentHTML += `<p><strong>卡片信息获取:</strong> ${formatDateTime(account.last_card_info_attempt)} - ${account.last_card_info_success === true ? '<span class="status-ok">成功</span>' : (account.last_card_info_success === false ? '<span class="status-error">失败</span>' : 'N/A')}</p>`;
337
- if (account.card_info_error) {
338
- contentHTML += `<p class="error-details">卡片错误: ${account.card_info_error}</p>`;
339
- }
340
-
341
  if (account.profile) {
342
  contentHTML += `<p><strong>UID:</strong> ${account.profile.uid || 'N/A'}</p>`;
343
-
344
  contentHTML += `<p><strong>邀请码:</strong> ${account.profile.invitation_code || 'N/A'}</p>`;
345
  contentHTML += `<p><strong>账户状态:</strong> ${account.profile.status || 'N/A'}</p>`;
346
- } else {
347
- contentHTML += `<p>Profile 数据不可用。</p>`;
348
  }
349
 
350
  if (account.cards_info) {
@@ -352,69 +302,41 @@
352
  contentHTML += `<div class="card-details-integrated">`;
353
  contentHTML += `<p><strong>卡号:</strong> ${ (card.provider_bin && card.card_last_four_digits) ? `${card.provider_bin}xxxxxx${card.card_last_four_digits}` : (card.provider_bin ? `${card.provider_bin}xxxxxx` : (card.card_last_four_digits ? `xxxxxx${card.card_last_four_digits}` : '-')) }</p>`;
354
  contentHTML += `<p><strong>可用余额:</strong> <span class="highlight-balance">$${card.available_balance || '0.00'}</span></p>`;
355
-
356
-
357
  if (account.profile) {
358
  contentHTML += `<p><strong>每日消耗:</strong> $${account.profile.daily_consumption || '0.00'}</p>`;
359
  contentHTML += `<p><strong>总收益:</strong> $${account.profile.total_earn_balance || '0.00'}</p>`;
360
  }
361
-
362
- let dailyLimitDisplay = '-';
363
- if (card.consumption_limit !== null && card.consumption_limit !== undefined) {
364
- if (String(card.consumption_limit) === '-1') {
365
- dailyLimitDisplay = '无限制';
366
- } else {
367
- dailyLimitDisplay = `$${card.consumption_limit}`;
368
- }
369
- }
370
- contentHTML += `<p><strong>卡日限额:</strong> ${dailyLimitDisplay}</p>`;
371
- contentHTML += `</div>`;
372
- } else if (account.last_card_info_success === true) {
373
- contentHTML += `<div class="card-details-integrated">`;
374
- if (account.profile) {
375
- contentHTML += `<p><strong>每日消耗:</strong> $${account.profile.daily_consumption || '0.00'}</p>`;
376
- contentHTML += `<p><strong>总收益:</strong> $${account.profile.total_earn_balance || '0.00'}</p>`;
377
- }
378
- contentHTML += `<p><strong>卡信息:</strong> 无可用卡片。</p></div>`;
379
- } else {
380
- if (account.profile) {
381
- contentHTML += `<div class="card-details-integrated">`;
382
- contentHTML += `<p><strong>每日消耗:</strong> $${account.profile.daily_consumption || '0.00'}</p>`;
383
- contentHTML += `<p><strong>总收益:</strong> $${account.profile.total_earn_balance || '0.00'}</p>`;
384
- contentHTML += `</div>`;
385
- }
386
  }
387
-
388
  contentHTML += `</div>`;
389
  accountCard.innerHTML = contentHTML;
390
- accountCardsContainer.appendChild(accountCard);
 
391
  }
392
 
393
- totalBalanceValueElem.textContent = foundBalance ? `$${totalAvailableBalance.toFixed(2)}` : '$0.00';
394
- totalDailyConsumptionValueElem.textContent = foundConsumption ? `$${totalDailyConsumption.toFixed(2)}` : '$0.00';
395
  }
396
 
397
- async function fetchData() {
398
- loadingIndicator.style.display = 'block';
399
  try {
400
- const response = await fetch('/api/data');
401
- if (response.status === 401) {
402
- window.location.href = '/';
403
- return;
404
- }
405
- if (!response.ok) {
406
- throw new Error(`HTTP error! status: ${response.status}`);
407
- }
408
  const data = await response.json();
409
  if (data.error) {
410
- console.error("Error fetching data:", data.error);
411
- loadingIndicator.style.display = 'none';
 
412
  } else {
413
- displayData(data);
414
  }
415
  } catch (error) {
416
- console.error('Error fetching data:', error);
417
- loadingIndicator.style.display = 'none';
 
418
  }
419
  }
420
 
@@ -422,18 +344,16 @@
422
  const originalButtonText = refreshButton.textContent;
423
  refreshButton.textContent = '正在刷新...';
424
  refreshButton.disabled = true;
425
- loadingIndicator.textContent = '手动刷新中...';
426
- loadingIndicator.style.display = 'block';
 
427
 
428
  try {
429
- const response = await fetch('/api/refresh', { method: 'POST' });
430
- if (response.status === 401) {
431
- window.location.href = '/';
432
- return;
433
- }
434
-
435
  setTimeout(async () => {
436
- await fetchData();
437
  refreshButton.textContent = originalButtonText;
438
  refreshButton.disabled = false;
439
  }, 3000);
@@ -443,18 +363,15 @@
443
  lastUpdatedElem.textContent = `手动刷新失败: ${new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })}`;
444
  refreshButton.textContent = originalButtonText;
445
  refreshButton.disabled = false;
446
- loadingIndicator.style.display = 'none';
447
  }
448
  });
449
 
450
- logoutButton.addEventListener('click', () => {
451
- window.location.href = '/logout';
452
- });
453
-
454
- fetchData();
455
 
456
- if (autoRefreshInterval) clearInterval(autoRefreshInterval);
457
- autoRefreshInterval = setInterval(fetchData, 60000);
 
458
  });
459
  </script>
460
  </body>
 
10
  <style>
11
  :root {
12
  --bg-color: #ffffff;
13
+ --text-color: #111827;
14
+ --secondary-text-color: #6b7280;
15
+ --border-color: #e5e7eb;
16
  --card-bg-color: #ffffff;
17
  --accent-color: #000000;
18
+ --error-color: #ef4444;
19
+ --success-color: #10b981;
20
+ --summary-bar-bg: #f9fafb;
21
  }
22
 
23
  body {
24
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
25
  margin: 0;
26
+ background-color: var(--summary-bar-bg);
27
  color: var(--text-color);
28
  line-height: 1.6;
29
  -webkit-font-smoothing: antialiased;
 
32
  .container {
33
  max-width: 1200px;
34
  margin: 0 auto;
35
+ padding: 32px 20px;
36
  }
37
  header {
38
  display: flex;
39
+ justify-content: space-between;
40
+ align-items: center;
41
+ margin-bottom: 16px;
42
+ padding-bottom: 24px;
43
+ border-bottom: 1px solid var(--border-color);
44
  }
45
  header h1 {
46
+ margin: 0;
47
+ font-size: 28px;
48
  color: var(--text-color);
49
  font-weight: 700;
50
  }
51
+ .header-actions button {
52
+ padding: 8px 16px;
53
+ background-color: var(--accent-color);
54
+ color: var(--bg-color);
55
+ border: 1px solid var(--accent-color);
56
+ border-radius: 6px;
57
+ cursor: pointer;
58
+ font-size: 14px;
59
+ font-weight: 500;
60
+ margin-left: 12px;
61
+ transition: background-color 0.2s ease;
62
  }
63
+ .header-actions button:hover {
64
+ background-color: #333333;
65
+ }
66
+ .header-actions button#logout-btn {
67
+ background-color: var(--bg-color);
68
+ color: var(--secondary-text-color);
69
+ border: 1px solid var(--border-color);
70
+ }
71
+ .header-actions button#logout-btn:hover {
72
+ background-color: #f3f4f6;
73
+ border-color: #d1d5db;
74
+ }
75
+ #last-updated {
76
+ font-size: 0.875em;
77
+ color: var(--secondary-text-color);
78
+ margin-bottom: 24px;
79
+ text-align: right;
80
  }
 
81
  #summary-bar {
82
+ display: grid;
83
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
84
+ gap: 20px;
85
+ background-color: var(--card-bg-color);
86
  padding: 20px;
87
  border-radius: 8px;
88
+ margin-bottom: 30px;
89
  border: 1px solid var(--border-color);
90
+ box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
91
  }
92
  .summary-item {
93
+ text-align: left;
 
 
 
 
 
94
  }
95
  .summary-label {
96
  display: block;
97
+ font-size: 0.875em;
98
  color: var(--secondary-text-color);
99
+ margin-bottom: 4px;
100
  font-weight: 500;
101
  }
102
  .summary-value {
103
  display: block;
104
+ font-size: 1.5em;
105
  color: var(--text-color);
106
  font-weight: 600;
107
  }
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  #account-cards-container {
110
  display: grid;
111
+ grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
112
+ gap: 20px;
113
+ }
114
+ .account-card-link {
115
+ text-decoration: none;
116
+ color: inherit;
117
+ display: flex;
118
+ flex-direction: column;
119
  }
 
120
  .account-card {
121
+ padding: 20px;
122
+ flex-grow: 1;
123
  background-color: var(--card-bg-color);
124
  border-radius: 8px;
125
  border: 1px solid var(--border-color);
126
+ box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
127
  transition: box-shadow 0.2s ease, transform 0.2s ease;
128
+ height: 100%;
129
+ display: flex;
130
+ flex-direction: column;
131
  }
132
+ .account-card-link:hover .account-card {
133
+ box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06);
134
+ transform: translateY(-2px);
135
+ }
136
+ .account-info {
137
+ flex-grow: 1;
138
  }
 
139
  .account-info h3 {
140
  margin-top: 0;
141
+ font-size: 1.125em;
142
  color: var(--text-color);
143
  border-bottom: 1px solid var(--border-color);
144
  padding-bottom: 12px;
145
  margin-bottom: 12px;
146
+ font-weight: 600;
147
  }
148
+ .account-info p { margin: 8px 0; font-size: 0.875em; color: var(--secondary-text-color); }
149
+ .account-info p strong {
150
+ color: var(--text-color);
151
+ min-width: 110px;
152
  display: inline-block;
153
  font-weight: 500;
154
  }
155
  .account-info .highlight-balance {
156
+ font-weight: 600;
157
+ font-size: 1.1em;
158
+ color: var(--text-color);
159
  }
160
  .status-ok { color: var(--success-color); font-weight: 500; }
161
  .status-error { color: var(--error-color); font-weight: 500; }
162
  .error-details {
163
+ font-size: 0.8em;
164
  color: var(--error-color);
165
+ margin-left: 0;
166
  white-space: pre-wrap;
167
+ background-color: rgba(239, 68, 68, 0.05);
168
+ padding: 6px 8px;
169
  border-radius: 4px;
170
+ margin-top: 4px;
171
+ border: 1px solid rgba(239, 68, 68, 0.1);
172
  }
173
  .account-info .card-details-integrated {
174
  margin-top: 15px;
175
  padding-top: 15px;
176
  border-top: 1px solid var(--border-color);
177
  }
178
+
 
 
 
 
 
 
 
179
  #loading-indicator {
180
  text-align: center;
181
+ padding: 40px 0;
182
+ font-size: 1em;
183
  color: var(--secondary-text-color);
184
  display: none;
185
  width: 100%;
186
  }
187
  #loading-indicator::before {
188
+ content: ''; display: inline-block; width: 24px; height: 24px;
189
+ border: 3px solid rgba(0,0,0, 0.1); border-radius: 50%;
190
+ border-top-color: var(--text-color); animation: spin 0.8s linear infinite;
191
+ margin-right: 12px; position: relative; top: 4px;
 
 
 
 
 
 
 
192
  }
193
  @keyframes spin { to { transform: rotate(360deg); } }
194
  </style>
 
197
  <div class="container">
198
  <header>
199
  <h1>账户仪表盘</h1>
200
+ <div class="header-actions">
 
 
 
 
201
  <button id="refresh-btn">刷新数据</button>
202
  <button id="logout-btn">登出</button>
203
  </div>
204
+ </header>
205
+
206
+ <div id="last-updated">最后更新时间: N/A</div>
207
 
208
  <div id="summary-bar">
209
  <div class="summary-item">
 
220
  </div>
221
  </div>
222
 
223
+ <div id="loading-indicator">正在加载账户数据...</div>
224
  <div id="account-cards-container">
225
  </div>
226
  </div>
 
228
  <script>
229
  document.addEventListener('DOMContentLoaded', function() {
230
  const accountCardsContainer = document.getElementById('account-cards-container');
231
+ const mainLoadingIndicator = document.getElementById('loading-indicator');
232
  const refreshButton = document.getElementById('refresh-btn');
233
  const logoutButton = document.getElementById('logout-btn');
234
+ const lastUpdatedElem = document.getElementById('last-updated');
235
  const totalAccountsValueElem = document.getElementById('total-accounts-value');
236
  const totalBalanceValueElem = document.getElementById('total-balance-value');
237
  const totalDailyConsumptionValueElem = document.getElementById('total-daily-consumption-value');
238
 
239
+ let autoRefreshAccountsInterval;
240
 
241
+ function formatGeneralDateTime(isoString) {
 
 
242
  if (!isoString) return 'N/A';
243
  try {
 
244
  return new Date(isoString).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
245
+ } catch (e) { return 'Invalid Date'; }
 
 
246
  }
247
+
248
+ function displayAccountData(data) {
249
  accountCardsContainer.innerHTML = '';
250
+ mainLoadingIndicator.style.display = 'none';
251
 
252
  const numAccounts = Object.keys(data).length;
253
  totalAccountsValueElem.textContent = numAccounts;
254
  const currentTime = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
255
  lastUpdatedElem.textContent = `最后更新时间: ${currentTime}`;
256
 
 
257
  if (numAccounts === 0) {
258
  accountCardsContainer.innerHTML = '<p style="text-align:center; color: #888; grid-column: 1 / -1;">没有可显示的账户数据。</p>';
259
  totalBalanceValueElem.textContent = '$0.00';
 
263
 
264
  let totalAvailableBalance = 0;
265
  let totalDailyConsumption = 0;
 
 
266
 
267
  for (const email in data) {
268
  const account = data[email];
269
  if (account.cards_info && account.cards_info.available_balance) {
270
+ totalAvailableBalance += parseFloat(account.cards_info.available_balance) || 0;
 
 
 
 
271
  }
272
  if (account.profile && account.profile.daily_consumption) {
273
+ totalDailyConsumption += parseFloat(String(account.profile.daily_consumption).replace('$', '')) || 0;
 
 
 
 
274
  }
275
 
276
+ const accountCardLink = document.createElement('a');
277
+ accountCardLink.classList.add('account-card-link');
278
+ accountCardLink.href = `/dashboard/statements?email=${encodeURIComponent(email)}`;
279
+
280
  const accountCard = document.createElement('div');
281
  accountCard.classList.add('account-card');
 
 
282
 
283
+ let contentHTML = `<div class="account-info"><h3>${email}</h3>`;
284
  contentHTML += `<p><strong>Token 状态:</strong> ${account.token_present ? '<span class="status-ok">存在</span>' : '<span class="status-error">不存在</span>'}</p>`;
285
+ contentHTML += `<p><strong>最后登录:</strong> ${formatGeneralDateTime(account.last_login_attempt)} - ${account.last_login_success === true ? '<span class="status-ok">成功</span>' : (account.last_login_success === false ? '<span class="status-error">失败</span>' : 'N/A')}</p>`;
286
+ if (account.login_error) contentHTML += `<p class="error-details">登录错误: ${account.login_error}</p>`;
287
+
288
+ contentHTML += `<p><strong>Profile 获取:</strong> ${formatGeneralDateTime(account.last_profile_attempt)} - ${account.last_profile_success === true ? '<span class="status-ok">成功</span>' : (account.last_profile_success === false ? '<span class="status-error">失败</span>' : 'N/A')}</p>`;
289
+ if (account.profile_error) contentHTML += `<p class="error-details">Profile 错误: ${account.profile_error}</p>`;
290
 
291
+ contentHTML += `<p><strong>卡片获取:</strong> ${formatGeneralDateTime(account.last_card_info_attempt)} - ${account.last_card_info_success === true ? '<span class="status-ok">成功</span>' : (account.last_card_info_success === false ? '<span class="status-error">失败</span>' : 'N/A')}</p>`;
292
+ if (account.card_info_error) contentHTML += `<p class="error-details">卡片错误: ${account.card_info_error}</p>`;
 
 
293
 
 
 
 
 
 
 
 
 
 
 
 
294
  if (account.profile) {
295
  contentHTML += `<p><strong>UID:</strong> ${account.profile.uid || 'N/A'}</p>`;
 
296
  contentHTML += `<p><strong>邀请码:</strong> ${account.profile.invitation_code || 'N/A'}</p>`;
297
  contentHTML += `<p><strong>账户状态:</strong> ${account.profile.status || 'N/A'}</p>`;
 
 
298
  }
299
 
300
  if (account.cards_info) {
 
302
  contentHTML += `<div class="card-details-integrated">`;
303
  contentHTML += `<p><strong>卡号:</strong> ${ (card.provider_bin && card.card_last_four_digits) ? `${card.provider_bin}xxxxxx${card.card_last_four_digits}` : (card.provider_bin ? `${card.provider_bin}xxxxxx` : (card.card_last_four_digits ? `xxxxxx${card.card_last_four_digits}` : '-')) }</p>`;
304
  contentHTML += `<p><strong>可用余额:</strong> <span class="highlight-balance">$${card.available_balance || '0.00'}</span></p>`;
 
 
305
  if (account.profile) {
306
  contentHTML += `<p><strong>每日消耗:</strong> $${account.profile.daily_consumption || '0.00'}</p>`;
307
  contentHTML += `<p><strong>总收益:</strong> $${account.profile.total_earn_balance || '0.00'}</p>`;
308
  }
309
+ let dailyLimitDisplay = (card.consumption_limit === null || card.consumption_limit === undefined) ? '-' : (String(card.consumption_limit) === '-1' ? '无限制' : `$${card.consumption_limit}`);
310
+ contentHTML += `<p><strong>卡日限额:</strong> ${dailyLimitDisplay}</p></div>`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  }
 
312
  contentHTML += `</div>`;
313
  accountCard.innerHTML = contentHTML;
314
+ accountCardLink.appendChild(accountCard);
315
+ accountCardsContainer.appendChild(accountCardLink);
316
  }
317
 
318
+ totalBalanceValueElem.textContent = `$${totalAvailableBalance.toFixed(2)}`;
319
+ totalDailyConsumptionValueElem.textContent = `$${totalDailyConsumption.toFixed(2)}`;
320
  }
321
 
322
+ async function fetchInitialAccountData() {
323
+ mainLoadingIndicator.style.display = 'block';
324
  try {
325
+ const response = await fetch('/api/data');
326
+ if (response.status === 401) { window.location.href = '/'; return; }
327
+ if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`);}
 
 
 
 
 
328
  const data = await response.json();
329
  if (data.error) {
330
+ console.error("Error fetching account data:", data.error);
331
+ mainLoadingIndicator.style.display = 'none';
332
+ accountCardsContainer.innerHTML = `<p style="text-align:center; color: var(--error-color);">获取账户数据失败: ${data.error}</p>`;
333
  } else {
334
+ displayAccountData(data);
335
  }
336
  } catch (error) {
337
+ console.error('Error fetching account data:', error);
338
+ mainLoadingIndicator.style.display = 'none';
339
+ accountCardsContainer.innerHTML = `<p style="text-align:center; color: var(--error-color);">获取账户数据时发生网络错误。</p>`;
340
  }
341
  }
342
 
 
344
  const originalButtonText = refreshButton.textContent;
345
  refreshButton.textContent = '正在刷新...';
346
  refreshButton.disabled = true;
347
+ mainLoadingIndicator.textContent = '手动刷新中...';
348
+ mainLoadingIndicator.style.display = 'block';
349
+ accountCardsContainer.innerHTML = '';
350
 
351
  try {
352
+ const refreshApiResponse = await fetch('/api/refresh', { method: 'POST' });
353
+ if (refreshApiResponse.status === 401) { window.location.href = '/'; return; }
354
+
 
 
 
355
  setTimeout(async () => {
356
+ await fetchInitialAccountData();
357
  refreshButton.textContent = originalButtonText;
358
  refreshButton.disabled = false;
359
  }, 3000);
 
363
  lastUpdatedElem.textContent = `手动刷新失败: ${new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })}`;
364
  refreshButton.textContent = originalButtonText;
365
  refreshButton.disabled = false;
366
+ mainLoadingIndicator.style.display = 'none';
367
  }
368
  });
369
 
370
+ logoutButton.addEventListener('click', () => { window.location.href = '/logout'; });
 
 
 
 
371
 
372
+ fetchInitialAccountData();
373
+ if (autoRefreshAccountsInterval) clearInterval(autoRefreshAccountsInterval);
374
+ autoRefreshAccountsInterval = setInterval(fetchInitialAccountData, 600000);
375
  });
376
  </script>
377
  </body>