-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathadmin.py
More file actions
2224 lines (1953 loc) · 81.6 KB
/
Copy pathadmin.py
File metadata and controls
2224 lines (1953 loc) · 81.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Blueprint, render_template, request, redirect, url_for, flash, session, jsonify, Response
from functools import wraps
from urllib.parse import urlparse
from models import (
db,
User,
ActivationCode,
ActivationCodeRequest,
PredictionRecord,
SystemConfig,
InviteCode,
ZodiacSetting,
ManualBetRecord,
LotteryDraw,
BacktestRun,
UserNotification,
)
from datetime import datetime, timedelta
import csv
import json
import io
import threading
from collections import OrderedDict
from sqlalchemy import func, case, or_
admin_bp = Blueprint('admin', __name__, url_prefix='/admin')
_retrain_learning_lock = threading.RLock()
_retrain_learning_status = {
'status': 'idle',
'regions': [],
'current_region': '',
'started_at': '',
'finished_at': '',
'errors': [],
'message': '尚未启动重算任务',
}
_RETRAIN_LEARNING_STATUS_KEY = 'retrain_learning_status'
def _retrain_learning_status_label(status):
return {
'idle': '空闲',
'running': '运行中',
'completed': '已完成',
'failed': '失败',
}.get(str(status or '').strip(), str(status or '').strip() or '未知')
def _retrain_region_label(region):
return {
'hk': '香港',
'macau': '澳门',
'all': '全部',
}.get(str(region or '').strip(), str(region or '').strip() or '-')
def _retrain_region_labels(regions):
return [_retrain_region_label(region) for region in (regions or [])]
def _set_retrain_learning_status(**updates):
with _retrain_learning_lock:
_retrain_learning_status.update(updates)
_retrain_learning_status['status_label'] = _retrain_learning_status_label(
_retrain_learning_status.get('status')
)
_retrain_learning_status['region_labels'] = _retrain_region_labels(
_retrain_learning_status.get('regions')
)
_retrain_learning_status['current_region_label'] = _retrain_region_label(
_retrain_learning_status.get('current_region')
) if _retrain_learning_status.get('current_region') else ''
status_snapshot = dict(_retrain_learning_status)
try:
SystemConfig.set_config(
_RETRAIN_LEARNING_STATUS_KEY,
json.dumps(status_snapshot, ensure_ascii=False),
'后台学习参数重算状态',
)
except Exception as exc:
print(f"保存学习参数重算状态失败: {exc}")
print(f"学习参数重算状态: {status_snapshot.get('status_label')} - {status_snapshot.get('message')}")
return status_snapshot
def _get_retrain_learning_status():
with _retrain_learning_lock:
_retrain_learning_status['status_label'] = _retrain_learning_status_label(
_retrain_learning_status.get('status')
)
status_snapshot = dict(_retrain_learning_status)
if status_snapshot.get('status') != 'idle':
return status_snapshot
try:
raw = SystemConfig.get_config(_RETRAIN_LEARNING_STATUS_KEY, '')
if raw:
stored = json.loads(raw)
if isinstance(stored, dict):
stored['status_label'] = _retrain_learning_status_label(stored.get('status'))
stored['region_labels'] = _retrain_region_labels(stored.get('regions'))
stored['current_region_label'] = _retrain_region_label(stored.get('current_region')) if stored.get('current_region') else ''
return stored
except Exception:
pass
return status_snapshot
DATA_EXPORT_MODELS = [
('users', User),
('activation_codes', ActivationCode),
('activation_code_requests', ActivationCodeRequest),
('prediction_records', PredictionRecord),
('backtest_runs', BacktestRun),
('invite_codes', InviteCode),
('system_configs', SystemConfig),
('zodiac_settings', ZodiacSetting),
('manual_bet_records', ManualBetRecord),
('lottery_draws', LotteryDraw),
]
DATA_EXPORT_LABELS = {
'users': '用户',
'activation_codes': '激活码',
'activation_code_requests': '激活码申请',
'prediction_records': '预测记录',
'backtest_runs': '历史模拟记录',
'invite_codes': '邀请码',
'system_configs': '系统配置',
'zodiac_settings': '生肖设置',
'manual_bet_records': '下注记录',
'lottery_draws': '开奖数据',
}
LEARNING_PANEL_TERM_LABELS = {
'hot': '热门',
'cold': '冷门',
'trend': '走势',
'balanced': '均衡',
'hybrid': '综合',
'ml': '机器学习',
'ai': 'AI智能',
'feedback': '反馈',
'color': '波色',
'normal': '平码',
'overdue': '遗漏',
'parity': '单双',
'zodiac': '生肖',
}
PREDICTION_STRATEGY_LABELS = {
'hot': '热门预测',
'cold': '冷门预测',
'trend': '走势预测',
'balanced': '均衡预测',
'hybrid': '综合预测',
'ml': '机器学习预测',
'ai': 'AI预测',
}
LEARNING_PANEL_TERM_LABELS['markov'] = '马尔科夫'
LEARNING_PANEL_TERM_LABELS['transition'] = '转移概率'
LEARNING_PANEL_TERM_LABELS['second_order'] = '二阶转移'
LEARNING_PANEL_TERM_LABELS['phase_transition'] = '阶段转移'
LEARNING_PANEL_TERM_LABELS['attribute_transition'] = '属性转移'
LEARNING_PANEL_TERM_LABELS['special_transition'] = '特码转移'
LEARNING_PANEL_TERM_LABELS['failure'] = '失误修正'
PREDICTION_STRATEGY_LABELS['markov'] = '马尔科夫预测'
def _normalize_visual_weights(weight_map):
cleaned = OrderedDict()
total = 0.0
for label, value in (weight_map or {}).items():
try:
numeric = max(0.0, float(value))
except Exception:
numeric = 0.0
cleaned[label] = numeric
total += numeric
if total <= 0:
return []
items = []
for label, numeric in cleaned.items():
percent = round((numeric / total) * 100, 1)
value = f"{int(percent)}%" if float(percent).is_integer() else f"{percent}%"
items.append({
'key': label,
'label': label,
'value': value,
})
return items
def _build_ml_visual_weights(config):
runtime_profile = str(config.get('primary_runtime_profile') or 'base').strip()
feature_profile = str(config.get('primary_feature_profile') or 'full').strip()
weight_map = OrderedDict([
('历史样本', 26),
('近期走势', 18),
('策略共识', 18),
('单双参考', 13),
('波色参考', 13),
('生肖参考', 12),
])
if runtime_profile == 'recent_bias':
weight_map['近期走势'] += 8
weight_map['历史样本'] -= 4
weight_map['策略共识'] -= 4
elif runtime_profile == 'context_bias':
weight_map['单双参考'] += 4
weight_map['波色参考'] += 4
weight_map['生肖参考'] += 4
weight_map['历史样本'] -= 6
weight_map['近期走势'] -= 3
weight_map['策略共识'] -= 3
elif runtime_profile == 'recency_trim':
weight_map['近期走势'] += 6
weight_map['历史样本'] -= 6
elif runtime_profile == 'learned_feature_bias':
weight_map['策略共识'] += 5
weight_map['单双参考'] += 2
weight_map['波色参考'] += 2
weight_map['历史样本'] -= 5
weight_map['近期走势'] -= 2
weight_map['生肖参考'] -= 2
if feature_profile == 'compact_attributes':
weight_map['单双参考'] -= 3
weight_map['波色参考'] -= 3
weight_map['生肖参考'] -= 2
weight_map['历史样本'] += 4
weight_map['近期走势'] += 2
weight_map['策略共识'] += 2
elif feature_profile == 'compact_structure':
weight_map['策略共识'] -= 4
weight_map['近期走势'] -= 2
weight_map['历史样本'] -= 1
weight_map['单双参考'] += 2
weight_map['波色参考'] += 2
weight_map['生肖参考'] += 3
elif feature_profile == 'compact_recency':
weight_map['近期走势'] -= 6
weight_map['历史样本'] += 4
weight_map['策略共识'] += 2
return _normalize_visual_weights(weight_map)
def _build_ai_visual_weights(config):
history_window = max(1, int(config.get('history_window') or 12))
temperature = max(0.0, float(config.get('temperature') or 0.35))
weight_map = OrderedDict([
('历史样本', 30),
('近期走势', 18),
('单双参考', 14),
('波色参考', 14),
('生肖参考', 10),
('策略共识', 14),
])
if history_window >= 18:
weight_map['历史样本'] += 6
weight_map['策略共识'] += 2
weight_map['近期走势'] -= 3
weight_map['波色参考'] -= 2
weight_map['生肖参考'] -= 1
weight_map['单双参考'] -= 2
elif history_window <= 8:
weight_map['近期走势'] += 5
weight_map['单双参考'] += 2
weight_map['波色参考'] += 2
weight_map['历史样本'] -= 5
weight_map['策略共识'] -= 4
if temperature <= 0.3:
weight_map['策略共识'] += 4
weight_map['历史样本'] += 2
weight_map['近期走势'] -= 2
weight_map['生肖参考'] -= 2
weight_map['波色参考'] -= 1
weight_map['单双参考'] -= 1
elif temperature >= 0.7:
weight_map['近期走势'] += 4
weight_map['生肖参考'] += 2
weight_map['波色参考'] += 2
weight_map['历史样本'] -= 4
weight_map['策略共识'] -= 4
return _normalize_visual_weights(weight_map)
def _count_distinct_prediction_periods(query):
return query.with_entities(
PredictionRecord.region,
PredictionRecord.period,
).distinct().count()
def _build_strategy_visual_weights(strategy, config):
weights = config.get('weights') or {}
if weights:
if strategy == 'markov':
visible_keys = (
'transition',
'special_transition',
'feedback',
'second_order',
'phase_transition',
'failure',
)
weights = OrderedDict(
(key, weights[key])
for key in visible_keys
if key in weights
)
return [
{
'key': key,
'label': LEARNING_PANEL_TERM_LABELS.get(key, key),
'value': value
}
for key, value in sorted(weights.items())
]
if strategy == 'ml':
return _build_ml_visual_weights(config)
if strategy == 'ai':
return _build_ai_visual_weights(config)
return []
def _serialize_model_row(instance):
payload = {}
for column in instance.__table__.columns:
value = getattr(instance, column.name)
if isinstance(value, datetime):
payload[column.name] = value.isoformat()
else:
payload[column.name] = value
return payload
def _parse_datetime_value(value):
if value in (None, ""):
return None
if isinstance(value, datetime):
return value
text = str(value).strip()
if not text:
return None
text = text.replace("Z", "+00:00")
try:
return datetime.fromisoformat(text)
except ValueError:
pass
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
try:
return datetime.strptime(text, fmt)
except ValueError:
continue
raise ValueError(f"无法解析时间字段: {value}")
def _deserialize_model_row(model, row):
values = {}
for column in model.__table__.columns:
name = column.name
if name not in row:
continue
value = row.get(name)
if value is None:
values[name] = None
continue
python_type = None
try:
python_type = column.type.python_type
except Exception:
python_type = None
if python_type is datetime:
values[name] = _parse_datetime_value(value)
elif python_type is bool:
if isinstance(value, str):
values[name] = value.strip().lower() in ("1", "true", "yes", "y", "on")
else:
values[name] = bool(value)
elif python_type is int:
values[name] = int(value)
elif python_type is float:
values[name] = float(value)
else:
values[name] = value
return model(**values)
def _build_data_export_payload():
exported_at = datetime.now().isoformat()
data = {}
counts = {}
for key, model in DATA_EXPORT_MODELS:
rows = model.query.order_by(model.id.asc()).all()
data[key] = [_serialize_model_row(row) for row in rows]
counts[key] = len(data[key])
return {
"meta": {
"exported_at": exported_at,
"version": 1,
},
"counts": counts,
"data": data,
}
def _validate_import_payload(payload):
if not isinstance(payload, dict):
raise ValueError("导入文件格式不正确")
data = payload.get("data")
if not isinstance(data, dict):
raise ValueError("导入文件缺少 data 节点")
users = data.get("users") or []
if not any(bool(item.get("is_admin")) for item in users):
raise ValueError("导入数据里至少需要保留一个管理员账号")
def _clear_all_data():
delete_order = [
UserNotification,
ManualBetRecord,
PredictionRecord,
ActivationCodeRequest,
ActivationCode,
InviteCode,
LotteryDraw,
ZodiacSetting,
SystemConfig,
BacktestRun,
User,
]
for model in delete_order:
db.session.query(model).delete()
def _import_data_payload(payload, mode):
_validate_import_payload(payload)
data = payload["data"]
imported_counts = {}
if mode == "replace":
_clear_all_data()
for key, model in DATA_EXPORT_MODELS:
rows = data.get(key) or []
imported_counts[key] = len(rows)
for row in rows:
instance = _deserialize_model_row(model, row)
db.session.merge(instance)
db.session.commit()
ZodiacSetting._macau_year_match_cache.clear()
return imported_counts
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
try:
# 检查用户是否登录
if 'user_id' not in session:
flash('请先登录', 'error')
return redirect(url_for('auth.login'))
# 检查用户是否是管理员
user = User.query.get(session['user_id'])
if not user or not user.is_admin:
flash('需要管理员权限才能访问此页面', 'error')
return redirect(url_for('auth.login'))
return f(*args, **kwargs)
except Exception as e:
flash(f'权限检查失败: {str(e)}', 'error')
return redirect(url_for('auth.login'))
return decorated_function
def _safe_redirect_back(default_endpoint):
referrer = request.referrer or ''
if referrer:
parsed = urlparse(referrer)
if not parsed.netloc or parsed.netloc == request.host:
return redirect(referrer)
return redirect(url_for(default_endpoint))
def _strategy_learning_panel_data():
from app import _load_strategy_config, _get_strategy_label
regions = [('hk', '香港'), ('macau', '澳门')]
strategies = ['hot', 'cold', 'trend', 'balanced', 'hybrid', 'markov', 'ml', 'ai']
panel = []
for region_key, region_label in regions:
items = []
for strategy in strategies:
config = _load_strategy_config(strategy, region_key)
weight_items = _build_strategy_visual_weights(strategy, config)
mix = config.get('mix') or {}
mix_items = [
{
'key': key,
'label': LEARNING_PANEL_TERM_LABELS.get(key, key),
'value': value
}
for key, value in mix.items()
]
items.append({
'key': strategy,
'display_key': LEARNING_PANEL_TERM_LABELS.get(strategy, strategy),
'label': _get_strategy_label(strategy),
'updated_at': config.get('updated_at', ''),
'last_accuracy': round(float(config.get('last_accuracy') or 0.0) * 100, 1),
'last_total': int(config.get('last_total') or 0),
'accuracy_delta': round(float(config.get('accuracy_delta') or 0.0) * 100, 1),
'window': config.get('window'),
'trend_window': config.get('trend_window'),
'history_window': config.get('history_window'),
'feature_window': config.get('feature_window'),
'transition_decay': config.get('transition_decay'),
'transition_min_samples': config.get('transition_min_samples'),
'source_special_weight': config.get('source_special_weight'),
'promotion_cooldown_hours': config.get('promotion_cooldown_hours'),
'promotion_min_gain': config.get('promotion_min_gain'),
'learning_adaptation_mode': config.get('learning_adaptation_mode', 'balanced'),
'pool': config.get('pool'),
'special_pool': config.get('special_pool'),
'epochs': config.get('epochs'),
'learning_rate': config.get('learning_rate'),
'bucket_counts': config.get('bucket_counts') or [],
'mix': mix,
'mix_items': mix_items,
'weights': weight_items,
})
panel.append({
'region_key': region_key,
'region_label': region_label,
'items': items,
})
return panel
@admin_bp.route('/dashboard')
@admin_required
def dashboard():
try:
# 获取统计数据
now = datetime.now()
week_ago = now - timedelta(days=7)
expiring_cutoff = now + timedelta(days=3)
total_users = User.query.count()
active_users = User.query.filter_by(is_active=True).count()
inactive_users = total_users - active_users
total_codes = ActivationCode.query.count()
used_codes = ActivationCode.query.filter_by(is_used=True).count()
unused_codes = total_codes - used_codes
total_predictions = _count_distinct_prediction_periods(PredictionRecord.query)
recent_signups_7d = User.query.filter(User.created_at >= week_ago).count()
recent_predictions_7d = _count_distinct_prediction_periods(
PredictionRecord.query.filter(PredictionRecord.created_at >= week_ago)
)
pending_predictions = PredictionRecord.query.filter(
(PredictionRecord.is_result_updated.is_(False)) | (PredictionRecord.is_result_updated.is_(None))
).count()
expiring_users_count = User.query.filter(
User.is_active.is_(True),
User.activation_expires_at.isnot(None),
User.activation_expires_at >= now,
User.activation_expires_at <= expiring_cutoff
).count()
expired_active_users = User.query.filter(
User.is_active.is_(True),
User.activation_expires_at.isnot(None),
User.activation_expires_at < now
).count()
# 计算不同策略的准确率(只对比特码)
def calculate_accuracy(strategy):
predictions = PredictionRecord.query.filter_by(strategy=strategy, is_result_updated=True).all()
if not predictions:
return 0.0
correct_count = 0
total_count = 0
for pred in predictions:
if pred.actual_special_number and pred.special_number:
total_count += 1
if pred.special_number == pred.actual_special_number:
correct_count += 1
return round(correct_count / total_count * 100, 1) if total_count > 0 else 0.0
# 计算平均准确率(只对比特码)
all_predictions = PredictionRecord.query.filter_by(is_result_updated=True).all()
if all_predictions:
correct_count = 0
total_count = 0
for pred in all_predictions:
if pred.actual_special_number and pred.special_number:
total_count += 1
if pred.special_number == pred.actual_special_number:
correct_count += 1
avg_accuracy = round(correct_count / total_count * 100, 1) if total_count > 0 else 0.0
else:
avg_accuracy = 0.0
balanced_accuracy = calculate_accuracy('balanced')
ai_accuracy = calculate_accuracy('ai')
total_invite_codes = InviteCode.query.count()
used_invite_codes = InviteCode.query.filter_by(is_used=True).count()
unused_invite_codes = total_invite_codes - used_invite_codes
actionable_cards = [
{
'title': '待开奖预测',
'value': pending_predictions,
'hint': '优先检查开奖同步和结果回填',
'url': url_for('admin.predictions'),
'tone': 'warning',
},
{
'title': '3天内到期用户',
'value': expiring_users_count,
'hint': '适合主动提醒续费或重新激活',
'url': url_for('admin.users'),
'tone': 'danger' if expiring_users_count else 'success',
},
{
'title': '失效但仍激活',
'value': expired_active_users,
'hint': '大于 0 时建议尽快核查账号状态',
'url': url_for('admin.users'),
'tone': 'danger' if expired_active_users else 'success',
},
{
'title': '未使用邀请码',
'value': unused_invite_codes,
'hint': '可直接用于拉新或补充库存',
'url': url_for('admin.invite_codes'),
'tone': 'info',
},
]
total_invites = User.query.filter(User.invited_by.isnot(None)).count()
invite_stats = {
'total_invite_codes': total_invite_codes,
'used_invite_codes': used_invite_codes,
'unused_invite_codes': unused_invite_codes,
'total_invites': total_invites
}
stats = {
'total_users': total_users,
'active_users': active_users,
'inactive_users': inactive_users,
'total_codes': total_codes,
'used_codes': used_codes,
'unused_codes': unused_codes,
'total_predictions': total_predictions,
'avg_accuracy': avg_accuracy,
'balanced_accuracy': balanced_accuracy,
'ai_accuracy': ai_accuracy,
'recent_signups_7d': recent_signups_7d,
'recent_predictions_7d': recent_predictions_7d,
'pending_predictions': pending_predictions,
'expiring_users_count': expiring_users_count,
'expired_active_users': expired_active_users,
'total_invite_codes': total_invite_codes,
'used_invite_codes': used_invite_codes,
'unused_invite_codes': unused_invite_codes,
'actionable_cards': actionable_cards,
'invite_stats': invite_stats
}
return render_template('admin/dashboard.html', stats=stats)
except Exception as e:
flash(f'加载控制台数据失败: {str(e)}', 'error')
return render_template('admin/dashboard.html', stats={
'total_users': 0,
'active_users': 0,
'inactive_users': 0,
'total_codes': 0,
'used_codes': 0,
'unused_codes': 0,
'total_predictions': 0,
'avg_accuracy': 0.0,
'balanced_accuracy': 0.0,
'ai_accuracy': 0.0,
'recent_signups_7d': 0,
'recent_predictions_7d': 0,
'pending_predictions': 0,
'expiring_users_count': 0,
'expired_active_users': 0,
'total_invite_codes': 0,
'used_invite_codes': 0,
'unused_invite_codes': 0,
'actionable_cards': [],
'invite_stats': {
'total_invite_codes': 0,
'used_invite_codes': 0,
'unused_invite_codes': 0,
'total_invites': 0
}
})
@admin_bp.route('/data_transfer')
@admin_required
def data_transfer():
summary = []
for key, model in DATA_EXPORT_MODELS:
try:
count = model.query.count()
except Exception:
count = 0
summary.append({
'key': key,
'label': DATA_EXPORT_LABELS.get(key, key),
'count': count,
})
return render_template('admin/data_transfer.html', summary=summary)
@admin_bp.route('/system_logs')
@admin_required
def system_logs():
from app import get_system_log_file_path, get_system_logs
limit = request.args.get('limit', 200, type=int)
logs = get_system_logs(limit=limit)
return render_template(
'admin/system_logs.html',
logs=logs,
log_limit=limit,
log_file_path=get_system_log_file_path(),
)
@admin_bp.route('/system_logs/data')
@admin_required
def system_logs_data():
from app import get_system_logs
limit = request.args.get('limit', 200, type=int)
logs = get_system_logs(limit=limit)
return jsonify({
'success': True,
'logs': logs,
'count': len(logs),
})
@admin_bp.route('/system_logs/clear', methods=['POST'])
@admin_required
def clear_system_logs_view():
from app import clear_system_logs
clear_system_logs()
return jsonify({
'success': True,
'message': '系统日志已清空'
})
@admin_bp.route('/data_transfer/export')
@admin_required
def export_all_data():
try:
payload = _build_data_export_payload()
exported_at = datetime.now().strftime('%Y%m%d_%H%M%S')
return Response(
json.dumps(payload, ensure_ascii=False, indent=2),
mimetype='application/json',
headers={
'Content-Disposition': f'attachment; filename=mark_six_backup_{exported_at}.json'
}
)
except Exception as e:
flash(f'导出全部数据失败: {str(e)}', 'error')
return redirect(url_for('admin.data_transfer'))
@admin_bp.route('/data_transfer/import', methods=['POST'])
@admin_required
def import_all_data():
try:
upload = request.files.get('file')
if not upload or not upload.filename:
flash('请选择要导入的 JSON 备份文件', 'error')
return redirect(url_for('admin.data_transfer'))
payload = json.load(upload.stream)
mode = str(request.form.get('import_mode') or 'merge').strip().lower()
if mode not in ('merge', 'replace'):
mode = 'merge'
imported_counts = _import_data_payload(payload, mode)
flash(
f"全部数据导入成功,模式:{'覆盖现有数据' if mode == 'replace' else '按主键合并'}。",
'success'
)
flash(
";".join(f"{key} {count} 条" for key, count in imported_counts.items()),
'success'
)
except Exception as e:
db.session.rollback()
flash(f'导入全部数据失败: {str(e)}', 'error')
return redirect(url_for('admin.data_transfer'))
@admin_bp.route('/users')
@admin_required
def users():
try:
page = request.args.get('page', 1, type=int)
search_query = request.args.get('search', '')
# 构建查询
query = User.query
# 如果有搜索关键词,添加搜索条件
if search_query:
search_term = f"%{search_query}%"
query = query.filter(
(User.username.like(search_term)) |
(User.email.like(search_term))
)
# 分页
users = query.paginate(
page=page, per_page=20, error_out=False
)
admin_count = User.query.filter(User.is_admin.is_(True)).count()
return render_template('admin/users.html', users=users, search_query=search_query, admin_count=admin_count)
except Exception as e:
flash(f'加载用户数据失败: {str(e)}', 'error')
# 创建空的分页对象
# 创建空的分页对象
class EmptyPagination:
def __init__(self):
self.items = []
self.page = 1
self.per_page = 20
self.total = 0
self.pages = 0
self.has_prev = False
self.has_next = False
self.prev_num = None
self.next_num = None
empty_users = EmptyPagination()
return render_template('admin/users.html', users=empty_users, admin_count=0)
@admin_bp.route('/user/<int:user_id>/edit', methods=['GET', 'POST'])
@admin_required
def edit_user(user_id):
try:
user = User.query.get_or_404(user_id)
if request.method == 'POST':
# 获取表单数据
new_username = request.form.get('username')
new_email = request.form.get('email')
new_password = request.form.get('new_password')
is_active = 'is_active' in request.form
is_admin = 'is_admin' in request.form
# 保存原始用户名,用于判断是否是admin账号
original_username = user.username
print(f"DEBUG: original_username={original_username}, is_active={is_active}, user.is_active={user.is_active}")
# 对于admin账号,强制保持激活状态
if original_username == 'admin':
is_active = True
print(f"DEBUG: 设置admin用户is_active=True")
# 防止停用admin账号
if original_username == 'admin' and not is_active:
flash('不能停用admin账号', 'error')
return render_template('admin/edit_user.html', user=user)
# 更新用户信息
user.username = new_username
user.email = new_email
# 如果由未激活状态变为激活状态,默认开启预测
if is_active and not user.is_active:
user.auto_prediction_enabled = True
user.is_active = is_active
# 如果是admin账号,保持管理员权限
if original_username == 'admin':
user.is_admin = True
else:
user.is_admin = is_admin
# 如果提供了新密码,则更新密码
if new_password:
user.set_password(new_password)
# 处理激活过期时间
activation_expires_at = request.form.get('activation_expires_at')
if activation_expires_at:
try:
user.activation_expires_at = datetime.strptime(activation_expires_at, '%Y-%m-%dT%H:%M')
except ValueError:
flash('激活过期时间格式无效', 'error')
return render_template('admin/edit_user.html', user=user)
else:
# 如果用户是激活状态,则设置为永久有效期,否则不设置有效期
if user.is_active:
user.activation_expires_at = None
else:
# 未激活用户不应该有有效期
user.activation_expires_at = None
try:
db.session.commit()
flash('用户信息更新成功', 'success')
return redirect(url_for('admin.users'))
except Exception as e:
db.session.rollback()
flash(f'更新失败: {str(e)}', 'error')
return render_template('admin/edit_user.html', user=user)
except Exception as e:
flash(f'编辑用户失败: {str(e)}', 'error')
return redirect(url_for('admin.users'))
@admin_bp.route('/users/add', methods=['POST'])
@admin_required
def add_user():
"""添加新用户"""
try:
data = request.get_json()
if not data:
return jsonify({'success': False, 'message': '无效的数据格式'})
username = data.get('username', '').strip()
email = data.get('email', '').strip()
password = data.get('password', '')
is_admin = data.get('is_admin', False)
# 验证输入
if not username:
return jsonify({'success': False, 'message': '用户名不能为空'})
if not email:
return jsonify({'success': False, 'message': '邮箱不能为空'})
if not password or len(password) < 6:
return jsonify({'success': False, 'message': '密码长度不能少于6个字符'})
# 检查用户名是否已存在
if User.query.filter_by(username=username).first():
return jsonify({'success': False, 'message': '用户名已存在'})
# 检查邮箱是否已存在
if User.query.filter_by(email=email).first():
return jsonify({'success': False, 'message': '邮箱已被使用'})
# 创建新用户
user = User(username=username, email=email, is_active=True, is_admin=is_admin)
user.set_password(password)
db.session.add(user)
db.session.commit()
return jsonify({'success': True, 'message': '用户添加成功'})
except Exception as e:
db.session.rollback()
return jsonify({'success': False, 'message': str(e)})
@admin_bp.route('/users/<int:user_id>/activate', methods=['POST'])
@admin_required
def activate_user(user_id):
try:
user = User.query.get_or_404(user_id)
user.is_active = True
user.auto_prediction_enabled = True
db.session.commit()
return jsonify({'success': True})
except Exception as e:
db.session.rollback()
return jsonify({'success': False, 'message': str(e)})
@admin_bp.route('/users/<int:user_id>/deactivate', methods=['POST'])
@admin_required