422 lines
17 KiB
Python
422 lines
17 KiB
Python
|
|
from django.contrib import admin, messages
|
||
|
|
from django.core.exceptions import ValidationError
|
||
|
|
from django.utils.html import format_html
|
||
|
|
|
||
|
|
from .models import (
|
||
|
|
ClientSession,
|
||
|
|
Device,
|
||
|
|
LearnedRouteRule,
|
||
|
|
Node,
|
||
|
|
NodeDeployment,
|
||
|
|
NodeTrafficSample,
|
||
|
|
Plan,
|
||
|
|
PlanCatalogDraft,
|
||
|
|
Team,
|
||
|
|
TeamMembership,
|
||
|
|
TeamAuditEvent,
|
||
|
|
PlanApplication,
|
||
|
|
RouteObservation,
|
||
|
|
RoutingPolicy,
|
||
|
|
Subscription,
|
||
|
|
UsageRecord,
|
||
|
|
VpnAiFinding,
|
||
|
|
VpnAiRuntime,
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(Plan)
|
||
|
|
class PlanAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("name", "audience", "employee_benefit", "price_cny", "traffic_limit_gb", "billing_months", "duration_days", "online_payment_required", "device_limit", "active")
|
||
|
|
list_filter = ("audience", "employee_benefit", "online_payment_required", "active")
|
||
|
|
search_fields = ("name", "slug", "description")
|
||
|
|
prepopulated_fields = {"slug": ("name",)}
|
||
|
|
ordering = ("sort_order", "price_cny")
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(PlanCatalogDraft)
|
||
|
|
class PlanCatalogDraftAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("name", "scope", "display_quota", "display_price", "member_limit", "device_limit", "concurrent_limit", "publication_state")
|
||
|
|
list_filter = ("scope",)
|
||
|
|
search_fields = ("name", "slug", "description")
|
||
|
|
readonly_fields = ("publication_state", "created_at", "updated_at")
|
||
|
|
fieldsets = (
|
||
|
|
("未上架的商业草案", {"fields": ("publication_state", "name", "slug", "scope", "traffic_limit_gb", "price_cny"),
|
||
|
|
"description": "这里只编辑草稿,不展示给客户、不产生订单、不修改现有套餐或订阅。团队成员共享账本尚未接入;不可用个人订阅代替团队共享。"}),
|
||
|
|
("使用范围", {"fields": ("member_limit", "device_limit", "concurrent_limit", "description", "sort_order"),
|
||
|
|
"description": "无限流量仅指不设代理流量总额;带宽、设备及并发规则仍须确认。只有本公司的已核实内部员工免费,外部团队成员不自动免单。"}),
|
||
|
|
("记录", {"fields": ("created_at", "updated_at")}),
|
||
|
|
)
|
||
|
|
|
||
|
|
@admin.display(description="流量档位")
|
||
|
|
def display_quota(self, obj):
|
||
|
|
return obj.quota_label
|
||
|
|
|
||
|
|
@admin.display(description="月价")
|
||
|
|
def display_price(self, obj):
|
||
|
|
return obj.price_label
|
||
|
|
|
||
|
|
@admin.display(description="上架状态")
|
||
|
|
def publication_state(self, obj):
|
||
|
|
return "仅草稿 · 未上架 · 不收款"
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(Team)
|
||
|
|
class TeamAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("name", "owner", "active", "plan_draft", "setup_member_limit", "package_state")
|
||
|
|
search_fields = ("name", "owner__username")
|
||
|
|
list_filter = ("active",)
|
||
|
|
readonly_fields = ("package_state",)
|
||
|
|
|
||
|
|
def get_readonly_fields(self, request, obj=None):
|
||
|
|
return (*self.readonly_fields, "owner") if obj else self.readonly_fields
|
||
|
|
|
||
|
|
def has_delete_permission(self, request, obj=None):
|
||
|
|
return False
|
||
|
|
|
||
|
|
def save_model(self, request, obj, form, change):
|
||
|
|
super().save_model(request, obj, form, change)
|
||
|
|
TeamAuditEvent.objects.create(team=obj, actor=request.user, action="platform_configured")
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(TeamMembership)
|
||
|
|
class TeamMembershipAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("team", "user", "role", "status", "invited_by")
|
||
|
|
list_filter = ("role", "status")
|
||
|
|
|
||
|
|
def has_add_permission(self, request):
|
||
|
|
return False
|
||
|
|
|
||
|
|
def has_change_permission(self, request, obj=None):
|
||
|
|
return False
|
||
|
|
|
||
|
|
def has_delete_permission(self, request, obj=None):
|
||
|
|
return False
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(TeamAuditEvent)
|
||
|
|
class TeamAuditEventAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("team", "actor", "subject", "action", "created_at")
|
||
|
|
list_filter = ("action",)
|
||
|
|
|
||
|
|
def has_add_permission(self, request):
|
||
|
|
return False
|
||
|
|
|
||
|
|
def has_change_permission(self, request, obj=None):
|
||
|
|
return False
|
||
|
|
|
||
|
|
def has_delete_permission(self, request, obj=None):
|
||
|
|
return False
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(RoutingPolicy)
|
||
|
|
class RoutingPolicyAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("name", "is_global", "active", "updated_at")
|
||
|
|
list_filter = ("is_global", "active")
|
||
|
|
search_fields = ("name", "description")
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(Node)
|
||
|
|
class NodeAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("name", "region", "server", "port", "protocol", "status", "fallback_only", "subscription_enabled", "last_seen_at")
|
||
|
|
list_filter = ("protocol", "status", "active", "subscription_enabled", "region", "office_access_scope")
|
||
|
|
search_fields = ("name", "slug", "server", "region")
|
||
|
|
prepopulated_fields = {"slug": ("name",)}
|
||
|
|
readonly_fields = ("last_seen_at", "agent_version", "total_upload_bytes", "total_download_bytes", "created_at", "updated_at")
|
||
|
|
fieldsets = (
|
||
|
|
("基本信息", {"fields": ("name", "slug", "region", "server", "port", "protocol", "status", "active", "subscription_enabled", "sort_order", "fallback_only")}),
|
||
|
|
("协议参数", {"fields": ("sni", "reality_public_key", "reality_short_id", "flow", "transport", "client_fingerprint", "skip_cert_verify")}),
|
||
|
|
("办公室权限(接入验证中)", {"fields": ("office_only", "office_access_scope", "office_users"), "description": "公司网络模式依据当前接入的登记站点,不按人员所属办公室判断;白名单字段仅供保留原白名单模式使用。两种模式都只是验证候选,尚不进入普通订阅或自动调度;真实站点验证及加密入口通过前不得上线。"}),
|
||
|
|
("运行状态", {"fields": ("last_seen_at", "agent_version", "total_upload_bytes", "total_download_bytes", "created_at", "updated_at")}),
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
class DeviceInline(admin.TabularInline):
|
||
|
|
model = Device
|
||
|
|
extra = 0
|
||
|
|
readonly_fields = ("device_id", "last_seen_at", "upload_bytes", "download_bytes", "created_at")
|
||
|
|
|
||
|
|
|
||
|
|
class NodeDeploymentInline(admin.TabularInline):
|
||
|
|
model = NodeDeployment
|
||
|
|
extra = 0
|
||
|
|
can_delete = False
|
||
|
|
readonly_fields = ("node", "deployed", "applied_at", "revoked_at", "last_error", "updated_at")
|
||
|
|
|
||
|
|
|
||
|
|
@admin.action(description="开通所选订阅")
|
||
|
|
def activate_subscriptions(modeladmin, request, queryset):
|
||
|
|
success = 0
|
||
|
|
for subscription in queryset:
|
||
|
|
try:
|
||
|
|
subscription.activate()
|
||
|
|
success += 1
|
||
|
|
except ValidationError as exc:
|
||
|
|
modeladmin.message_user(request, f"{subscription}: {exc}", level=messages.ERROR)
|
||
|
|
if success:
|
||
|
|
modeladmin.message_user(request, f"已开通 {success} 个订阅。", level=messages.SUCCESS)
|
||
|
|
|
||
|
|
|
||
|
|
@admin.action(description="暂停所选订阅")
|
||
|
|
def suspend_subscriptions(modeladmin, request, queryset):
|
||
|
|
for subscription in queryset:
|
||
|
|
subscription.suspend(reason="管理员暂停")
|
||
|
|
|
||
|
|
|
||
|
|
@admin.action(description="取消并撤销所选订阅")
|
||
|
|
def cancel_subscriptions(modeladmin, request, queryset):
|
||
|
|
for subscription in queryset:
|
||
|
|
subscription.cancel(reason="管理员取消")
|
||
|
|
|
||
|
|
|
||
|
|
@admin.action(description="重置订阅地址")
|
||
|
|
def rotate_subscription_tokens(modeladmin, request, queryset):
|
||
|
|
for subscription in queryset:
|
||
|
|
subscription.rotate_subscription()
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(Subscription)
|
||
|
|
class SubscriptionAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("user", "plan", "status", "usage_summary", "expires_at", "route_mode", "provisioning_state")
|
||
|
|
list_filter = ("status", "plan", "route_mode", "provisioning_state")
|
||
|
|
search_fields = ("user__username", "user__display_name", "user__email", "credential_uuid")
|
||
|
|
autocomplete_fields = ("user", "plan", "routing_policy", "allowed_nodes")
|
||
|
|
filter_horizontal = ("allowed_nodes",)
|
||
|
|
readonly_fields = (
|
||
|
|
"credential_uuid",
|
||
|
|
"subscription_link",
|
||
|
|
"upload_bytes",
|
||
|
|
"download_bytes",
|
||
|
|
"created_at",
|
||
|
|
"updated_at",
|
||
|
|
)
|
||
|
|
actions = (activate_subscriptions, suspend_subscriptions, cancel_subscriptions, rotate_subscription_tokens)
|
||
|
|
inlines = (DeviceInline, NodeDeploymentInline)
|
||
|
|
fieldsets = (
|
||
|
|
("订阅", {"fields": ("user", "plan", "status", "starts_at", "expires_at", "state_reason")}),
|
||
|
|
("额度", {"fields": ("traffic_limit_bytes", "upload_bytes", "download_bytes", "device_limit")}),
|
||
|
|
("路由与节点", {"fields": ("route_mode", "routing_policy", "allowed_nodes")}),
|
||
|
|
("下发与凭据", {"fields": ("provisioning_state", "credential_uuid", "subscription_link")}),
|
||
|
|
("审计", {"fields": ("created_at", "updated_at"), "classes": ("collapse",)}),
|
||
|
|
)
|
||
|
|
|
||
|
|
@admin.display(description="流量")
|
||
|
|
def usage_summary(self, obj):
|
||
|
|
used_gb = obj.used_bytes / 1024**3
|
||
|
|
if obj.traffic_limit_bytes:
|
||
|
|
return f"{used_gb:.2f} / {obj.traffic_limit_bytes / 1024**3:.0f} GB"
|
||
|
|
return f"{used_gb:.2f} GB / 不限"
|
||
|
|
|
||
|
|
@admin.display(description="订阅地址")
|
||
|
|
def subscription_link(self, obj):
|
||
|
|
if not obj.pk:
|
||
|
|
return "保存后生成"
|
||
|
|
return format_html('<a href="{}" target="_blank" rel="noreferrer">打开订阅</a>', obj.subscription_url)
|
||
|
|
|
||
|
|
|
||
|
|
@admin.action(description="批准所选申请")
|
||
|
|
def approve_applications(modeladmin, request, queryset):
|
||
|
|
success = 0
|
||
|
|
for application in queryset:
|
||
|
|
try:
|
||
|
|
application.approve(request.user)
|
||
|
|
success += 1
|
||
|
|
except ValidationError as exc:
|
||
|
|
modeladmin.message_user(request, f"{application}: {exc}", level=messages.ERROR)
|
||
|
|
if success:
|
||
|
|
modeladmin.message_user(request, f"已批准并开通 {success} 个申请。", level=messages.SUCCESS)
|
||
|
|
|
||
|
|
|
||
|
|
@admin.action(description="拒绝所选申请")
|
||
|
|
def reject_applications(modeladmin, request, queryset):
|
||
|
|
queryset.filter(status=PlanApplication.Status.PENDING).update(status=PlanApplication.Status.REJECTED)
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(PlanApplication)
|
||
|
|
class PlanApplicationAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("user", "plan", "status", "payment_status", "subscription", "created_at", "reviewed_by")
|
||
|
|
list_filter = ("status", "payment_status", "plan")
|
||
|
|
search_fields = ("user__username", "user__display_name", "user__email", "note")
|
||
|
|
autocomplete_fields = ("user", "plan", "reviewed_by")
|
||
|
|
readonly_fields = ("status", "subscription", "reviewed_by", "reviewed_at", "created_at", "updated_at")
|
||
|
|
actions = (approve_applications, reject_applications)
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(UsageRecord)
|
||
|
|
class UsageRecordAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("day", "subscription", "node", "upload_gb", "download_gb", "total_gb")
|
||
|
|
list_filter = ("day", "node")
|
||
|
|
search_fields = ("subscription__user__username", "subscription__user__display_name", "node__name")
|
||
|
|
autocomplete_fields = ("subscription", "node")
|
||
|
|
date_hierarchy = "day"
|
||
|
|
|
||
|
|
@admin.display(description="上传 GB")
|
||
|
|
def upload_gb(self, obj):
|
||
|
|
return f"{obj.upload_bytes / 1024**3:.3f}"
|
||
|
|
|
||
|
|
@admin.display(description="下载 GB")
|
||
|
|
def download_gb(self, obj):
|
||
|
|
return f"{obj.download_bytes / 1024**3:.3f}"
|
||
|
|
|
||
|
|
@admin.display(description="合计 GB")
|
||
|
|
def total_gb(self, obj):
|
||
|
|
return f"{(obj.upload_bytes + obj.download_bytes) / 1024**3:.3f}"
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(NodeTrafficSample)
|
||
|
|
class NodeTrafficSampleAdmin(admin.ModelAdmin):
|
||
|
|
list_display = (
|
||
|
|
"sampled_at", "node", "upload_speed", "download_speed",
|
||
|
|
"active_subscriptions", "interval_seconds",
|
||
|
|
)
|
||
|
|
list_filter = ("node", "sampled_at")
|
||
|
|
readonly_fields = (
|
||
|
|
"node", "report", "sampled_at", "interval_seconds", "upload_bytes", "download_bytes",
|
||
|
|
"upload_bytes_per_second", "download_bytes_per_second", "active_subscriptions",
|
||
|
|
)
|
||
|
|
date_hierarchy = "sampled_at"
|
||
|
|
|
||
|
|
@admin.display(description="上传 Mbps")
|
||
|
|
def upload_speed(self, obj):
|
||
|
|
return f"{obj.upload_bytes_per_second * 8 / 1_000_000:.3f}"
|
||
|
|
|
||
|
|
@admin.display(description="下载 Mbps")
|
||
|
|
def download_speed(self, obj):
|
||
|
|
return f"{obj.download_bytes_per_second * 8 / 1_000_000:.3f}"
|
||
|
|
|
||
|
|
def has_add_permission(self, request):
|
||
|
|
return False
|
||
|
|
|
||
|
|
def has_change_permission(self, request, obj=None):
|
||
|
|
return False
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(Device)
|
||
|
|
class DeviceAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("name", "device_id", "subscription", "platform", "active", "last_seen_at")
|
||
|
|
list_filter = ("active", "platform")
|
||
|
|
search_fields = ("name", "device_id", "subscription__user__username")
|
||
|
|
autocomplete_fields = ("subscription",)
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(ClientSession)
|
||
|
|
class ClientSessionAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("subscription", "device", "created_at", "last_seen_at", "expires_at", "revoked_at")
|
||
|
|
list_filter = ("created_at", "expires_at", "revoked_at")
|
||
|
|
search_fields = ("subscription__user__username", "subscription__user__display_name", "device__name", "device__device_id")
|
||
|
|
readonly_fields = ("subscription", "device", "token_digest", "created_at", "last_seen_at", "expires_at", "revoked_at")
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(NodeDeployment)
|
||
|
|
class NodeDeploymentAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("subscription", "node", "deployed", "applied_at", "revoked_at", "updated_at")
|
||
|
|
list_filter = ("deployed", "node")
|
||
|
|
search_fields = ("subscription__user__username", "node__name", "last_error")
|
||
|
|
readonly_fields = ("subscription", "node", "deployed", "applied_at", "revoked_at", "last_error", "updated_at")
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(RouteObservation)
|
||
|
|
class RouteObservationAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("target", "port", "access_kind", "network", "outcome", "failure_kind", "device", "node", "received_at")
|
||
|
|
list_filter = ("access_kind", "target_type", "network", "outcome", "failure_kind", "node", "received_at")
|
||
|
|
search_fields = ("target", "device__name", "device__device_id", "subscription__user__username")
|
||
|
|
readonly_fields = (
|
||
|
|
"report_id", "subscription", "device", "node", "target_type", "target", "port", "access_kind", "network",
|
||
|
|
"outcome", "failure_kind", "client_version", "received_at",
|
||
|
|
)
|
||
|
|
date_hierarchy = "received_at"
|
||
|
|
|
||
|
|
def has_add_permission(self, request):
|
||
|
|
return False
|
||
|
|
|
||
|
|
def has_change_permission(self, request, obj=None):
|
||
|
|
return False
|
||
|
|
|
||
|
|
|
||
|
|
@admin.action(description="启用为公司智能路由")
|
||
|
|
def activate_learned_rules(modeladmin, request, queryset):
|
||
|
|
queryset.update(
|
||
|
|
status=LearnedRouteRule.Status.ACTIVE,
|
||
|
|
source=LearnedRouteRule.Source.MANUAL,
|
||
|
|
manually_locked=True,
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
@admin.action(description="禁用并锁定所选 AI 路由")
|
||
|
|
def disable_learned_rules(modeladmin, request, queryset):
|
||
|
|
queryset.update(status=LearnedRouteRule.Status.DISABLED, manually_locked=True)
|
||
|
|
|
||
|
|
|
||
|
|
@admin.action(description="交还 vpn-ai 自动管理")
|
||
|
|
def unlock_learned_rules(modeladmin, request, queryset):
|
||
|
|
queryset.update(manually_locked=False)
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(LearnedRouteRule)
|
||
|
|
class LearnedRouteRuleAdmin(admin.ModelAdmin):
|
||
|
|
list_display = (
|
||
|
|
"target", "target_type", "match_mode", "source", "status", "confidence",
|
||
|
|
"distinct_devices", "failure_reports", "valid_until", "manually_locked",
|
||
|
|
)
|
||
|
|
list_filter = ("source", "status", "target_type", "match_mode", "manually_locked", "valid_until")
|
||
|
|
search_fields = ("target", "reason")
|
||
|
|
readonly_fields = ("confidence", "failure_reports", "proxy_success_reports", "distinct_devices", "reason", "first_seen_at", "last_evaluated_at", "updated_at")
|
||
|
|
actions = (activate_learned_rules, disable_learned_rules, unlock_learned_rules)
|
||
|
|
|
||
|
|
def has_add_permission(self, request):
|
||
|
|
return False
|
||
|
|
|
||
|
|
def save_model(self, request, obj, form, change):
|
||
|
|
if not change and obj.source == LearnedRouteRule.Source.AI:
|
||
|
|
obj.source = LearnedRouteRule.Source.MANUAL
|
||
|
|
obj.manually_locked = True
|
||
|
|
super().save_model(request, obj, form, change)
|
||
|
|
|
||
|
|
|
||
|
|
@admin.action(description="将所选诊断标记为已忽略")
|
||
|
|
def ignore_ai_findings(modeladmin, request, queryset):
|
||
|
|
queryset.update(status=VpnAiFinding.Status.IGNORED)
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(VpnAiFinding)
|
||
|
|
class VpnAiFindingAdmin(admin.ModelAdmin):
|
||
|
|
list_display = ("title", "category", "severity", "status", "last_seen_at")
|
||
|
|
list_filter = ("category", "severity", "status", "last_seen_at")
|
||
|
|
search_fields = ("title", "summary", "fingerprint")
|
||
|
|
readonly_fields = ("fingerprint", "category", "severity", "title", "summary", "evidence", "first_seen_at", "last_seen_at", "resolved_at")
|
||
|
|
actions = (ignore_ai_findings,)
|
||
|
|
|
||
|
|
def has_add_permission(self, request):
|
||
|
|
return False
|
||
|
|
|
||
|
|
|
||
|
|
@admin.register(VpnAiRuntime)
|
||
|
|
class VpnAiRuntimeAdmin(admin.ModelAdmin):
|
||
|
|
change_list_template = "admin/control/vpnairuntime/change_list.html"
|
||
|
|
list_display = ("service_name", "health_label", "version", "last_heartbeat_at", "last_cycle_at", "cycle_count", "active_rules", "open_findings")
|
||
|
|
readonly_fields = (
|
||
|
|
"service_name", "version", "worker_id", "started_at", "last_heartbeat_at", "last_cycle_at",
|
||
|
|
"cycle_count", "observations_7d", "active_rules", "open_findings", "last_error", "updated_at", "dispatch_snapshot",
|
||
|
|
)
|
||
|
|
|
||
|
|
@admin.display(description="运行状态")
|
||
|
|
def health_label(self, obj):
|
||
|
|
return "正常" if obj.is_healthy else "心跳异常"
|
||
|
|
|
||
|
|
def has_add_permission(self, request):
|
||
|
|
return False
|
||
|
|
|
||
|
|
def has_delete_permission(self, request, obj=None):
|
||
|
|
return False
|
||
|
|
|
||
|
|
def changelist_view(self, request, extra_context=None):
|
||
|
|
runtime = VpnAiRuntime.objects.first()
|
||
|
|
from .learning import learning_summary
|
||
|
|
extra_context = {
|
||
|
|
**(extra_context or {}),
|
||
|
|
"vpn_ai_runtime": runtime,
|
||
|
|
"learning": learning_summary(),
|
||
|
|
"recent_findings": VpnAiFinding.objects.select_related().all()[:8],
|
||
|
|
"recent_rules": LearnedRouteRule.objects.all()[:8],
|
||
|
|
}
|
||
|
|
return super().changelist_view(request, extra_context=extra_context)
|