初始提交:卡密授权管理系统
This commit is contained in:
commit
59586775c4
202 files changed
+25427
No files matched your search
+20
@@ -0,0 +1,20 @@
|
||||
# CardAuth - 授权管理系统
|
||||
|
||||
# 后端
|
||||
/backend/.env
|
||||
/backend/storage/cache/*
|
||||
/backend/vendor/
|
||||
|
||||
# 前端
|
||||
/frontend/node_modules/
|
||||
/frontend/dist/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# 系统文件
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
APP_DEBUG=true
|
||||
APP_URL=http://your-domain.com
|
||||
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_NAME=card_auth
|
||||
DB_USER=root
|
||||
DB_PASS=your_password
|
||||
DB_PREFIX=ca_
|
||||
|
||||
JWT_SECRET=change_this_to_random_64_chars_string
|
||||
|
||||
PAYMENT_TYPE=epay
|
||||
PAYMENT_API_URL=https://pay.example.com
|
||||
PAYMENT_APP_ID=your_app_id
|
||||
PAYMENT_APP_KEY=your_app_key
|
||||
@@ -0,0 +1 @@
|
||||
{"version":2,"defects":{"Tests\\Integration\\AuthProfileApiTest::testGetCurrentUserProfile":7,"Tests\\Integration\\AuthProfileApiTest::testUpdateProfile":7,"Tests\\Integration\\AuthProfileApiTest::testUpdateProfileWithInvalidEmail":7,"Tests\\Integration\\BlacklistApiTest::testCreateAndListBlacklist":7,"Tests\\Integration\\BlacklistApiTest::testUpdateBlacklistStatus":7,"Tests\\Integration\\BlacklistApiTest::testNonAdminCannotAccessBlacklist":7,"Tests\\Integration\\BlacklistApiTest::testBlockedUserCannotAccessApi":7,"Tests\\Integration\\SystemApiTest::testGetSystemConfigs":7,"Tests\\Integration\\SystemApiTest::testSaveAndGetSiteName":7},"times":{"Tests\\Unit\\JwtServiceTest::testGenerateAndVerifyToken":0.014,"Tests\\Unit\\JwtServiceTest::testVerifyExpiredToken":0,"Tests\\Unit\\JwtServiceTest::testVerifyInvalidToken":0,"Tests\\Unit\\JwtServiceTest::testRefreshTokenFlow":0.001,"Tests\\Unit\\ValidatorTest::testRequiredValidation":0.003,"Tests\\Unit\\ValidatorTest::testEmailValidation":0.001,"Tests\\Unit\\ValidatorTest::testMinMaxLength":0,"Tests\\Unit\\ValidatorTest::testIntegerValidation":0.001,"Tests\\Unit\\ValidatorTest::testInValidation":0,"Tests\\Integration\\AuthProfileApiTest::testGetCurrentUserProfile":0.103,"Tests\\Integration\\AuthProfileApiTest::testUpdateProfile":0.008,"Tests\\Integration\\AuthProfileApiTest::testUpdateProfileWithInvalidEmail":0.008,"Tests\\Integration\\SystemApiTest::testGetSystemConfigs":0.032,"Tests\\Integration\\SystemApiTest::testSaveAndGetSiteName":0.01,"Tests\\Unit\\BlacklistServiceTest::testIsBlockedWithUserId":0.12,"Tests\\Unit\\BlacklistServiceTest::testIsBlockedWithIp":0.046,"Tests\\Unit\\BlacklistServiceTest::testCacheRefreshAndClear":0.049,"Tests\\Unit\\BlacklistServiceTest::testIsBlockedWithExpiredItem":0.046,"Tests\\Integration\\BlacklistApiTest::testCreateAndListBlacklist":0.008,"Tests\\Integration\\BlacklistApiTest::testUpdateBlacklistStatus":0.007,"Tests\\Integration\\BlacklistApiTest::testNonAdminCannotAccessBlacklist":0.007,"Tests\\Integration\\BlacklistApiTest::testBlockedUserCannotAccessApi":0.013}}
|
||||
@@ -0,0 +1,2 @@
|
||||
HTTP Code: 200
|
||||
Response: {"code":200,"message":"登录成功","data":{"user":{"id":1,"username":"admin","nickname":"超级管理员","role":"admin","email":""},"token":{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjYXJkYXV0aCIsImlhdCI6MTc4MTkzOTIzMiwiZXhwIjoxNzgxOTQ2NDMyLCJuYmYiOjE3ODE5MzkyMzIsInN1YiI6MSwiZGF0YSI6eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsInJvbGUiOiJhZG1pbiJ9fQ.u3sxVN3rzB6khVeW8ZM63EIm69Oa5Kzw7VsOuQpeqlc","refresh_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjYXJkYXV0aCIsImlhdCI6MTc4MTkzOTIzMiwiZXhwIjoxNzgzMTQ4ODMyLCJuYmYiOjE3ODE5MzkyMzIsInN1YiI6MSwiZGF0YSI6eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsInJvbGUiOiJhZG1pbiJ9LCJ0eXBlIjoicmVmcmVzaCJ9.sJa2rxDvatpBEZfj7eTo4PZOXScLxC5t3cAQ5_rIWG4","expires_in":7200,"token_type":"Bearer"}}}
|
||||
@@ -0,0 +1,2 @@
|
||||
HTTP Code: 200
|
||||
Response: {"code":200,"message":"操作成功","data":[]}
|
||||
@@ -0,0 +1,508 @@
|
||||
<?php
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Controller;
|
||||
use App\Core\Database;
|
||||
use App\Core\Validator;
|
||||
|
||||
/**
|
||||
* 代理与额度管理控制器
|
||||
*/
|
||||
class AgentController extends Controller
|
||||
{
|
||||
/**
|
||||
* 代理列表
|
||||
*/
|
||||
/**
|
||||
* 代理列表
|
||||
* GET /api/agents
|
||||
* Query: keyword, status, sort_by, sort_order, page, page_size
|
||||
*/
|
||||
public function list(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$page = max(1, (int) ($_GET['page'] ?? 1));
|
||||
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
|
||||
$keyword = trim($_GET['keyword'] ?? '');
|
||||
$status = $_GET['status'] ?? '';
|
||||
$offset = ($page - 1) * $pageSize;
|
||||
|
||||
$where = "WHERE u.role = 'agent' AND u.deleted_at IS NULL";
|
||||
$params = [];
|
||||
|
||||
if ($status !== '') {
|
||||
$where .= " AND u.status = ?";
|
||||
$params[] = (int) $status;
|
||||
}
|
||||
if ($keyword) {
|
||||
$where .= " AND (u.username LIKE ? OR u.nickname LIKE ?)";
|
||||
$params[] = "%{$keyword}%";
|
||||
$params[] = "%{$keyword}%";
|
||||
}
|
||||
|
||||
$total = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('users')} u {$where}",
|
||||
$params
|
||||
);
|
||||
|
||||
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'username', 'total_quota', 'used_quota', 'remain_quota', 'created_at']) ? $_GET['sort_by'] : 'id';
|
||||
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
|
||||
$orderSql = $sortBy === 'remain_quota' ? "(COALESCE(a.total_quota, 0) - COALESCE(a.used_quota, 0) - COALESCE(a.frozen_quota, 0)) {$sortOrder}" : "u.{$sortBy} {$sortOrder}";
|
||||
|
||||
$agents = $db->fetchAll(
|
||||
"SELECT u.id, u.username, u.nickname, u.email, u.status, u.last_login_at, u.created_at,
|
||||
COALESCE(a.total_quota, 0) AS total_quota,
|
||||
COALESCE(a.used_quota, 0) AS used_quota,
|
||||
COALESCE(a.frozen_quota, 0) AS frozen_quota,
|
||||
(COALESCE(a.total_quota, 0) - COALESCE(a.used_quota, 0) - COALESCE(a.frozen_quota, 0)) AS remain_quota
|
||||
FROM {$db->table('users')} u
|
||||
LEFT JOIN {$db->table('agents')} a ON u.id = a.user_id
|
||||
{$where}
|
||||
ORDER BY {$orderSql}
|
||||
LIMIT {$offset}, {$pageSize}",
|
||||
$params
|
||||
);
|
||||
|
||||
$this->success([
|
||||
'list' => $agents,
|
||||
'total' => (int) $total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出代理
|
||||
* GET /api/agents/export
|
||||
* Query: ids, format(csv|excel)
|
||||
*/
|
||||
public function export(): void
|
||||
{
|
||||
$ids = $_GET['ids'] ?? [];
|
||||
$format = strtolower($_GET['format'] ?? 'csv');
|
||||
if (!in_array($format, ['csv', 'excel'])) {
|
||||
$format = 'csv';
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$where = "WHERE u.role = 'agent' AND u.deleted_at IS NULL";
|
||||
$params = [];
|
||||
|
||||
if (!empty($ids)) {
|
||||
$ids = is_array($ids) ? $ids : explode(',', $ids);
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (!empty($ids)) {
|
||||
$where .= ' AND u.id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
|
||||
$params = array_merge($params, $ids);
|
||||
}
|
||||
}
|
||||
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT u.id, u.username, u.nickname, u.email, u.status, u.created_at,
|
||||
COALESCE(a.total_quota, 0) AS total_quota,
|
||||
COALESCE(a.used_quota, 0) AS used_quota,
|
||||
(COALESCE(a.total_quota, 0) - COALESCE(a.used_quota, 0) - COALESCE(a.frozen_quota, 0)) AS remain_quota
|
||||
FROM {$db->table('users')} u
|
||||
LEFT JOIN {$db->table('agents')} a ON u.id = a.user_id
|
||||
{$where}
|
||||
ORDER BY u.id DESC
|
||||
LIMIT 50000",
|
||||
$params
|
||||
);
|
||||
|
||||
if ($format === 'excel') {
|
||||
$filename = 'agents_export_' . date('YmdHis') . '.xls';
|
||||
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
$html = '<table border="1"><tr><th>ID</th><th>用户名</th><th>昵称</th><th>邮箱</th><th>状态</th><th>总额度</th><th>已使用</th><th>剩余额度</th><th>创建时间</th></tr>';
|
||||
foreach ($rows as $row) {
|
||||
$html .= '<tr>';
|
||||
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['username']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['nickname'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['email'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['status'] == 1 ? '正常' : '禁用') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['total_quota']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['used_quota']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['remain_quota']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
|
||||
$html .= '</tr>';
|
||||
}
|
||||
$html .= '</table>';
|
||||
echo $html;
|
||||
exit;
|
||||
}
|
||||
|
||||
$filename = 'agents_export_' . date('YmdHis') . '.csv';
|
||||
header('Content-Type: text/csv; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
|
||||
$output = fopen('php://output', 'w');
|
||||
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($output, ['ID', '用户名', '昵称', '邮箱', '状态', '总额度', '已使用', '剩余额度', '创建时间']);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($output, [
|
||||
$row['id'],
|
||||
$row['username'],
|
||||
$row['nickname'] ?? '',
|
||||
$row['email'] ?? '',
|
||||
$row['status'] == 1 ? '正常' : '禁用',
|
||||
$row['total_quota'],
|
||||
$row['used_quota'],
|
||||
$row['remain_quota'],
|
||||
$row['created_at'],
|
||||
]);
|
||||
}
|
||||
fclose($output);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* 给代理充值额度
|
||||
*/
|
||||
public function recharge(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate([
|
||||
'agent_id' => 'required|integer',
|
||||
'amount' => 'required|numeric',
|
||||
])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
$agentId = (int) $input['agent_id'];
|
||||
$amount = (float) $input['amount'];
|
||||
$remark = $input['remark'] ?? '';
|
||||
|
||||
if ($amount <= 0) {
|
||||
$this->error('额度必须大于0');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// 验证代理存在
|
||||
$agent = $db->fetch(
|
||||
"SELECT u.id, a.id AS agent_record_id, COALESCE(a.total_quota, 0) AS total_quota,
|
||||
COALESCE(a.used_quota, 0) AS used_quota
|
||||
FROM {$db->table('users')} u
|
||||
LEFT JOIN {$db->table('agents')} a ON u.id = a.user_id
|
||||
WHERE u.id = ? AND u.role = 'agent' AND u.deleted_at IS NULL",
|
||||
[$agentId]
|
||||
);
|
||||
if (!$agent) {
|
||||
$this->error('代理不存在');
|
||||
}
|
||||
|
||||
$balanceBefore = (float) ($agent['total_quota'] ?? 0) - (float) ($agent['used_quota'] ?? 0);
|
||||
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
if ($agent['agent_record_id']) {
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('agents')} SET total_quota = total_quota + ? WHERE user_id = ?",
|
||||
[$amount, $agentId]
|
||||
);
|
||||
} else {
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('agents')} (user_id, total_quota, used_quota) VALUES (?, ?, 0)",
|
||||
[$agentId, $amount]
|
||||
);
|
||||
}
|
||||
|
||||
$balanceAfter = $balanceBefore + $amount;
|
||||
|
||||
// 记录额度变动
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, remark, operator_id, created_at)
|
||||
VALUES (?, 'recharge', ?, ?, ?, ?, ?, NOW())",
|
||||
[$agentId, $amount, $balanceBefore, $balanceAfter, $remark, $this->getUserId()]
|
||||
);
|
||||
|
||||
$db->commit();
|
||||
} catch (\Throwable $e) {
|
||||
$db->rollback();
|
||||
$this->error('充值失败: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
logger('agent_recharge', 'agent', $agentId, ['amount' => $amount]);
|
||||
|
||||
$this->success([
|
||||
'balance_before' => $balanceBefore,
|
||||
'balance_after' => $balanceAfter,
|
||||
], '充值成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 调整代理额度
|
||||
*/
|
||||
public function adjustQuota(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$agentId = (int) ($input['agent_id'] ?? 0);
|
||||
$amount = (float) ($input['amount'] ?? 0);
|
||||
$remark = $input['remark'] ?? '';
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
$agent = $db->fetch(
|
||||
"SELECT a.* FROM {$db->table('agents')} a
|
||||
JOIN {$db->table('users')} u ON a.user_id = u.id
|
||||
WHERE a.user_id = ? AND u.role = 'agent'",
|
||||
[$agentId]
|
||||
);
|
||||
if (!$agent) {
|
||||
$this->error('代理不存在');
|
||||
}
|
||||
|
||||
$balanceBefore = (float) $agent['total_quota'] - (float) $agent['used_quota'];
|
||||
$balanceAfter = $balanceBefore + $amount;
|
||||
|
||||
if ($balanceAfter < 0) {
|
||||
$this->error('调整后额度不能为负');
|
||||
}
|
||||
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('agents')} SET total_quota = total_quota + ? WHERE user_id = ?",
|
||||
[$amount, $agentId]
|
||||
);
|
||||
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, remark, operator_id, created_at)
|
||||
VALUES (?, 'adjust', ?, ?, ?, ?, ?, NOW())",
|
||||
[$agentId, $amount, $balanceBefore, $balanceAfter, $remark, $this->getUserId()]
|
||||
);
|
||||
|
||||
$db->commit();
|
||||
} catch (\Throwable $e) {
|
||||
$db->rollback();
|
||||
$this->error('调整失败');
|
||||
}
|
||||
|
||||
logger('agent_adjust_quota', 'agent', $agentId, ['amount' => $amount]);
|
||||
|
||||
$this->success([
|
||||
'balance_before' => $balanceBefore,
|
||||
'balance_after' => $balanceAfter,
|
||||
], '调整成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理额度变动日志
|
||||
*/
|
||||
public function quotaLogs(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$page = (int) ($_GET['page'] ?? 1);
|
||||
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
|
||||
$agentId = $_GET['agent_id'] ?? '';
|
||||
$offset = ($page - 1) * $pageSize;
|
||||
|
||||
$where = "WHERE 1=1";
|
||||
$params = [];
|
||||
|
||||
if ($agentId) {
|
||||
$where .= " AND agent_id = ?";
|
||||
$params[] = $agentId;
|
||||
}
|
||||
|
||||
$total = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('agent_quota_logs')} {$where}",
|
||||
$params
|
||||
);
|
||||
|
||||
$logs = $db->fetchAll(
|
||||
"SELECT l.*, u.username AS agent_name, op.username AS operator_name
|
||||
FROM {$db->table('agent_quota_logs')} l
|
||||
LEFT JOIN {$db->table('users')} u ON l.agent_id = u.id
|
||||
LEFT JOIN {$db->table('users')} op ON l.operator_id = op.id
|
||||
{$where}
|
||||
ORDER BY l.id DESC
|
||||
LIMIT {$offset}, {$pageSize}",
|
||||
$params
|
||||
);
|
||||
|
||||
$this->success([
|
||||
'list' => $logs,
|
||||
'total' => (int) $total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取代理可用额度 (Agent自己查看)
|
||||
*/
|
||||
public function myQuota(): void
|
||||
{
|
||||
$userId = $this->getUserId();
|
||||
$db = Database::getInstance();
|
||||
|
||||
$agent = $db->fetch(
|
||||
"SELECT total_quota, used_quota, frozen_quota FROM {$db->table('agents')} WHERE user_id = ?",
|
||||
[$userId]
|
||||
);
|
||||
|
||||
if (!$agent) {
|
||||
$this->success(['total_quota' => 0, 'used_quota' => 0, 'frozen_quota' => 0, 'remain_quota' => 0]);
|
||||
return;
|
||||
}
|
||||
|
||||
$this->success([
|
||||
'total_quota' => (float) $agent['total_quota'],
|
||||
'used_quota' => (float) $agent['used_quota'],
|
||||
'frozen_quota' => (float) $agent['frozen_quota'],
|
||||
'remain_quota' => (float) $agent['total_quota'] - (float) $agent['used_quota'] - (float) $agent['frozen_quota'],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理为下级用户授权(消耗额度)
|
||||
*/
|
||||
public function authorizeCard(): void
|
||||
{
|
||||
// 仅代理角色可使用此接口
|
||||
if ($this->getUserRole() !== 'agent') {
|
||||
$this->error('仅代理用户可执行此操作', 403);
|
||||
}
|
||||
|
||||
$userId = $this->getUserId();
|
||||
$input = $this->getJsonInput();
|
||||
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate([
|
||||
'project_id' => 'required|integer',
|
||||
'card_type_id' => 'required|integer',
|
||||
])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
$projectId = (int) $input['project_id'];
|
||||
$cardTypeId = (int) $input['card_type_id'];
|
||||
$bindInfo = $input['bind_info'] ?? [];
|
||||
$remark = $input['remark'] ?? '';
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// 验证项目
|
||||
$project = $db->fetch("SELECT id FROM {$db->table('projects')} WHERE id = ? AND status = 1 AND deleted_at IS NULL", [$projectId]);
|
||||
if (!$project) {
|
||||
$this->error('项目不存在或已禁用');
|
||||
}
|
||||
|
||||
// 验证卡密类型
|
||||
$cardType = $db->fetch(
|
||||
"SELECT * FROM {$db->table('card_types')} WHERE id = ? AND project_id = ? AND status = 1",
|
||||
[$cardTypeId, $projectId]
|
||||
);
|
||||
if (!$cardType) {
|
||||
$this->error('卡密类型不存在');
|
||||
}
|
||||
if ((float) $cardType['agent_cost'] <= 0) {
|
||||
$this->error('该套餐未配置代理价格,无法生成');
|
||||
}
|
||||
|
||||
// 检查额度
|
||||
$agent = $db->fetch("SELECT * FROM {$db->table('agents')} WHERE user_id = ?", [$userId]);
|
||||
if (!$agent) {
|
||||
$this->error('代理额度账户不存在,请联系管理员充值');
|
||||
}
|
||||
$remainQuota = (float) ($agent['total_quota'] ?? 0) - (float) ($agent['used_quota'] ?? 0) - (float) ($agent['frozen_quota'] ?? 0);
|
||||
|
||||
if ($remainQuota < (float) $cardType['agent_cost']) {
|
||||
$this->error('可用额度不足,请充值');
|
||||
}
|
||||
|
||||
$snowflake = new \App\Services\SnowflakeService();
|
||||
$cardKey = $snowflake->generateCardKey();
|
||||
|
||||
$expireTime = null;
|
||||
if ($cardType['duration_days'] > 0) {
|
||||
$expireTime = date('Y-m-d H:i:s', strtotime("+{$cardType['duration_days']} days"));
|
||||
}
|
||||
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
// 创建卡密
|
||||
$cardId = $db->insert(
|
||||
"INSERT INTO {$db->table('cards')} (card_key, project_id, card_type_id, type, duration_days, status, bind_info, bound_at, expire_time, use_user_id, remark)
|
||||
VALUES (?, ?, ?, ?, ?, 'used', ?, NOW(), ?, ?, ?)",
|
||||
[
|
||||
$cardKey,
|
||||
$projectId,
|
||||
$cardTypeId,
|
||||
$cardType['name'],
|
||||
$cardType['duration_days'],
|
||||
json_encode($bindInfo, JSON_UNESCAPED_UNICODE),
|
||||
$expireTime,
|
||||
$userId,
|
||||
$remark,
|
||||
]
|
||||
);
|
||||
|
||||
// 扣减额度
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('agents')} SET used_quota = used_quota + ? WHERE user_id = ?",
|
||||
[(float) $cardType['agent_cost'], $userId]
|
||||
);
|
||||
|
||||
$balanceBefore = $remainQuota;
|
||||
$balanceAfter = $remainQuota - (float) $cardType['agent_cost'];
|
||||
|
||||
// 记录额度变动
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, target_type, target_id, remark, operator_id, created_at)
|
||||
VALUES (?, 'consume', ?, ?, ?, 'card', ?, ?, ?, NOW())",
|
||||
[$userId, (float) $cardType['agent_cost'], $balanceBefore, $balanceAfter, $cardId, $remark, $this->getUserId()]
|
||||
);
|
||||
|
||||
$db->commit();
|
||||
} catch (\Throwable $e) {
|
||||
$db->rollback();
|
||||
$this->error('授权失败: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
logger('agent_authorize', 'card', $cardId, ['project_id' => $projectId, 'card_type' => $cardType['name']]);
|
||||
|
||||
$this->success([
|
||||
'card_id' => $cardId,
|
||||
'card_key' => $cardKey,
|
||||
'expire_time' => $expireTime,
|
||||
], '授权成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置代理密码
|
||||
* POST /api/agents/{id}/reset-password
|
||||
*/
|
||||
public function resetPassword(int $agentId): void
|
||||
{
|
||||
if ($this->getUserRole() !== 'admin') {
|
||||
$this->error('权限不足', 403);
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$agent = $db->fetch(
|
||||
"SELECT id, username FROM {$db->table('users')} WHERE id = ? AND role = 'agent' AND deleted_at IS NULL",
|
||||
[$agentId]
|
||||
);
|
||||
if (!$agent) {
|
||||
$this->error('代理不存在');
|
||||
}
|
||||
|
||||
$newPassword = substr(bin2hex(random_bytes(4)), 0, 8);
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('users')} SET password = ? WHERE id = ?",
|
||||
[passwordHash($newPassword), $agentId]
|
||||
);
|
||||
|
||||
logger('reset_agent_password', 'user', $agentId, ['username' => $agent['username']]);
|
||||
|
||||
$this->success(['password' => $newPassword], '密码已重置');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,713 @@
|
||||
<?php
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Controller;
|
||||
use App\Core\Application;
|
||||
use App\Core\Database;
|
||||
use App\Core\Validator;
|
||||
use App\Services\JwtService;
|
||||
|
||||
/**
|
||||
* 认证控制器
|
||||
* 处理登录、登出、Token刷新、密码修改
|
||||
*/
|
||||
class AuthController extends Controller
|
||||
{
|
||||
/**
|
||||
* 管理员登录
|
||||
* POST /api/auth/admin-login
|
||||
*/
|
||||
public function adminLogin(): void
|
||||
{
|
||||
$this->doLogin(['admin', 'project_admin'], 'admin');
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理登录
|
||||
* POST /api/auth/agent-login
|
||||
*/
|
||||
public function agentLogin(): void
|
||||
{
|
||||
$this->doLogin(['agent'], 'agent');
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一登录处理
|
||||
* @param array $allowedRoles 允许登录的角色
|
||||
* @param string $portal 登录入口标识,用于日志
|
||||
*/
|
||||
private function doLogin(array $allowedRoles, string $portal): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$account = $input['username'] ?? ($input['email'] ?? '');
|
||||
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate([
|
||||
'password' => 'required|min:6|max:50',
|
||||
])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
if (empty($account)) {
|
||||
$this->error('请输入用户名或邮箱');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// 根据是否包含@选择查询方式
|
||||
if (filter_var($account, FILTER_VALIDATE_EMAIL)) {
|
||||
$user = $db->fetch(
|
||||
"SELECT * FROM {$db->table('users')} WHERE email = ? AND deleted_at IS NULL",
|
||||
[$account]
|
||||
);
|
||||
} else {
|
||||
$user = $db->fetch(
|
||||
"SELECT * FROM {$db->table('users')} WHERE username = ? AND deleted_at IS NULL",
|
||||
[$account]
|
||||
);
|
||||
}
|
||||
|
||||
if (!$user || !passwordVerify($input['password'], $user['password'])) {
|
||||
$this->error('用户名或密码错误');
|
||||
}
|
||||
|
||||
if ($user['status'] != 1) {
|
||||
$this->error('账号已被禁用,请联系管理员');
|
||||
}
|
||||
|
||||
if (!in_array($user['role'], $allowedRoles, true)) {
|
||||
$this->error('该账号无此入口登录权限');
|
||||
}
|
||||
|
||||
// 更新登录信息
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('users')} SET last_login_at = NOW(), last_login_ip = ? WHERE id = ?",
|
||||
[clientIp(), $user['id']]
|
||||
);
|
||||
|
||||
// 生成Token
|
||||
$jwtService = new JwtService();
|
||||
$tokens = $jwtService->generateToken($user);
|
||||
|
||||
logger('login', 'user', $user['id'], ['portal' => $portal, 'role' => $user['role']]);
|
||||
|
||||
$this->success([
|
||||
'user' => [
|
||||
'id' => $user['id'],
|
||||
'username' => $user['username'],
|
||||
'nickname' => $user['nickname'],
|
||||
'role' => $user['role'],
|
||||
'email' => $user['email'],
|
||||
],
|
||||
'token' => $tokens,
|
||||
], '登录成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理注册
|
||||
* POST /api/auth/agent-register
|
||||
*/
|
||||
public function agentRegister(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate([
|
||||
'username' => 'required|min:3|max:50',
|
||||
'password' => 'required|min:6|max:50',
|
||||
'confirm_password'=> 'required',
|
||||
'email' => 'required|email|max:100',
|
||||
'phone' => 'required|max:20',
|
||||
])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
if ($input['password'] !== $input['confirm_password']) {
|
||||
$this->error('两次输入的密码不一致');
|
||||
}
|
||||
|
||||
// 手机号格式验证
|
||||
if (!preg_match('/^1[3-9]\d{9}$/', $input['phone'])) {
|
||||
$this->error('手机号格式不正确');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// 检查用户名是否已存在
|
||||
$exists = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('users')} WHERE username = ? AND deleted_at IS NULL",
|
||||
[$input['username']]
|
||||
);
|
||||
if ($exists > 0) {
|
||||
$this->error('用户名已被注册');
|
||||
}
|
||||
|
||||
// 检查邮箱是否已存在
|
||||
$emailExists = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('users')} WHERE email = ? AND deleted_at IS NULL",
|
||||
[$input['email']]
|
||||
);
|
||||
if ($emailExists > 0) {
|
||||
$this->error('邮箱已被注册');
|
||||
}
|
||||
|
||||
// 解析上级代理邀请码(用户名)
|
||||
$parentId = 0;
|
||||
$inviteCode = trim($input['invite_code'] ?? '');
|
||||
if ($inviteCode !== '') {
|
||||
$parent = $db->fetch(
|
||||
"SELECT id, role FROM {$db->table('users')} WHERE username = ? AND deleted_at IS NULL AND status = 1",
|
||||
[$inviteCode]
|
||||
);
|
||||
if (!$parent) {
|
||||
$this->error('邀请码不存在或已禁用');
|
||||
}
|
||||
if ($parent['role'] !== 'agent') {
|
||||
$this->error('邀请码无效,仅代理可邀请下级代理');
|
||||
}
|
||||
$parentId = (int) $parent['id'];
|
||||
}
|
||||
|
||||
$userId = $db->insert(
|
||||
"INSERT INTO {$db->table('users')} (username, password, nickname, email, phone, role, parent_id, status, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, 'agent', ?, 1, NOW(), NOW())",
|
||||
[
|
||||
$input['username'],
|
||||
passwordHash($input['password']),
|
||||
$input['username'],
|
||||
$input['email'],
|
||||
$input['phone'],
|
||||
$parentId,
|
||||
]
|
||||
);
|
||||
logger('agent_register', 'user', $userId, ['username' => $input['username'], 'parent_id' => $parentId]);
|
||||
|
||||
$this->success(['id' => $userId], '注册成功,请登录');
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新Token
|
||||
*/
|
||||
public function refreshToken(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$refreshToken = $input['refresh_token'] ?? '';
|
||||
|
||||
if (empty($refreshToken)) {
|
||||
$this->error('缺少刷新Token');
|
||||
}
|
||||
|
||||
$jwtService = new JwtService();
|
||||
$tokens = $jwtService->refreshToken($refreshToken);
|
||||
|
||||
if (!$tokens) {
|
||||
$this->error('刷新Token无效或已过期');
|
||||
}
|
||||
|
||||
$this->success($tokens, 'Token刷新成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户信息
|
||||
*/
|
||||
public function me(): void
|
||||
{
|
||||
$userId = $this->getUserId();
|
||||
if (!$userId) {
|
||||
$this->error('用户不存在', 404);
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$user = $db->fetch(
|
||||
"SELECT id, username, nickname, email, phone, avatar, role, status, parent_id, last_login_at, last_login_ip, created_at
|
||||
FROM {$db->table('users')}
|
||||
WHERE id = ? AND deleted_at IS NULL",
|
||||
[$userId]
|
||||
);
|
||||
|
||||
if (!$user) {
|
||||
$this->error('用户不存在', 404);
|
||||
}
|
||||
|
||||
// 如果是代理,获取额度信息
|
||||
if ($user['role'] === 'agent') {
|
||||
$db = Database::getInstance();
|
||||
$agent = $db->fetch(
|
||||
"SELECT total_quota, used_quota, frozen_quota FROM {$db->table('agents')} WHERE user_id = ?",
|
||||
[$user['id']]
|
||||
);
|
||||
$user['agent_info'] = $agent ?: ['total_quota' => 0, 'used_quota' => 0, 'frozen_quota' => 0];
|
||||
}
|
||||
|
||||
$this->success($user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改密码
|
||||
*/
|
||||
public function changePassword(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate([
|
||||
'old_password' => 'required|min:6',
|
||||
'new_password' => 'required|min:6|max:50',
|
||||
])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
$user = $this->getCurrentUser();
|
||||
if (!passwordVerify($input['old_password'], $user['password'])) {
|
||||
$this->error('原密码错误');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('users')} SET password = ? WHERE id = ?",
|
||||
[passwordHash($input['new_password']), $user['id']]
|
||||
);
|
||||
|
||||
logger('change_password', 'user', $user['id']);
|
||||
|
||||
$this->success(null, '密码修改成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新当前管理员个人资料
|
||||
* PUT /api/auth/profile
|
||||
* Body: { nickname: string, email: string, phone: string, avatar: string }
|
||||
*/
|
||||
public function updateProfile(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate([
|
||||
'nickname' => 'max:50',
|
||||
'email' => 'email|max:100',
|
||||
'phone' => 'max:20',
|
||||
'avatar' => 'max:500',
|
||||
])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
$userId = $this->getUserId();
|
||||
if (!$userId) {
|
||||
$this->error('用户不存在', 404);
|
||||
}
|
||||
|
||||
$allowed = ['nickname', 'email', 'phone', 'avatar'];
|
||||
$updates = [];
|
||||
$params = [];
|
||||
foreach ($allowed as $field) {
|
||||
if (array_key_exists($field, $input)) {
|
||||
$updates[] = "{$field} = ?";
|
||||
$params[] = $input[$field] ?? '';
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($updates)) {
|
||||
$this->error('没有要更新的字段');
|
||||
}
|
||||
|
||||
$params[] = $userId;
|
||||
$db = Database::getInstance();
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('users')} SET " . implode(', ', $updates) . " WHERE id = ?",
|
||||
$params
|
||||
);
|
||||
|
||||
logger('update_profile', 'user', $userId, ['fields' => array_keys(array_intersect_key($input, array_flip($allowed)))]);
|
||||
|
||||
$this->success(null, '个人资料更新成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传头像
|
||||
* POST /api/auth/avatar
|
||||
* Body: multipart/form-data, field: avatar (image file)
|
||||
*/
|
||||
public function uploadAvatar(): void
|
||||
{
|
||||
$userId = $this->getUserId();
|
||||
if (!$userId) {
|
||||
$this->error('用户不存在', 404);
|
||||
}
|
||||
|
||||
if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
|
||||
$this->error('请选择要上传的头像图片');
|
||||
}
|
||||
|
||||
$file = $_FILES['avatar'];
|
||||
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
|
||||
if (!in_array($file['type'], $allowedTypes)) {
|
||||
$this->error('仅支持 JPG、PNG、GIF、WebP 格式的图片');
|
||||
}
|
||||
|
||||
if ($file['size'] > 2 * 1024 * 1024) {
|
||||
$this->error('图片大小不能超过 2MB');
|
||||
}
|
||||
|
||||
// 确保上传目录存在
|
||||
$uploadDir = BASE_PATH . '/public/uploads/avatars';
|
||||
if (!is_dir($uploadDir)) {
|
||||
mkdir($uploadDir, 0755, true);
|
||||
}
|
||||
|
||||
// 生成唯一文件名
|
||||
$ext = pathinfo($file['name'], PATHINFO_EXTENSION) ?: 'jpg';
|
||||
$filename = 'avatar_' . $userId . '_' . time() . '.' . $ext;
|
||||
$filepath = $uploadDir . '/' . $filename;
|
||||
|
||||
if (!move_uploaded_file($file['tmp_name'], $filepath)) {
|
||||
$this->error('头像上传失败,请重试');
|
||||
}
|
||||
|
||||
// 更新数据库
|
||||
$avatarUrl = '/uploads/avatars/' . $filename;
|
||||
$db = Database::getInstance();
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('users')} SET avatar = ? WHERE id = ?",
|
||||
[$avatarUrl, $userId]
|
||||
);
|
||||
|
||||
// 删除旧头像文件(如果存在)
|
||||
$oldUser = $db->fetch("SELECT avatar FROM {$db->table('users')} WHERE id = ?", [$userId]);
|
||||
// 实际上新头像路径已更新,但旧文件还在,这里简单处理:不删除旧文件,避免并发问题
|
||||
|
||||
logger('upload_avatar', 'user', $userId);
|
||||
|
||||
$this->success(['avatar' => $avatarUrl], '头像上传成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户列表 (Admin专用)
|
||||
* GET /api/users
|
||||
* Query: role, keyword, status, start_date, end_date, sort_by, sort_order, page, page_size
|
||||
*/
|
||||
public function list(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$page = max(1, (int) ($_GET['page'] ?? 1));
|
||||
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
|
||||
$offset = ($page - 1) * $pageSize;
|
||||
$role = $_GET['role'] ?? '';
|
||||
$keyword = trim($_GET['keyword'] ?? '');
|
||||
$status = $_GET['status'] ?? '';
|
||||
$startDate = $_GET['start_date'] ?? '';
|
||||
$endDate = $_GET['end_date'] ?? '';
|
||||
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'username', 'nickname', 'role', 'status', 'last_login_at', 'created_at']) ? $_GET['sort_by'] : 'id';
|
||||
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
|
||||
|
||||
$where = "WHERE deleted_at IS NULL";
|
||||
$params = [];
|
||||
|
||||
if ($role && in_array($role, ['admin', 'project_admin', 'agent'])) {
|
||||
$where .= " AND role = ?";
|
||||
$params[] = $role;
|
||||
}
|
||||
if ($status !== '') {
|
||||
$where .= " AND status = ?";
|
||||
$params[] = (int) $status;
|
||||
}
|
||||
if ($keyword) {
|
||||
$where .= " AND (username LIKE ? OR nickname LIKE ? OR email LIKE ?)";
|
||||
$params[] = "%{$keyword}%";
|
||||
$params[] = "%{$keyword}%";
|
||||
$params[] = "%{$keyword}%";
|
||||
}
|
||||
if ($startDate) {
|
||||
$where .= " AND DATE(created_at) >= ?";
|
||||
$params[] = $startDate;
|
||||
}
|
||||
if ($endDate) {
|
||||
$where .= " AND DATE(created_at) <= ?";
|
||||
$params[] = $endDate;
|
||||
}
|
||||
|
||||
$total = $db->fetchColumn("SELECT COUNT(*) FROM {$db->table('users')} {$where}", $params);
|
||||
$users = $db->fetchAll(
|
||||
"SELECT id, username, nickname, email, phone, avatar, role, project_ids, status, last_login_at, last_login_ip, created_at
|
||||
FROM {$db->table('users')} {$where} ORDER BY {$sortBy} {$sortOrder} LIMIT {$offset}, {$pageSize}",
|
||||
$params
|
||||
);
|
||||
|
||||
$this->success([
|
||||
'list' => $users,
|
||||
'total' => (int) $total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建用户 (Admin)
|
||||
*/
|
||||
public function create(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate([
|
||||
'username' => 'required|min:3|max:50',
|
||||
'password' => 'required|min:6|max:50',
|
||||
'role' => 'required',
|
||||
])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
if (!in_array($input['role'], ['admin', 'project_admin', 'agent'])) {
|
||||
$this->error('无效的角色类型');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// 检查用户名唯一
|
||||
$exist = $db->fetch("SELECT id FROM {$db->table('users')} WHERE username = ? AND deleted_at IS NULL", [$input['username']]);
|
||||
if ($exist) {
|
||||
$this->error('用户名已存在');
|
||||
}
|
||||
|
||||
$userId = $db->insert(
|
||||
"INSERT INTO {$db->table('users')} (username, password, nickname, email, role, project_ids, status) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
[
|
||||
$input['username'],
|
||||
passwordHash($input['password']),
|
||||
$input['nickname'] ?? '',
|
||||
$input['email'] ?? '',
|
||||
$input['role'],
|
||||
isset($input['project_ids']) ? json_encode($input['project_ids']) : null,
|
||||
$input['status'] ?? 1,
|
||||
]
|
||||
);
|
||||
|
||||
// 如果是代理,创建额度记录
|
||||
if ($input['role'] === 'agent') {
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('agents')} (user_id, total_quota, used_quota) VALUES (?, 0, 0)",
|
||||
[$userId]
|
||||
);
|
||||
}
|
||||
|
||||
logger('create_user', 'user', $userId, ['username' => $input['username'], 'role' => $input['role']]);
|
||||
|
||||
$this->success(['id' => $userId], '用户创建成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新用户
|
||||
*/
|
||||
public function update(int $id): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$db = Database::getInstance();
|
||||
|
||||
$user = $db->fetch("SELECT * FROM {$db->table('users')} WHERE id = ? AND deleted_at IS NULL", [$id]);
|
||||
if (!$user) {
|
||||
$this->error('用户不存在');
|
||||
}
|
||||
|
||||
$updates = [];
|
||||
$params = [];
|
||||
|
||||
if (isset($input['nickname'])) {
|
||||
$updates[] = 'nickname = ?';
|
||||
$params[] = $input['nickname'];
|
||||
}
|
||||
if (isset($input['email'])) {
|
||||
$updates[] = 'email = ?';
|
||||
$params[] = $input['email'];
|
||||
}
|
||||
if (isset($input['status'])) {
|
||||
$updates[] = 'status = ?';
|
||||
$params[] = $input['status'];
|
||||
}
|
||||
if (isset($input['password']) && !empty($input['password'])) {
|
||||
$updates[] = 'password = ?';
|
||||
$params[] = passwordHash($input['password']);
|
||||
}
|
||||
if (isset($input['project_ids']) && $user['role'] === 'project_admin') {
|
||||
$updates[] = 'project_ids = ?';
|
||||
$params[] = json_encode($input['project_ids']);
|
||||
}
|
||||
|
||||
if (empty($updates)) {
|
||||
$this->error('没有需要更新的字段');
|
||||
}
|
||||
|
||||
$params[] = $id;
|
||||
$db->execute("UPDATE {$db->table('users')} SET " . implode(', ', $updates) . " WHERE id = ?", $params);
|
||||
|
||||
logger('update_user', 'user', $id);
|
||||
|
||||
$this->success(null, '更新成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除用户
|
||||
*/
|
||||
public function delete(int $id): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$user = $db->fetch("SELECT id, role FROM {$db->table('users')} WHERE id = ? AND deleted_at IS NULL", [$id]);
|
||||
if (!$user) {
|
||||
$this->error('用户不存在');
|
||||
}
|
||||
|
||||
if ($user['role'] === 'admin') {
|
||||
$this->error('不能删除超级管理员');
|
||||
}
|
||||
|
||||
$db->execute("UPDATE {$db->table('users')} SET deleted_at = NOW() WHERE id = ?", [$id]);
|
||||
|
||||
logger('delete_user', 'user', $id);
|
||||
|
||||
$this->success(null, '删除成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除用户
|
||||
* POST /api/users/batch-delete
|
||||
* Body: { ids: [int] }
|
||||
*/
|
||||
public function batchDelete(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$ids = $input['ids'] ?? [];
|
||||
|
||||
if (!is_array($ids) || empty($ids)) {
|
||||
$this->error('请选择要删除的用户');
|
||||
}
|
||||
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (empty($ids)) {
|
||||
$this->error('无效的用户ID');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||||
|
||||
// 不能删除管理员
|
||||
$adminCount = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('users')} WHERE id IN ({$placeholders}) AND role = 'admin' AND deleted_at IS NULL",
|
||||
$ids
|
||||
);
|
||||
if ($adminCount > 0) {
|
||||
$this->error('选中的用户中包含管理员,不能删除');
|
||||
}
|
||||
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('users')} SET deleted_at = NOW() WHERE id IN ({$placeholders})",
|
||||
$ids
|
||||
);
|
||||
|
||||
logger('batch_delete_users', 'user', 0, ['count' => count($ids)]);
|
||||
|
||||
$this->success(['count' => count($ids)], '批量删除成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户统计
|
||||
* GET /api/users/stats
|
||||
*/
|
||||
public function stats(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$table = $db->table('users');
|
||||
|
||||
$total = $db->fetchColumn("SELECT COUNT(*) FROM {$table} WHERE deleted_at IS NULL");
|
||||
$admin = $db->fetchColumn("SELECT COUNT(*) FROM {$table} WHERE role = 'admin' AND deleted_at IS NULL");
|
||||
$projectAdmin = $db->fetchColumn("SELECT COUNT(*) FROM {$table} WHERE role = 'project_admin' AND deleted_at IS NULL");
|
||||
$agent = $db->fetchColumn("SELECT COUNT(*) FROM {$table} WHERE role = 'agent' AND deleted_at IS NULL");
|
||||
|
||||
$this->success([
|
||||
'total' => (int) $total,
|
||||
'admin' => (int) $admin,
|
||||
'projectAdmin' => (int) $projectAdmin,
|
||||
'agent' => (int) $agent,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出用户
|
||||
* GET /api/users/export
|
||||
* Query: ids, format(csv|excel)
|
||||
*/
|
||||
public function export(): void
|
||||
{
|
||||
$ids = $_GET['ids'] ?? [];
|
||||
$format = strtolower($_GET['format'] ?? 'csv');
|
||||
if (!in_array($format, ['csv', 'excel'])) {
|
||||
$format = 'csv';
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$table = $db->table('users');
|
||||
$where = 'WHERE deleted_at IS NULL';
|
||||
$params = [];
|
||||
|
||||
if (!empty($ids)) {
|
||||
$ids = is_array($ids) ? $ids : explode(',', $ids);
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (!empty($ids)) {
|
||||
$where .= ' AND id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
|
||||
$params = $ids;
|
||||
}
|
||||
}
|
||||
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT id, username, nickname, email, role, status, last_login_at, last_login_ip, created_at
|
||||
FROM {$table} {$where}
|
||||
ORDER BY id DESC LIMIT 50000",
|
||||
$params
|
||||
);
|
||||
|
||||
$roleMap = ['admin' => '超级管理员', 'project_admin' => '项目管理员', 'agent' => '代理'];
|
||||
|
||||
if ($format === 'excel') {
|
||||
$filename = 'users_export_' . date('YmdHis') . '.xls';
|
||||
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
$html = '<table border="1"><tr><th>ID</th><th>用户名</th><th>昵称</th><th>邮箱</th><th>角色</th><th>状态</th><th>最后登录</th><th>登录IP</th><th>创建时间</th></tr>';
|
||||
foreach ($rows as $row) {
|
||||
$html .= '<tr>';
|
||||
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['username']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['nickname'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['email'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($roleMap[$row['role']] ?? $row['role']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['status'] == 1 ? '正常' : '禁用') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['last_login_at'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['last_login_ip'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
|
||||
$html .= '</tr>';
|
||||
}
|
||||
$html .= '</table>';
|
||||
echo $html;
|
||||
exit;
|
||||
}
|
||||
|
||||
$filename = 'users_export_' . date('YmdHis') . '.csv';
|
||||
header('Content-Type: text/csv; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
|
||||
$output = fopen('php://output', 'w');
|
||||
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($output, ['ID', '用户名', '昵称', '邮箱', '角色', '状态', '最后登录', '登录IP', '创建时间']);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($output, [
|
||||
$row['id'],
|
||||
$row['username'],
|
||||
$row['nickname'] ?? '',
|
||||
$row['email'] ?? '',
|
||||
$roleMap[$row['role']] ?? $row['role'],
|
||||
$row['status'] == 1 ? '正常' : '禁用',
|
||||
$row['last_login_at'] ?? '',
|
||||
$row['last_login_ip'] ?? '',
|
||||
$row['created_at'],
|
||||
]);
|
||||
}
|
||||
fclose($output);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,932 @@
|
||||
<?php
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Controller;
|
||||
use App\Core\Database;
|
||||
use App\Services\PermissionService;
|
||||
|
||||
/**
|
||||
* 卡密授权控制器
|
||||
* 管理机器人QQ与联系人QQ的授权绑定关系
|
||||
*/
|
||||
class AuthorizationController extends Controller
|
||||
{
|
||||
/**
|
||||
* 授权列表
|
||||
* GET /api/authorizations?bot_qq=&contact_qq=&status=&project_id=&card_key=&page=&page_size=
|
||||
*/
|
||||
public function list(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$page = max(1, (int) ($_GET['page'] ?? 1));
|
||||
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
|
||||
$offset = ($page - 1) * $pageSize;
|
||||
$botQq = trim($_GET['bot_qq'] ?? '');
|
||||
$contactQq = trim($_GET['contact_qq'] ?? '');
|
||||
$status = $_GET['status'] ?? '';
|
||||
$projectId = $_GET['project_id'] ?? '';
|
||||
$cardKey = trim($_GET['card_key'] ?? '');
|
||||
$isExpired = $_GET['is_expired'] ?? '';
|
||||
|
||||
$where = 'WHERE 1=1';
|
||||
$params = [];
|
||||
|
||||
// 数据范围权限过滤(管理员查看全部,代理仅查看自身及下级代理的授权)
|
||||
$scope = PermissionService::authorizationScope($this->getCurrentUser());
|
||||
$where .= $scope['where'];
|
||||
$params = array_merge($params, $scope['params']);
|
||||
|
||||
if ($botQq) {
|
||||
$where .= ' AND a.bot_qq = ?';
|
||||
$params[] = $botQq;
|
||||
}
|
||||
if ($contactQq) {
|
||||
$where .= ' AND a.contact_qq = ?';
|
||||
$params[] = $contactQq;
|
||||
}
|
||||
if ($status) {
|
||||
$where .= ' AND a.status = ?';
|
||||
$params[] = $status;
|
||||
}
|
||||
if ($projectId) {
|
||||
$where .= ' AND a.project_id = ?';
|
||||
$params[] = $projectId;
|
||||
}
|
||||
if ($cardKey) {
|
||||
$where .= ' AND a.card_key LIKE ?';
|
||||
$params[] = "%{$cardKey}%";
|
||||
}
|
||||
if ($isExpired === '1') {
|
||||
$where .= ' AND a.status = \'active\' AND a.expire_time IS NOT NULL AND a.expire_time < NOW()';
|
||||
}
|
||||
if ($isExpired === '0') {
|
||||
$where .= ' AND (a.expire_time IS NULL OR a.expire_time >= NOW() OR a.status != \'active\')';
|
||||
}
|
||||
|
||||
$total = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('authorizations')} a {$where}",
|
||||
$params
|
||||
);
|
||||
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT a.*, p.name AS project_name, ct.name AS card_type_name
|
||||
FROM {$db->table('authorizations')} a
|
||||
LEFT JOIN {$db->table('projects')} p ON a.project_id = p.id
|
||||
LEFT JOIN {$db->table('cards')} c ON a.card_id = c.id
|
||||
LEFT JOIN {$db->table('card_types')} ct ON c.card_type_id = ct.id
|
||||
{$where}
|
||||
ORDER BY a.id DESC
|
||||
LIMIT {$offset}, {$pageSize}",
|
||||
$params
|
||||
);
|
||||
|
||||
// 实时计算过期状态
|
||||
$now = time();
|
||||
foreach ($rows as &$row) {
|
||||
$row['is_expired'] = $row['status'] === 'active'
|
||||
&& $row['expire_time']
|
||||
&& strtotime($row['expire_time']) < $now;
|
||||
}
|
||||
|
||||
$this->success([
|
||||
'list' => $rows,
|
||||
'total' => (int) $total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 授权详情
|
||||
* GET /api/authorizations/{id}
|
||||
*/
|
||||
public function detail(int $id): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$row = $db->fetch(
|
||||
"SELECT a.*, p.name AS project_name, ct.name AS card_type_name
|
||||
FROM {$db->table('authorizations')} a
|
||||
LEFT JOIN {$db->table('projects')} p ON a.project_id = p.id
|
||||
LEFT JOIN {$db->table('cards')} c ON a.card_id = c.id
|
||||
LEFT JOIN {$db->table('card_types')} ct ON c.card_type_id = ct.id
|
||||
WHERE a.id = ?",
|
||||
[$id]
|
||||
);
|
||||
|
||||
if (!$row) {
|
||||
$this->error('授权记录不存在', 404);
|
||||
}
|
||||
|
||||
$row['is_expired'] = $row['status'] === 'active'
|
||||
&& $row['expire_time']
|
||||
&& strtotime($row['expire_time']) < time();
|
||||
|
||||
$this->success($row);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增授权(绑定卡密到机器人QQ/联系人QQ)
|
||||
* POST /api/authorizations
|
||||
* Body: { card_key, bot_qq, contact_qq, contact_name? }
|
||||
*/
|
||||
public function create(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$projectId = (int) ($input['project_id'] ?? 0);
|
||||
$cardTypeId = (int) ($input['card_type_id'] ?? 0);
|
||||
$botQq = trim($input['bot_qq'] ?? '');
|
||||
$contactQq = trim($input['contact_qq'] ?? '');
|
||||
$contactName = trim($input['contact_name'] ?? '');
|
||||
|
||||
// 参数校验
|
||||
if (empty($projectId)) {
|
||||
$this->error('请选择项目');
|
||||
}
|
||||
if (empty($cardTypeId)) {
|
||||
$this->error('请选择套餐');
|
||||
}
|
||||
if (empty($botQq)) {
|
||||
$this->error('机器人QQ不能为空');
|
||||
}
|
||||
if (empty($contactQq)) {
|
||||
$this->error('联系人QQ不能为空');
|
||||
}
|
||||
if (!preg_match('/^\d{5,15}$/', $botQq)) {
|
||||
$this->error('机器人QQ格式不正确');
|
||||
}
|
||||
if (!preg_match('/^\d{5,15}$/', $contactQq)) {
|
||||
$this->error('联系人QQ格式不正确');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$userId = $this->getUserId() ?? 0;
|
||||
$currentRole = $this->getUserRole();
|
||||
|
||||
// 验证项目存在
|
||||
$project = $db->fetch("SELECT * FROM {$db->table('projects')} WHERE id = ? AND deleted_at IS NULL", [$projectId]);
|
||||
if (!$project) {
|
||||
$this->error('项目不存在');
|
||||
}
|
||||
|
||||
// 验证套餐
|
||||
$cardType = $db->fetch(
|
||||
"SELECT * FROM {$db->table('card_types')} WHERE id = ? AND project_id = ?",
|
||||
[$cardTypeId, $projectId]
|
||||
);
|
||||
if (!$cardType) {
|
||||
$this->error('套餐不存在或不属于该项目');
|
||||
}
|
||||
|
||||
// 项目管理员:只能在自己负责的项目中创建授权
|
||||
if ($currentRole === 'project_admin') {
|
||||
$currentUser = $this->getCurrentUser();
|
||||
$projectIds = $currentUser['project_ids'] ?? [];
|
||||
if (!in_array($projectId, $projectIds)) {
|
||||
$this->error('无权在此项目中创建授权', 403);
|
||||
}
|
||||
}
|
||||
|
||||
// 代理扣费
|
||||
$needDeductQuota = false;
|
||||
$deductAmount = 0;
|
||||
$quotaBefore = 0;
|
||||
|
||||
if ($currentRole === 'agent') {
|
||||
if ((float) $cardType['agent_cost'] <= 0) {
|
||||
$this->error('该套餐未配置代理价格,无法创建授权');
|
||||
}
|
||||
|
||||
$agentAccount = $db->fetch("SELECT * FROM {$db->table('agents')} WHERE user_id = ?", [$userId]);
|
||||
if (!$agentAccount) {
|
||||
$this->error('代理额度账户不存在,请联系管理员充值');
|
||||
}
|
||||
|
||||
$remainQuota = (float) ($agentAccount['total_quota'] ?? 0) - (float) ($agentAccount['used_quota'] ?? 0) - (float) ($agentAccount['frozen_quota'] ?? 0);
|
||||
|
||||
if ($remainQuota < (float) $cardType['agent_cost']) {
|
||||
$this->error('可用额度不足,需要 ¥' . $cardType['agent_cost'] . ',当前剩余 ¥' . $remainQuota);
|
||||
}
|
||||
|
||||
$needDeductQuota = true;
|
||||
$deductAmount = (float) $cardType['agent_cost'];
|
||||
$quotaBefore = $remainQuota;
|
||||
}
|
||||
|
||||
// 计算过期时间
|
||||
$expireTime = null;
|
||||
if ($cardType['duration_days'] > 0) {
|
||||
$expireTime = date('Y-m-d H:i:s', strtotime("+{$cardType['duration_days']} days"));
|
||||
}
|
||||
|
||||
// 确定 agent_id
|
||||
$agentId = 0;
|
||||
if ($currentRole === 'agent') {
|
||||
$agentId = $userId;
|
||||
}
|
||||
|
||||
// 写入授权记录
|
||||
$authId = $db->insert(
|
||||
"INSERT INTO {$db->table('authorizations')}
|
||||
(card_id, card_key, project_id, project_name, bot_qq, contact_qq,
|
||||
contact_name, duration_days, status, expire_time, operator_id, agent_id, authorized_at, created_at)
|
||||
VALUES (0, '', ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, NOW(), NOW())",
|
||||
[
|
||||
$projectId,
|
||||
$project['name'] ?? '',
|
||||
$botQq,
|
||||
$contactQq,
|
||||
$contactName,
|
||||
(int) $cardType['duration_days'],
|
||||
$expireTime,
|
||||
$userId,
|
||||
$agentId,
|
||||
]
|
||||
);
|
||||
|
||||
// 如果需要扣减代理额度
|
||||
if ($needDeductQuota) {
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('agents')} SET used_quota = used_quota + ? WHERE user_id = ?",
|
||||
[$deductAmount, $userId]
|
||||
);
|
||||
|
||||
$quotaAfter = $quotaBefore - $deductAmount;
|
||||
|
||||
// 记录额度变动
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, target_type, target_id, remark, operator_id, created_at)
|
||||
VALUES (?, 'consume', ?, ?, ?, 'authorization', ?, '授权扣费', ?, NOW())",
|
||||
[$userId, $deductAmount, $quotaBefore, $quotaAfter, $authId, $this->getUserId()]
|
||||
);
|
||||
}
|
||||
|
||||
// 记录操作日志
|
||||
$this->logAction('authorization_create', 'authorization', $authId, [
|
||||
'project_id' => $projectId,
|
||||
'card_type_id'=> $cardTypeId,
|
||||
'bot_qq' => $botQq,
|
||||
'contact_qq' => $contactQq,
|
||||
]);
|
||||
|
||||
$this->success([
|
||||
'id' => $authId,
|
||||
'bot_qq' => $botQq,
|
||||
'contact_qq' => $contactQq,
|
||||
'expire_time' => $expireTime,
|
||||
], '授权成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 公开在线授权(使用卡密激活机器人授权)
|
||||
* POST /api/public/authorizations/activate
|
||||
* Body: { card_key, bot_qq, contact_qq, contact_name? }
|
||||
*/
|
||||
public function publicActivate(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$cardKey = trim($input['card_key'] ?? '');
|
||||
$botQq = trim($input['bot_qq'] ?? '');
|
||||
$contactQq = trim($input['contact_qq'] ?? '');
|
||||
$contactName = trim($input['contact_name'] ?? '');
|
||||
|
||||
if (empty($cardKey)) {
|
||||
$this->error('卡密不能为空');
|
||||
}
|
||||
if (empty($botQq)) {
|
||||
$this->error('机器人QQ不能为空');
|
||||
}
|
||||
if (empty($contactQq)) {
|
||||
$this->error('联系人QQ不能为空');
|
||||
}
|
||||
if (!preg_match('/^\d{5,15}$/', $botQq)) {
|
||||
$this->error('机器人QQ格式不正确');
|
||||
}
|
||||
if (!preg_match('/^\d{5,15}$/', $contactQq)) {
|
||||
$this->error('联系人QQ格式不正确');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
$card = $db->fetch(
|
||||
"SELECT c.*, p.name AS project_name
|
||||
FROM {$db->table('cards')} c
|
||||
LEFT JOIN {$db->table('projects')} p ON c.project_id = p.id
|
||||
WHERE c.card_key = ?",
|
||||
[$cardKey]
|
||||
);
|
||||
|
||||
if (!$card) {
|
||||
$this->error('卡密不存在');
|
||||
}
|
||||
|
||||
if ($card['status'] === 'disabled') {
|
||||
$this->error('该卡密已被禁用');
|
||||
}
|
||||
|
||||
if ($card['status'] === 'used') {
|
||||
$this->error('该卡密已被使用');
|
||||
}
|
||||
|
||||
// 卡密归属与使用权限验证 + 代理扣费
|
||||
$currentUserId = $this->getUserId() ?? 0;
|
||||
$currentRole = $this->getUserRole();
|
||||
$cardAgentId = (int) ($card['use_user_id'] ?? 0);
|
||||
$needDeductQuota = false;
|
||||
|
||||
if ($cardAgentId > 0) {
|
||||
// 该卡密是某个代理生成的(已扣费)
|
||||
// 公开接口无登录态 → 拒绝使用代理卡密
|
||||
if (empty($currentUserId)) {
|
||||
$this->error('该卡密需要登录后使用,请先登录');
|
||||
}
|
||||
// 非归属代理 → 禁止使用他人卡密
|
||||
if ($cardAgentId !== $currentUserId) {
|
||||
$this->error('此卡密不属于您,无法使用');
|
||||
}
|
||||
// 归属代理本人 → 允许(生成时已扣费)
|
||||
} else {
|
||||
// 该卡密非代理生成(管理员生成或其他渠道)
|
||||
// 如果当前用户是代理,使用此类卡密需按代理价格扣费
|
||||
if ($currentRole === 'agent' && $currentUserId > 0) {
|
||||
$cardTypeForCost = $db->fetch(
|
||||
"SELECT agent_cost FROM {$db->table('card_types')} WHERE id = ? AND project_id = ?",
|
||||
[$card['card_type_id'], $card['project_id']]
|
||||
);
|
||||
|
||||
if (!$cardTypeForCost || (float) $cardTypeForCost['agent_cost'] <= 0) {
|
||||
$this->error('该卡密套餐未配置代理价格,无法使用');
|
||||
}
|
||||
|
||||
$agentAccount = $db->fetch("SELECT * FROM {$db->table('agents')} WHERE user_id = ?", [$currentUserId]);
|
||||
if (!$agentAccount) {
|
||||
$this->error('代理额度账户不存在,请联系管理员充值');
|
||||
}
|
||||
|
||||
$remainQuota = (float) ($agentAccount['total_quota'] ?? 0) - (float) ($agentAccount['used_quota'] ?? 0) - (float) ($agentAccount['frozen_quota'] ?? 0);
|
||||
|
||||
if ($remainQuota < (float) $cardTypeForCost['agent_cost']) {
|
||||
$this->error('可用额度不足,需要 ¥' . $cardTypeForCost['agent_cost'] . ',当前剩余 ¥' . $remainQuota);
|
||||
}
|
||||
|
||||
$needDeductQuota = true;
|
||||
$deductAmount = (float) $cardTypeForCost['agent_cost'];
|
||||
$quotaBefore = $remainQuota;
|
||||
}
|
||||
}
|
||||
|
||||
// 检查当前机器人QQ在同一项目下是否已有授权(未撤销),有则续费
|
||||
$existingAuth = $db->fetch(
|
||||
"SELECT * FROM {$db->table('authorizations')}
|
||||
WHERE project_id = ? AND bot_qq = ? AND status != 'revoked'
|
||||
ORDER BY expire_time IS NULL DESC, expire_time DESC, id DESC
|
||||
LIMIT 1",
|
||||
[$card['project_id'], $botQq]
|
||||
);
|
||||
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('cards')} SET status = 'used', bound_at = NOW() WHERE id = ?",
|
||||
[$card['id']]
|
||||
);
|
||||
|
||||
$agentId = (int) ($card['use_user_id'] ?? 0);
|
||||
|
||||
if ($existingAuth) {
|
||||
// 续费:在原有过期时间基础上累加
|
||||
$baseTime = null;
|
||||
if ($existingAuth['expire_time']) {
|
||||
$baseTime = max(date('Y-m-d H:i:s'), $existingAuth['expire_time']);
|
||||
}
|
||||
|
||||
$newExpireTime = null;
|
||||
if ($card['duration_days'] > 0) {
|
||||
if ($baseTime) {
|
||||
$newExpireTime = date('Y-m-d H:i:s', strtotime("+{$card['duration_days']} days", strtotime($baseTime)));
|
||||
} else {
|
||||
// 原授权为永久,新卡密有时长:从当前时间开始加
|
||||
$newExpireTime = date('Y-m-d H:i:s', strtotime("+{$card['duration_days']} days"));
|
||||
}
|
||||
} else {
|
||||
// 新卡密为永久卡,直接变为永久
|
||||
$newExpireTime = null;
|
||||
}
|
||||
|
||||
$newDuration = (int) $existingAuth['duration_days'] + (int) $card['duration_days'];
|
||||
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('authorizations')}
|
||||
SET expire_time = ?, duration_days = ?, status = 'active', contact_qq = ?, contact_name = ?, updated_at = NOW()
|
||||
WHERE id = ?",
|
||||
[$newExpireTime, $newDuration, $contactQq, $contactName, $existingAuth['id']]
|
||||
);
|
||||
|
||||
// 记录使用记录(便于追踪每次续费卡密)
|
||||
$renewAuthId = $db->insert(
|
||||
"INSERT INTO {$db->table('authorizations')}
|
||||
(card_id, card_key, project_id, project_name, bot_qq, contact_qq,
|
||||
contact_name, duration_days, status, expire_time, operator_id, agent_id, authorized_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, NOW(), NOW())",
|
||||
[
|
||||
$card['id'],
|
||||
$card['card_key'],
|
||||
$card['project_id'],
|
||||
$card['project_name'] ?? '',
|
||||
$botQq,
|
||||
$contactQq,
|
||||
$contactName,
|
||||
(int) $card['duration_days'],
|
||||
$newExpireTime,
|
||||
0,
|
||||
$agentId,
|
||||
]
|
||||
);
|
||||
|
||||
// 如果需要扣减代理额度(续费场景)
|
||||
if ($needDeductQuota) {
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('agents')} SET used_quota = used_quota + ? WHERE user_id = ?",
|
||||
[$deductAmount, $currentUserId]
|
||||
);
|
||||
|
||||
$quotaAfter = $quotaBefore - $deductAmount;
|
||||
|
||||
// 记录额度变动
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, target_type, target_id, remark, operator_id, created_at)
|
||||
VALUES (?, 'consume', ?, ?, ?, 'authorization', ?, '续费扣费', ?, NOW())",
|
||||
[$currentUserId, $deductAmount, $quotaBefore, $quotaAfter, $renewAuthId, $this->getUserId()]
|
||||
);
|
||||
}
|
||||
|
||||
$this->success([
|
||||
'id' => (int) $existingAuth['id'],
|
||||
'card_key' => $cardKey,
|
||||
'bot_qq' => $botQq,
|
||||
'contact_qq' => $contactQq,
|
||||
'contact_name'=> $contactName,
|
||||
'project_id' => (int) $card['project_id'],
|
||||
'project_name'=> $card['project_name'] ?? '',
|
||||
'expire_time' => $newExpireTime,
|
||||
'is_renew' => true,
|
||||
], '续费成功');
|
||||
return;
|
||||
}
|
||||
|
||||
$expireTime = null;
|
||||
if ($card['duration_days'] > 0) {
|
||||
$expireTime = date('Y-m-d H:i:s', strtotime("+{$card['duration_days']} days"));
|
||||
}
|
||||
|
||||
$authId = $db->insert(
|
||||
"INSERT INTO {$db->table('authorizations')}
|
||||
(card_id, card_key, project_id, project_name, bot_qq, contact_qq,
|
||||
contact_name, duration_days, status, expire_time, operator_id, agent_id, authorized_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, NOW(), NOW())",
|
||||
[
|
||||
$card['id'],
|
||||
$card['card_key'],
|
||||
$card['project_id'],
|
||||
$card['project_name'] ?? '',
|
||||
$botQq,
|
||||
$contactQq,
|
||||
$contactName,
|
||||
(int) $card['duration_days'],
|
||||
$expireTime,
|
||||
0,
|
||||
$agentId,
|
||||
]
|
||||
);
|
||||
|
||||
// 如果需要扣减代理额度(新授权场景)
|
||||
if ($needDeductQuota) {
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('agents')} SET used_quota = used_quota + ? WHERE user_id = ?",
|
||||
[$deductAmount, $currentUserId]
|
||||
);
|
||||
|
||||
$quotaAfter = $quotaBefore - $deductAmount;
|
||||
|
||||
// 记录额度变动
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, target_type, target_id, remark, operator_id, created_at)
|
||||
VALUES (?, 'consume', ?, ?, ?, 'authorization', ?, '授权扣费', ?, NOW())",
|
||||
[$currentUserId, $deductAmount, $quotaBefore, $quotaAfter, $authId, $this->getUserId()]
|
||||
);
|
||||
}
|
||||
|
||||
$this->success([
|
||||
'id' => $authId,
|
||||
'card_key' => $cardKey,
|
||||
'bot_qq' => $botQq,
|
||||
'contact_qq' => $contactQq,
|
||||
'contact_name'=> $contactName,
|
||||
'project_id' => (int) $card['project_id'],
|
||||
'project_name'=> $card['project_name'] ?? '',
|
||||
'expire_time' => $expireTime,
|
||||
'is_renew' => false,
|
||||
], '授权成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 撤销授权
|
||||
* PUT /api/authorizations/{id}/revoke
|
||||
* Body: { reason? }
|
||||
*/
|
||||
public function revoke(int $id): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$auth = $db->fetch("SELECT * FROM {$db->table('authorizations')} WHERE id = ?", [$id]);
|
||||
|
||||
if (!$auth) {
|
||||
$this->error('授权记录不存在', 404);
|
||||
}
|
||||
|
||||
if ($auth['status'] === 'revoked') {
|
||||
$this->error('授权已被撤销');
|
||||
}
|
||||
|
||||
$input = $this->getJsonInput();
|
||||
$reason = $input['reason'] ?? '';
|
||||
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('authorizations')}
|
||||
SET status = 'revoked', revoked_at = NOW(), revoke_reason = ?, updated_at = NOW()
|
||||
WHERE id = ?",
|
||||
[$reason, $id]
|
||||
);
|
||||
|
||||
$this->logAction('authorization_revoke', 'authorization', $id, [
|
||||
'card_key' => $auth['card_key'],
|
||||
'bot_qq' => $auth['bot_qq'],
|
||||
'contact_qq' => $auth['contact_qq'],
|
||||
'reason' => $reason,
|
||||
]);
|
||||
|
||||
$this->success(null, '授权已撤销');
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除授权记录
|
||||
* DELETE /api/authorizations/{id}
|
||||
*/
|
||||
public function delete(int $id): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$auth = $db->fetch("SELECT * FROM {$db->table('authorizations')} WHERE id = ?", [$id]);
|
||||
|
||||
if (!$auth) {
|
||||
$this->error('授权记录不存在', 404);
|
||||
}
|
||||
|
||||
$db->execute("DELETE FROM {$db->table('authorizations')} WHERE id = ?", [$id]);
|
||||
|
||||
$this->logAction('authorization_delete', 'authorization', $id, [
|
||||
'card_key' => $auth['card_key'],
|
||||
'bot_qq' => $auth['bot_qq'],
|
||||
'contact_qq' => $auth['contact_qq'],
|
||||
]);
|
||||
|
||||
$this->success(null, '授权记录已删除');
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除授权记录
|
||||
* POST /api/authorizations/batch-delete
|
||||
* Body: { ids: [int] }
|
||||
*/
|
||||
public function batchDelete(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$ids = $input['ids'] ?? [];
|
||||
|
||||
if (!is_array($ids) || empty($ids)) {
|
||||
$this->error('请选择要删除的授权记录');
|
||||
}
|
||||
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (empty($ids)) {
|
||||
$this->error('无效的授权ID');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||||
|
||||
$this->logAction('authorization_batch_delete', 'authorization', 0, ['count' => count($ids)]);
|
||||
|
||||
$db->execute(
|
||||
"DELETE FROM {$db->table('authorizations')} WHERE id IN ({$placeholders})",
|
||||
$ids
|
||||
);
|
||||
|
||||
$this->success(['count' => count($ids)], '批量删除成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出授权记录
|
||||
* GET /api/authorizations/export
|
||||
* Query: ids, format(csv|excel)
|
||||
*/
|
||||
public function export(): void
|
||||
{
|
||||
$ids = $_GET['ids'] ?? [];
|
||||
$format = strtolower($_GET['format'] ?? 'csv');
|
||||
if (!in_array($format, ['csv', 'excel'])) {
|
||||
$format = 'csv';
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$where = 'WHERE 1=1';
|
||||
$params = [];
|
||||
|
||||
if (!empty($ids)) {
|
||||
$ids = is_array($ids) ? $ids : explode(',', $ids);
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (!empty($ids)) {
|
||||
$where .= ' AND a.id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
|
||||
$params = array_merge($params, $ids);
|
||||
}
|
||||
}
|
||||
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT a.*, p.name AS project_name, ct.name AS card_type_name
|
||||
FROM {$db->table('authorizations')} a
|
||||
LEFT JOIN {$db->table('projects')} p ON a.project_id = p.id
|
||||
LEFT JOIN {$db->table('cards')} c ON a.card_id = c.id
|
||||
LEFT JOIN {$db->table('card_types')} ct ON c.card_type_id = ct.id
|
||||
{$where}
|
||||
ORDER BY a.id DESC
|
||||
LIMIT 50000",
|
||||
$params
|
||||
);
|
||||
|
||||
$statusMap = ['active' => '有效', 'revoked' => '已撤销'];
|
||||
|
||||
if ($format === 'excel') {
|
||||
$filename = 'authorizations_export_' . date('YmdHis') . '.xls';
|
||||
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
$html = '<table border="1"><tr><th>ID</th><th>机器人QQ</th><th>联系人QQ</th><th>项目</th><th>卡密</th><th>有效天数</th><th>状态</th><th>过期时间</th><th>授权时间</th></tr>';
|
||||
foreach ($rows as $row) {
|
||||
$html .= '<tr>';
|
||||
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['bot_qq']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['contact_qq']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['project_name'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['card_key']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['duration_days'] == 0 ? '永久' : $row['duration_days'] . '天') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($statusMap[$row['status']] ?? $row['status']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['expire_time'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['authorized_at']) . '</td>';
|
||||
$html .= '</tr>';
|
||||
}
|
||||
$html .= '</table>';
|
||||
echo $html;
|
||||
exit;
|
||||
}
|
||||
|
||||
$filename = 'authorizations_export_' . date('YmdHis') . '.csv';
|
||||
header('Content-Type: text/csv; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
|
||||
$output = fopen('php://output', 'w');
|
||||
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($output, ['ID', '机器人QQ', '联系人QQ', '项目', '卡密', '有效天数', '状态', '过期时间', '授权时间']);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($output, [
|
||||
$row['id'],
|
||||
$row['bot_qq'],
|
||||
$row['contact_qq'],
|
||||
$row['project_name'] ?? '',
|
||||
$row['card_key'],
|
||||
$row['duration_days'] == 0 ? '永久' : $row['duration_days'] . '天',
|
||||
$statusMap[$row['status']] ?? $row['status'],
|
||||
$row['expire_time'] ?? '',
|
||||
$row['authorized_at'],
|
||||
]);
|
||||
}
|
||||
fclose($output);
|
||||
exit;
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// 公开接口(无需认证)
|
||||
// ========================================
|
||||
|
||||
/**
|
||||
* 按机器人QQ查询授权状态(主要查询方式)
|
||||
* GET /api/public/authorizations/query?bot_qq=
|
||||
*/
|
||||
public function queryByBot(): void
|
||||
{
|
||||
$botQq = trim($_GET['bot_qq'] ?? '');
|
||||
|
||||
if (empty($botQq)) {
|
||||
$this->error('请输入机器人QQ号');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT a.id, a.card_key, a.project_name, a.bot_qq, a.contact_qq, a.contact_name,
|
||||
a.duration_days, a.status, a.authorized_at, a.expire_time,
|
||||
p.name AS project_name_full
|
||||
FROM {$db->table('authorizations')} a
|
||||
LEFT JOIN {$db->table('projects')} p ON a.project_id = p.id
|
||||
WHERE a.bot_qq = ?
|
||||
ORDER BY a.id DESC",
|
||||
[$botQq]
|
||||
);
|
||||
|
||||
$activeCount = 0;
|
||||
$expiredCount = 0;
|
||||
$revokedCount = 0;
|
||||
|
||||
foreach ($rows as &$row) {
|
||||
$row['is_expired'] = $row['status'] === 'active'
|
||||
&& $row['expire_time']
|
||||
&& strtotime($row['expire_time']) < time();
|
||||
|
||||
if ($row['is_expired']) {
|
||||
$expiredCount++;
|
||||
} elseif ($row['status'] === 'active') {
|
||||
$activeCount++;
|
||||
} elseif ($row['status'] === 'revoked') {
|
||||
$revokedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$this->success([
|
||||
'bot_qq' => $botQq,
|
||||
'total' => count($rows),
|
||||
'active_count' => $activeCount,
|
||||
'expired_count' => $expiredCount,
|
||||
'revoked_count' => $revokedCount,
|
||||
'has_valid_auth' => $activeCount > 0,
|
||||
'list' => $rows,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按联系人QQ查询授权状态
|
||||
* GET /api/public/authorizations/query-by-contact?contact_qq=
|
||||
*/
|
||||
public function queryByContact(): void
|
||||
{
|
||||
$contactQq = trim($_GET['contact_qq'] ?? '');
|
||||
|
||||
if (empty($contactQq)) {
|
||||
$this->error('请输入联系人QQ号');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT a.id, a.card_key, a.project_name, a.bot_qq, a.contact_qq, a.contact_name,
|
||||
a.duration_days, a.status, a.authorized_at, a.expire_time
|
||||
FROM {$db->table('authorizations')} a
|
||||
WHERE a.contact_qq = ?
|
||||
ORDER BY a.id DESC",
|
||||
[$contactQq]
|
||||
);
|
||||
|
||||
foreach ($rows as &$row) {
|
||||
$row['is_expired'] = $row['status'] === 'active'
|
||||
&& $row['expire_time']
|
||||
&& strtotime($row['expire_time']) < time();
|
||||
}
|
||||
|
||||
$this->success([
|
||||
'contact_qq' => $contactQq,
|
||||
'total' => count($rows),
|
||||
'list' => $rows,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证授权有效性(客户端调用)
|
||||
* POST /api/public/authorizations/verify
|
||||
* Body: { bot_qq, card_key?, contact_qq? }
|
||||
*/
|
||||
public function verify(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$botQq = trim($input['bot_qq'] ?? '');
|
||||
$cardKey = trim($input['card_key'] ?? '');
|
||||
$contactQq = trim($input['contact_qq'] ?? '');
|
||||
|
||||
if (empty($botQq)) {
|
||||
$this->error('机器人QQ不能为空');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
|
||||
$where = 'WHERE a.bot_qq = ?';
|
||||
$params = [$botQq];
|
||||
|
||||
if ($cardKey) {
|
||||
$where .= ' AND a.card_key = ?';
|
||||
$params[] = $cardKey;
|
||||
}
|
||||
if ($contactQq) {
|
||||
$where .= ' AND a.contact_qq = ?';
|
||||
$params[] = $contactQq;
|
||||
}
|
||||
|
||||
$where .= " AND a.status = 'active' AND (a.expire_time IS NULL OR a.expire_time >= ?)";
|
||||
$params[] = $now;
|
||||
|
||||
$auth = $db->fetch(
|
||||
"SELECT a.* FROM {$db->table('authorizations')} a {$where} ORDER BY a.id DESC LIMIT 1",
|
||||
$params
|
||||
);
|
||||
|
||||
if (!$auth) {
|
||||
$this->success([
|
||||
'valid' => false,
|
||||
'bot_qq' => $botQq,
|
||||
'message' => '未找到有效授权',
|
||||
'has_valid_auth' => false,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$this->success([
|
||||
'valid' => true,
|
||||
'bot_qq' => $auth['bot_qq'],
|
||||
'contact_qq' => $auth['contact_qq'],
|
||||
'card_key' => $auth['card_key'],
|
||||
'project_name' => $auth['project_name'],
|
||||
'expire_time' => $auth['expire_time'],
|
||||
'days_left' => $auth['expire_time']
|
||||
? max(0, (int) ceil((strtotime($auth['expire_time']) - time()) / 86400))
|
||||
: -1,
|
||||
'has_valid_auth' => true,
|
||||
'message' => '授权有效',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 授权统计
|
||||
* GET /api/authorizations/stats
|
||||
*/
|
||||
public function stats(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
|
||||
$total = $db->fetchColumn("SELECT COUNT(*) FROM {$db->table('authorizations')}");
|
||||
$active = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('authorizations')}
|
||||
WHERE status = 'active' AND (expire_time IS NULL OR expire_time >= ?)",
|
||||
[$now]
|
||||
);
|
||||
$expired = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('authorizations')}
|
||||
WHERE status = 'active' AND expire_time IS NOT NULL AND expire_time < ?",
|
||||
[$now]
|
||||
);
|
||||
$revoked = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('authorizations')} WHERE status = 'revoked'"
|
||||
);
|
||||
$todayNew = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('authorizations')} WHERE DATE(authorized_at) = CURDATE()"
|
||||
);
|
||||
|
||||
$this->success([
|
||||
'total' => (int) $total,
|
||||
'active' => (int) $active,
|
||||
'expired' => (int) $expired,
|
||||
'revoked' => (int) $revoked,
|
||||
'today_new' => (int) $todayNew,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录操作日志
|
||||
*/
|
||||
private function logAction(string $action, string $targetType, int $targetId, array $detail = []): void
|
||||
{
|
||||
try {
|
||||
$db = Database::getInstance();
|
||||
$userId = (int) ($_SERVER['HTTP_X_USER_ID'] ?? 0);
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('logs')} (user_id, action, target_type, target_id, detail, ip, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, NOW())",
|
||||
[
|
||||
$userId,
|
||||
$action,
|
||||
$targetType,
|
||||
$targetId,
|
||||
json_encode($detail, JSON_UNESCAPED_UNICODE),
|
||||
$_SERVER['REMOTE_ADDR'] ?? '',
|
||||
]
|
||||
);
|
||||
} catch (\Throwable $e) {
|
||||
// 日志写入失败不影响主流程
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
<?php
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Controller;
|
||||
use App\Core\Database;
|
||||
use App\Core\Validator;
|
||||
use App\Services\BlacklistService;
|
||||
|
||||
/**
|
||||
* 黑名单管理控制器
|
||||
*/
|
||||
class BlacklistController extends Controller
|
||||
{
|
||||
/**
|
||||
* 黑名单列表
|
||||
* GET /api/blacklists
|
||||
*/
|
||||
public function list(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$page = max(1, (int) ($_GET['page'] ?? 1));
|
||||
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
|
||||
$offset = ($page - 1) * $pageSize;
|
||||
$targetType = $_GET['target_type'] ?? '';
|
||||
$keyword = trim($_GET['keyword'] ?? '');
|
||||
$status = $_GET['status'] ?? '';
|
||||
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'created_at', 'updated_at']) ? $_GET['sort_by'] : 'id';
|
||||
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
|
||||
|
||||
$where = "WHERE 1=1";
|
||||
$params = [];
|
||||
|
||||
if ($targetType && in_array($targetType, ['user', 'ip'])) {
|
||||
$where .= " AND target_type = ?";
|
||||
$params[] = $targetType;
|
||||
}
|
||||
if ($status !== '') {
|
||||
$where .= " AND status = ?";
|
||||
$params[] = (int)$status;
|
||||
}
|
||||
if ($keyword) {
|
||||
$where .= " AND (target_value LIKE ? OR remark LIKE ?)";
|
||||
$params[] = "%{$keyword}%";
|
||||
$params[] = "%{$keyword}%";
|
||||
}
|
||||
|
||||
$total = $db->fetchColumn("SELECT COUNT(*) FROM {$db->table('blacklists')} {$where}", $params);
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT id, target_type, target_value, status, expire_time, operator_id, operator_name, remark, created_at, updated_at
|
||||
FROM {$db->table('blacklists')} {$where}
|
||||
ORDER BY {$sortBy} {$sortOrder}
|
||||
LIMIT {$offset}, {$pageSize}",
|
||||
$params
|
||||
);
|
||||
|
||||
$this->success([
|
||||
'list' => $rows,
|
||||
'total' => (int)$total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加黑名单
|
||||
* POST /api/blacklists
|
||||
*/
|
||||
public function create(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate([
|
||||
'target_type' => 'required|in:user,ip',
|
||||
'target_value' => 'required|max:255',
|
||||
])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
$this->insertItem($input['target_type'], $input['target_value'], $input['expire_time'] ?? null, $input['remark'] ?? '');
|
||||
|
||||
(new BlacklistService())->clearCache();
|
||||
logger('blacklist_create', 'blacklist', 0, [
|
||||
'target_type' => $input['target_type'],
|
||||
'target_value' => $input['target_value'],
|
||||
'role' => ($this->getCurrentUser()['role'] ?? ''),
|
||||
]);
|
||||
|
||||
$this->success(null, '黑名单添加成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量添加黑名单
|
||||
* POST /api/blacklists/batch
|
||||
*/
|
||||
public function batchCreate(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$items = $input['items'] ?? [];
|
||||
|
||||
if (!is_array($items) || empty($items)) {
|
||||
$this->error('请选择要添加的黑名单对象');
|
||||
}
|
||||
|
||||
if (count($items) > 500) {
|
||||
$this->error('单次批量添加不能超过500条');
|
||||
}
|
||||
|
||||
$success = 0;
|
||||
$failed = 0;
|
||||
foreach ($items as $item) {
|
||||
$type = $item['target_type'] ?? '';
|
||||
$value = $item['target_value'] ?? '';
|
||||
if (!in_array($type, ['user', 'ip']) || empty($value)) {
|
||||
$failed++;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$this->insertItem($type, $value, $item['expire_time'] ?? null, $item['remark'] ?? '');
|
||||
$success++;
|
||||
} catch (\Throwable $e) {
|
||||
$failed++;
|
||||
}
|
||||
}
|
||||
|
||||
(new BlacklistService())->clearCache();
|
||||
logger('blacklist_batch_create', 'blacklist', 0, ['success' => $success, 'failed' => $failed, 'role' => ($this->getCurrentUser()['role'] ?? '')]);
|
||||
|
||||
$this->success(['success' => $success, 'failed' => $failed], "批量添加完成,成功 {$success} 条,失败 {$failed} 条");
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新黑名单状态/备注/过期时间
|
||||
* PUT /api/blacklists/{id}
|
||||
*/
|
||||
public function update(int $id): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$db = Database::getInstance();
|
||||
|
||||
$updates = [];
|
||||
$params = [];
|
||||
|
||||
if (isset($input['status']) && in_array((int)$input['status'], [0, 1], true)) {
|
||||
$updates[] = 'status = ?';
|
||||
$params[] = (int)$input['status'];
|
||||
}
|
||||
if (array_key_exists('remark', $input)) {
|
||||
$updates[] = 'remark = ?';
|
||||
$params[] = $input['remark'];
|
||||
}
|
||||
if (array_key_exists('expire_time', $input)) {
|
||||
$updates[] = 'expire_time = ?';
|
||||
$params[] = empty($input['expire_time']) ? null : $input['expire_time'];
|
||||
}
|
||||
|
||||
if (empty($updates)) {
|
||||
$this->error('没有要更新的字段');
|
||||
}
|
||||
|
||||
$params[] = $id;
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('blacklists')} SET " . implode(', ', $updates) . " WHERE id = ?",
|
||||
$params
|
||||
);
|
||||
|
||||
(new BlacklistService())->clearCache();
|
||||
logger('blacklist_update', 'blacklist', $id, array_merge($input, ['role' => ($this->getCurrentUser()['role'] ?? '')]));
|
||||
|
||||
$this->success(null, '黑名单更新成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除黑名单
|
||||
* DELETE /api/blacklists/{id}
|
||||
*/
|
||||
public function delete(int $id): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$db->execute("DELETE FROM {$db->table('blacklists')} WHERE id = ?", [$id]);
|
||||
|
||||
(new BlacklistService())->clearCache();
|
||||
logger('blacklist_delete', 'blacklist', $id, ['role' => ($this->getCurrentUser()['role'] ?? '')]);
|
||||
|
||||
$this->success(null, '黑名单删除成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除黑名单
|
||||
* POST /api/blacklists/batch-delete
|
||||
*/
|
||||
public function batchDelete(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$ids = $input['ids'] ?? [];
|
||||
|
||||
if (!is_array($ids) || empty($ids)) {
|
||||
$this->error('请选择要删除的黑名单');
|
||||
}
|
||||
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (empty($ids)) {
|
||||
$this->error('无效的黑名单ID');
|
||||
}
|
||||
|
||||
if (count($ids) > 500) {
|
||||
$this->error('单次批量删除不能超过500条');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||||
$db->execute("DELETE FROM {$db->table('blacklists')} WHERE id IN ({$placeholders})", $ids);
|
||||
|
||||
(new BlacklistService())->clearCache();
|
||||
logger('blacklist_batch_delete', 'blacklist', 0, ['count' => count($ids), 'role' => ($this->getCurrentUser()['role'] ?? '')]);
|
||||
|
||||
$this->success(['count' => count($ids)], '批量删除成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入黑名单(CSV)
|
||||
* POST /api/blacklists/import
|
||||
*/
|
||||
public function import(): void
|
||||
{
|
||||
$file = $_FILES['file'] ?? null;
|
||||
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
|
||||
$this->error('请上传CSV文件');
|
||||
}
|
||||
|
||||
$handle = fopen($file['tmp_name'], 'r');
|
||||
if (!$handle) {
|
||||
$this->error('无法读取文件');
|
||||
}
|
||||
|
||||
// 跳过 BOM
|
||||
$bom = fread($handle, 3);
|
||||
if ($bom !== "\xEF\xBB\xBF") {
|
||||
rewind($handle);
|
||||
}
|
||||
|
||||
$header = fgetcsv($handle);
|
||||
if (!$header || !in_array('target_type', $header) || !in_array('target_value', $header)) {
|
||||
fclose($handle);
|
||||
$this->error('CSV格式错误,必须包含 target_type 和 target_value 列');
|
||||
}
|
||||
|
||||
$success = 0;
|
||||
$failed = 0;
|
||||
$rowCount = 0;
|
||||
while (($row = fgetcsv($handle)) !== false) {
|
||||
$rowCount++;
|
||||
if ($rowCount > 1000) break;
|
||||
|
||||
$data = array_combine($header, $row);
|
||||
$type = $data['target_type'] ?? '';
|
||||
$value = $data['target_value'] ?? '';
|
||||
if (!in_array($type, ['user', 'ip']) || empty($value)) {
|
||||
$failed++;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$this->insertItem($type, $value, $data['expire_time'] ?? null, $data['remark'] ?? '');
|
||||
$success++;
|
||||
} catch (\Throwable $e) {
|
||||
$failed++;
|
||||
}
|
||||
}
|
||||
fclose($handle);
|
||||
|
||||
(new BlacklistService())->clearCache();
|
||||
logger('blacklist_import', 'blacklist', 0, ['success' => $success, 'failed' => $failed, 'role' => ($this->getCurrentUser()['role'] ?? '')]);
|
||||
|
||||
$this->success(['success' => $success, 'failed' => $failed], "导入完成,成功 {$success} 条,失败 {$failed} 条");
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出黑名单
|
||||
* GET /api/blacklists/export
|
||||
*/
|
||||
public function export(): void
|
||||
{
|
||||
$ids = $_GET['ids'] ?? [];
|
||||
if (!empty($ids) && !is_array($ids)) {
|
||||
$ids = explode(',', $ids);
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$params = [];
|
||||
$where = "WHERE 1=1";
|
||||
|
||||
if (!empty($ids)) {
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
$where .= " AND id IN (" . implode(',', array_fill(0, count($ids), '?')) . ")";
|
||||
$params = $ids;
|
||||
}
|
||||
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT target_type, target_value, status, expire_time, operator_name, remark, created_at
|
||||
FROM {$db->table('blacklists')} {$where} ORDER BY id DESC LIMIT 50000",
|
||||
$params
|
||||
);
|
||||
|
||||
$filename = 'blacklist_export_' . date('YmdHis') . '.csv';
|
||||
header('Content-Type: text/csv; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
|
||||
$output = fopen('php://output', 'w');
|
||||
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($output, ['target_type', 'target_value', 'status', 'expire_time', 'operator_name', 'remark', 'created_at']);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($output, [
|
||||
$row['target_type'],
|
||||
$row['target_value'],
|
||||
$row['status'],
|
||||
$row['expire_time'] ?? '',
|
||||
$row['operator_name'],
|
||||
$row['remark'],
|
||||
$row['created_at'],
|
||||
]);
|
||||
}
|
||||
fclose($output);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入单条黑名单记录
|
||||
*/
|
||||
private function insertItem(string $type, string $value, ?string $expireTime, string $remark): void
|
||||
{
|
||||
$user = $this->getCurrentUser();
|
||||
$db = Database::getInstance();
|
||||
|
||||
$expire = empty($expireTime) ? null : $expireTime;
|
||||
|
||||
$db->execute(
|
||||
"INSERT INTO {$db->table('blacklists')} (target_type, target_value, status, expire_time, operator_id, operator_name, remark)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE status = VALUES(status), expire_time = VALUES(expire_time), remark = VALUES(remark), updated_at = NOW()",
|
||||
[
|
||||
$type,
|
||||
$value,
|
||||
1,
|
||||
$expire,
|
||||
$user['id'] ?? 0,
|
||||
$user['username'] ?? 'system',
|
||||
$remark,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,663 @@
|
||||
<?php
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Controller;
|
||||
use App\Core\Database;
|
||||
use App\Core\Validator;
|
||||
use App\Services\PermissionService;
|
||||
use App\Services\SnowflakeService;
|
||||
|
||||
/**
|
||||
* 卡密管理控制器
|
||||
*/
|
||||
class CardController extends Controller
|
||||
{
|
||||
/**
|
||||
* 卡密列表
|
||||
*/
|
||||
/**
|
||||
* 卡密列表
|
||||
* GET /api/cards
|
||||
* Query: project_id, card_type_id, status, keyword, start_date, end_date, sort_by, sort_order, page, page_size
|
||||
*/
|
||||
public function list(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$page = max(1, (int) ($_GET['page'] ?? 1));
|
||||
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
|
||||
$offset = ($page - 1) * $pageSize;
|
||||
$projectId = $_GET['project_id'] ?? '';
|
||||
$status = $_GET['status'] ?? '';
|
||||
$cardTypeId = $_GET['card_type_id'] ?? '';
|
||||
$keyword = trim($_GET['keyword'] ?? '');
|
||||
$startDate = $_GET['start_date'] ?? '';
|
||||
$endDate = $_GET['end_date'] ?? '';
|
||||
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'card_key', 'project_id', 'card_type_id', 'status', 'duration_days', 'expire_time', 'bound_at', 'created_at']) ? $_GET['sort_by'] : 'id';
|
||||
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
|
||||
|
||||
$where = "WHERE 1=1";
|
||||
$params = [];
|
||||
|
||||
// 数据范围权限过滤(管理员查看全部,代理仅查看自身及下级代理生成的卡密)
|
||||
$scope = PermissionService::cardScope($this->getCurrentUser());
|
||||
$where .= $scope['where'];
|
||||
$params = array_merge($params, $scope['params']);
|
||||
|
||||
if ($projectId) {
|
||||
$where .= " AND c.project_id = ?";
|
||||
$params[] = $projectId;
|
||||
}
|
||||
if ($status) {
|
||||
$where .= " AND c.status = ?";
|
||||
$params[] = $status;
|
||||
}
|
||||
if ($cardTypeId) {
|
||||
$where .= " AND c.card_type_id = ?";
|
||||
$params[] = $cardTypeId;
|
||||
}
|
||||
if ($keyword) {
|
||||
$where .= " AND c.card_key LIKE ?";
|
||||
$params[] = "%{$keyword}%";
|
||||
}
|
||||
if ($startDate) {
|
||||
$where .= " AND DATE(c.created_at) >= ?";
|
||||
$params[] = $startDate;
|
||||
}
|
||||
if ($endDate) {
|
||||
$where .= " AND DATE(c.created_at) <= ?";
|
||||
$params[] = $endDate;
|
||||
}
|
||||
|
||||
$total = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('cards')} c {$where}",
|
||||
$params
|
||||
);
|
||||
|
||||
$cards = $db->fetchAll(
|
||||
"SELECT c.*, p.name AS project_name, ct.name AS card_type_name,
|
||||
a.bot_qq, a.contact_qq, a.contact_name
|
||||
FROM {$db->table('cards')} c
|
||||
LEFT JOIN {$db->table('projects')} p ON c.project_id = p.id
|
||||
LEFT JOIN {$db->table('card_types')} ct ON c.card_type_id = ct.id
|
||||
LEFT JOIN {$db->table('authorizations')} a ON c.id = a.card_id
|
||||
{$where}
|
||||
ORDER BY c.{$sortBy} {$sortOrder}
|
||||
LIMIT {$offset}, {$pageSize}",
|
||||
$params
|
||||
);
|
||||
|
||||
$this->success([
|
||||
'list' => $cards,
|
||||
'total' => (int) $total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量生成卡密
|
||||
*/
|
||||
public function generate(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate([
|
||||
'project_id' => 'required|integer',
|
||||
'card_type_id' => 'required|integer',
|
||||
'count' => 'required|integer',
|
||||
])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
$projectId = (int) $input['project_id'];
|
||||
$cardTypeId = (int) $input['card_type_id'];
|
||||
$count = min((int) $input['count'], 10000); // 单次最多10000张
|
||||
$remark = $input['remark'] ?? '';
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// 验证项目存在
|
||||
$project = $db->fetch("SELECT id FROM {$db->table('projects')} WHERE id = ? AND deleted_at IS NULL", [$projectId]);
|
||||
if (!$project) {
|
||||
$this->error('项目不存在');
|
||||
}
|
||||
|
||||
// 验证卡密类型
|
||||
$cardType = $db->fetch(
|
||||
"SELECT * FROM {$db->table('card_types')} WHERE id = ? AND project_id = ?",
|
||||
[$cardTypeId, $projectId]
|
||||
);
|
||||
if (!$cardType) {
|
||||
$this->error('卡密类型不存在');
|
||||
}
|
||||
|
||||
$userId = $this->getUserId();
|
||||
$userRole = $this->getUserRole();
|
||||
|
||||
// 项目管理员:只能在自己负责的项目中生成卡密
|
||||
if ($userRole === 'project_admin') {
|
||||
$currentUser = $this->getCurrentUser();
|
||||
$projectIds = $currentUser['project_ids'] ?? [];
|
||||
if (!in_array($projectId, $projectIds)) {
|
||||
$this->error('无权在此项目中生成卡密', 403);
|
||||
}
|
||||
}
|
||||
|
||||
// 代理身份:验证余额并扣费
|
||||
$needDeduct = false;
|
||||
$deductAmount = 0;
|
||||
$quotaBefore = 0;
|
||||
|
||||
if ($userRole === 'agent') {
|
||||
if ((float) $cardType['agent_cost'] <= 0) {
|
||||
$this->error('该套餐未配置代理价格,无法生成');
|
||||
}
|
||||
|
||||
$agent = $db->fetch("SELECT * FROM {$db->table('agents')} WHERE user_id = ?", [$userId]);
|
||||
if (!$agent) {
|
||||
$this->error('代理额度账户不存在,请联系管理员充值');
|
||||
}
|
||||
|
||||
$remainQuota = (float) ($agent['total_quota'] ?? 0) - (float) ($agent['used_quota'] ?? 0) - (float) ($agent['frozen_quota'] ?? 0);
|
||||
$totalCost = (float) $cardType['agent_cost'] * $count;
|
||||
|
||||
if ($remainQuota < $totalCost) {
|
||||
$this->error("可用额度不足,需要 ¥{$totalCost},当前剩余 ¥{$remainQuota}");
|
||||
}
|
||||
|
||||
$needDeduct = true;
|
||||
$deductAmount = $totalCost;
|
||||
$quotaBefore = $remainQuota;
|
||||
}
|
||||
|
||||
$snowflake = new SnowflakeService();
|
||||
$cards = [];
|
||||
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
$cardKey = $snowflake->generateCardKey();
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('cards')} (card_key, project_id, card_type_id, type, duration_days, status, use_user_id, remark) VALUES (?, ?, ?, ?, ?, 'unused', ?, ?)",
|
||||
[$cardKey, $projectId, $cardTypeId, $cardType['name'], $cardType['duration_days'], $userId, $remark]
|
||||
);
|
||||
$cards[] = $cardKey;
|
||||
}
|
||||
|
||||
// 代理扣费
|
||||
if ($needDeduct) {
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('agents')} SET used_quota = used_quota + ? WHERE user_id = ?",
|
||||
[$deductAmount, $userId]
|
||||
);
|
||||
|
||||
$quotaAfter = $quotaBefore - $deductAmount;
|
||||
|
||||
// 记录额度变动
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, target_type, target_id, remark, operator_id, created_at)
|
||||
VALUES (?, 'consume', ?, ?, ?, 'card_generate', ?, ?, ?, NOW())",
|
||||
[$userId, $deductAmount, $quotaBefore, $quotaAfter, $count, "生成{$count}张卡密", $this->getUserId()]
|
||||
);
|
||||
}
|
||||
|
||||
$db->commit();
|
||||
} catch (\Throwable $e) {
|
||||
$db->rollback();
|
||||
$this->error('生成卡密失败: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
logger('generate_cards', 'card', 0, [
|
||||
'count' => $count,
|
||||
'project_id' => $projectId,
|
||||
'card_type_id' => $cardTypeId,
|
||||
'role' => $this->getUserRole(),
|
||||
]);
|
||||
|
||||
$this->success([
|
||||
'count' => $count,
|
||||
'cards' => $cards,
|
||||
], "成功生成{$count}张卡密");
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出卡密
|
||||
* GET /api/cards/export
|
||||
* Query: ids, format(csv|excel), project_id, status, card_type_id
|
||||
*/
|
||||
public function export(): void
|
||||
{
|
||||
$projectId = $_GET['project_id'] ?? '';
|
||||
$status = $_GET['status'] ?? '';
|
||||
$cardTypeId = $_GET['card_type_id'] ?? '';
|
||||
$ids = $_GET['ids'] ?? [];
|
||||
$format = strtolower($_GET['format'] ?? 'csv');
|
||||
if (!in_array($format, ['csv', 'excel'])) {
|
||||
$format = 'csv';
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$where = "WHERE 1=1";
|
||||
$params = [];
|
||||
|
||||
if (!empty($ids)) {
|
||||
$ids = is_array($ids) ? $ids : explode(',', $ids);
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (!empty($ids)) {
|
||||
$where .= " AND c.id IN (" . implode(',', array_fill(0, count($ids), '?')) . ")";
|
||||
$params = array_merge($params, $ids);
|
||||
}
|
||||
}
|
||||
if ($projectId) {
|
||||
$where .= " AND c.project_id = ?";
|
||||
$params[] = $projectId;
|
||||
}
|
||||
if ($status) {
|
||||
$where .= " AND c.status = ?";
|
||||
$params[] = $status;
|
||||
}
|
||||
if ($cardTypeId) {
|
||||
$where .= " AND c.card_type_id = ?";
|
||||
$params[] = $cardTypeId;
|
||||
}
|
||||
|
||||
$cards = $db->fetchAll(
|
||||
"SELECT c.card_key, c.type, c.status, c.duration_days, c.expire_time, c.bound_at, c.created_at,
|
||||
p.name AS project_name
|
||||
FROM {$db->table('cards')} c
|
||||
LEFT JOIN {$db->table('projects')} p ON c.project_id = p.id
|
||||
{$where}
|
||||
ORDER BY c.id DESC
|
||||
LIMIT 50000",
|
||||
$params
|
||||
);
|
||||
|
||||
if ($format === 'excel') {
|
||||
$this->exportExcel($cards);
|
||||
} else {
|
||||
$this->exportCsv($cards);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出CSV
|
||||
*/
|
||||
private function exportCsv(array $cards): never
|
||||
{
|
||||
$filename = 'cards_export_' . date('YmdHis') . '.csv';
|
||||
header('Content-Type: text/csv; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
|
||||
$output = fopen('php://output', 'w');
|
||||
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($output, ['卡密', '项目', '类型', '有效天数', '状态', '绑定时间', '过期时间', '生成时间']);
|
||||
|
||||
$statusMap = ['unused' => '未使用', 'used' => '已使用', 'disabled' => '已禁用'];
|
||||
foreach ($cards as $card) {
|
||||
fputcsv($output, [
|
||||
$card['card_key'],
|
||||
$card['project_name'] ?? '',
|
||||
$card['type'],
|
||||
$card['duration_days'] == 0 ? '永久' : $card['duration_days'] . '天',
|
||||
$statusMap[$card['status']] ?? $card['status'],
|
||||
$card['bound_at'] ?? '',
|
||||
$card['expire_time'] ?? '',
|
||||
$card['created_at'],
|
||||
]);
|
||||
}
|
||||
fclose($output);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出Excel (HTML表格伪Excel)
|
||||
*/
|
||||
private function exportExcel(array $cards): never
|
||||
{
|
||||
$filename = 'cards_export_' . date('YmdHis') . '.xls';
|
||||
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
|
||||
$statusMap = ['unused' => '未使用', 'used' => '已使用', 'disabled' => '已禁用'];
|
||||
$html = '<table border="1"><tr><th>卡密</th><th>项目</th><th>类型</th><th>有效天数</th><th>状态</th><th>绑定时间</th><th>过期时间</th><th>生成时间</th></tr>';
|
||||
foreach ($cards as $card) {
|
||||
$html .= '<tr>';
|
||||
$html .= '<td>' . htmlspecialchars($card['card_key']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($card['project_name'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($card['type']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($card['duration_days'] == 0 ? '永久' : $card['duration_days'] . '天') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($statusMap[$card['status']] ?? $card['status']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($card['bound_at'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($card['expire_time'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($card['created_at']) . '</td>';
|
||||
$html .= '</tr>';
|
||||
}
|
||||
$html .= '</table>';
|
||||
echo $html;
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入卡密
|
||||
* POST /api/cards/import
|
||||
* Body: multipart/form-data { file, project_id }
|
||||
*/
|
||||
public function import(): void
|
||||
{
|
||||
if (!isset($_FILES['file'])) {
|
||||
$this->error('请上传文件');
|
||||
}
|
||||
|
||||
$projectId = (int) ($_POST['project_id'] ?? 0);
|
||||
$cardTypeId = (int) ($_POST['card_type_id'] ?? 0);
|
||||
if (!$projectId) {
|
||||
$this->error('请选择项目');
|
||||
}
|
||||
if (!$cardTypeId) {
|
||||
$this->error('请选择套餐');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$userId = $this->getUserId();
|
||||
$userRole = $this->getUserRole();
|
||||
|
||||
// 项目管理员:只能在自己负责的项目中导入卡密
|
||||
if ($userRole === 'project_admin') {
|
||||
$currentUser = $this->getCurrentUser();
|
||||
$projectIds = $currentUser['project_ids'] ?? [];
|
||||
if (!in_array($projectId, $projectIds)) {
|
||||
$this->error('无权在此项目中导入卡密', 403);
|
||||
}
|
||||
}
|
||||
|
||||
$project = $db->fetch("SELECT id FROM {$db->table('projects')} WHERE id = ? AND deleted_at IS NULL", [$projectId]);
|
||||
if (!$project) {
|
||||
$this->error('项目不存在');
|
||||
}
|
||||
|
||||
$cardType = $db->fetch(
|
||||
"SELECT * FROM {$db->table('card_types')} WHERE id = ? AND project_id = ?",
|
||||
[$cardTypeId, $projectId]
|
||||
);
|
||||
if (!$cardType) {
|
||||
$this->error('套餐不存在或不属于该项目');
|
||||
}
|
||||
|
||||
$file = $_FILES['file'];
|
||||
if ($file['error'] !== UPLOAD_ERR_OK) {
|
||||
$this->error('文件上传失败');
|
||||
}
|
||||
if ($file['size'] > 10 * 1024 * 1024) {
|
||||
$this->error('文件大小不能超过10MB');
|
||||
}
|
||||
|
||||
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
|
||||
if (!in_array($ext, ['csv', 'xlsx', 'xls'])) {
|
||||
$this->error('仅支持 CSV、Excel 格式');
|
||||
}
|
||||
|
||||
// 先读取所有行,统计数量
|
||||
$rows = [];
|
||||
if ($ext === 'csv') {
|
||||
$handle = fopen($file['tmp_name'], 'r');
|
||||
if (!$handle) {
|
||||
$this->error('无法读取文件');
|
||||
}
|
||||
$bom = fread($handle, 3);
|
||||
if ($bom !== "\xEF\xBB\xBF") {
|
||||
rewind($handle);
|
||||
}
|
||||
$header = fgetcsv($handle);
|
||||
while (($row = fgetcsv($handle)) !== false) {
|
||||
$cardKey = trim($row[0] ?? '');
|
||||
if ($cardKey) {
|
||||
$rows[] = $cardKey;
|
||||
}
|
||||
}
|
||||
fclose($handle);
|
||||
} else {
|
||||
$this->error('Excel 解析暂不支持,请上传 CSV 文件');
|
||||
}
|
||||
|
||||
$count = count($rows);
|
||||
if ($count === 0) {
|
||||
$this->error('文件中没有有效的卡密数据');
|
||||
}
|
||||
|
||||
// 代理身份:验证余额并扣费
|
||||
$needDeduct = false;
|
||||
$deductAmount = 0;
|
||||
$quotaBefore = 0;
|
||||
|
||||
if ($userRole === 'agent') {
|
||||
if ((float) $cardType['agent_cost'] <= 0) {
|
||||
$this->error('该套餐未配置代理价格,无法导入');
|
||||
}
|
||||
|
||||
$agent = $db->fetch("SELECT * FROM {$db->table('agents')} WHERE user_id = ?", [$userId]);
|
||||
if (!$agent) {
|
||||
$this->error('代理额度账户不存在,请联系管理员充值');
|
||||
}
|
||||
|
||||
$remainQuota = (float) ($agent['total_quota'] ?? 0) - (float) ($agent['used_quota'] ?? 0) - (float) ($agent['frozen_quota'] ?? 0);
|
||||
$totalCost = (float) $cardType['agent_cost'] * $count;
|
||||
|
||||
if ($remainQuota < $totalCost) {
|
||||
$this->error("可用额度不足,需要 ¥{$totalCost},当前剩余 ¥{$remainQuota}");
|
||||
}
|
||||
|
||||
$needDeduct = true;
|
||||
$deductAmount = $totalCost;
|
||||
$quotaBefore = $remainQuota;
|
||||
}
|
||||
|
||||
$snowflake = new SnowflakeService();
|
||||
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
foreach ($rows as $cardKey) {
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('cards')} (card_key, project_id, card_type_id, type, duration_days, status, use_user_id, created_at) VALUES (?, ?, ?, ?, ?, 'unused', ?, NOW())",
|
||||
[$cardKey, $projectId, $cardTypeId, $cardType['name'], $cardType['duration_days'], $userId]
|
||||
);
|
||||
}
|
||||
|
||||
// 代理扣费
|
||||
if ($needDeduct) {
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('agents')} SET used_quota = used_quota + ? WHERE user_id = ?",
|
||||
[$deductAmount, $userId]
|
||||
);
|
||||
|
||||
$quotaAfter = $quotaBefore - $deductAmount;
|
||||
$db->insert(
|
||||
"INSERT INTO {$db->table('agent_quota_logs')} (agent_id, change_type, amount, balance_before, balance_after, target_type, target_id, remark, operator_id, created_at)
|
||||
VALUES (?, 'deduct', ?, ?, ?, 'card_import', 0, ?, ?, NOW())",
|
||||
[$agent['id'], $deductAmount, $quotaBefore, $quotaAfter, "导入{$count}张卡密", $userId]
|
||||
);
|
||||
}
|
||||
|
||||
$db->commit();
|
||||
} catch (\Throwable $e) {
|
||||
$db->rollback();
|
||||
$this->error('导入失败: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
logger('import_cards', 'card', $projectId, ['count' => $count]);
|
||||
|
||||
$this->success([
|
||||
'success_count' => $count,
|
||||
'error_count' => 0,
|
||||
'errors' => [],
|
||||
], "成功导入 {$count} 张卡密");
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁用/启用卡密
|
||||
*/
|
||||
public function toggleStatus(int $id): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$status = $input['status'] ?? '';
|
||||
|
||||
if (!in_array($status, ['unused', 'disabled'])) {
|
||||
$this->error('无效的状态值');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$card = $db->fetch("SELECT id, status FROM {$db->table('cards')} WHERE id = ?", [$id]);
|
||||
if (!$card) {
|
||||
$this->error('卡密不存在');
|
||||
}
|
||||
|
||||
if ($card['status'] === 'used') {
|
||||
$this->error('已使用的卡密不能修改状态');
|
||||
}
|
||||
|
||||
$db->execute("UPDATE {$db->table('cards')} SET status = ? WHERE id = ?", [$status, $id]);
|
||||
|
||||
logger('toggle_card_status', 'card', $id, ['status' => $status]);
|
||||
|
||||
$this->success(null, '操作成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 卡密详情
|
||||
*/
|
||||
public function detail(int $id): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$card = $db->fetch(
|
||||
"SELECT c.*, p.name AS project_name, ct.name AS card_type_name,
|
||||
a.bot_qq, a.contact_qq, a.contact_name
|
||||
FROM {$db->table('cards')} c
|
||||
LEFT JOIN {$db->table('projects')} p ON c.project_id = p.id
|
||||
LEFT JOIN {$db->table('card_types')} ct ON c.card_type_id = ct.id
|
||||
LEFT JOIN {$db->table('authorizations')} a ON c.id = a.card_id
|
||||
WHERE c.id = ?",
|
||||
[$id]
|
||||
);
|
||||
if (!$card) {
|
||||
$this->error('卡密不存在', 404);
|
||||
}
|
||||
|
||||
// 数据范围权限检查
|
||||
$scope = PermissionService::cardScope($this->getCurrentUser());
|
||||
if ($scope['where'] && !in_array((int) $card['use_user_id'], $scope['params'], true)) {
|
||||
$this->error('无权查看该卡密', 403);
|
||||
}
|
||||
|
||||
$card['bind_info'] = json_decode($card['bind_info'] ?? '{}', true);
|
||||
$this->success($card);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新卡密状态
|
||||
* POST /api/cards/batch-status
|
||||
* Body: { ids: [int], status: 'unused'|'disabled' }
|
||||
*/
|
||||
public function batchStatus(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$ids = $input['ids'] ?? [];
|
||||
$status = $input['status'] ?? '';
|
||||
|
||||
if (!is_array($ids) || empty($ids)) {
|
||||
$this->error('请选择要更新的卡密');
|
||||
}
|
||||
if (!in_array($status, ['unused', 'disabled'], true)) {
|
||||
$this->error('无效的状态值,只能是 unused 或 disabled');
|
||||
}
|
||||
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (empty($ids)) {
|
||||
$this->error('无效的卡密ID');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||||
|
||||
// 检查是否有已使用的卡密
|
||||
$usedCount = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('cards')} WHERE id IN ({$placeholders}) AND status = 'used'",
|
||||
$ids
|
||||
);
|
||||
if ($usedCount > 0) {
|
||||
$this->error('已使用的卡密不能修改状态');
|
||||
}
|
||||
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('cards')} SET status = ? WHERE id IN ({$placeholders})",
|
||||
array_merge([$status], $ids)
|
||||
);
|
||||
|
||||
logger('batch_toggle_card_status', 'card', 0, ['count' => count($ids), 'status' => $status]);
|
||||
|
||||
$this->success(['count' => count($ids)], '批量状态更新成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除卡密
|
||||
* POST /api/cards/batch-delete
|
||||
* Body: { ids: [int] }
|
||||
*/
|
||||
public function batchDelete(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$ids = $input['ids'] ?? [];
|
||||
|
||||
if (!is_array($ids) || empty($ids)) {
|
||||
$this->error('请选择要删除的卡密');
|
||||
}
|
||||
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (empty($ids)) {
|
||||
$this->error('无效的卡密ID');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||||
|
||||
// 删除前记录日志
|
||||
logger('batch_delete_cards', 'card', 0, ['count' => count($ids)]);
|
||||
|
||||
$db->execute(
|
||||
"DELETE FROM {$db->table('cards')} WHERE id IN ({$placeholders})",
|
||||
$ids
|
||||
);
|
||||
|
||||
$this->success(['count' => count($ids)], '批量删除成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 卡密统计
|
||||
* GET /api/cards/stats
|
||||
*/
|
||||
public function stats(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$projectId = $_GET['project_id'] ?? '';
|
||||
|
||||
$where = '';
|
||||
$params = [];
|
||||
if ($projectId) {
|
||||
$where = "WHERE project_id = ?";
|
||||
$params[] = $projectId;
|
||||
}
|
||||
|
||||
$stats = $db->fetchAll(
|
||||
"SELECT status, COUNT(*) AS count FROM {$db->table('cards')} {$where} GROUP BY status",
|
||||
$params
|
||||
);
|
||||
|
||||
$result = ['unused' => 0, 'used' => 0, 'disabled' => 0, 'total' => 0];
|
||||
foreach ($stats as $row) {
|
||||
$result[$row['status']] = (int) $row['count'];
|
||||
$result['total'] += (int) $row['count'];
|
||||
}
|
||||
|
||||
$this->success($result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
<?php
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Controller;
|
||||
use App\Core\Database;
|
||||
use App\Core\Validator;
|
||||
|
||||
/**
|
||||
* 优惠码管理控制器
|
||||
*/
|
||||
class CouponController extends Controller
|
||||
{
|
||||
/**
|
||||
* 优惠码列表
|
||||
* GET /api/coupons
|
||||
* Query: keyword, status, project_id, sort_by, sort_order, page, page_size
|
||||
*/
|
||||
public function list(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$page = max(1, (int) ($_GET['page'] ?? 1));
|
||||
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
|
||||
$offset = ($page - 1) * $pageSize;
|
||||
$keyword = trim($_GET['keyword'] ?? '');
|
||||
$status = $_GET['status'] ?? '';
|
||||
$projectId = $_GET['project_id'] ?? '';
|
||||
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'code', 'name', 'discount_percent', 'used_count', 'max_use_count', 'min_amount', 'status', 'expire_at', 'created_at']) ? $_GET['sort_by'] : 'id';
|
||||
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
|
||||
|
||||
$where = 'WHERE 1=1';
|
||||
$params = [];
|
||||
|
||||
if ($keyword) {
|
||||
$where .= ' AND (code LIKE ? OR name LIKE ?)';
|
||||
$params[] = "%{$keyword}%";
|
||||
$params[] = "%{$keyword}%";
|
||||
}
|
||||
if ($status !== '') {
|
||||
$where .= ' AND status = ?';
|
||||
$params[] = (int) $status;
|
||||
}
|
||||
if ($projectId !== '') {
|
||||
$where .= ' AND (project_ids = ? OR project_ids LIKE ? OR project_ids LIKE ? OR project_ids = "")';
|
||||
$params[] = (string) $projectId;
|
||||
$params[] = "{$projectId},%";
|
||||
$params[] = "%,{$projectId}";
|
||||
}
|
||||
|
||||
$total = $db->fetchColumn("SELECT COUNT(*) FROM {$db->table('coupons')} {$where}", $params);
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT * FROM {$db->table('coupons')} {$where} ORDER BY {$sortBy} {$sortOrder} LIMIT {$offset}, {$pageSize}",
|
||||
$params
|
||||
);
|
||||
|
||||
$this->success([
|
||||
'list' => $rows,
|
||||
'total' => (int) $total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建优惠码
|
||||
* POST /api/coupons
|
||||
*/
|
||||
public function create(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate(['code' => 'required|min:2|max:32', 'discount_percent' => 'required|numeric'])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
$code = strtoupper(trim($input['code']));
|
||||
$discountPercent = (float) $input['discount_percent'];
|
||||
|
||||
if ($discountPercent <= 0 || $discountPercent > 100) {
|
||||
$this->error('折扣百分比必须在1-100之间');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$exists = $db->fetchColumn("SELECT id FROM {$db->table('coupons')} WHERE code = ?", [$code]);
|
||||
if ($exists) {
|
||||
$this->error('优惠码已存在');
|
||||
}
|
||||
|
||||
$id = $db->insert(
|
||||
"INSERT INTO {$db->table('coupons')} (code, name, discount_percent, max_use_count, min_amount, project_ids, status, expire_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
[
|
||||
$code,
|
||||
$input['name'] ?? '',
|
||||
$discountPercent,
|
||||
(int) ($input['max_use_count'] ?? 0),
|
||||
(float) ($input['min_amount'] ?? 0),
|
||||
$input['project_ids'] ?? '',
|
||||
(int) ($input['status'] ?? 1),
|
||||
$input['expire_at'] ?: null,
|
||||
]
|
||||
);
|
||||
|
||||
$this->success(['id' => $id], '优惠码创建成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新优惠码
|
||||
* PUT /api/coupons/{id}
|
||||
*/
|
||||
public function update(int $id): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$db = Database::getInstance();
|
||||
|
||||
$coupon = $db->fetch("SELECT * FROM {$db->table('coupons')} WHERE id = ?", [$id]);
|
||||
if (!$coupon) {
|
||||
$this->error('优惠码不存在', 404);
|
||||
}
|
||||
|
||||
$updates = [];
|
||||
$params = [];
|
||||
foreach (['name', 'discount_percent', 'max_use_count', 'min_amount', 'project_ids', 'status', 'expire_at'] as $field) {
|
||||
if (array_key_exists($field, $input)) {
|
||||
$updates[] = "`{$field}` = ?";
|
||||
$val = $input[$field];
|
||||
if ($field === 'discount_percent') {
|
||||
if ((float) $val <= 0 || (float) $val > 100) {
|
||||
$this->error('折扣百分比必须在1-100之间');
|
||||
}
|
||||
$val = (float) $val;
|
||||
}
|
||||
$params[] = $field === 'expire_at' ? ($val ?: null) : $val;
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($updates)) {
|
||||
$this->error('没有需要更新的字段');
|
||||
}
|
||||
|
||||
$params[] = $id;
|
||||
$db->execute("UPDATE {$db->table('coupons')} SET " . implode(', ', $updates) . ' WHERE id = ?', $params);
|
||||
|
||||
$this->success(null, '更新成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除优惠码
|
||||
* DELETE /api/coupons/{id}
|
||||
*/
|
||||
public function delete(int $id): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$db->execute("DELETE FROM {$db->table('coupons')} WHERE id = ?", [$id]);
|
||||
$this->success(null, '删除成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出优惠码
|
||||
* GET /api/coupons/export
|
||||
* Query: ids, format(csv|excel)
|
||||
*/
|
||||
public function export(): void
|
||||
{
|
||||
$ids = $_GET['ids'] ?? [];
|
||||
$format = strtolower($_GET['format'] ?? 'csv');
|
||||
if (!in_array($format, ['csv', 'excel'])) {
|
||||
$format = 'csv';
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$where = 'WHERE 1=1';
|
||||
$params = [];
|
||||
|
||||
if (!empty($ids)) {
|
||||
$ids = is_array($ids) ? $ids : explode(',', $ids);
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (!empty($ids)) {
|
||||
$where .= ' AND id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
|
||||
$params = array_merge($params, $ids);
|
||||
}
|
||||
}
|
||||
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT * FROM {$db->table('coupons')} {$where} ORDER BY id DESC LIMIT 50000",
|
||||
$params
|
||||
);
|
||||
|
||||
if ($format === 'excel') {
|
||||
$filename = 'coupons_export_' . date('YmdHis') . '.xls';
|
||||
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
$html = '<table border="1"><tr><th>ID</th><th>优惠码</th><th>名称</th><th>折扣%</th><th>已用/上限</th><th>最低消费</th><th>状态</th><th>过期时间</th><th>创建时间</th></tr>';
|
||||
foreach ($rows as $row) {
|
||||
$html .= '<tr>';
|
||||
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['code']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['name'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['discount_percent']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['used_count'] . ' / ' . ($row['max_use_count'] > 0 ? $row['max_use_count'] : '不限')) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['min_amount']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['status'] == 1 ? '启用' : '禁用') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['expire_at'] ?? '永久有效') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
|
||||
$html .= '</tr>';
|
||||
}
|
||||
$html .= '</table>';
|
||||
echo $html;
|
||||
exit;
|
||||
}
|
||||
|
||||
$filename = 'coupons_export_' . date('YmdHis') . '.csv';
|
||||
header('Content-Type: text/csv; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
|
||||
$output = fopen('php://output', 'w');
|
||||
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($output, ['ID', '优惠码', '名称', '折扣%', '已用/上限', '最低消费', '状态', '过期时间', '创建时间']);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($output, [
|
||||
$row['id'],
|
||||
$row['code'],
|
||||
$row['name'] ?? '',
|
||||
$row['discount_percent'],
|
||||
$row['used_count'] . ' / ' . ($row['max_use_count'] > 0 ? $row['max_use_count'] : '不限'),
|
||||
$row['min_amount'],
|
||||
$row['status'] == 1 ? '启用' : '禁用',
|
||||
$row['expire_at'] ?? '永久有效',
|
||||
$row['created_at'],
|
||||
]);
|
||||
}
|
||||
fclose($output);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* 公开接口:验证优惠码
|
||||
* POST /api/public/coupons/validate
|
||||
* Body: { code, project_id, amount }
|
||||
*/
|
||||
public function validate(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$code = strtoupper(trim($input['code'] ?? ''));
|
||||
$projectId = (int) ($input['project_id'] ?? 0);
|
||||
$amount = (float) ($input['amount'] ?? 0);
|
||||
|
||||
if (empty($code)) {
|
||||
$this->error('请输入优惠码');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$coupon = $db->fetch(
|
||||
"SELECT * FROM {$db->table('coupons')} WHERE code = ? AND status = 1",
|
||||
[$code]
|
||||
);
|
||||
|
||||
if (!$coupon) {
|
||||
$this->success(['valid' => false, 'message' => '优惠码不存在或已失效']);
|
||||
return;
|
||||
}
|
||||
|
||||
if ($coupon['expire_at'] && strtotime($coupon['expire_at']) < time()) {
|
||||
$this->success(['valid' => false, 'message' => '优惠码已过期']);
|
||||
return;
|
||||
}
|
||||
|
||||
if ($coupon['max_use_count'] > 0 && $coupon['used_count'] >= $coupon['max_use_count']) {
|
||||
$this->success(['valid' => false, 'message' => '优惠码已达使用上限']);
|
||||
return;
|
||||
}
|
||||
|
||||
if ($coupon['min_amount'] > 0 && $amount < $coupon['min_amount']) {
|
||||
$this->success(['valid' => false, 'message' => "订单金额需满¥{$coupon['min_amount']}"]);
|
||||
return;
|
||||
}
|
||||
|
||||
if ($coupon['project_ids'] && $projectId) {
|
||||
$allowedProjects = array_map('trim', explode(',', $coupon['project_ids']));
|
||||
if (!in_array((string) $projectId, $allowedProjects)) {
|
||||
$this->success(['valid' => false, 'message' => '该优惠码不适用于此项目']);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$discountAmount = round($amount * ($coupon['discount_percent'] / 100), 2);
|
||||
|
||||
$this->success([
|
||||
'valid' => true,
|
||||
'message' => '优惠码有效',
|
||||
'coupon_id' => $coupon['id'],
|
||||
'code' => $coupon['code'],
|
||||
'discount_percent' => (float) $coupon['discount_percent'],
|
||||
'discount_amount' => $discountAmount,
|
||||
'final_amount' => max(0, round($amount - $discountAmount, 2)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
<?php
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Controller;
|
||||
use App\Core\Database;
|
||||
|
||||
/**
|
||||
* Dashboard与统计控制器
|
||||
*/
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
/**
|
||||
* 首页Dashboard数据
|
||||
*/
|
||||
public function index(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$userRole = $this->getUserRole();
|
||||
$userId = $this->getUserId();
|
||||
|
||||
$data = [];
|
||||
|
||||
if ($userRole === 'admin') {
|
||||
// 项目总数
|
||||
$data['total_projects'] = (int) $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('projects')} WHERE deleted_at IS NULL"
|
||||
);
|
||||
// 用户总数
|
||||
$data['total_users'] = (int) $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('users')} WHERE deleted_at IS NULL"
|
||||
);
|
||||
// 卡密总数
|
||||
$data['total_cards'] = (int) $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('cards')}"
|
||||
);
|
||||
// 已使用卡密
|
||||
$data['used_cards'] = (int) $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('cards')} WHERE status = 'used'"
|
||||
);
|
||||
// 订单总数
|
||||
$data['total_orders'] = (int) $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('orders')}"
|
||||
);
|
||||
// 已支付订单
|
||||
$data['paid_orders'] = (int) $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('orders')} WHERE status = 'paid'"
|
||||
);
|
||||
// 总收入
|
||||
$data['total_revenue'] = (float) $db->fetchColumn(
|
||||
"SELECT COALESCE(SUM(amount), 0) FROM {$db->table('orders')} WHERE status = 'paid'"
|
||||
);
|
||||
// 今日收入
|
||||
$data['today_revenue'] = (float) $db->fetchColumn(
|
||||
"SELECT COALESCE(SUM(amount), 0) FROM {$db->table('orders')} WHERE status = 'paid' AND DATE(paid_at) = CURDATE()"
|
||||
);
|
||||
// 代理总数
|
||||
$data['total_agents'] = (int) $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('users')} WHERE role = 'agent' AND deleted_at IS NULL"
|
||||
);
|
||||
// 近7天订单趋势
|
||||
$data['order_trend'] = $db->fetchAll(
|
||||
"SELECT DATE(created_at) AS date, COUNT(*) AS count, COALESCE(SUM(CASE WHEN status='paid' THEN amount ELSE 0 END), 0) AS amount
|
||||
FROM {$db->table('orders')}
|
||||
WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
|
||||
GROUP BY DATE(created_at)
|
||||
ORDER BY date ASC"
|
||||
);
|
||||
} elseif ($userRole === 'agent') {
|
||||
// 代理数据
|
||||
$agent = $db->fetch(
|
||||
"SELECT total_quota, used_quota, frozen_quota FROM {$db->table('agents')} WHERE user_id = ?",
|
||||
[$userId]
|
||||
);
|
||||
$data['agent_quota'] = $agent ?: ['total_quota' => 0, 'used_quota' => 0, 'frozen_quota' => 0];
|
||||
$data['remain_quota'] = (float) ($data['agent_quota']['total_quota'] ?? 0) - (float) ($data['agent_quota']['used_quota'] ?? 0);
|
||||
|
||||
// 代理生成的卡密总数
|
||||
$data['total_authorized'] = (int) $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('cards')} WHERE use_user_id = ?",
|
||||
[$userId]
|
||||
);
|
||||
// 今日生成卡密数
|
||||
$data['today_authorized'] = (int) $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('cards')} WHERE use_user_id = ? AND DATE(created_at) = CURDATE()",
|
||||
[$userId]
|
||||
);
|
||||
}
|
||||
|
||||
$this->success($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 操作日志列表
|
||||
* GET /api/logs
|
||||
* Query: action, user_id, username, start_date, end_date, sort_by, sort_order, page, page_size
|
||||
*/
|
||||
public function logs(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$page = max(1, (int) ($_GET['page'] ?? 1));
|
||||
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
|
||||
$offset = ($page - 1) * $pageSize;
|
||||
$action = $_GET['action'] ?? '';
|
||||
$userId = $_GET['user_id'] ?? '';
|
||||
$username = trim($_GET['username'] ?? '');
|
||||
$startDate = $_GET['start_date'] ?? '';
|
||||
$endDate = $_GET['end_date'] ?? '';
|
||||
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'user_id', 'action', 'target_type', 'target_id', 'created_at']) ? $_GET['sort_by'] : 'id';
|
||||
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
|
||||
|
||||
$where = "WHERE 1=1";
|
||||
$params = [];
|
||||
|
||||
if ($action) {
|
||||
$where .= " AND l.action = ?";
|
||||
$params[] = $action;
|
||||
}
|
||||
if ($userId) {
|
||||
$where .= " AND l.user_id = ?";
|
||||
$params[] = $userId;
|
||||
}
|
||||
if ($username) {
|
||||
$where .= " AND (u.username LIKE ? OR u.nickname LIKE ?)";
|
||||
$params[] = "%{$username}%";
|
||||
$params[] = "%{$username}%";
|
||||
}
|
||||
if ($startDate) {
|
||||
$where .= " AND DATE(l.created_at) >= ?";
|
||||
$params[] = $startDate;
|
||||
}
|
||||
if ($endDate) {
|
||||
$where .= " AND DATE(l.created_at) <= ?";
|
||||
$params[] = $endDate;
|
||||
}
|
||||
|
||||
$total = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('logs')} l LEFT JOIN {$db->table('users')} u ON l.user_id = u.id {$where}",
|
||||
$params
|
||||
);
|
||||
|
||||
$logs = $db->fetchAll(
|
||||
"SELECT l.*, u.username, u.nickname
|
||||
FROM {$db->table('logs')} l
|
||||
LEFT JOIN {$db->table('users')} u ON l.user_id = u.id
|
||||
{$where}
|
||||
ORDER BY l.{$sortBy} {$sortOrder}
|
||||
LIMIT {$offset}, {$pageSize}",
|
||||
$params
|
||||
);
|
||||
|
||||
$this->success([
|
||||
'list' => $logs,
|
||||
'total' => (int) $total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出日志
|
||||
* GET /api/logs/export
|
||||
* Query: ids, format(csv|excel)
|
||||
*/
|
||||
public function exportLogs(): void
|
||||
{
|
||||
$ids = $_GET['ids'] ?? [];
|
||||
$format = strtolower($_GET['format'] ?? 'csv');
|
||||
if (!in_array($format, ['csv', 'excel'])) {
|
||||
$format = 'csv';
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$where = 'WHERE 1=1';
|
||||
$params = [];
|
||||
|
||||
if (!empty($ids)) {
|
||||
$ids = is_array($ids) ? $ids : explode(',', $ids);
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (!empty($ids)) {
|
||||
$where .= ' AND l.id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
|
||||
$params = array_merge($params, $ids);
|
||||
}
|
||||
}
|
||||
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT l.*, u.username, u.nickname
|
||||
FROM {$db->table('logs')} l
|
||||
LEFT JOIN {$db->table('users')} u ON l.user_id = u.id
|
||||
{$where}
|
||||
ORDER BY l.id DESC
|
||||
LIMIT 50000",
|
||||
$params
|
||||
);
|
||||
|
||||
if ($format === 'excel') {
|
||||
$filename = 'logs_export_' . date('YmdHis') . '.xls';
|
||||
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
$html = '<table border="1"><tr><th>ID</th><th>用户</th><th>昵称</th><th>操作类型</th><th>目标类型</th><th>目标ID</th><th>详情</th><th>IP</th><th>时间</th></tr>';
|
||||
foreach ($rows as $row) {
|
||||
$html .= '<tr>';
|
||||
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['username'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['nickname'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['action']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['target_type']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['target_id']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['detail'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['ip'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
|
||||
$html .= '</tr>';
|
||||
}
|
||||
$html .= '</table>';
|
||||
echo $html;
|
||||
exit;
|
||||
}
|
||||
|
||||
$filename = 'logs_export_' . date('YmdHis') . '.csv';
|
||||
header('Content-Type: text/csv; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
|
||||
$output = fopen('php://output', 'w');
|
||||
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($output, ['ID', '用户', '昵称', '操作类型', '目标类型', '目标ID', '详情', 'IP', '时间']);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($output, [
|
||||
$row['id'],
|
||||
$row['username'] ?? '',
|
||||
$row['nickname'] ?? '',
|
||||
$row['action'],
|
||||
$row['target_type'],
|
||||
$row['target_id'],
|
||||
$row['detail'] ?? '',
|
||||
$row['ip'] ?? '',
|
||||
$row['created_at'],
|
||||
]);
|
||||
}
|
||||
fclose($output);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
<?php
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Controller;
|
||||
use App\Core\Database;
|
||||
use App\Core\Validator;
|
||||
|
||||
/**
|
||||
* 订单管理控制器
|
||||
*/
|
||||
class OrderController extends Controller
|
||||
{
|
||||
/**
|
||||
* 订单列表
|
||||
*/
|
||||
/**
|
||||
* 订单列表
|
||||
* GET /api/orders
|
||||
* Query: status, pay_type, project_id, keyword, start_date, end_date, sort_by, sort_order, page, page_size
|
||||
*/
|
||||
public function list(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$page = max(1, (int) ($_GET['page'] ?? 1));
|
||||
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
|
||||
$offset = ($page - 1) * $pageSize;
|
||||
$status = $_GET['status'] ?? '';
|
||||
$payType = $_GET['pay_type'] ?? '';
|
||||
$projectId = $_GET['project_id'] ?? '';
|
||||
$keyword = trim($_GET['keyword'] ?? '');
|
||||
$startDate = $_GET['start_date'] ?? '';
|
||||
$endDate = $_GET['end_date'] ?? '';
|
||||
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'amount', 'status', 'pay_type', 'paid_at', 'created_at']) ? $_GET['sort_by'] : 'id';
|
||||
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
|
||||
|
||||
$where = "WHERE 1=1";
|
||||
$params = [];
|
||||
|
||||
if ($status) {
|
||||
$where .= " AND o.status = ?";
|
||||
$params[] = $status;
|
||||
}
|
||||
if ($payType) {
|
||||
$where .= " AND o.pay_type = ?";
|
||||
$params[] = $payType;
|
||||
}
|
||||
if ($projectId) {
|
||||
$where .= " AND o.project_id = ?";
|
||||
$params[] = $projectId;
|
||||
}
|
||||
if ($keyword) {
|
||||
$where .= " AND (o.order_no LIKE ? OR o.trade_no LIKE ? OR c.card_key LIKE ?)";
|
||||
$params[] = "%{$keyword}%";
|
||||
$params[] = "%{$keyword}%";
|
||||
$params[] = "%{$keyword}%";
|
||||
}
|
||||
if ($startDate) {
|
||||
$where .= " AND DATE(o.created_at) >= ?";
|
||||
$params[] = $startDate;
|
||||
}
|
||||
if ($endDate) {
|
||||
$where .= " AND DATE(o.created_at) <= ?";
|
||||
$params[] = $endDate;
|
||||
}
|
||||
|
||||
$total = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('orders')} o {$where}",
|
||||
$params
|
||||
);
|
||||
|
||||
$orders = $db->fetchAll(
|
||||
"SELECT o.*, p.name AS project_name, ct.name AS card_type_name
|
||||
FROM {$db->table('orders')} o
|
||||
LEFT JOIN {$db->table('projects')} p ON o.project_id = p.id
|
||||
LEFT JOIN {$db->table('card_types')} ct ON o.card_type_id = ct.id
|
||||
{$where}
|
||||
ORDER BY o.{$sortBy} {$sortOrder}
|
||||
LIMIT {$offset}, {$pageSize}",
|
||||
$params
|
||||
);
|
||||
|
||||
$this->success([
|
||||
'list' => $orders,
|
||||
'total' => (int) $total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单详情
|
||||
*/
|
||||
public function detail(int $id): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$order = $db->fetch(
|
||||
"SELECT o.*, p.name AS project_name, ct.name AS card_type_name, c.card_key
|
||||
FROM {$db->table('orders')} o
|
||||
LEFT JOIN {$db->table('projects')} p ON o.project_id = p.id
|
||||
LEFT JOIN {$db->table('card_types')} ct ON o.card_type_id = ct.id
|
||||
LEFT JOIN {$db->table('cards')} c ON o.card_id = c.id
|
||||
WHERE o.id = ?",
|
||||
[$id]
|
||||
);
|
||||
if (!$order) {
|
||||
$this->error('订单不存在', 404);
|
||||
}
|
||||
$this->success($order);
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动补单 (Admin操作)
|
||||
*/
|
||||
public function manualComplete(int $id): void
|
||||
{
|
||||
if ($this->getUserRole() !== 'admin') {
|
||||
$this->error('仅管理员可执行此操作', 403);
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$order = $db->fetch("SELECT * FROM {$db->table('orders')} WHERE id = ?", [$id]);
|
||||
if (!$order) {
|
||||
$this->error('订单不存在');
|
||||
}
|
||||
if ($order['status'] !== 'pending') {
|
||||
$this->error('订单状态不允许补单');
|
||||
}
|
||||
|
||||
$this->processOrderPaid($order['id']);
|
||||
logger('manual_complete_order', 'order', $id);
|
||||
|
||||
$this->success(null, '补单成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出订单
|
||||
* GET /api/orders/export
|
||||
* Query: ids, format(csv|excel)
|
||||
*/
|
||||
public function export(): void
|
||||
{
|
||||
$ids = $_GET['ids'] ?? [];
|
||||
$format = strtolower($_GET['format'] ?? 'csv');
|
||||
if (!in_array($format, ['csv', 'excel'])) {
|
||||
$format = 'csv';
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$where = 'WHERE 1=1';
|
||||
$params = [];
|
||||
|
||||
if (!empty($ids)) {
|
||||
$ids = is_array($ids) ? $ids : explode(',', $ids);
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (!empty($ids)) {
|
||||
$where .= ' AND o.id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
|
||||
$params = array_merge($params, $ids);
|
||||
}
|
||||
}
|
||||
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT o.*, p.name AS project_name, ct.name AS card_type_name, c.card_key
|
||||
FROM {$db->table('orders')} o
|
||||
LEFT JOIN {$db->table('projects')} p ON o.project_id = p.id
|
||||
LEFT JOIN {$db->table('card_types')} ct ON o.card_type_id = ct.id
|
||||
LEFT JOIN {$db->table('cards')} c ON o.card_id = c.id
|
||||
{$where}
|
||||
ORDER BY o.id DESC
|
||||
LIMIT 50000",
|
||||
$params
|
||||
);
|
||||
|
||||
$payTypeMap = ['alipay' => '支付宝', 'wxpay' => '微信', 'qqpay' => 'QQ钱包'];
|
||||
$statusMap = ['pending' => '待支付', 'paid' => '已支付', 'expired' => '已过期', 'refunded' => '已退款'];
|
||||
|
||||
if ($format === 'excel') {
|
||||
$filename = 'orders_export_' . date('YmdHis') . '.xls';
|
||||
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
$html = '<table border="1"><tr><th>订单号</th><th>项目</th><th>套餐</th><th>金额</th><th>支付方式</th><th>状态</th><th>卡密</th><th>支付时间</th><th>创建时间</th></tr>';
|
||||
foreach ($rows as $row) {
|
||||
$html .= '<tr>';
|
||||
$html .= '<td>' . htmlspecialchars($row['order_no']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['project_name'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['card_type_name'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['amount']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($payTypeMap[$row['pay_type']] ?? ($row['pay_type'] ?: '-')) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($statusMap[$row['status']] ?? $row['status']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['card_key'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['paid_at'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
|
||||
$html .= '</tr>';
|
||||
}
|
||||
$html .= '</table>';
|
||||
echo $html;
|
||||
exit;
|
||||
}
|
||||
|
||||
$filename = 'orders_export_' . date('YmdHis') . '.csv';
|
||||
header('Content-Type: text/csv; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
|
||||
$output = fopen('php://output', 'w');
|
||||
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($output, ['订单号', '项目', '套餐', '金额', '支付方式', '状态', '卡密', '支付时间', '创建时间']);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($output, [
|
||||
$row['order_no'],
|
||||
$row['project_name'] ?? '',
|
||||
$row['card_type_name'] ?? '',
|
||||
$row['amount'],
|
||||
$payTypeMap[$row['pay_type']] ?? ($row['pay_type'] ?: '-'),
|
||||
$statusMap[$row['status']] ?? $row['status'],
|
||||
$row['card_key'] ?? '',
|
||||
$row['paid_at'] ?? '',
|
||||
$row['created_at'],
|
||||
]);
|
||||
}
|
||||
fclose($output);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理支付成功
|
||||
*/
|
||||
public function processOrderPaid(int $orderId): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$order = $db->fetch("SELECT * FROM {$db->table('orders')} WHERE id = ?", [$orderId]);
|
||||
if (!$order || $order['status'] !== 'pending') return;
|
||||
|
||||
$snowflake = new \App\Services\SnowflakeService();
|
||||
$cardKey = $snowflake->generateCardKey();
|
||||
|
||||
$cardType = $db->fetch(
|
||||
"SELECT * FROM {$db->table('card_types')} WHERE id = ?",
|
||||
[$order['card_type_id']]
|
||||
);
|
||||
|
||||
$expireTime = null;
|
||||
$durationDays = $cardType['duration_days'] ?? 0;
|
||||
if ($durationDays > 0) {
|
||||
$expireTime = date('Y-m-d H:i:s', strtotime("+{$durationDays} days"));
|
||||
}
|
||||
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
// 创建卡密
|
||||
$cardId = $db->insert(
|
||||
"INSERT INTO {$db->table('cards')} (card_key, project_id, card_type_id, type, duration_days, status, expire_time, order_id, remark)
|
||||
VALUES (?, ?, ?, ?, ?, 'unused', ?, ?, '在线购买')",
|
||||
[
|
||||
$cardKey,
|
||||
$order['project_id'],
|
||||
$order['card_type_id'],
|
||||
$cardType['name'] ?? '',
|
||||
$durationDays,
|
||||
$expireTime,
|
||||
$orderId,
|
||||
]
|
||||
);
|
||||
|
||||
// 更新订单
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('orders')} SET status = 'paid', card_id = ?, paid_at = NOW() WHERE id = ?",
|
||||
[$cardId, $orderId]
|
||||
);
|
||||
|
||||
$db->commit();
|
||||
} catch (\Throwable $e) {
|
||||
$db->rollback();
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
<?php
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Controller;
|
||||
use App\Core\Database;
|
||||
use App\Core\Validator;
|
||||
|
||||
/**
|
||||
* 项目管理控制器
|
||||
*/
|
||||
class ProjectController extends Controller
|
||||
{
|
||||
/**
|
||||
* 项目列表
|
||||
*/
|
||||
public function list(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$page = max(1, (int) ($_GET['page'] ?? 1));
|
||||
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
|
||||
$keyword = trim($_GET['keyword'] ?? '');
|
||||
$offset = ($page - 1) * $pageSize;
|
||||
$userRole = $this->getUserRole();
|
||||
$userId = $this->getUserId();
|
||||
|
||||
$where = "WHERE deleted_at IS NULL";
|
||||
$params = [];
|
||||
|
||||
// 项目管理员只能看到自己的项目
|
||||
if ($userRole === 'project_admin') {
|
||||
$user = $this->getCurrentUser();
|
||||
$projectIds = json_decode($user['project_ids'] ?? '[]', true) ?: [];
|
||||
if (empty($projectIds)) {
|
||||
$this->success(['list' => [], 'total' => 0, 'page' => $page, 'page_size' => $pageSize]);
|
||||
return;
|
||||
}
|
||||
$placeholders = implode(',', array_fill(0, count($projectIds), '?'));
|
||||
$where .= " AND id IN ({$placeholders})";
|
||||
$params = $projectIds;
|
||||
}
|
||||
|
||||
if ($keyword) {
|
||||
$where .= " AND name LIKE ?";
|
||||
$params[] = "%{$keyword}%";
|
||||
}
|
||||
|
||||
$total = $db->fetchColumn("SELECT COUNT(*) FROM {$db->table('projects')} {$where}", $params);
|
||||
$projects = $db->fetchAll(
|
||||
"SELECT * FROM {$db->table('projects')} {$where} ORDER BY id DESC LIMIT {$offset}, {$pageSize}",
|
||||
$params
|
||||
);
|
||||
|
||||
$this->success([
|
||||
'list' => $projects,
|
||||
'total' => (int) $total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 项目详情
|
||||
*/
|
||||
public function detail(int $id): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$project = $db->fetch("SELECT * FROM {$db->table('projects')} WHERE id = ? AND deleted_at IS NULL", [$id]);
|
||||
if (!$project) {
|
||||
$this->error('项目不存在', 404);
|
||||
}
|
||||
|
||||
// 获取卡密类型
|
||||
$types = $db->fetchAll(
|
||||
"SELECT * FROM {$db->table('card_types')} WHERE project_id = ? AND status = 1 ORDER BY sort ASC",
|
||||
[$id]
|
||||
);
|
||||
$project['card_types'] = $types;
|
||||
|
||||
$this->success($project);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建项目
|
||||
*/
|
||||
public function create(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate(['name' => 'required|min:1|max:100'])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$apiKey = 'ak_' . bin2hex(random_bytes(16));
|
||||
|
||||
$id = $db->insert(
|
||||
"INSERT INTO {$db->table('projects')} (name, description, api_key, status) VALUES (?, ?, ?, ?)",
|
||||
[$input['name'], $input['description'] ?? '', $apiKey, $input['status'] ?? 1]
|
||||
);
|
||||
|
||||
logger('create_project', 'project', $id, ['name' => $input['name']]);
|
||||
|
||||
$this->success(['id' => $id, 'api_key' => $apiKey], '项目创建成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新项目
|
||||
*/
|
||||
public function update(int $id): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$db = Database::getInstance();
|
||||
|
||||
$project = $db->fetch("SELECT id FROM {$db->table('projects')} WHERE id = ? AND deleted_at IS NULL", [$id]);
|
||||
if (!$project) {
|
||||
$this->error('项目不存在');
|
||||
}
|
||||
|
||||
$updates = [];
|
||||
$params = [];
|
||||
foreach (['name', 'description', 'status'] as $field) {
|
||||
if (isset($input[$field])) {
|
||||
$updates[] = "{$field} = ?";
|
||||
$params[] = $input[$field];
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($updates)) {
|
||||
$this->error('没有需要更新的字段');
|
||||
}
|
||||
|
||||
$params[] = $id;
|
||||
$db->execute("UPDATE {$db->table('projects')} SET " . implode(', ', $updates) . " WHERE id = ?", $params);
|
||||
|
||||
logger('update_project', 'project', $id);
|
||||
|
||||
$this->success(null, '更新成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除项目
|
||||
*/
|
||||
public function delete(int $id): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$db->execute("UPDATE {$db->table('projects')} SET deleted_at = NOW() WHERE id = ?", [$id]);
|
||||
|
||||
logger('delete_project', 'project', $id);
|
||||
|
||||
$this->success(null, '删除成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新生成API Key
|
||||
*/
|
||||
public function regenerateApiKey(int $id): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$apiKey = 'ak_' . bin2hex(random_bytes(16));
|
||||
$db->execute("UPDATE {$db->table('projects')} SET api_key = ? WHERE id = ?", [$apiKey, $id]);
|
||||
|
||||
logger('regenerate_api_key', 'project', $id);
|
||||
|
||||
$this->success(['api_key' => $apiKey], 'API Key已重新生成');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取项目的卡密类型列表
|
||||
*/
|
||||
public function cardTypes(int $projectId): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$types = $db->fetchAll(
|
||||
"SELECT * FROM {$db->table('card_types')} WHERE project_id = ? ORDER BY sort ASC",
|
||||
[$projectId]
|
||||
);
|
||||
$this->success($types);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建卡密类型
|
||||
*/
|
||||
public function createCardType(int $projectId): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate([
|
||||
'name' => 'required|min:1|max:50',
|
||||
'duration_days' => 'required|integer',
|
||||
'price' => 'required|numeric',
|
||||
'agent_cost' => 'required|numeric',
|
||||
])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$id = $db->insert(
|
||||
"INSERT INTO {$db->table('card_types')} (project_id, name, description, duration_days, price, original_price, agent_cost, sort, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
[
|
||||
$projectId,
|
||||
$input['name'],
|
||||
$input['description'] ?? '',
|
||||
(int) $input['duration_days'],
|
||||
(float) $input['price'],
|
||||
(float) ($input['original_price'] ?? 0),
|
||||
(float) $input['agent_cost'],
|
||||
$input['sort'] ?? 0,
|
||||
$input['status'] ?? 1,
|
||||
]
|
||||
);
|
||||
|
||||
logger('create_card_type', 'card_type', $id, ['project_id' => $projectId, 'name' => $input['name']]);
|
||||
|
||||
$this->success(['id' => $id], '卡密类型创建成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新卡密类型
|
||||
*/
|
||||
public function updateCardType(int $projectId, int $typeId): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$db = Database::getInstance();
|
||||
|
||||
$updates = [];
|
||||
$params = [];
|
||||
foreach (['name', 'description', 'duration_days', 'price', 'original_price', 'agent_cost', 'sort', 'status'] as $field) {
|
||||
if (isset($input[$field])) {
|
||||
$updates[] = "{$field} = ?";
|
||||
$params[] = $input[$field];
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($updates)) {
|
||||
$this->error('没有需要更新的字段');
|
||||
}
|
||||
|
||||
$params[] = $typeId;
|
||||
$params[] = $projectId;
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('card_types')} SET " . implode(', ', $updates) . " WHERE id = ? AND project_id = ?",
|
||||
$params
|
||||
);
|
||||
|
||||
$this->success(null, '更新成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除卡密类型
|
||||
*/
|
||||
public function deleteCardType(int $projectId, int $typeId): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$db->execute("DELETE FROM {$db->table('card_types')} WHERE id = ? AND project_id = ?", [$typeId, $projectId]);
|
||||
$this->success(null, '删除成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 所有项目简单列表 (下拉选项用)
|
||||
*/
|
||||
public function allProjects(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$projects = $db->fetchAll(
|
||||
"SELECT id, name FROM {$db->table('projects')} WHERE status = 1 AND deleted_at IS NULL ORDER BY id DESC"
|
||||
);
|
||||
$this->success($projects);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有项目的商品列表 (全量,用于商品管理页面)
|
||||
*/
|
||||
public function allProducts(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$page = max(1, (int) ($_GET['page'] ?? 1));
|
||||
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
|
||||
$offset = ($page - 1) * $pageSize;
|
||||
$projectId = $_GET['project_id'] ?? '';
|
||||
$keyword = trim($_GET['keyword'] ?? '');
|
||||
$status = $_GET['status'] ?? '';
|
||||
$sortBy = in_array($_GET['sort_by'] ?? '', ['id', 'name', 'price', 'agent_cost', 'sort', 'status', 'created_at']) ? $_GET['sort_by'] : 'id';
|
||||
$sortOrder = in_array(strtolower($_GET['sort_order'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_order']) : 'DESC';
|
||||
|
||||
$where = 'WHERE 1=1';
|
||||
$params = [];
|
||||
|
||||
if ($projectId) {
|
||||
$where .= ' AND ct.project_id = ?';
|
||||
$params[] = $projectId;
|
||||
}
|
||||
if ($status !== '') {
|
||||
$where .= ' AND ct.status = ?';
|
||||
$params[] = (int) $status;
|
||||
}
|
||||
if ($keyword) {
|
||||
$where .= ' AND ct.name LIKE ?';
|
||||
$params[] = "%{$keyword}%";
|
||||
}
|
||||
|
||||
$total = $db->fetchColumn(
|
||||
"SELECT COUNT(*) FROM {$db->table('card_types')} ct {$where}",
|
||||
$params
|
||||
);
|
||||
|
||||
$products = $db->fetchAll(
|
||||
"SELECT ct.*, p.name AS project_name
|
||||
FROM {$db->table('card_types')} ct
|
||||
LEFT JOIN {$db->table('projects')} p ON ct.project_id = p.id
|
||||
{$where}
|
||||
ORDER BY ct.{$sortBy} {$sortOrder}
|
||||
LIMIT {$offset}, {$pageSize}",
|
||||
$params
|
||||
);
|
||||
|
||||
$this->success([
|
||||
'list' => $products,
|
||||
'total' => (int) $total,
|
||||
'page' => $page,
|
||||
'page_size' => $pageSize,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出商品
|
||||
* GET /api/products/export
|
||||
* Query: ids, format(csv|excel)
|
||||
*/
|
||||
public function productsExport(): void
|
||||
{
|
||||
$ids = $_GET['ids'] ?? [];
|
||||
$format = strtolower($_GET['format'] ?? 'csv');
|
||||
if (!in_array($format, ['csv', 'excel'])) {
|
||||
$format = 'csv';
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$where = 'WHERE 1=1';
|
||||
$params = [];
|
||||
|
||||
if (!empty($ids)) {
|
||||
$ids = is_array($ids) ? $ids : explode(',', $ids);
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (!empty($ids)) {
|
||||
$where .= ' AND ct.id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
|
||||
$params = array_merge($params, $ids);
|
||||
}
|
||||
}
|
||||
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT ct.*, p.name AS project_name
|
||||
FROM {$db->table('card_types')} ct
|
||||
LEFT JOIN {$db->table('projects')} p ON ct.project_id = p.id
|
||||
{$where}
|
||||
ORDER BY ct.id DESC LIMIT 50000",
|
||||
$params
|
||||
);
|
||||
|
||||
if ($format === 'excel') {
|
||||
$filename = 'products_export_' . date('YmdHis') . '.xls';
|
||||
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
$html = '<table border="1"><tr><th>ID</th><th>所属项目</th><th>商品名称</th><th>有效天数</th><th>售价</th><th>原价</th><th>代理价格</th><th>排序</th><th>状态</th><th>创建时间</th></tr>';
|
||||
foreach ($rows as $row) {
|
||||
$html .= '<tr>';
|
||||
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['project_name'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['name']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['duration_days'] == 0 ? '永久' : $row['duration_days'] . '天') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['price']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['original_price'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['agent_cost']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['sort']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['status'] == 1 ? '启用' : '禁用') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
|
||||
$html .= '</tr>';
|
||||
}
|
||||
$html .= '</table>';
|
||||
echo $html;
|
||||
exit;
|
||||
}
|
||||
|
||||
$filename = 'products_export_' . date('YmdHis') . '.csv';
|
||||
header('Content-Type: text/csv; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
|
||||
$output = fopen('php://output', 'w');
|
||||
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($output, ['ID', '所属项目', '商品名称', '有效天数', '售价', '原价', '代理价格', '排序', '状态', '创建时间']);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($output, [
|
||||
$row['id'],
|
||||
$row['project_name'] ?? '',
|
||||
$row['name'],
|
||||
$row['duration_days'] == 0 ? '永久' : $row['duration_days'] . '天',
|
||||
$row['price'],
|
||||
$row['original_price'] ?? '',
|
||||
$row['agent_cost'],
|
||||
$row['sort'],
|
||||
$row['status'] == 1 ? '启用' : '禁用',
|
||||
$row['created_at'],
|
||||
]);
|
||||
}
|
||||
fclose($output);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出项目
|
||||
* GET /api/projects/export
|
||||
* Query: ids, format(csv|excel)
|
||||
*/
|
||||
public function export(): void
|
||||
{
|
||||
$ids = $_GET['ids'] ?? [];
|
||||
$format = strtolower($_GET['format'] ?? 'csv');
|
||||
if (!in_array($format, ['csv', 'excel'])) {
|
||||
$format = 'csv';
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$where = 'WHERE deleted_at IS NULL';
|
||||
$params = [];
|
||||
|
||||
if (!empty($ids)) {
|
||||
$ids = is_array($ids) ? $ids : explode(',', $ids);
|
||||
$ids = array_filter(array_map('intval', $ids));
|
||||
if (!empty($ids)) {
|
||||
$where .= ' AND id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')';
|
||||
$params = array_merge($params, $ids);
|
||||
}
|
||||
}
|
||||
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT id, name, description, api_key, status, created_at FROM {$db->table('projects')} {$where} ORDER BY id DESC LIMIT 50000",
|
||||
$params
|
||||
);
|
||||
|
||||
if ($format === 'excel') {
|
||||
$filename = 'projects_export_' . date('YmdHis') . '.xls';
|
||||
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
$html = '<table border="1"><tr><th>ID</th><th>项目名称</th><th>描述</th><th>API Key</th><th>状态</th><th>创建时间</th></tr>';
|
||||
foreach ($rows as $row) {
|
||||
$html .= '<tr>';
|
||||
$html .= '<td>' . htmlspecialchars($row['id']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['name']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['description'] ?? '') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['api_key']) . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['status'] == 1 ? '启用' : '禁用') . '</td>';
|
||||
$html .= '<td>' . htmlspecialchars($row['created_at']) . '</td>';
|
||||
$html .= '</tr>';
|
||||
}
|
||||
$html .= '</table>';
|
||||
echo $html;
|
||||
exit;
|
||||
}
|
||||
|
||||
$filename = 'projects_export_' . date('YmdHis') . '.csv';
|
||||
header('Content-Type: text/csv; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
header('Cache-Control: no-cache');
|
||||
|
||||
$output = fopen('php://output', 'w');
|
||||
fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
|
||||
fputcsv($output, ['ID', '项目名称', '描述', 'API Key', '状态', '创建时间']);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($output, [
|
||||
$row['id'],
|
||||
$row['name'],
|
||||
$row['description'] ?? '',
|
||||
$row['api_key'],
|
||||
$row['status'] == 1 ? '启用' : '禁用',
|
||||
$row['created_at'],
|
||||
]);
|
||||
}
|
||||
fclose($output);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
<?php
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Controller;
|
||||
use App\Core\Database;
|
||||
use App\Core\Validator;
|
||||
|
||||
/**
|
||||
* 公开接口控制器
|
||||
* 包含:购买页、查询页、授权验证、支付回调
|
||||
*/
|
||||
class PublicController extends Controller
|
||||
{
|
||||
/**
|
||||
* 获取可购买的项目列表
|
||||
*/
|
||||
public function projects(): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$projects = $db->fetchAll(
|
||||
"SELECT id, name, description FROM {$db->table('projects')} WHERE status = 1 AND deleted_at IS NULL ORDER BY id DESC"
|
||||
);
|
||||
$this->success($projects);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取项目的卡密类型(套餐)列表
|
||||
*/
|
||||
public function cardTypes(int $projectId): void
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$types = $db->fetchAll(
|
||||
"SELECT id, name, description, duration_days, price, original_price FROM {$db->table('card_types')}
|
||||
WHERE project_id = ? AND status = 1 ORDER BY sort ASC",
|
||||
[$projectId]
|
||||
);
|
||||
$this->success($types);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建订单并发起支付
|
||||
*/
|
||||
public function createOrder(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$validator = new Validator($input);
|
||||
if (!$validator->validate([
|
||||
'project_id' => 'required|integer',
|
||||
'card_type_id' => 'required|integer',
|
||||
'pay_type' => 'required',
|
||||
])) {
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
$projectId = (int) $input['project_id'];
|
||||
$cardTypeId = (int) $input['card_type_id'];
|
||||
$payType = $input['pay_type'];
|
||||
$contactInfo = $input['contact_info'] ?? '';
|
||||
$couponCode = strtoupper(trim($input['coupon_code'] ?? ''));
|
||||
$botQq = trim($input['bot_qq'] ?? '');
|
||||
$contactQq = trim($input['contact_qq'] ?? '');
|
||||
|
||||
if (!in_array($payType, ['alipay', 'wxpay', 'qqpay'])) {
|
||||
$this->error('不支持的支付方式');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// 验证项目
|
||||
$project = $db->fetch(
|
||||
"SELECT id, name FROM {$db->table('projects')} WHERE id = ? AND status = 1 AND deleted_at IS NULL",
|
||||
[$projectId]
|
||||
);
|
||||
if (!$project) {
|
||||
$this->error('项目不存在或已下架');
|
||||
}
|
||||
|
||||
// 验证卡密类型
|
||||
$cardType = $db->fetch(
|
||||
"SELECT * FROM {$db->table('card_types')} WHERE id = ? AND project_id = ? AND status = 1",
|
||||
[$cardTypeId, $projectId]
|
||||
);
|
||||
if (!$cardType) {
|
||||
$this->error('套餐不存在或已下架');
|
||||
}
|
||||
|
||||
if ((float) $cardType['price'] <= 0) {
|
||||
$this->error('套餐价格配置错误');
|
||||
}
|
||||
|
||||
$originalAmount = (float) $cardType['price'];
|
||||
$finalAmount = $originalAmount;
|
||||
$validCoupon = null;
|
||||
|
||||
// 验证优惠码
|
||||
if ($couponCode) {
|
||||
$validCoupon = $db->fetch(
|
||||
"SELECT * FROM {$db->table('coupons')} WHERE code = ? AND status = 1",
|
||||
[$couponCode]
|
||||
);
|
||||
if (!$validCoupon) {
|
||||
$this->error('优惠码不存在或已失效');
|
||||
}
|
||||
if ($validCoupon['expire_at'] && strtotime($validCoupon['expire_at']) < time()) {
|
||||
$this->error('优惠码已过期');
|
||||
}
|
||||
if ($validCoupon['max_use_count'] > 0 && $validCoupon['used_count'] >= $validCoupon['max_use_count']) {
|
||||
$this->error('优惠码已达使用上限');
|
||||
}
|
||||
if ($validCoupon['min_amount'] > 0 && $originalAmount < $validCoupon['min_amount']) {
|
||||
$this->error("订单金额需满¥{$validCoupon['min_amount']}");
|
||||
}
|
||||
if ($validCoupon['project_ids']) {
|
||||
$allowedProjects = array_map('trim', explode(',', $validCoupon['project_ids']));
|
||||
if (!in_array((string) $projectId, $allowedProjects)) {
|
||||
$this->error('该优惠码不适用于此项目');
|
||||
}
|
||||
}
|
||||
$discountAmount = round($originalAmount * ($validCoupon['discount_percent'] / 100), 2);
|
||||
$finalAmount = max(0.01, round($originalAmount - $discountAmount, 2));
|
||||
}
|
||||
|
||||
// 生成订单号
|
||||
$orderNo = date('YmdHis') . rand(10000, 99999);
|
||||
|
||||
$expireMinutes = 15;
|
||||
$expiredAt = date('Y-m-d H:i:s', strtotime("+{$expireMinutes} minutes"));
|
||||
|
||||
$orderId = $db->insert(
|
||||
"INSERT INTO {$db->table('orders')} (order_no, project_id, card_type_id, amount, pay_amount, pay_type, status, contact_info, coupon_code, expired_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, NOW())",
|
||||
[
|
||||
$orderNo,
|
||||
$projectId,
|
||||
$cardTypeId,
|
||||
$originalAmount,
|
||||
$finalAmount,
|
||||
$payType,
|
||||
$contactInfo,
|
||||
$couponCode,
|
||||
$expiredAt,
|
||||
]
|
||||
);
|
||||
|
||||
// 优惠码使用计数+1
|
||||
if ($validCoupon) {
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('coupons')} SET used_count = used_count + 1 WHERE id = ?",
|
||||
[$validCoupon['id']]
|
||||
);
|
||||
}
|
||||
|
||||
// 构建支付参数
|
||||
$payUrl = $this->buildPayUrl($orderNo, $finalAmount, $payType, $project['name'] . ' - ' . $cardType['name']);
|
||||
|
||||
$this->success([
|
||||
'order_id' => $orderId,
|
||||
'order_no' => $orderNo,
|
||||
'amount' => $originalAmount,
|
||||
'pay_amount' => $finalAmount,
|
||||
'coupon_code' => $couponCode,
|
||||
'pay_url' => $payUrl,
|
||||
'expired_at' => $expiredAt,
|
||||
], '订单创建成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建支付链接
|
||||
*/
|
||||
private function buildPayUrl(string $orderNo, float $amount, string $payType, string $subject): string
|
||||
{
|
||||
// 优先从数据库读取支付配置,回退到文件配置
|
||||
$apiUrl = $this->getPaymentConfig('payment_api_url', config('app.payment.api_url', ''));
|
||||
$appId = $this->getPaymentConfig('payment_app_id', config('app.payment.app_id', ''));
|
||||
$appKey = $this->getPaymentConfig('payment_app_key', config('app.payment.app_key', ''));
|
||||
$notifyUrl = config('app.payment.notify_url', '');
|
||||
$returnUrl = config('app.payment.return_url', '');
|
||||
|
||||
$typeMap = ['alipay' => 'alipay', 'wxpay' => 'wxpay', 'qqpay' => 'qqpay'];
|
||||
|
||||
$params = [
|
||||
'pid' => $appId,
|
||||
'type' => $typeMap[$payType] ?? $payType,
|
||||
'out_trade_no' => $orderNo,
|
||||
'notify_url' => $notifyUrl,
|
||||
'return_url' => $returnUrl,
|
||||
'name' => $subject,
|
||||
'money' => $amount,
|
||||
];
|
||||
|
||||
// 签名
|
||||
ksort($params);
|
||||
$signStr = '';
|
||||
foreach ($params as $k => $v) {
|
||||
$signStr .= $k . '=' . $v . '&';
|
||||
}
|
||||
$signStr = rtrim($signStr, '&');
|
||||
$params['sign'] = md5($signStr . $appKey);
|
||||
$params['sign_type'] = 'MD5';
|
||||
|
||||
return $apiUrl . '/submit.php?' . http_build_query($params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从数据库获取支付配置
|
||||
*/
|
||||
private function getPaymentConfig(string $key, string $default = ''): string
|
||||
{
|
||||
try {
|
||||
$db = Database::getInstance();
|
||||
$value = $db->fetchColumn(
|
||||
"SELECT `value` FROM {$db->table('configs')} WHERE `key` = ?",
|
||||
[$key]
|
||||
);
|
||||
return $value !== false ? $value : $default;
|
||||
} catch (\Throwable $e) {
|
||||
return $default;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 支付异步回调
|
||||
*/
|
||||
public function paymentNotify(): void
|
||||
{
|
||||
$tradeNo = $_GET['trade_no'] ?? $_POST['trade_no'] ?? '';
|
||||
$outTradeNo = $_GET['out_trade_no'] ?? $_POST['out_trade_no'] ?? '';
|
||||
$tradeStatus = $_GET['trade_status'] ?? $_POST['trade_status'] ?? '';
|
||||
$sign = $_GET['sign'] ?? $_POST['sign'] ?? '';
|
||||
|
||||
// 验证签名
|
||||
$appKey = $this->getPaymentConfig('payment_app_key', config('app.payment.app_key', ''));
|
||||
$params = $_GET + $_POST;
|
||||
unset($params['sign'], $params['sign_type']);
|
||||
ksort($params);
|
||||
$signStr = '';
|
||||
foreach ($params as $k => $v) {
|
||||
$signStr .= $k . '=' . $v . '&';
|
||||
}
|
||||
$signStr = rtrim($signStr, '&');
|
||||
$calcSign = md5($signStr . $appKey);
|
||||
|
||||
if ($calcSign !== $sign) {
|
||||
echo 'sign error';
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($tradeStatus !== 'TRADE_SUCCESS') {
|
||||
echo 'fail';
|
||||
exit;
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$order = $db->fetch(
|
||||
"SELECT * FROM {$db->table('orders')} WHERE order_no = ? AND status = 'pending'",
|
||||
[$outTradeNo]
|
||||
);
|
||||
|
||||
if (!$order) {
|
||||
echo 'order not found';
|
||||
exit;
|
||||
}
|
||||
|
||||
// 更新订单
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('orders')} SET trade_no = ?, status = 'paid', paid_at = NOW() WHERE id = ?",
|
||||
[$tradeNo, $order['id']]
|
||||
);
|
||||
|
||||
// 生成卡密发货
|
||||
$orderController = new OrderController();
|
||||
$orderController->processOrderPaid($order['id']);
|
||||
|
||||
$db->commit();
|
||||
} catch (\Throwable $e) {
|
||||
$db->rollback();
|
||||
error_log('Payment notify error: ' . $e->getMessage());
|
||||
echo 'error';
|
||||
exit;
|
||||
}
|
||||
|
||||
echo 'success';
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询卡密状态
|
||||
*/
|
||||
public function queryCard(): void
|
||||
{
|
||||
$cardKey = $this->getInput('card_key', '');
|
||||
|
||||
if (empty($cardKey)) {
|
||||
$this->error('请输入卡密');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$card = $db->fetch(
|
||||
"SELECT c.card_key, c.type, c.status, c.duration_days, c.bind_info, c.bound_at, c.expire_time, c.created_at,
|
||||
p.name AS project_name
|
||||
FROM {$db->table('cards')} c
|
||||
LEFT JOIN {$db->table('projects')} p ON c.project_id = p.id
|
||||
WHERE c.card_key = ?",
|
||||
[$cardKey]
|
||||
);
|
||||
|
||||
if (!$card) {
|
||||
$this->error('卡密不存在');
|
||||
}
|
||||
|
||||
$card['bind_info'] = json_decode($card['bind_info'] ?? '{}', true);
|
||||
|
||||
$statusText = match ($card['status']) {
|
||||
'unused' => '未使用',
|
||||
'used' => '已使用',
|
||||
'disabled' => '已禁用',
|
||||
default => '未知',
|
||||
};
|
||||
|
||||
$card['status_text'] = $statusText;
|
||||
$card['is_expired'] = $card['expire_time'] && strtotime($card['expire_time']) < time();
|
||||
|
||||
$this->success($card);
|
||||
}
|
||||
|
||||
/**
|
||||
* 授权验证接口 (客户端调用)
|
||||
* Header: X-Api-Key: {project_api_key}
|
||||
* POST: {card_key, machine_id, ip, device_info}
|
||||
*/
|
||||
public function verify(): void
|
||||
{
|
||||
$projectId = $_SERVER['HTTP_X_PROJECT_ID'] ?? 0;
|
||||
$input = $this->getJsonInput();
|
||||
|
||||
$cardKey = $input['card_key'] ?? '';
|
||||
$machineId = $input['machine_id'] ?? '';
|
||||
$deviceIp = $input['ip'] ?? clientIp();
|
||||
$deviceInfo = $input['device_info'] ?? '';
|
||||
|
||||
if (empty($cardKey) || empty($machineId)) {
|
||||
$this->error('参数不完整', 400);
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
$card = $db->fetch(
|
||||
"SELECT * FROM {$db->table('cards')} WHERE card_key = ? AND project_id = ?",
|
||||
[$cardKey, $projectId]
|
||||
);
|
||||
|
||||
if (!$card) {
|
||||
// 尝试查找跨项目卡密(兼容)
|
||||
$card = $db->fetch(
|
||||
"SELECT * FROM {$db->table('cards')} WHERE card_key = ?",
|
||||
[$cardKey]
|
||||
);
|
||||
if (!$card) {
|
||||
$this->success(['valid' => false, 'message' => '卡密不存在'], 'ok');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if ($card['status'] === 'disabled') {
|
||||
$this->success(['valid' => false, 'message' => '卡密已被禁用'], 'ok');
|
||||
return;
|
||||
}
|
||||
|
||||
if ($card['status'] === 'unused') {
|
||||
// 首次激活:绑定机器指纹
|
||||
$bindInfo = [
|
||||
'machine_id' => $machineId,
|
||||
'ip' => $deviceIp,
|
||||
'device_info' => $deviceInfo,
|
||||
'first_bind_at' => date('Y-m-d H:i:s'),
|
||||
];
|
||||
|
||||
$expireTime = null;
|
||||
if ($card['duration_days'] > 0) {
|
||||
$expireTime = date('Y-m-d H:i:s', strtotime("+{$card['duration_days']} days"));
|
||||
}
|
||||
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('cards')} SET status = 'used', bind_info = ?, bound_at = NOW(), expire_time = ? WHERE id = ?",
|
||||
[json_encode($bindInfo, JSON_UNESCAPED_UNICODE), $expireTime, $card['id']]
|
||||
);
|
||||
|
||||
$this->success([
|
||||
'valid' => true,
|
||||
'message' => '激活成功',
|
||||
'type' => $card['type'],
|
||||
'duration_days' => $card['duration_days'],
|
||||
'expire_time' => $expireTime,
|
||||
'is_permanent' => $card['duration_days'] == 0,
|
||||
], 'ok');
|
||||
return;
|
||||
}
|
||||
|
||||
if ($card['status'] === 'used') {
|
||||
// 验证绑定
|
||||
$bindInfo = json_decode($card['bind_info'] ?? '{}', true);
|
||||
|
||||
if (($bindInfo['machine_id'] ?? '') !== $machineId) {
|
||||
$this->success(['valid' => false, 'message' => '设备不匹配,请使用绑定的设备'], 'ok');
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否过期
|
||||
if ($card['expire_time'] && strtotime($card['expire_time']) < time()) {
|
||||
$this->success(['valid' => false, 'message' => '授权已过期'], 'ok');
|
||||
return;
|
||||
}
|
||||
|
||||
$this->success([
|
||||
'valid' => true,
|
||||
'message' => '授权有效',
|
||||
'type' => $card['type'],
|
||||
'duration_days' => $card['duration_days'],
|
||||
'expire_time' => $card['expire_time'],
|
||||
'bound_at' => $card['bound_at'],
|
||||
'is_permanent' => $card['duration_days'] == 0,
|
||||
'remaining_days' => $card['expire_time'] ? max(0, ceil((strtotime($card['expire_time']) - time()) / 86400)) : null,
|
||||
], 'ok');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询订单状态
|
||||
*/
|
||||
public function queryOrder(): void
|
||||
{
|
||||
$orderNo = $this->getInput('order_no', '');
|
||||
|
||||
if (empty($orderNo)) {
|
||||
$this->error('缺少订单号');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$order = $db->fetch(
|
||||
"SELECT o.id, o.order_no, o.amount, o.status, o.paid_at, o.created_at,
|
||||
c.card_key,
|
||||
p.name AS project_name,
|
||||
ct.name AS card_type_name
|
||||
FROM {$db->table('orders')} o
|
||||
LEFT JOIN {$db->table('cards')} c ON o.card_id = c.id
|
||||
LEFT JOIN {$db->table('projects')} p ON o.project_id = p.id
|
||||
LEFT JOIN {$db->table('card_types')} ct ON o.card_type_id = ct.id
|
||||
WHERE o.order_no = ?",
|
||||
[$orderNo]
|
||||
);
|
||||
|
||||
if (!$order) {
|
||||
$this->error('订单不存在');
|
||||
}
|
||||
|
||||
$this->success($order);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Controller;
|
||||
use App\Core\Database;
|
||||
use App\Core\Validator;
|
||||
|
||||
/**
|
||||
* 系统配置控制器
|
||||
*/
|
||||
class SystemController extends Controller
|
||||
{
|
||||
/**
|
||||
* 获取系统配置 (支持批量获取)
|
||||
* GET /api/system/configs?keys=key1,key2,key3
|
||||
*/
|
||||
public function getConfigs(): void
|
||||
{
|
||||
$keysStr = $_GET['keys'] ?? '';
|
||||
$db = Database::getInstance();
|
||||
|
||||
if ($keysStr) {
|
||||
$keys = explode(',', $keysStr);
|
||||
$placeholders = implode(',', array_fill(0, count($keys), '?'));
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT `key`, `value` FROM {$db->table('configs')} WHERE `key` IN ({$placeholders})",
|
||||
$keys
|
||||
);
|
||||
} else {
|
||||
$rows = $db->fetchAll(
|
||||
"SELECT `key`, `value`, `description` FROM {$db->table('configs')} ORDER BY id ASC"
|
||||
);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($rows as $row) {
|
||||
$result[$row['key']] = $row['value'];
|
||||
}
|
||||
|
||||
$this->success($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存系统配置 (批量)
|
||||
* POST /api/system/configs
|
||||
* Body: { "configs": { "key1": "value1", "key2": "value2" } }
|
||||
*/
|
||||
public function saveConfigs(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$configs = $input['configs'] ?? [];
|
||||
|
||||
if (empty($configs) || !is_array($configs)) {
|
||||
$this->error('参数错误');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$db->beginTransaction();
|
||||
|
||||
try {
|
||||
foreach ($configs as $key => $value) {
|
||||
// 使用 INSERT ... ON DUPLICATE KEY UPDATE
|
||||
$db->execute(
|
||||
"INSERT INTO {$db->table('configs')} (`key`, `value`) VALUES (?, ?)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`)",
|
||||
[$key, $value]
|
||||
);
|
||||
}
|
||||
$db->commit();
|
||||
} catch (\Throwable $e) {
|
||||
$db->rollback();
|
||||
$this->error('保存失败: ' . $e->getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
logger('update_system_config', 'config', 0, $configs);
|
||||
$this->success(null, '配置保存成功');
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试支付网关连接
|
||||
* POST /api/system/test-payment
|
||||
*/
|
||||
public function testPayment(): void
|
||||
{
|
||||
$input = $this->getJsonInput();
|
||||
$apiUrl = $input['api_url'] ?? '';
|
||||
$appId = $input['app_id'] ?? '';
|
||||
$appKey = $input['app_key'] ?? '';
|
||||
|
||||
if (empty($apiUrl) || empty($appId) || empty($appKey)) {
|
||||
$this->error('参数不完整');
|
||||
}
|
||||
|
||||
// 构建测试请求参数
|
||||
$params = [
|
||||
'pid' => $appId,
|
||||
'type' => 'alipay',
|
||||
'out_trade_no' => 'TEST_' . date('YmdHis'),
|
||||
'notify_url' => '',
|
||||
'return_url' => '',
|
||||
'name' => 'test',
|
||||
'money' => '0.01',
|
||||
];
|
||||
|
||||
ksort($params);
|
||||
$signStr = '';
|
||||
foreach ($params as $k => $v) {
|
||||
$signStr .= $k . '=' . $v . '&';
|
||||
}
|
||||
$signStr = rtrim($signStr, '&');
|
||||
$params['sign'] = md5($signStr . $appKey);
|
||||
$params['sign_type'] = 'MD5';
|
||||
|
||||
// 测试连接 (尝试请求网关)
|
||||
$testUrl = rtrim($apiUrl, '/submit.php') . '/api.php?act=query&pid=' . $appId . '&key=' . $appKey;
|
||||
|
||||
$ch = curl_init();
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_URL => $testUrl,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
CURLOPT_SSL_VERIFYHOST => false,
|
||||
CURLOPT_USERAGENT => 'CardAuth/1.0',
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$error = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($error) {
|
||||
$this->error('连接失败: ' . $error);
|
||||
return;
|
||||
}
|
||||
|
||||
if ($httpCode >= 200 && $httpCode < 300) {
|
||||
$this->success([
|
||||
'http_code' => $httpCode,
|
||||
'response' => $response,
|
||||
], '连接测试成功,网关可达');
|
||||
} else {
|
||||
$this->error("连接失败,HTTP状态码: {$httpCode}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
namespace App\Core;
|
||||
|
||||
/**
|
||||
* 应用程序核心类
|
||||
* 负责请求分发、路由匹配、中间件执行
|
||||
*/
|
||||
class Application
|
||||
{
|
||||
private Router $router;
|
||||
private array $middleware = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->router = new Router();
|
||||
$this->loadRoutes();
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载路由文件
|
||||
*/
|
||||
private function loadRoutes(): void
|
||||
{
|
||||
$this->router = require ROUTES_PATH . '/api.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行应用
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
// 跨域处理
|
||||
$this->handleCors();
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
||||
http_response_code(204);
|
||||
exit;
|
||||
}
|
||||
|
||||
$method = $_SERVER['REQUEST_METHOD'];
|
||||
$uri = $this->parseUri();
|
||||
|
||||
// 匹配路由
|
||||
$route = $this->router->match($method, $uri);
|
||||
|
||||
if (!$route) {
|
||||
$this->jsonResponse(404, '接口不存在');
|
||||
return;
|
||||
}
|
||||
|
||||
// 执行路由中间件和处理器
|
||||
$this->dispatch($route);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析请求URI
|
||||
*/
|
||||
private function parseUri(): string
|
||||
{
|
||||
$uri = $_SERVER['REQUEST_URI'] ?? '/';
|
||||
$uri = parse_url($uri, PHP_URL_PATH);
|
||||
$uri = trim($uri, '/');
|
||||
// 移除入口文件前缀(仅当 SCRIPT_NAME 是真实脚本文件时,非 PHP 内置服务器转发的 URI)
|
||||
$scriptName = trim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/');
|
||||
$scriptBasename = basename($_SERVER['SCRIPT_FILENAME'] ?? '');
|
||||
if ($scriptName && $scriptBasename && str_ends_with($_SERVER['SCRIPT_NAME'] ?? '', $scriptBasename) && strpos($uri, $scriptName) === 0) {
|
||||
$uri = substr($uri, strlen($scriptName));
|
||||
}
|
||||
$uri = trim($uri, '/');
|
||||
return $uri ?: '/';
|
||||
}
|
||||
|
||||
/**
|
||||
* 分发路由
|
||||
*/
|
||||
private function dispatch(array $route): void
|
||||
{
|
||||
$middleware = $route['middleware'] ?? [];
|
||||
$handler = $route['handler'];
|
||||
$params = array_values($route['params'] ?? []);
|
||||
|
||||
// 构建中间件链
|
||||
$pipeline = array_reduce(
|
||||
array_reverse($middleware),
|
||||
function ($next, $m) {
|
||||
return function ($request) use ($m, $next) {
|
||||
$instance = is_object($m) ? $m : new $m();
|
||||
return $instance->handle($request, $next);
|
||||
};
|
||||
},
|
||||
function ($request) use ($handler, $params) {
|
||||
if (is_array($handler) && count($handler) === 2) {
|
||||
[$class, $method] = $handler;
|
||||
$controller = new $class();
|
||||
return call_user_func_array([$controller, $method], $params);
|
||||
}
|
||||
if (is_callable($handler)) {
|
||||
return call_user_func_array($handler, $params);
|
||||
}
|
||||
return $this->jsonResponse(500, '无效的路由处理器');
|
||||
}
|
||||
);
|
||||
|
||||
$pipeline([]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理跨域请求
|
||||
*/
|
||||
private function handleCors(): void
|
||||
{
|
||||
$origins = config('app.allowed_origins', ['*']);
|
||||
$origin = $_SERVER['HTTP_ORIGIN'] ?? '*';
|
||||
|
||||
if (in_array('*', $origins) || in_array($origin, $origins)) {
|
||||
header('Access-Control-Allow-Origin: ' . ($origins === ['*'] ? '*' : $origin));
|
||||
}
|
||||
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS');
|
||||
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, X-Api-Key');
|
||||
header('Access-Control-Max-Age: 86400');
|
||||
header('Access-Control-Allow-Credentials: true');
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON响应
|
||||
*/
|
||||
public static function jsonResponse(int $code, string $message, mixed $data = null, int $httpCode = 200): never
|
||||
{
|
||||
http_response_code($httpCode);
|
||||
echo json_encode([
|
||||
'code' => $code,
|
||||
'message' => $message,
|
||||
'data' => $data,
|
||||
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
namespace App\Core;
|
||||
|
||||
/**
|
||||
* 控制器基类
|
||||
*/
|
||||
abstract class Controller
|
||||
{
|
||||
/**
|
||||
* 获取请求体JSON数据
|
||||
*/
|
||||
protected function getJsonInput(): array
|
||||
{
|
||||
$input = file_get_contents('php://input');
|
||||
return json_decode($input, true) ?: [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取GET参数
|
||||
*/
|
||||
protected function getQuery(string $key, mixed $default = null): mixed
|
||||
{
|
||||
return $_GET[$key] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取请求参数(合并GET和JSON Body)
|
||||
*/
|
||||
protected function getInput(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$json = $this->getJsonInput();
|
||||
return $json[$key] ?? $_GET[$key] ?? $_POST[$key] ?? $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功响应
|
||||
*/
|
||||
protected function success(mixed $data = null, string $message = '操作成功', int $code = 200): never
|
||||
{
|
||||
Application::jsonResponse($code, $message, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回错误响应
|
||||
*/
|
||||
protected function error(string $message = '操作失败', int $code = 400, mixed $data = null, int $httpCode = 200): never
|
||||
{
|
||||
Application::jsonResponse($code, $message, $data, $httpCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户ID(由Auth中间件注入)
|
||||
*/
|
||||
protected function getUserId(): ?int
|
||||
{
|
||||
return $_SERVER['HTTP_X_USER_ID'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户角色
|
||||
*/
|
||||
protected function getUserRole(): string
|
||||
{
|
||||
return $_SERVER['HTTP_X_USER_ROLE'] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户信息(由Auth中间件从数据库实时刷新)
|
||||
*/
|
||||
protected function getCurrentUser(): ?array
|
||||
{
|
||||
$userId = $this->getUserId();
|
||||
if (!$userId) return null;
|
||||
|
||||
return [
|
||||
'id' => (int) $userId,
|
||||
'username' => $_SERVER['HTTP_X_USER_NAME'] ?? '',
|
||||
'nickname' => $_SERVER['HTTP_X_USER_NICKNAME'] ?? '',
|
||||
'role' => $_SERVER['HTTP_X_USER_ROLE'] ?? '',
|
||||
'parent_id' => (int) ($_SERVER['HTTP_X_USER_PARENT'] ?? 0),
|
||||
'project_ids' => json_decode($_SERVER['HTTP_X_USER_PROJECT_IDS'] ?? '[]', true) ?: [],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
namespace App\Core;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
|
||||
/**
|
||||
* 数据库操作类 (PDO Singleton)
|
||||
*/
|
||||
class Database
|
||||
{
|
||||
private static ?Database $instance = null;
|
||||
private PDO $pdo;
|
||||
private array $config;
|
||||
|
||||
private function __construct()
|
||||
{
|
||||
$this->config = require CONFIG_PATH . '/database.php';
|
||||
$this->connect();
|
||||
}
|
||||
|
||||
private function connect(): void
|
||||
{
|
||||
$dsn = sprintf(
|
||||
'%s:host=%s;port=%s;dbname=%s;charset=%s',
|
||||
$this->config['driver'],
|
||||
$this->config['host'],
|
||||
$this->config['port'],
|
||||
$this->config['database'],
|
||||
$this->config['charset']
|
||||
);
|
||||
|
||||
$options = [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
PDO::ATTR_EMULATE_PREPARES => false,
|
||||
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$this->config['charset']} COLLATE {$this->config['collation']}",
|
||||
];
|
||||
|
||||
try {
|
||||
$this->pdo = new PDO($dsn, $this->config['username'], $this->config['password'], $options);
|
||||
} catch (PDOException $e) {
|
||||
throw new \RuntimeException('数据库连接失败: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static function getInstance(): self
|
||||
{
|
||||
if (self::$instance === null) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public function getPdo(): PDO
|
||||
{
|
||||
return $this->pdo;
|
||||
}
|
||||
|
||||
public function getPrefix(): string
|
||||
{
|
||||
return $this->config['prefix'];
|
||||
}
|
||||
|
||||
public function table(string $name): string
|
||||
{
|
||||
return $this->config['prefix'] . $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行查询并返回所有结果
|
||||
*/
|
||||
public function fetchAll(string $sql, array $params = []): array
|
||||
{
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行查询并返回单行结果
|
||||
*/
|
||||
public function fetch(string $sql, array $params = []): ?array
|
||||
{
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$result = $stmt->fetch();
|
||||
return $result ?: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行插入并返回最后插入ID
|
||||
*/
|
||||
public function insert(string $sql, array $params = []): int
|
||||
{
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
return (int) $this->pdo->lastInsertId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行更新/删除
|
||||
*/
|
||||
public function execute(string $sql, array $params = []): int
|
||||
{
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
return $stmt->rowCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* 开启事务
|
||||
*/
|
||||
public function beginTransaction(): void
|
||||
{
|
||||
$this->pdo->beginTransaction();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交事务
|
||||
*/
|
||||
public function commit(): void
|
||||
{
|
||||
$this->pdo->commit();
|
||||
}
|
||||
|
||||
/**
|
||||
* 回滚事务
|
||||
*/
|
||||
public function rollback(): void
|
||||
{
|
||||
$this->pdo->rollBack();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单列值
|
||||
*/
|
||||
public function fetchColumn(string $sql, array $params = [], int $column = 0): mixed
|
||||
{
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
return $stmt->fetchColumn($column);
|
||||
}
|
||||
|
||||
private function __clone() {}
|
||||
public function __wakeup()
|
||||
{
|
||||
throw new \RuntimeException('Cannot unserialize singleton');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
namespace App\Core;
|
||||
|
||||
/**
|
||||
* 中间件基类
|
||||
*/
|
||||
abstract class Middleware
|
||||
{
|
||||
/**
|
||||
* 处理请求
|
||||
* @param array $request 请求上下文
|
||||
* @param callable $next 下一个处理器
|
||||
* @return mixed
|
||||
*/
|
||||
abstract public function handle(array $request, callable $next): mixed;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
namespace App\Core;
|
||||
|
||||
/**
|
||||
* 简易路由器
|
||||
* 支持GET/POST/PUT/DELETE/PATCH方法,支持中间件
|
||||
*/
|
||||
class Router
|
||||
{
|
||||
private array $routes = [];
|
||||
private array $groupMiddleware = [];
|
||||
private string $groupPrefix = '';
|
||||
|
||||
/**
|
||||
* 注册路由
|
||||
*/
|
||||
public function add(string $method, string $uri, mixed $handler, array $middleware = []): void
|
||||
{
|
||||
$uri = trim($this->groupPrefix . '/' . trim($uri, '/'), '/');
|
||||
$uri = $uri ?: '/';
|
||||
$this->routes[] = [
|
||||
'method' => strtoupper($method),
|
||||
'uri' => $uri,
|
||||
'pattern' => $this->compilePattern($uri),
|
||||
'handler' => $handler,
|
||||
'middleware' => array_merge($this->groupMiddleware, $middleware),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 路由分组
|
||||
*/
|
||||
public function group(string $prefix, callable $callback, array $middleware = []): void
|
||||
{
|
||||
$prevPrefix = $this->groupPrefix;
|
||||
$prevMiddleware = $this->groupMiddleware;
|
||||
|
||||
$this->groupPrefix = $prevPrefix . '/' . trim($prefix, '/');
|
||||
$this->groupMiddleware = array_merge($prevMiddleware, $middleware);
|
||||
|
||||
$callback($this);
|
||||
|
||||
$this->groupPrefix = $prevPrefix;
|
||||
$this->groupMiddleware = $prevMiddleware;
|
||||
}
|
||||
|
||||
/**
|
||||
* 编译路由模式
|
||||
*/
|
||||
private function compilePattern(string $uri): string
|
||||
{
|
||||
$pattern = preg_replace('/\{(\w+)\}/', '(?P<$1>[^/]+)', $uri);
|
||||
return '#^' . $pattern . '$#';
|
||||
}
|
||||
|
||||
/**
|
||||
* 匹配路由
|
||||
*/
|
||||
public function match(string $method, string $uri): ?array
|
||||
{
|
||||
foreach ($this->routes as $route) {
|
||||
if ($route['method'] !== strtoupper($method)) continue;
|
||||
|
||||
if (preg_match($route['pattern'], $uri, $matches)) {
|
||||
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
|
||||
return [
|
||||
'handler' => $route['handler'],
|
||||
'middleware' => $route['middleware'],
|
||||
'params' => $params,
|
||||
];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 便捷方法
|
||||
public function get(string $uri, mixed $handler, array $middleware = []): void
|
||||
{
|
||||
$this->add('GET', $uri, $handler, $middleware);
|
||||
}
|
||||
public function post(string $uri, mixed $handler, array $middleware = []): void
|
||||
{
|
||||
$this->add('POST', $uri, $handler, $middleware);
|
||||
}
|
||||
public function put(string $uri, mixed $handler, array $middleware = []): void
|
||||
{
|
||||
$this->add('PUT', $uri, $handler, $middleware);
|
||||
}
|
||||
public function delete(string $uri, mixed $handler, array $middleware = []): void
|
||||
{
|
||||
$this->add('DELETE', $uri, $handler, $middleware);
|
||||
}
|
||||
public function patch(string $uri, mixed $handler, array $middleware = []): void
|
||||
{
|
||||
$this->add('PATCH', $uri, $handler, $middleware);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
namespace App\Core;
|
||||
|
||||
/**
|
||||
* 输入验证器
|
||||
*/
|
||||
class Validator
|
||||
{
|
||||
private array $errors = [];
|
||||
private array $data;
|
||||
|
||||
public function __construct(array $data)
|
||||
{
|
||||
$this->data = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证规则
|
||||
*/
|
||||
public function validate(array $rules): bool
|
||||
{
|
||||
foreach ($rules as $field => $ruleSet) {
|
||||
$fieldRules = is_string($ruleSet) ? explode('|', $ruleSet) : $ruleSet;
|
||||
foreach ($fieldRules as $rule) {
|
||||
$params = [];
|
||||
if (str_contains($rule, ':')) {
|
||||
[$rule, $paramStr] = explode(':', $rule, 2);
|
||||
$params = explode(',', $paramStr);
|
||||
}
|
||||
$method = 'rule' . ucfirst($rule);
|
||||
if (method_exists($this, $method)) {
|
||||
$value = $this->data[$field] ?? null;
|
||||
$this->$method($field, $value, $params);
|
||||
}
|
||||
}
|
||||
}
|
||||
return empty($this->errors);
|
||||
}
|
||||
|
||||
public function getErrors(): array
|
||||
{
|
||||
return $this->errors;
|
||||
}
|
||||
|
||||
public function getFirstError(): string
|
||||
{
|
||||
return $this->errors[0] ?? '验证失败';
|
||||
}
|
||||
|
||||
private function addError(string $field, string $message): void
|
||||
{
|
||||
$this->errors[] = $message;
|
||||
}
|
||||
|
||||
private function ruleRequired(string $field, mixed $value, array $params): void
|
||||
{
|
||||
if ($value === null || $value === '' || (is_array($value) && empty($value))) {
|
||||
$this->addError($field, "{$field}不能为空");
|
||||
}
|
||||
}
|
||||
|
||||
private function ruleNumeric(string $field, mixed $value, array $params): void
|
||||
{
|
||||
if ($value !== null && $value !== '' && !is_numeric($value)) {
|
||||
$this->addError($field, "{$field}必须是数字");
|
||||
}
|
||||
}
|
||||
|
||||
private function ruleInteger(string $field, mixed $value, array $params): void
|
||||
{
|
||||
if ($value !== null && $value !== '' && !filter_var($value, FILTER_VALIDATE_INT)) {
|
||||
$this->addError($field, "{$field}必须是整数");
|
||||
}
|
||||
}
|
||||
|
||||
private function ruleEmail(string $field, mixed $value, array $params): void
|
||||
{
|
||||
if ($value !== null && $value !== '' && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
|
||||
$this->addError($field, "{$field}格式不正确");
|
||||
}
|
||||
}
|
||||
|
||||
private function ruleMin(string $field, mixed $value, array $params): void
|
||||
{
|
||||
$min = (int) ($params[0] ?? 0);
|
||||
if ($value !== null && $value !== '' && mb_strlen((string)$value) < $min) {
|
||||
$this->addError($field, "{$field}长度不能少于{$min}个字符");
|
||||
}
|
||||
}
|
||||
|
||||
private function ruleMax(string $field, mixed $value, array $params): void
|
||||
{
|
||||
$max = (int) ($params[0] ?? 255);
|
||||
if ($value !== null && $value !== '' && mb_strlen((string)$value) > $max) {
|
||||
$this->addError($field, "{$field}长度不能超过{$max}个字符");
|
||||
}
|
||||
}
|
||||
|
||||
private function ruleIn(string $field, mixed $value, array $params): void
|
||||
{
|
||||
if ($value !== null && $value !== '' && !in_array($value, $params)) {
|
||||
$this->addError($field, "{$field}值不在允许范围内");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
/**
|
||||
* 全局辅助函数
|
||||
*/
|
||||
|
||||
/**
|
||||
* 获取配置值
|
||||
*/
|
||||
function config(string $key, mixed $default = null): mixed
|
||||
{
|
||||
static $configs = [];
|
||||
$keys = explode('.', $key, 2);
|
||||
|
||||
if (!isset($configs[$keys[0]])) {
|
||||
$file = CONFIG_PATH . '/' . $keys[0] . '.php';
|
||||
if (file_exists($file)) {
|
||||
$configs[$keys[0]] = require $file;
|
||||
} else {
|
||||
return $default;
|
||||
}
|
||||
}
|
||||
|
||||
if (count($keys) === 1) {
|
||||
return $configs[$keys[0]];
|
||||
}
|
||||
|
||||
return dotGet($configs[$keys[0]], $keys[1], $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* 点号访问数组
|
||||
*/
|
||||
function dotGet(array $array, string $key, mixed $default = null): mixed
|
||||
{
|
||||
$keys = explode('.', $key);
|
||||
foreach ($keys as $segment) {
|
||||
if (!is_array($array) || !array_key_exists($segment, $array)) {
|
||||
return $default;
|
||||
}
|
||||
$array = $array[$segment];
|
||||
}
|
||||
return $array;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取环境变量
|
||||
*/
|
||||
function env(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$value = $_ENV[$key] ?? getenv($key);
|
||||
if ($value === false) return $default;
|
||||
|
||||
return match (strtolower($value)) {
|
||||
'true', '(true)' => true,
|
||||
'false', '(false)' => false,
|
||||
'null', '(null)' => null,
|
||||
default => $value,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据库实例
|
||||
*/
|
||||
function db(): \App\Core\Database
|
||||
{
|
||||
return \App\Core\Database::getInstance();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成UUID v4
|
||||
*/
|
||||
function uuid(): string
|
||||
{
|
||||
$data = random_bytes(16);
|
||||
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
|
||||
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
|
||||
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机字符串
|
||||
*/
|
||||
function randomStr(int $length = 32): string
|
||||
{
|
||||
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
$str = '';
|
||||
for ($i = 0; $i < $length; $i++) {
|
||||
$str .= $chars[random_int(0, strlen($chars) - 1)];
|
||||
}
|
||||
return $str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 密码哈希
|
||||
*/
|
||||
function passwordHash(string $password): string
|
||||
{
|
||||
return password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证密码
|
||||
*/
|
||||
function passwordVerify(string $password, string $hash): bool
|
||||
{
|
||||
return password_verify($password, $hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取客户端IP
|
||||
*/
|
||||
function clientIp(): string
|
||||
{
|
||||
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
|
||||
$ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
|
||||
return trim($ips[0]);
|
||||
}
|
||||
if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
|
||||
return $_SERVER['HTTP_X_REAL_IP'];
|
||||
}
|
||||
return $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取User-Agent
|
||||
*/
|
||||
function userAgent(): string
|
||||
{
|
||||
return $_SERVER['HTTP_USER_AGENT'] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录日志(简化版)
|
||||
*/
|
||||
function logger(string $action, string $targetType = '', int $targetId = 0, array $detail = []): void
|
||||
{
|
||||
try {
|
||||
$db = db();
|
||||
$db->insert("INSERT INTO {$db->table('logs')} (user_id, action, target_type, target_id, detail, ip, user_agent, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())", [
|
||||
$_SERVER['HTTP_X_USER_ID'] ?? 0,
|
||||
$action,
|
||||
$targetType,
|
||||
$targetId,
|
||||
json_encode($detail, JSON_UNESCAPED_UNICODE),
|
||||
clientIp(),
|
||||
userAgent(),
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
error_log('Logger error: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
namespace App\Middleware;
|
||||
|
||||
use App\Core\Middleware;
|
||||
use App\Core\Application;
|
||||
|
||||
/**
|
||||
* API密钥验证中间件
|
||||
* 用于客户端授权验证接口
|
||||
*/
|
||||
class ApiKeyMiddleware extends Middleware
|
||||
{
|
||||
public function handle(array $request, callable $next): mixed
|
||||
{
|
||||
$apiKey = $_SERVER['HTTP_X_API_KEY'] ?? ($_GET['api_key'] ?? '');
|
||||
|
||||
if (empty($apiKey)) {
|
||||
Application::jsonResponse(401, '缺少API密钥', null, 401);
|
||||
}
|
||||
|
||||
$db = \App\Core\Database::getInstance();
|
||||
$project = $db->fetch(
|
||||
"SELECT id, api_key FROM {$db->table('projects')} WHERE api_key = ? AND status = 1 AND deleted_at IS NULL",
|
||||
[$apiKey]
|
||||
);
|
||||
|
||||
if (!$project) {
|
||||
Application::jsonResponse(403, 'API密钥无效或项目已禁用', null, 403);
|
||||
}
|
||||
|
||||
$_SERVER['HTTP_X_PROJECT_ID'] = $project['id'];
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
namespace App\Middleware;
|
||||
|
||||
use App\Core\Middleware;
|
||||
use App\Core\Application;
|
||||
use App\Core\Database;
|
||||
use App\Services\JwtService;
|
||||
|
||||
/**
|
||||
* JWT认证中间件
|
||||
* 验证Token并从数据库刷新用户信息,确保权限变更实时生效
|
||||
*/
|
||||
class AuthMiddleware extends Middleware
|
||||
{
|
||||
public function handle(array $request, callable $next): mixed
|
||||
{
|
||||
// 优先从 Authorization 请求头获取 Token
|
||||
$header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
|
||||
$token = '';
|
||||
|
||||
if (!empty($header) && str_starts_with($header, 'Bearer ')) {
|
||||
$token = substr($header, 7);
|
||||
}
|
||||
|
||||
// 兼容导出/下载场景:从 URL 查询参数获取 Token
|
||||
if (empty($token)) {
|
||||
$token = $_GET['token'] ?? '';
|
||||
}
|
||||
|
||||
if (empty($token)) {
|
||||
Application::jsonResponse(401, '未登录或Token已过期', null, 401);
|
||||
}
|
||||
|
||||
$jwtService = new JwtService();
|
||||
$tokenUser = $jwtService->verifyToken($token);
|
||||
|
||||
if (!$tokenUser) {
|
||||
Application::jsonResponse(401, 'Token无效或已过期,请重新登录', null, 401);
|
||||
}
|
||||
|
||||
// 每次请求从数据库刷新用户状态,确保权限变更实时生效
|
||||
$db = Database::getInstance();
|
||||
$user = $db->fetch(
|
||||
"SELECT id, username, nickname, role, email, phone, parent_id, project_ids, status, deleted_at
|
||||
FROM {$db->table('users')}
|
||||
WHERE id = ? AND deleted_at IS NULL",
|
||||
[$tokenUser['id']]
|
||||
);
|
||||
|
||||
if (!$user) {
|
||||
Application::jsonResponse(401, '用户不存在或已被删除', null, 401);
|
||||
}
|
||||
|
||||
if ((int) $user['status'] !== 1) {
|
||||
Application::jsonResponse(401, '账号已被禁用,请联系管理员', null, 401);
|
||||
}
|
||||
|
||||
// 将用户信息注入请求上下文
|
||||
$_SERVER['HTTP_X_USER_ID'] = $user['id'];
|
||||
$_SERVER['HTTP_X_USER_ROLE'] = $user['role'];
|
||||
$_SERVER['HTTP_X_USER_NAME'] = $user['username'];
|
||||
$_SERVER['HTTP_X_USER_NICKNAME'] = $user['nickname'];
|
||||
$_SERVER['HTTP_X_USER_PARENT'] = $user['parent_id'];
|
||||
$_SERVER['HTTP_X_USER_PROJECT_IDS'] = $user['project_ids'] ?? '[]';
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
namespace App\Middleware;
|
||||
|
||||
use App\Core\Middleware;
|
||||
use App\Core\Application;
|
||||
use App\Services\BlacklistService;
|
||||
|
||||
/**
|
||||
* 黑名单拦截中间件
|
||||
* 在请求处理前检查当前用户或IP是否被拉黑
|
||||
*/
|
||||
class BlacklistMiddleware extends Middleware
|
||||
{
|
||||
public function handle(array $request, callable $next): mixed
|
||||
{
|
||||
$userId = $_SERVER['HTTP_X_USER_ID'] ?? null;
|
||||
$ip = clientIp();
|
||||
|
||||
$service = new BlacklistService();
|
||||
if ($service->isBlocked($userId, $ip)) {
|
||||
Application::jsonResponse(403, '您的账号或IP已被列入黑名单,禁止访问', null, 403);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
namespace App\Middleware;
|
||||
|
||||
use App\Core\Middleware;
|
||||
use App\Core\Application;
|
||||
|
||||
/**
|
||||
* 频率限制中间件
|
||||
* 基于IP的简单频率控制
|
||||
*/
|
||||
class RateLimitMiddleware extends Middleware
|
||||
{
|
||||
private int $maxRequests;
|
||||
private int $windowSeconds;
|
||||
private string $prefix;
|
||||
|
||||
public function __construct(int $maxRequests = 60, int $windowSeconds = 60, string $prefix = 'api')
|
||||
{
|
||||
$this->maxRequests = $maxRequests;
|
||||
$this->windowSeconds = $windowSeconds;
|
||||
$this->prefix = $prefix;
|
||||
}
|
||||
|
||||
public function handle(array $request, callable $next): mixed
|
||||
{
|
||||
$ip = md5(clientIp());
|
||||
$key = "rate_limit:{$this->prefix}:{$ip}";
|
||||
$now = time();
|
||||
$window = $now - $this->windowSeconds;
|
||||
|
||||
$cacheDir = STORAGE_PATH . '/cache';
|
||||
if (!is_dir($cacheDir)) {
|
||||
mkdir($cacheDir, 0755, true);
|
||||
}
|
||||
|
||||
$cacheFile = $cacheDir . '/rate_limit.json';
|
||||
$data = [];
|
||||
if (file_exists($cacheFile)) {
|
||||
$data = json_decode(file_get_contents($cacheFile), true) ?: [];
|
||||
}
|
||||
|
||||
// 清理过期记录
|
||||
if (!isset($data[$key])) {
|
||||
$data[$key] = [];
|
||||
}
|
||||
$data[$key] = array_filter($data[$key], fn($t) => $t > $window);
|
||||
|
||||
if (count($data[$key]) >= $this->maxRequests) {
|
||||
Application::jsonResponse(429, '请求过于频繁,请稍后再试', null, 429);
|
||||
}
|
||||
|
||||
$data[$key][] = $now;
|
||||
file_put_contents($cacheFile, json_encode($data), LOCK_EX);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
namespace App\Middleware;
|
||||
|
||||
use App\Core\Middleware;
|
||||
use App\Core\Application;
|
||||
|
||||
/**
|
||||
* 角色权限中间件
|
||||
* 验证用户角色是否在允许列表中
|
||||
*/
|
||||
class RoleMiddleware
|
||||
{
|
||||
private string $role;
|
||||
|
||||
public function __construct(string $role)
|
||||
{
|
||||
$this->role = $role;
|
||||
}
|
||||
|
||||
public function handle(array $request, callable $next): mixed
|
||||
{
|
||||
$userRole = $_SERVER['HTTP_X_USER_ROLE'] ?? '';
|
||||
|
||||
if ($this->role === 'admin') {
|
||||
if ($userRole !== 'admin') {
|
||||
Application::jsonResponse(403, '仅超级管理员可操作', null, 403);
|
||||
}
|
||||
} elseif ($this->role === 'admin_or_project_admin') {
|
||||
if (!in_array($userRole, ['admin', 'project_admin'])) {
|
||||
Application::jsonResponse(403, '无权限操作', null, 403);
|
||||
}
|
||||
} elseif ($this->role === 'agent') {
|
||||
if ($userRole !== 'agent') {
|
||||
Application::jsonResponse(403, '仅代理可操作', null, 403);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
namespace App\Services;
|
||||
|
||||
use App\Core\Database;
|
||||
|
||||
/**
|
||||
* 黑名单服务
|
||||
* 提供黑名单查询、缓存与拦截判断
|
||||
*/
|
||||
class BlacklistService
|
||||
{
|
||||
private string $cacheFile;
|
||||
private int $cacheTtl = 60; // 缓存60秒
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->cacheFile = STORAGE_PATH . '/cache/blacklist.json';
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断指定用户ID或IP是否被拉黑
|
||||
*/
|
||||
public function isBlocked(?int $userId, ?string $ip): bool
|
||||
{
|
||||
if (empty($userId) && empty($ip)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$list = $this->getActiveList();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
|
||||
foreach ($list as $item) {
|
||||
if ($item['status'] != 1) continue;
|
||||
if (!empty($item['expire_time']) && $item['expire_time'] < $now) continue;
|
||||
|
||||
if ($item['target_type'] === 'user' && (string)$userId === (string)$item['target_value']) {
|
||||
return true;
|
||||
}
|
||||
if ($item['target_type'] === 'ip' && $ip === $item['target_value']) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取生效中的黑名单列表(带缓存)
|
||||
*/
|
||||
public function getActiveList(): array
|
||||
{
|
||||
if ($this->cacheValid()) {
|
||||
$data = json_decode(file_get_contents($this->cacheFile), true);
|
||||
if (is_array($data)) {
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->refreshCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新黑名单缓存
|
||||
*/
|
||||
public function refreshCache(): array
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$list = $db->fetchAll(
|
||||
"SELECT target_type, target_value, status, expire_time
|
||||
FROM {$db->table('blacklists')}"
|
||||
);
|
||||
|
||||
$dir = dirname($this->cacheFile);
|
||||
if (!is_dir($dir)) {
|
||||
mkdir($dir, 0755, true);
|
||||
}
|
||||
|
||||
file_put_contents(
|
||||
$this->cacheFile,
|
||||
json_encode($list, JSON_UNESCAPED_UNICODE),
|
||||
LOCK_EX
|
||||
);
|
||||
touch($this->cacheFile);
|
||||
|
||||
return $list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除缓存
|
||||
*/
|
||||
public function clearCache(): void
|
||||
{
|
||||
if (file_exists($this->cacheFile)) {
|
||||
unlink($this->cacheFile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查缓存是否有效
|
||||
*/
|
||||
private function cacheValid(): bool
|
||||
{
|
||||
if (!file_exists($this->cacheFile)) {
|
||||
return false;
|
||||
}
|
||||
return (time() - filemtime($this->cacheFile)) < $this->cacheTtl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
namespace App\Services;
|
||||
|
||||
/**
|
||||
* JWT认证服务 (原生PHP实现,无需第三方依赖)
|
||||
*/
|
||||
class JwtService
|
||||
{
|
||||
private string $secret;
|
||||
private int $ttl;
|
||||
private int $refreshTtl;
|
||||
private string $algorithm = 'HS256';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->secret = config('app.jwt_secret', '');
|
||||
$this->ttl = config('app.jwt_ttl', 7200);
|
||||
$this->refreshTtl = config('app.jwt_refresh_ttl', 1209600);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成Token
|
||||
*/
|
||||
public function generateToken(array $user): array
|
||||
{
|
||||
$now = time();
|
||||
$payload = [
|
||||
'iss' => 'cardauth',
|
||||
'iat' => $now,
|
||||
'exp' => $now + $this->ttl,
|
||||
'nbf' => $now,
|
||||
'sub' => $user['id'],
|
||||
'data' => [
|
||||
'id' => $user['id'],
|
||||
'username' => $user['username'],
|
||||
'role' => $user['role'],
|
||||
],
|
||||
];
|
||||
|
||||
$accessToken = $this->encode($payload);
|
||||
|
||||
// 刷新Token
|
||||
$refreshPayload = array_merge($payload, [
|
||||
'exp' => $now + $this->refreshTtl,
|
||||
'type' => 'refresh',
|
||||
]);
|
||||
$refreshToken = $this->encode($refreshPayload);
|
||||
|
||||
return [
|
||||
'access_token' => $accessToken,
|
||||
'refresh_token' => $refreshToken,
|
||||
'expires_in' => $this->ttl,
|
||||
'token_type' => 'Bearer',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证Token
|
||||
*/
|
||||
public function verifyToken(string $token): ?array
|
||||
{
|
||||
$decoded = $this->decode($token);
|
||||
if ($decoded === null) {
|
||||
return null;
|
||||
}
|
||||
return $decoded['data'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新Token
|
||||
*/
|
||||
public function refreshToken(string $refreshToken): ?array
|
||||
{
|
||||
$decoded = $this->decode($refreshToken);
|
||||
if ($decoded === null) {
|
||||
return null;
|
||||
}
|
||||
if (($decoded['type'] ?? '') !== 'refresh') {
|
||||
return null;
|
||||
}
|
||||
$user = $decoded['data'] ?? [];
|
||||
return $this->generateToken($user);
|
||||
}
|
||||
|
||||
/**
|
||||
* JWT编码
|
||||
*/
|
||||
private function encode(array $payload): string
|
||||
{
|
||||
$header = $this->base64UrlEncode(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
|
||||
$payload = $this->base64UrlEncode(json_encode($payload));
|
||||
$signature = $this->base64UrlEncode(
|
||||
hash_hmac('sha256', "$header.$payload", $this->secret, true)
|
||||
);
|
||||
return "$header.$payload.$signature";
|
||||
}
|
||||
|
||||
/**
|
||||
* JWT解码
|
||||
*/
|
||||
private function decode(string $token): ?array
|
||||
{
|
||||
$parts = explode('.', $token);
|
||||
if (count($parts) !== 3) {
|
||||
return null;
|
||||
}
|
||||
|
||||
[$header, $payload, $signature] = $parts;
|
||||
|
||||
// 验证签名
|
||||
$expectedSig = $this->base64UrlEncode(
|
||||
hash_hmac('sha256', "$header.$payload", $this->secret, true)
|
||||
);
|
||||
|
||||
if (!hash_equals($expectedSig, $signature)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = json_decode($this->base64UrlDecode($payload), true);
|
||||
if ($data === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 检查过期
|
||||
if (isset($data['exp']) && $data['exp'] < time()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64Url编码
|
||||
*/
|
||||
private function base64UrlEncode(string $data): string
|
||||
{
|
||||
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64Url解码
|
||||
*/
|
||||
private function base64UrlDecode(string $data): string
|
||||
{
|
||||
$remainder = strlen($data) % 4;
|
||||
if ($remainder) {
|
||||
$data .= str_repeat('=', 4 - $remainder);
|
||||
}
|
||||
return base64_decode(strtr($data, '-_', '+/'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
namespace App\Services;
|
||||
|
||||
use App\Core\Database;
|
||||
|
||||
/**
|
||||
* 权限服务
|
||||
* 处理用户角色、数据范围及上下级关系
|
||||
*/
|
||||
class PermissionService
|
||||
{
|
||||
/**
|
||||
* 判断是否为管理员(超级管理员/项目管理员)
|
||||
*/
|
||||
public static function isAdmin(?string $role): bool
|
||||
{
|
||||
return in_array($role, ['admin', 'project_admin'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为代理
|
||||
*/
|
||||
public static function isAgent(?string $role): bool
|
||||
{
|
||||
return $role === 'agent';
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定用户的所有后代代理ID(包含自身)
|
||||
* 递归向上? 不,这里是获取所有下级代理
|
||||
* @return int[]
|
||||
*/
|
||||
public static function getAgentIdsUnder(int $userId): array
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$ids = [$userId];
|
||||
$queue = [$userId];
|
||||
$maxDepth = 10; // 防止异常循环
|
||||
$depth = 0;
|
||||
|
||||
while (!empty($queue) && $depth < $maxDepth) {
|
||||
$placeholders = implode(',', array_fill(0, count($queue), '?'));
|
||||
$children = $db->fetchAll(
|
||||
"SELECT id FROM {$db->table('users')} WHERE parent_id IN ({$placeholders}) AND role = 'agent' AND deleted_at IS NULL",
|
||||
$queue
|
||||
);
|
||||
$queue = [];
|
||||
foreach ($children as $child) {
|
||||
$childId = (int) $child['id'];
|
||||
if (!in_array($childId, $ids, true)) {
|
||||
$ids[] = $childId;
|
||||
$queue[] = $childId;
|
||||
}
|
||||
}
|
||||
$depth++;
|
||||
}
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建授权列表的数据范围过滤条件
|
||||
* @param array $user 当前用户(需包含 id、role、project_ids)
|
||||
* @return array ['where' => string, 'params' => array]
|
||||
*/
|
||||
public static function authorizationScope(array $user): array
|
||||
{
|
||||
if (($user['role'] ?? '') === 'admin') {
|
||||
return ['where' => '', 'params' => []];
|
||||
}
|
||||
|
||||
// 项目管理员:只看自己项目的授权
|
||||
if (($user['role'] ?? '') === 'project_admin') {
|
||||
$projectIds = $user['project_ids'] ?? [];
|
||||
if (empty($projectIds)) {
|
||||
return ['where' => ' AND 1=0', 'params' => []];
|
||||
}
|
||||
$placeholders = implode(',', array_fill(0, count($projectIds), '?'));
|
||||
return [
|
||||
'where' => " AND a.project_id IN ({$placeholders})",
|
||||
'params' => $projectIds,
|
||||
];
|
||||
}
|
||||
|
||||
// 代理
|
||||
$agentIds = self::getAgentIdsUnder((int) $user['id']);
|
||||
if (empty($agentIds)) {
|
||||
return ['where' => ' AND a.agent_id = 0', 'params' => []];
|
||||
}
|
||||
|
||||
$placeholders = implode(',', array_fill(0, count($agentIds), '?'));
|
||||
return [
|
||||
'where' => " AND a.agent_id IN ({$placeholders})",
|
||||
'params' => $agentIds,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建卡密列表的数据范围过滤条件
|
||||
* @param array $user 当前用户(需包含 id、role、project_ids)
|
||||
* @return array ['where' => string, 'params' => array]
|
||||
*/
|
||||
public static function cardScope(array $user): array
|
||||
{
|
||||
if (($user['role'] ?? '') === 'admin') {
|
||||
return ['where' => '', 'params' => []];
|
||||
}
|
||||
|
||||
// 项目管理员:只看自己项目的卡密
|
||||
if (($user['role'] ?? '') === 'project_admin') {
|
||||
$projectIds = $user['project_ids'] ?? [];
|
||||
if (empty($projectIds)) {
|
||||
return ['where' => ' AND 1=0', 'params' => []];
|
||||
}
|
||||
$placeholders = implode(',', array_fill(0, count($projectIds), '?'));
|
||||
return [
|
||||
'where' => " AND c.project_id IN ({$placeholders})",
|
||||
'params' => $projectIds,
|
||||
];
|
||||
}
|
||||
|
||||
// 代理
|
||||
$agentIds = self::getAgentIdsUnder((int) $user['id']);
|
||||
if (empty($agentIds)) {
|
||||
return ['where' => ' AND c.use_user_id = 0', 'params' => []];
|
||||
}
|
||||
|
||||
$placeholders = implode(',', array_fill(0, count($agentIds), '?'));
|
||||
return [
|
||||
'where' => " AND c.use_user_id IN ({$placeholders})",
|
||||
'params' => $agentIds,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
namespace App\Services;
|
||||
|
||||
/**
|
||||
* Snowflake ID生成器
|
||||
* 用于生成唯一的卡密标识
|
||||
*/
|
||||
class SnowflakeService
|
||||
{
|
||||
private int $epoch;
|
||||
private int $workerId;
|
||||
private int $datacenterId;
|
||||
private int $sequence = 0;
|
||||
private int $lastTimestamp = -1;
|
||||
|
||||
private const WORKER_ID_BITS = 5;
|
||||
private const DATACENTER_ID_BITS = 5;
|
||||
private const SEQUENCE_BITS = 12;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->epoch = strtotime('2024-01-01 00:00:00') * 1000;
|
||||
$this->workerId = (int) config('app.snowflake.worker_id', 1);
|
||||
$this->datacenterId = (int) config('app.snowflake.datacenter_id', 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成下一个ID
|
||||
*/
|
||||
public function nextId(): int
|
||||
{
|
||||
$timestamp = $this->currentTimestamp();
|
||||
|
||||
if ($timestamp < $this->lastTimestamp) {
|
||||
throw new \RuntimeException('时钟回拨,拒绝生成ID');
|
||||
}
|
||||
|
||||
if ($timestamp === $this->lastTimestamp) {
|
||||
$this->sequence = ($this->sequence + 1) & 4095;
|
||||
if ($this->sequence === 0) {
|
||||
$timestamp = $this->waitNextMillis($this->lastTimestamp);
|
||||
}
|
||||
} else {
|
||||
$this->sequence = 0;
|
||||
}
|
||||
|
||||
$this->lastTimestamp = $timestamp;
|
||||
|
||||
return (($timestamp - $this->epoch) << 22)
|
||||
| ($this->datacenterId << 17)
|
||||
| ($this->workerId << 12)
|
||||
| $this->sequence;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成卡密Key (Snowflake ID + 随机字符)
|
||||
*/
|
||||
public function generateCardKey(): string
|
||||
{
|
||||
$id = $this->nextId();
|
||||
$base = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
||||
$encoded = '';
|
||||
$num = $id;
|
||||
while ($num > 0) {
|
||||
$encoded = $base[$num % 36] . $encoded;
|
||||
$num = (int)($num / 36);
|
||||
}
|
||||
return strtoupper(substr(md5($id), 0, 4) . '-' . $encoded . '-' . substr(md5($id . randomStr(4)), 0, 4));
|
||||
}
|
||||
|
||||
private function currentTimestamp(): int
|
||||
{
|
||||
return (int) (microtime(true) * 1000);
|
||||
}
|
||||
|
||||
private function waitNextMillis(int $lastTimestamp): int
|
||||
{
|
||||
$timestamp = $this->currentTimestamp();
|
||||
while ($timestamp <= $lastTimestamp) {
|
||||
$timestamp = $this->currentTimestamp();
|
||||
}
|
||||
return $timestamp;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "cardauth/backend",
|
||||
"description": "CardAuth Authorization Management System",
|
||||
"type": "project",
|
||||
"require": {
|
||||
"php": ">=8.1",
|
||||
"firebase/php-jwt": "^6.10"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"App\\": "app/"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"optimize-autoloader": true
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^10"
|
||||
}
|
||||
}
|
||||
Generated
+1754
File diff suppressed because it is too large.
Load diff
Binary file not shown.
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
/**
|
||||
* 应用配置文件
|
||||
*/
|
||||
return [
|
||||
'name' => 'CardAuth',
|
||||
'version' => '1.0.0',
|
||||
'debug' => env('APP_DEBUG', false),
|
||||
'timezone' => 'Asia/Shanghai',
|
||||
'jwt_secret' => env('JWT_SECRET', ''),
|
||||
'jwt_ttl' => 7200, // Token有效期(秒)
|
||||
'jwt_refresh_ttl' => 1209600, // 刷新Token有效期(秒)
|
||||
'rate_limit' => [
|
||||
'api' => 60, // 普通API每分钟请求数
|
||||
'auth' => 10, // 认证接口每分钟请求数
|
||||
'public' => 30, // 公开接口每分钟请求数
|
||||
],
|
||||
'snowflake' => [
|
||||
'worker_id' => 1,
|
||||
'datacenter_id' => 1,
|
||||
],
|
||||
'payment' => [
|
||||
'type' => env('PAYMENT_TYPE', 'epay'), // epay | codepay
|
||||
'api_url' => env('PAYMENT_API_URL', ''),
|
||||
'app_id' => env('PAYMENT_APP_ID', ''),
|
||||
'app_key' => env('PAYMENT_APP_KEY', ''),
|
||||
'notify_url' => env('APP_URL', '') . '/api/public/payment/notify',
|
||||
'return_url' => env('APP_URL', '') . '/#/result',
|
||||
],
|
||||
'allowed_origins' => ['*'],
|
||||
];
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
/**
|
||||
* 数据库配置文件
|
||||
* 支持多环境配置,通过 .env 文件管理敏感信息
|
||||
*/
|
||||
return [
|
||||
'driver' => 'mysql',
|
||||
'host' => env('DB_HOST', '127.0.0.1'),
|
||||
'port' => env('DB_PORT', '3306'),
|
||||
'database' => env('DB_NAME', 'card_auth'),
|
||||
'username' => env('DB_USER', 'root'),
|
||||
'password' => env('DB_PASS', ''),
|
||||
'charset' => 'utf8mb4',
|
||||
'collation' => 'utf8mb4_unicode_ci',
|
||||
'prefix' => env('DB_PREFIX', 'ca_'),
|
||||
'strict' => true,
|
||||
'engine' => 'InnoDB',
|
||||
];
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
/**
|
||||
* 黑名单功能数据库迁移脚本
|
||||
* 用于在已部署的环境中创建 ca_blacklists 表
|
||||
*/
|
||||
define('BASE_PATH', dirname(__DIR__));
|
||||
define('APP_PATH', BASE_PATH . '/app');
|
||||
define('CONFIG_PATH', BASE_PATH . '/config');
|
||||
define('ROUTES_PATH', BASE_PATH . '/routes');
|
||||
define('STORAGE_PATH', BASE_PATH . '/storage');
|
||||
|
||||
require BASE_PATH . '/vendor/autoload.php';
|
||||
require APP_PATH . '/Helpers/functions.php';
|
||||
|
||||
if (file_exists(BASE_PATH . '/.env')) {
|
||||
$lines = file(BASE_PATH . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
foreach ($lines as $line) {
|
||||
if (strpos(trim($line), '#') === 0) continue;
|
||||
if (strpos($line, '=') !== false) {
|
||||
list($key, $value) = explode('=', $line, 2);
|
||||
$key = trim($key);
|
||||
$value = trim($value, " \t\n\r\0\x0B\"'");
|
||||
putenv("$key=$value");
|
||||
$_ENV[$key] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$db = App\Core\Database::getInstance();
|
||||
|
||||
try {
|
||||
$db->execute("DROP TABLE IF EXISTS {$db->table('blacklists')}");
|
||||
$db->execute("CREATE TABLE {$db->table('blacklists')} (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`target_type` ENUM('user', 'ip') NOT NULL DEFAULT 'ip' COMMENT '目标类型: user=用户, ip=IP地址',
|
||||
`target_value` VARCHAR(255) NOT NULL COMMENT '目标值: 用户ID或IP地址',
|
||||
`status` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '状态: 0=禁用, 1=启用',
|
||||
`expire_time` DATETIME DEFAULT NULL COMMENT '过期时间,NULL表示永久',
|
||||
`operator_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '操作人ID',
|
||||
`operator_name` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '操作人用户名',
|
||||
`remark` VARCHAR(500) DEFAULT '' COMMENT '备注',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_target` (`target_type`, `target_value`),
|
||||
KEY `idx_status` (`status`),
|
||||
KEY `idx_expire_time` (`expire_time`),
|
||||
KEY `idx_created_at` (`created_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='黑名单表'");
|
||||
|
||||
echo "黑名单表创建成功\n";
|
||||
} catch (\Throwable $e) {
|
||||
echo "迁移失败: " . $e->getMessage() . "\n";
|
||||
exit(1);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
$pdo = new PDO('mysql:host=127.0.0.1;port=3306;charset=utf8mb4;dbname=card_auth', 'root', 'root123456');
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
// 1. card_types 添加 original_price 字段
|
||||
$pdo->exec("ALTER TABLE `ca_card_types` ADD COLUMN `original_price` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '原价' AFTER `price`");
|
||||
echo "1. ca_card_types.original_price added\n";
|
||||
|
||||
// 2. orders 添加 coupon_code 字段
|
||||
$pdo->exec("ALTER TABLE `ca_orders` ADD COLUMN `coupon_code` VARCHAR(32) DEFAULT '' COMMENT '使用优惠码' AFTER `contact_info`");
|
||||
echo "2. ca_orders.coupon_code added\n";
|
||||
|
||||
// 3. 创建优惠码表
|
||||
$pdo->exec("DROP TABLE IF EXISTS `ca_coupons`");
|
||||
$pdo->exec("CREATE TABLE `ca_coupons` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`code` VARCHAR(32) NOT NULL COMMENT '优惠码',
|
||||
`name` VARCHAR(100) DEFAULT '' COMMENT '优惠码名称/备注',
|
||||
`discount_percent` DECIMAL(5,2) NOT NULL DEFAULT 0.00 COMMENT '折扣百分比(0-100),如20表示省20%',
|
||||
`max_use_count` INT NOT NULL DEFAULT 0 COMMENT '最大使用次数(0=不限)',
|
||||
`used_count` INT NOT NULL DEFAULT 0 COMMENT '已使用次数',
|
||||
`min_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '最低消费金额',
|
||||
`project_ids` VARCHAR(500) DEFAULT '' COMMENT '适用项目ID(逗号分隔,空=全部)',
|
||||
`status` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '状态: 0=禁用, 1=启用',
|
||||
`expire_at` DATETIME DEFAULT NULL COMMENT '过期时间',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_code` (`code`),
|
||||
KEY `idx_status` (`status`),
|
||||
KEY `idx_expire_at` (`expire_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='优惠码表'");
|
||||
echo "3. ca_coupons created\n";
|
||||
|
||||
// 4. configs 插入默认原价折扣配置
|
||||
$pdo->exec("INSERT IGNORE INTO `ca_configs` (`key`, `value`, `description`) VALUES ('default_price_ratio', '1.6', '默认原价倍数(售价×倍数=原价)')");
|
||||
echo "4. default_price_ratio config added\n";
|
||||
|
||||
echo "All migrations done.\n";
|
||||
@@ -0,0 +1,10 @@
|
||||
-- 代理权限与数据隔离字段迁移
|
||||
-- 添加用户上下级关系、授权归属代理字段
|
||||
|
||||
ALTER TABLE `ca_users`
|
||||
ADD COLUMN `parent_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '上级代理/用户ID,0表示无上级' AFTER `project_ids`,
|
||||
ADD KEY `idx_parent_id` (`parent_id`);
|
||||
|
||||
ALTER TABLE `ca_authorizations`
|
||||
ADD COLUMN `agent_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '归属代理用户ID,0表示系统生成/未归属' AFTER `operator_id`,
|
||||
ADD KEY `idx_agent_id` (`agent_id`);
|
||||
@@ -0,0 +1,2 @@
|
||||
-- 添加用户头像字段
|
||||
ALTER TABLE `ca_users` ADD COLUMN `avatar` VARCHAR(500) DEFAULT '' COMMENT '头像URL' AFTER `phone`;
|
||||
@@ -0,0 +1,322 @@
|
||||
-- ============================================
|
||||
-- CardAuth 授权管理系统 - 数据库初始化脚本
|
||||
-- 版本: 1.0.0
|
||||
-- 引擎: MySQL 8.0+ / InnoDB
|
||||
-- 字符集: utf8mb4
|
||||
-- ============================================
|
||||
|
||||
CREATE DATABASE IF NOT EXISTS `card_auth` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
USE `card_auth`;
|
||||
|
||||
-- ============================================
|
||||
-- 1. 用户表 (管理员/项目管理员/代理)
|
||||
-- ============================================
|
||||
DROP TABLE IF EXISTS `ca_users`;
|
||||
CREATE TABLE `ca_users` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`username` VARCHAR(50) NOT NULL COMMENT '用户名',
|
||||
`password` VARCHAR(255) NOT NULL COMMENT '密码(bcrypt)',
|
||||
`nickname` VARCHAR(50) DEFAULT '' COMMENT '昵称',
|
||||
`email` VARCHAR(100) DEFAULT '' COMMENT '邮箱',
|
||||
`phone` VARCHAR(20) DEFAULT '' COMMENT '手机号',
|
||||
`avatar` VARCHAR(500) DEFAULT '' COMMENT '头像URL',
|
||||
`role` ENUM('admin', 'project_admin', 'agent') NOT NULL DEFAULT 'agent' COMMENT '角色: admin=超级管理员, project_admin=项目管理员, agent=代理',
|
||||
`project_ids` JSON DEFAULT NULL COMMENT '项目管理员绑定的项目ID列表(JSON数组)',
|
||||
`parent_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '上级代理/用户ID,0表示无上级',
|
||||
`status` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '状态: 0=禁用, 1=正常',
|
||||
`last_login_at` DATETIME DEFAULT NULL COMMENT '最后登录时间',
|
||||
`last_login_ip` VARCHAR(45) DEFAULT '' COMMENT '最后登录IP',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_username` (`username`),
|
||||
KEY `idx_role` (`role`),
|
||||
KEY `idx_status` (`status`),
|
||||
KEY `idx_parent_id` (`parent_id`),
|
||||
KEY `idx_deleted_at` (`deleted_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';
|
||||
|
||||
-- ============================================
|
||||
-- 2. 项目表
|
||||
-- ============================================
|
||||
DROP TABLE IF EXISTS `ca_projects`;
|
||||
CREATE TABLE `ca_projects` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`name` VARCHAR(100) NOT NULL COMMENT '项目名称',
|
||||
`description` VARCHAR(500) DEFAULT '' COMMENT '项目描述',
|
||||
`api_key` VARCHAR(64) NOT NULL COMMENT 'API验证密钥',
|
||||
`status` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '状态: 0=禁用, 1=正常',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
`deleted_at` DATETIME DEFAULT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_api_key` (`api_key`),
|
||||
KEY `idx_status` (`status`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='项目表';
|
||||
|
||||
-- ============================================
|
||||
-- 3. 卡密类型表 (商品类型)
|
||||
-- ============================================
|
||||
DROP TABLE IF EXISTS `ca_card_types`;
|
||||
CREATE TABLE `ca_card_types` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`project_id` BIGINT UNSIGNED NOT NULL COMMENT '所属项目ID',
|
||||
`name` VARCHAR(50) NOT NULL COMMENT '类型名称(如:月卡、年卡、永久卡)',
|
||||
`description` VARCHAR(255) DEFAULT '' COMMENT '商品简介',
|
||||
`duration_days` INT NOT NULL DEFAULT 0 COMMENT '有效天数(0=永久)',
|
||||
`price` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '售价',
|
||||
`original_price` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '原价',
|
||||
`agent_cost` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '代理消耗额度',
|
||||
`sort` INT NOT NULL DEFAULT 0 COMMENT '排序',
|
||||
`status` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '状态: 0=禁用, 1=正常',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_project_id` (`project_id`),
|
||||
KEY `idx_status` (`status`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='卡密类型表';
|
||||
|
||||
-- ============================================
|
||||
-- 4. 卡密表 (核心)
|
||||
-- ============================================
|
||||
DROP TABLE IF EXISTS `ca_cards`;
|
||||
CREATE TABLE `ca_cards` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`card_key` VARCHAR(64) NOT NULL COMMENT '卡密(唯一标识)',
|
||||
`project_id` BIGINT UNSIGNED NOT NULL COMMENT '所属项目ID',
|
||||
`card_type_id` BIGINT UNSIGNED NOT NULL COMMENT '卡密类型ID',
|
||||
`type` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '卡密类型名称(冗余)',
|
||||
`duration_days` INT NOT NULL DEFAULT 0 COMMENT '有效天数(0=永久)',
|
||||
`status` ENUM('unused', 'used', 'disabled') NOT NULL DEFAULT 'unused' COMMENT '状态: unused=未使用, used=已使用, disabled=已禁用',
|
||||
`bind_info` JSON DEFAULT NULL COMMENT '绑定信息: {ip, device_id, mac, hostname}',
|
||||
`bound_at` DATETIME DEFAULT NULL COMMENT '绑定时间',
|
||||
`expire_time` DATETIME DEFAULT NULL COMMENT '过期时间',
|
||||
`use_user_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '使用者(代理)ID',
|
||||
`order_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '关联订单ID',
|
||||
`remark` VARCHAR(255) DEFAULT '' COMMENT '备注',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_card_key` (`card_key`),
|
||||
KEY `idx_project_id` (`project_id`),
|
||||
KEY `idx_card_type_id` (`card_type_id`),
|
||||
KEY `idx_status` (`status`),
|
||||
KEY `idx_expire_time` (`expire_time`),
|
||||
KEY `idx_use_user_id` (`use_user_id`),
|
||||
KEY `idx_order_id` (`order_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='卡密表';
|
||||
|
||||
-- ============================================
|
||||
-- 5. 代理额度表
|
||||
-- ============================================
|
||||
DROP TABLE IF EXISTS `ca_agents`;
|
||||
CREATE TABLE `ca_agents` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '代理用户ID',
|
||||
`total_quota` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '总分配额度',
|
||||
`used_quota` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '已使用额度',
|
||||
`frozen_quota` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '冻结额度',
|
||||
`status` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '状态: 0=禁用, 1=正常',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_user_id` (`user_id`),
|
||||
KEY `idx_status` (`status`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='代理额度表';
|
||||
|
||||
-- ============================================
|
||||
-- 6. 额度变动日志表
|
||||
-- ============================================
|
||||
DROP TABLE IF EXISTS `ca_agent_quota_logs`;
|
||||
CREATE TABLE `ca_agent_quota_logs` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`agent_id` BIGINT UNSIGNED NOT NULL COMMENT '代理用户ID',
|
||||
`change_type` ENUM('recharge', 'consume', 'refund', 'adjust') NOT NULL COMMENT '变动类型: recharge=充值, consume=消费, refund=退款, adjust=调整',
|
||||
`amount` DECIMAL(12,2) NOT NULL COMMENT '变动金额',
|
||||
`balance_before` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '变动前余额',
|
||||
`balance_after` DECIMAL(12,2) NOT NULL DEFAULT 0.00 COMMENT '变动后余额',
|
||||
`target_type` VARCHAR(50) DEFAULT '' COMMENT '关联类型',
|
||||
`target_id` BIGINT UNSIGNED DEFAULT 0 COMMENT '关联ID',
|
||||
`remark` VARCHAR(255) DEFAULT '' COMMENT '备注',
|
||||
`operator_id` BIGINT UNSIGNED DEFAULT 0 COMMENT '操作人ID',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_agent_id` (`agent_id`),
|
||||
KEY `idx_created_at` (`created_at`),
|
||||
KEY `idx_change_type` (`change_type`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='代理额度变动日志';
|
||||
|
||||
-- ============================================
|
||||
-- 7. 支付订单表
|
||||
-- ============================================
|
||||
DROP TABLE IF EXISTS `ca_orders`;
|
||||
CREATE TABLE `ca_orders` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`order_no` VARCHAR(32) NOT NULL COMMENT '订单号',
|
||||
`trade_no` VARCHAR(64) DEFAULT '' COMMENT '第三方交易号',
|
||||
`project_id` BIGINT UNSIGNED NOT NULL COMMENT '项目ID',
|
||||
`card_type_id` BIGINT UNSIGNED NOT NULL COMMENT '卡密类型ID',
|
||||
`user_id` BIGINT UNSIGNED DEFAULT 0 COMMENT '用户ID(购买者)',
|
||||
`amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '订单金额',
|
||||
`pay_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '实际支付金额',
|
||||
`pay_type` VARCHAR(20) DEFAULT '' COMMENT '支付方式: alipay, wxpay, qqpay',
|
||||
`status` ENUM('pending', 'paid', 'expired', 'refunded') NOT NULL DEFAULT 'pending' COMMENT '状态: pending=待支付, paid=已支付, expired=已过期, refunded=已退款',
|
||||
`card_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '关联卡密ID',
|
||||
`contact_info` VARCHAR(255) DEFAULT '' COMMENT '联系方式(用于发货)',
|
||||
`paid_at` DATETIME DEFAULT NULL COMMENT '支付时间',
|
||||
`expired_at` DATETIME DEFAULT NULL COMMENT '过期时间',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_order_no` (`order_no`),
|
||||
KEY `idx_trade_no` (`trade_no`),
|
||||
KEY `idx_project_id` (`project_id`),
|
||||
KEY `idx_user_id` (`user_id`),
|
||||
KEY `idx_status` (`status`),
|
||||
KEY `idx_card_id` (`card_id`),
|
||||
KEY `idx_created_at` (`created_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='支付订单表';
|
||||
|
||||
-- ============================================
|
||||
-- 8. 操作日志表
|
||||
-- ============================================
|
||||
DROP TABLE IF EXISTS `ca_logs`;
|
||||
CREATE TABLE `ca_logs` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`user_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '操作用户ID',
|
||||
`action` VARCHAR(50) NOT NULL COMMENT '操作类型',
|
||||
`target_type` VARCHAR(50) DEFAULT '' COMMENT '目标类型',
|
||||
`target_id` BIGINT UNSIGNED DEFAULT 0 COMMENT '目标ID',
|
||||
`detail` JSON DEFAULT NULL COMMENT '操作详情',
|
||||
`ip` VARCHAR(45) DEFAULT '' COMMENT '操作IP',
|
||||
`user_agent` VARCHAR(500) DEFAULT '' COMMENT 'User-Agent',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_user_id` (`user_id`),
|
||||
KEY `idx_action` (`action`),
|
||||
KEY `idx_target` (`target_type`, `target_id`),
|
||||
KEY `idx_created_at` (`created_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='操作日志表';
|
||||
|
||||
-- ============================================
|
||||
-- 9. 系统配置表
|
||||
-- ============================================
|
||||
DROP TABLE IF EXISTS `ca_configs`;
|
||||
CREATE TABLE `ca_configs` (
|
||||
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`key` VARCHAR(100) NOT NULL COMMENT '配置键',
|
||||
`value` TEXT COMMENT '配置值',
|
||||
`description` VARCHAR(255) DEFAULT '' COMMENT '说明',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_key` (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统配置表';
|
||||
|
||||
-- ============================================
|
||||
-- 10. 卡密授权记录表 (机器人QQ + 联系人QQ)
|
||||
-- ============================================
|
||||
DROP TABLE IF EXISTS `ca_authorizations`;
|
||||
CREATE TABLE `ca_authorizations` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`card_id` BIGINT UNSIGNED NOT NULL COMMENT '关联卡密ID',
|
||||
`card_key` VARCHAR(64) NOT NULL COMMENT '卡密(冗余)',
|
||||
`project_id` BIGINT UNSIGNED NOT NULL COMMENT '所属项目ID',
|
||||
`project_name` VARCHAR(100) DEFAULT '' COMMENT '项目名称(冗余)',
|
||||
`bot_qq` VARCHAR(20) NOT NULL COMMENT '机器人QQ号',
|
||||
`contact_qq` VARCHAR(20) NOT NULL COMMENT '联系人QQ号',
|
||||
`contact_name` VARCHAR(50) DEFAULT '' COMMENT '联系人名称',
|
||||
`duration_days` INT NOT NULL DEFAULT 0 COMMENT '有效天数(0=永久)',
|
||||
`status` ENUM('active', 'expired', 'revoked') NOT NULL DEFAULT 'active' COMMENT '状态: active=有效, expired=已过期, revoked=已撤销',
|
||||
`authorized_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
`expire_time` DATETIME DEFAULT NULL COMMENT '授权过期时间',
|
||||
`revoked_at` DATETIME DEFAULT NULL COMMENT '撤销时间',
|
||||
`revoke_reason` VARCHAR(255) DEFAULT '' COMMENT '撤销原因',
|
||||
`operator_id` BIGINT UNSIGNED DEFAULT 0 COMMENT '操作人ID',
|
||||
`agent_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '归属代理用户ID,0表示系统生成/未归属',
|
||||
`remark` VARCHAR(255) DEFAULT '' COMMENT '备注',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_card_bot_contact` (`card_id`, `bot_qq`, `contact_qq`),
|
||||
KEY `idx_bot_qq` (`bot_qq`),
|
||||
KEY `idx_contact_qq` (`contact_qq`),
|
||||
KEY `idx_card_id` (`card_id`),
|
||||
KEY `idx_project_id` (`project_id`),
|
||||
KEY `idx_agent_id` (`agent_id`),
|
||||
KEY `idx_status` (`status`),
|
||||
KEY `idx_expire_time` (`expire_time`),
|
||||
KEY `idx_authorized_at` (`authorized_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='卡密授权记录表';
|
||||
|
||||
-- ============================================
|
||||
-- 11. 优惠码表
|
||||
-- ============================================
|
||||
DROP TABLE IF EXISTS `ca_coupons`;
|
||||
CREATE TABLE `ca_coupons` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`code` VARCHAR(32) NOT NULL COMMENT '优惠码',
|
||||
`name` VARCHAR(100) DEFAULT '' COMMENT '优惠码名称/备注',
|
||||
`discount_percent` DECIMAL(5,2) NOT NULL DEFAULT 0.00 COMMENT '折扣百分比(0-100)',
|
||||
`max_use_count` INT NOT NULL DEFAULT 0 COMMENT '最大使用次数(0=不限)',
|
||||
`used_count` INT NOT NULL DEFAULT 0 COMMENT '已使用次数',
|
||||
`min_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '最低消费金额',
|
||||
`project_ids` VARCHAR(500) DEFAULT '' COMMENT '适用项目ID(逗号分隔,空=全部)',
|
||||
`status` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '状态: 0=禁用, 1=启用',
|
||||
`expire_at` DATETIME DEFAULT NULL COMMENT '过期时间',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_code` (`code`),
|
||||
KEY `idx_status` (`status`),
|
||||
KEY `idx_expire_at` (`expire_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='优惠码表';
|
||||
|
||||
-- ============================================
|
||||
-- 初始化数据
|
||||
-- ============================================
|
||||
|
||||
-- 初始化超级管理员 (密码: admin123456)
|
||||
INSERT INTO `ca_users` (`username`, `password`, `nickname`, `role`, `status`) VALUES
|
||||
('admin', '$2y$12$LJ3m4ys3OoMJ8zKR0gVNNe5hHOqFh0VhJmKqxXkGgFMfGZqXsQHqK', '超级管理员', 'admin', 1);
|
||||
|
||||
-- 初始化演示项目
|
||||
INSERT INTO `ca_projects` (`name`, `description`, `api_key`, `status`) VALUES
|
||||
('演示项目', '默认演示项目,可删除', 'ak_' . LOWER(REPLACE(UUID(), '-', '')), 1);
|
||||
|
||||
-- 初始化卡密类型
|
||||
INSERT INTO `ca_card_types` (`project_id`, `name`, `duration_days`, `price`, `agent_cost`, `sort`, `status`) VALUES
|
||||
(1, '月卡', 30, 29.90, 20.00, 1, 1),
|
||||
(1, '季卡', 90, 79.90, 50.00, 2, 1),
|
||||
(1, '年卡', 365, 299.00, 200.00, 3, 1),
|
||||
(1, '永久卡', 0, 699.00, 500.00, 4, 1);
|
||||
|
||||
-- ============================================
|
||||
-- 11. 黑名单表
|
||||
-- ============================================
|
||||
DROP TABLE IF EXISTS `ca_blacklists`;
|
||||
CREATE TABLE `ca_blacklists` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`target_type` ENUM('user', 'ip') NOT NULL DEFAULT 'ip' COMMENT '目标类型: user=用户, ip=IP地址',
|
||||
`target_value` VARCHAR(255) NOT NULL COMMENT '目标值: 用户ID或IP地址',
|
||||
`status` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '状态: 0=禁用, 1=启用',
|
||||
`expire_time` DATETIME DEFAULT NULL COMMENT '过期时间,NULL表示永久',
|
||||
`operator_id` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '操作人ID',
|
||||
`operator_name` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '操作人用户名',
|
||||
`remark` VARCHAR(500) DEFAULT '' COMMENT '备注',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_target` (`target_type`, `target_value`),
|
||||
KEY `idx_status` (`status`),
|
||||
KEY `idx_expire_time` (`expire_time`),
|
||||
KEY `idx_created_at` (`created_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='黑名单表';
|
||||
|
||||
-- 系统配置初始化
|
||||
INSERT INTO `ca_configs` (`key`, `value`, `description`) VALUES
|
||||
('site_name', 'CardAuth授权管理系统', '站点名称'),
|
||||
('site_logo', '', '站点Logo'),
|
||||
('card_key_prefix', 'CA', '卡密前缀'),
|
||||
('order_expire_minutes', '15', '订单过期时间(分钟)');
|
||||
@@ -0,0 +1 @@
|
||||
Error: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'card_auth.ca_users' doesn't exist
|
||||
@@ -0,0 +1,4 @@
|
||||
Executed: 10 statements
|
||||
Errors: 0
|
||||
|
||||
Tables: ca_agent_quota_logs, ca_agents, ca_card_types, ca_cards, ca_configs, ca_logs, ca_orders, ca_projects, ca_users
|
||||
@@ -0,0 +1,6 @@
|
||||
pdo_mysql: YES
|
||||
openssl: YES
|
||||
mbstring: YES
|
||||
json: YES
|
||||
curl: YES
|
||||
fileinfo: YES
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "backend",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd"
|
||||
bootstrap="tests/bootstrap.php"
|
||||
colors="true"
|
||||
testdox="true">
|
||||
<testsuites>
|
||||
<testsuite name="Unit">
|
||||
<directory>tests/Unit</directory>
|
||||
</testsuite>
|
||||
<testsuite name="Integration">
|
||||
<directory>tests/Integration</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<source>
|
||||
<include>
|
||||
<directory>app</directory>
|
||||
</include>
|
||||
</source>
|
||||
</phpunit>
|
||||
@@ -0,0 +1,4 @@
|
||||
RewriteEngine On
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
|
||||
@@ -0,0 +1 @@
|
||||
.auth-container[data-v-a91149b4]{min-height:100vh;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#1a1a2e,#16213e,#0f3460);position:relative;overflow:hidden;padding:24px}.auth-bg[data-v-a91149b4]{position:absolute;top:0;right:0;bottom:0;left:0;overflow:hidden}.bg-circle[data-v-a91149b4]{position:absolute;border-radius:50%;opacity:.06;background:#409eff}.bg-circle.c1[data-v-a91149b4]{width:500px;height:500px;top:-150px;right:-100px}.bg-circle.c2[data-v-a91149b4]{width:300px;height:300px;bottom:-80px;left:-80px}.bg-circle.c3[data-v-a91149b4]{width:200px;height:200px;top:40%;left:60%}.auth-card[data-v-a91149b4]{position:relative;width:100%;max-width:420px;padding:40px 36px 32px;background:#fff;border-radius:16px;box-shadow:0 24px 80px #00000040;z-index:1}.auth-header[data-v-a91149b4]{text-align:center;margin-bottom:28px}.auth-icon[data-v-a91149b4]{margin-bottom:12px}.auth-title[data-v-a91149b4]{color:#1a1a2e;font-size:24px;font-weight:700;margin-bottom:6px}.auth-subtitle[data-v-a91149b4]{color:#909399;font-size:14px}.auth-form[data-v-a91149b4] .el-input__wrapper{border-radius:8px}.form-options[data-v-a91149b4]{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;font-size:14px}.auth-footer[data-v-a91149b4]{text-align:center;margin-top:20px;color:#606266;font-size:14px}.auth-link[data-v-a91149b4]{color:#409eff;margin-left:6px;text-decoration:none;font-weight:500}.auth-link[data-v-a91149b4]:hover{text-decoration:underline}@media (max-width: 480px){.auth-card[data-v-a91149b4]{padding:32px 24px 24px;border-radius:12px}.auth-title[data-v-a91149b4]{font-size:22px}.form-options[data-v-a91149b4]{flex-direction:column;gap:10px;align-items:flex-start}}
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as I,m as C,o as F,c as S,a as s,b as t,w as a,j as B,E as L,d as U,r as q,u as z,n as m,p as A,e as N,f as R,q as K,g as M,s as j,t as P,i as n,v as T,h as D,k as f,l as g}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css */import{u as G}from"./user-KptFbP1d.js";import"./index-CZCGMR8A.js";const H={class:"auth-container"},J={class:"auth-card"},O={class:"auth-header"},Q={class:"auth-icon"},W={class:"form-options"},X={class:"auth-footer"},Y={__name:"AgentLogin",setup(Z){const v=z(),b=G(),u=g(!1),d=g(null),o=B({account:"",password:"",remember:!1}),w={account:[{required:!0,message:"请输入用户名或邮箱",trigger:"blur"}],password:[{required:!0,message:"请输入密码",trigger:"blur"}]};C(()=>{const l=localStorage.getItem("agent_remember_account");l&&(o.account=l,o.remember=!0)});async function p(){d.value&&await d.value.validate(async l=>{if(l){u.value=!0;try{await b.login(o.account,o.password,"agent"),o.remember?localStorage.setItem("agent_remember_account",o.account):localStorage.removeItem("agent_remember_account"),f.success("登录成功"),v.push("/dashboard")}catch{}finally{u.value=!1}}})}function h(){f.info("请联系管理员重置密码")}return(l,e)=>{const i=L,_=R,c=N,k=P,y=T,V=D,x=U,E=q("router-link");return F(),S("div",H,[e[10]||(e[10]=s("div",{class:"auth-bg"},[s("div",{class:"bg-circle c1"}),s("div",{class:"bg-circle c2"}),s("div",{class:"bg-circle c3"})],-1)),s("div",J,[s("div",O,[s("div",Q,[t(i,{size:40,color:"#409EFF"},{default:a(()=>[t(m(A))]),_:1})]),e[3]||(e[3]=s("h2",{class:"auth-title"},"代理登录",-1)),e[4]||(e[4]=s("p",{class:"auth-subtitle"},"CardAuth 代理合作伙伴中心",-1))]),t(x,{ref_key:"formRef",ref:d,model:o,rules:w,size:"large",class:"auth-form"},{default:a(()=>[t(c,{prop:"account"},{default:a(()=>[t(_,{modelValue:o.account,"onUpdate:modelValue":e[0]||(e[0]=r=>o.account=r),placeholder:"用户名 / 邮箱",maxlength:"100",clearable:""},{prefix:a(()=>[t(i,null,{default:a(()=>[t(m(K))]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(c,{prop:"password"},{default:a(()=>[t(_,{modelValue:o.password,"onUpdate:modelValue":e[1]||(e[1]=r=>o.password=r),type:"password",placeholder:"密码",maxlength:"50","show-password":"",onKeyup:M(p,["enter"])},{prefix:a(()=>[t(i,null,{default:a(()=>[t(m(j))]),_:1})]),_:1},8,["modelValue"])]),_:1}),s("div",W,[t(k,{modelValue:o.remember,"onUpdate:modelValue":e[2]||(e[2]=r=>o.remember=r)},{default:a(()=>[...e[5]||(e[5]=[n("记住我",-1)])]),_:1},8,["modelValue"]),t(y,{type:"primary",underline:!1,onClick:h},{default:a(()=>[...e[6]||(e[6]=[n("忘记密码?",-1)])]),_:1})]),t(c,null,{default:a(()=>[t(V,{type:"primary",loading:u.value,style:{width:"100%"},size:"large",onClick:p},{default:a(()=>[...e[7]||(e[7]=[n(" 登 录 ",-1)])]),_:1},8,["loading"])]),_:1})]),_:1},8,["model"]),s("div",X,[e[9]||(e[9]=s("span",null,"还没有账号?",-1)),t(E,{to:"/agent/register",class:"auth-link"},{default:a(()=>[...e[8]||(e[8]=[n("立即注册",-1)])]),_:1})])])])}}},re=I(Y,[["__scopeId","data-v-a91149b4"]]);export{re as default};
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as I,m as C,o as F,c as S,a as s,b as t,w as a,j as B,E as L,d as U,r as q,u as z,n as m,p as A,e as N,f as R,q as K,g as M,s as j,t as P,i as n,v as T,h as D,k as f,l as g}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css */import{u as G}from"./user-DvAOsLmR.js";import"./index-DpFNINBG.js";const H={class:"auth-container"},J={class:"auth-card"},O={class:"auth-header"},Q={class:"auth-icon"},W={class:"form-options"},X={class:"auth-footer"},Y={__name:"AgentLogin",setup(Z){const v=z(),b=G(),u=g(!1),d=g(null),o=B({account:"",password:"",remember:!1}),w={account:[{required:!0,message:"请输入用户名或邮箱",trigger:"blur"}],password:[{required:!0,message:"请输入密码",trigger:"blur"}]};C(()=>{const l=localStorage.getItem("agent_remember_account");l&&(o.account=l,o.remember=!0)});async function p(){d.value&&await d.value.validate(async l=>{if(l){u.value=!0;try{await b.login(o.account,o.password,"agent"),o.remember?localStorage.setItem("agent_remember_account",o.account):localStorage.removeItem("agent_remember_account"),f.success("登录成功"),v.push("/dashboard")}catch{}finally{u.value=!1}}})}function h(){f.info("请联系管理员重置密码")}return(l,e)=>{const i=L,_=R,c=N,k=P,y=T,V=D,x=U,E=q("router-link");return F(),S("div",H,[e[10]||(e[10]=s("div",{class:"auth-bg"},[s("div",{class:"bg-circle c1"}),s("div",{class:"bg-circle c2"}),s("div",{class:"bg-circle c3"})],-1)),s("div",J,[s("div",O,[s("div",Q,[t(i,{size:40,color:"#409EFF"},{default:a(()=>[t(m(A))]),_:1})]),e[3]||(e[3]=s("h2",{class:"auth-title"},"代理登录",-1)),e[4]||(e[4]=s("p",{class:"auth-subtitle"},"CardAuth 代理合作伙伴中心",-1))]),t(x,{ref_key:"formRef",ref:d,model:o,rules:w,size:"large",class:"auth-form"},{default:a(()=>[t(c,{prop:"account"},{default:a(()=>[t(_,{modelValue:o.account,"onUpdate:modelValue":e[0]||(e[0]=r=>o.account=r),placeholder:"用户名 / 邮箱",maxlength:"100",clearable:""},{prefix:a(()=>[t(i,null,{default:a(()=>[t(m(K))]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(c,{prop:"password"},{default:a(()=>[t(_,{modelValue:o.password,"onUpdate:modelValue":e[1]||(e[1]=r=>o.password=r),type:"password",placeholder:"密码",maxlength:"50","show-password":"",onKeyup:M(p,["enter"])},{prefix:a(()=>[t(i,null,{default:a(()=>[t(m(j))]),_:1})]),_:1},8,["modelValue"])]),_:1}),s("div",W,[t(k,{modelValue:o.remember,"onUpdate:modelValue":e[2]||(e[2]=r=>o.remember=r)},{default:a(()=>[...e[5]||(e[5]=[n("记住我",-1)])]),_:1},8,["modelValue"]),t(y,{type:"primary",underline:!1,onClick:h},{default:a(()=>[...e[6]||(e[6]=[n("忘记密码?",-1)])]),_:1})]),t(c,null,{default:a(()=>[t(V,{type:"primary",loading:u.value,style:{width:"100%"},size:"large",onClick:p},{default:a(()=>[...e[7]||(e[7]=[n(" 登 录 ",-1)])]),_:1},8,["loading"])]),_:1})]),_:1},8,["model"]),s("div",X,[e[9]||(e[9]=s("span",null,"还没有账号?",-1)),t(E,{to:"/agent/register",class:"auth-link"},{default:a(()=>[...e[8]||(e[8]=[n("立即注册",-1)])]),_:1})])])])}}},re=I(Y,[["__scopeId","data-v-a91149b4"]]);export{re as default};
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as q,o as U,c as R,a as o,b as t,w as s,E as B,d as F,r as I,u as N,n as i,q as c,e as S,f as D,x as T,y as Z,z as j,s as v,A as L,B as M,C as W,t as $,i as m,v as G,h as H,j as J,D as p,k as K,l as w}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css */import{r as O}from"./index-CZCGMR8A.js";const Q={class:"auth-container"},X={class:"auth-card"},Y={class:"auth-header"},ee={class:"auth-icon"},te={class:"password-strength"},se={class:"strength-text"},ae={class:"auth-footer"},re={__name:"AgentRegister",setup(le){const h=N(),f=w(!1),g=w(null),a=J({username:"",email:"",phone:"",inviteCode:"",password:"",confirmPassword:"",agreement:!1}),x={username:[{required:!0,message:"请输入用户名",trigger:"blur"},{min:3,max:50,message:"用户名长度3-50位",trigger:"blur"}],email:[{required:!0,message:"请输入电子邮箱",trigger:"blur"},{type:"email",message:"邮箱格式不正确",trigger:"blur"}],phone:[{required:!0,validator:(l,e,r)=>{e?/^1[3-9]\d{9}$/.test(e)?r():r(new Error("手机号格式不正确")):r(new Error("请输入手机号码"))},trigger:"blur"}],password:[{required:!0,message:"请输入密码",trigger:"blur"},{min:6,max:50,message:"密码长度6-50位",trigger:"blur"}],confirmPassword:[{required:!0,validator:(l,e,r)=>{e?e!==a.password?r(new Error("两次输入的密码不一致")):r():r(new Error("请再次输入密码"))},trigger:"blur"}],agreement:[{validator:(l,e,r)=>{e?r():r(new Error("请同意代理服务协议"))},trigger:"change"}]},_=p(()=>{const l=a.password;if(!l)return 0;let e=0;return l.length>=8&&e++,/[a-z]/.test(l)&&/[A-Z]/.test(l)&&e++,/\d/.test(l)&&e++,/[^a-zA-Z0-9]/.test(l)&&e++,e}),V=p(()=>({0:"",1:"weak",2:"medium",3:"medium",4:"strong"})[_.value]),b=p(()=>({0:"0%",1:"33%",2:"50%",3:"75%",4:"100%"})[_.value]),y=p(()=>({0:"未输入",1:"弱",2:"中",3:"良",4:"强"})[_.value]);async function E(){g.value&&await g.value.validate(async l=>{if(l){f.value=!0;try{await O.post("/auth/agent-register",{username:a.username,password:a.password,confirm_password:a.confirmPassword,email:a.email,phone:a.phone,invite_code:a.inviteCode}),K.success("注册成功,请登录"),h.push("/agent/login")}catch{}finally{f.value=!1}}})}return(l,e)=>{const r=B,u=D,d=S,C=G,k=$,P=H,z=F,A=I("router-link");return U(),R("div",Q,[e[14]||(e[14]=o("div",{class:"auth-bg"},[o("div",{class:"bg-circle c1"}),o("div",{class:"bg-circle c2"}),o("div",{class:"bg-circle c3"})],-1)),o("div",X,[o("div",Y,[o("div",ee,[t(r,{size:40,color:"#409EFF"},{default:s(()=>[t(i(c))]),_:1})]),e[7]||(e[7]=o("h2",{class:"auth-title"},"代理注册",-1)),e[8]||(e[8]=o("p",{class:"auth-subtitle"},"成为 CardAuth 合作伙伴",-1))]),t(z,{ref_key:"formRef",ref:g,model:a,rules:x,size:"large",class:"auth-form"},{default:s(()=>[t(d,{prop:"username"},{default:s(()=>[t(u,{modelValue:a.username,"onUpdate:modelValue":e[0]||(e[0]=n=>a.username=n),placeholder:"用户名",maxlength:"50",clearable:""},{prefix:s(()=>[t(r,null,{default:s(()=>[t(i(c))]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(d,{prop:"email"},{default:s(()=>[t(u,{modelValue:a.email,"onUpdate:modelValue":e[1]||(e[1]=n=>a.email=n),placeholder:"电子邮箱",maxlength:"100",clearable:""},{prefix:s(()=>[t(r,null,{default:s(()=>[t(i(T))]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(d,{prop:"phone"},{default:s(()=>[t(u,{modelValue:a.phone,"onUpdate:modelValue":e[2]||(e[2]=n=>a.phone=n),placeholder:"手机号码",maxlength:"11",clearable:""},{prefix:s(()=>[t(r,null,{default:s(()=>[t(i(Z))]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(d,{prop:"inviteCode"},{default:s(()=>[t(u,{modelValue:a.inviteCode,"onUpdate:modelValue":e[3]||(e[3]=n=>a.inviteCode=n),placeholder:"邀请码(上级代理用户名,选填)",maxlength:"50",clearable:""},{prefix:s(()=>[t(r,null,{default:s(()=>[t(i(j))]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(d,{prop:"password"},{default:s(()=>[t(u,{modelValue:a.password,"onUpdate:modelValue":e[4]||(e[4]=n=>a.password=n),type:"password",placeholder:"密码",maxlength:"50","show-password":""},{prefix:s(()=>[t(r,null,{default:s(()=>[t(i(v))]),_:1})]),_:1},8,["modelValue"]),o("div",te,[o("div",{class:M(["strength-bar",V.value]),style:L({width:b.value})},null,6)]),o("div",se,"密码强度:"+W(y.value),1)]),_:1}),t(d,{prop:"confirmPassword"},{default:s(()=>[t(u,{modelValue:a.confirmPassword,"onUpdate:modelValue":e[5]||(e[5]=n=>a.confirmPassword=n),type:"password",placeholder:"确认密码",maxlength:"50","show-password":""},{prefix:s(()=>[t(r,null,{default:s(()=>[t(i(v))]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(d,{prop:"agreement"},{default:s(()=>[t(k,{modelValue:a.agreement,"onUpdate:modelValue":e[6]||(e[6]=n=>a.agreement=n)},{default:s(()=>[e[10]||(e[10]=m(" 我已阅读并同意 ",-1)),t(C,{type:"primary"},{default:s(()=>[...e[9]||(e[9]=[m("《代理服务协议》",-1)])]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(d,null,{default:s(()=>[t(P,{type:"primary",loading:f.value,stLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as q,o as U,c as R,a as o,b as t,w as s,E as B,d as F,r as I,u as N,n as i,q as c,e as S,f as D,x as T,y as Z,z as j,s as v,A as L,B as M,C as W,t as $,i as m,v as G,h as H,j as J,D as p,k as K,l as w}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css */import{r as O}from"./index-DpFNINBG.js";const Q={class:"auth-container"},X={class:"auth-card"},Y={class:"auth-header"},ee={class:"auth-icon"},te={class:"password-strength"},se={class:"strength-text"},ae={class:"auth-footer"},re={__name:"AgentRegister",setup(le){const h=N(),f=w(!1),g=w(null),a=J({username:"",email:"",phone:"",inviteCode:"",password:"",confirmPassword:"",agreement:!1}),x={username:[{required:!0,message:"请输入用户名",trigger:"blur"},{min:3,max:50,message:"用户名长度3-50位",trigger:"blur"}],email:[{required:!0,message:"请输入电子邮箱",trigger:"blur"},{type:"email",message:"邮箱格式不正确",trigger:"blur"}],phone:[{required:!0,validator:(l,e,r)=>{e?/^1[3-9]\d{9}$/.test(e)?r():r(new Error("手机号格式不正确")):r(new Error("请输入手机号码"))},trigger:"blur"}],password:[{required:!0,message:"请输入密码",trigger:"blur"},{min:6,max:50,message:"密码长度6-50位",trigger:"blur"}],confirmPassword:[{required:!0,validator:(l,e,r)=>{e?e!==a.password?r(new Error("两次输入的密码不一致")):r():r(new Error("请再次输入密码"))},trigger:"blur"}],agreement:[{validator:(l,e,r)=>{e?r():r(new Error("请同意代理服务协议"))},trigger:"change"}]},_=p(()=>{const l=a.password;if(!l)return 0;let e=0;return l.length>=8&&e++,/[a-z]/.test(l)&&/[A-Z]/.test(l)&&e++,/\d/.test(l)&&e++,/[^a-zA-Z0-9]/.test(l)&&e++,e}),V=p(()=>({0:"",1:"weak",2:"medium",3:"medium",4:"strong"})[_.value]),b=p(()=>({0:"0%",1:"33%",2:"50%",3:"75%",4:"100%"})[_.value]),y=p(()=>({0:"未输入",1:"弱",2:"中",3:"良",4:"强"})[_.value]);async function E(){g.value&&await g.value.validate(async l=>{if(l){f.value=!0;try{await O.post("/auth/agent-register",{username:a.username,password:a.password,confirm_password:a.confirmPassword,email:a.email,phone:a.phone,invite_code:a.inviteCode}),K.success("注册成功,请登录"),h.push("/agent/login")}catch{}finally{f.value=!1}}})}return(l,e)=>{const r=B,u=D,d=S,C=G,k=$,P=H,z=F,A=I("router-link");return U(),R("div",Q,[e[14]||(e[14]=o("div",{class:"auth-bg"},[o("div",{class:"bg-circle c1"}),o("div",{class:"bg-circle c2"}),o("div",{class:"bg-circle c3"})],-1)),o("div",X,[o("div",Y,[o("div",ee,[t(r,{size:40,color:"#409EFF"},{default:s(()=>[t(i(c))]),_:1})]),e[7]||(e[7]=o("h2",{class:"auth-title"},"代理注册",-1)),e[8]||(e[8]=o("p",{class:"auth-subtitle"},"成为 CardAuth 合作伙伴",-1))]),t(z,{ref_key:"formRef",ref:g,model:a,rules:x,size:"large",class:"auth-form"},{default:s(()=>[t(d,{prop:"username"},{default:s(()=>[t(u,{modelValue:a.username,"onUpdate:modelValue":e[0]||(e[0]=n=>a.username=n),placeholder:"用户名",maxlength:"50",clearable:""},{prefix:s(()=>[t(r,null,{default:s(()=>[t(i(c))]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(d,{prop:"email"},{default:s(()=>[t(u,{modelValue:a.email,"onUpdate:modelValue":e[1]||(e[1]=n=>a.email=n),placeholder:"电子邮箱",maxlength:"100",clearable:""},{prefix:s(()=>[t(r,null,{default:s(()=>[t(i(T))]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(d,{prop:"phone"},{default:s(()=>[t(u,{modelValue:a.phone,"onUpdate:modelValue":e[2]||(e[2]=n=>a.phone=n),placeholder:"手机号码",maxlength:"11",clearable:""},{prefix:s(()=>[t(r,null,{default:s(()=>[t(i(Z))]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(d,{prop:"inviteCode"},{default:s(()=>[t(u,{modelValue:a.inviteCode,"onUpdate:modelValue":e[3]||(e[3]=n=>a.inviteCode=n),placeholder:"邀请码(上级代理用户名,选填)",maxlength:"50",clearable:""},{prefix:s(()=>[t(r,null,{default:s(()=>[t(i(j))]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(d,{prop:"password"},{default:s(()=>[t(u,{modelValue:a.password,"onUpdate:modelValue":e[4]||(e[4]=n=>a.password=n),type:"password",placeholder:"密码",maxlength:"50","show-password":""},{prefix:s(()=>[t(r,null,{default:s(()=>[t(i(v))]),_:1})]),_:1},8,["modelValue"]),o("div",te,[o("div",{class:M(["strength-bar",V.value]),style:L({width:b.value})},null,6)]),o("div",se,"密码强度:"+W(y.value),1)]),_:1}),t(d,{prop:"confirmPassword"},{default:s(()=>[t(u,{modelValue:a.confirmPassword,"onUpdate:modelValue":e[5]||(e[5]=n=>a.confirmPassword=n),type:"password",placeholder:"确认密码",maxlength:"50","show-password":""},{prefix:s(()=>[t(r,null,{default:s(()=>[t(i(v))]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(d,{prop:"agreement"},{default:s(()=>[t(k,{modelValue:a.agreement,"onUpdate:modelValue":e[6]||(e[6]=n=>a.agreement=n)},{default:s(()=>[e[10]||(e[10]=m(" 我已阅读并同意 ",-1)),t(C,{type:"primary"},{default:s(()=>[...e[9]||(e[9]=[m("《代理服务协议》",-1)])]),_:1})]),_:1},8,["modelValue"])]),_:1}),t(d,null,{default:s(()=>[t(P,{type:"primary",loading:f.value,stLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
.auth-container[data-v-7d9a6591]{min-height:100vh;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#1a1a2e,#16213e,#0f3460);position:relative;overflow:hidden;padding:24px}.auth-bg[data-v-7d9a6591]{position:absolute;top:0;right:0;bottom:0;left:0;overflow:hidden}.bg-circle[data-v-7d9a6591]{position:absolute;border-radius:50%;opacity:.06;background:#409eff}.bg-circle.c1[data-v-7d9a6591]{width:500px;height:500px;top:-150px;right:-100px}.bg-circle.c2[data-v-7d9a6591]{width:300px;height:300px;bottom:-80px;left:-80px}.bg-circle.c3[data-v-7d9a6591]{width:200px;height:200px;top:40%;left:60%}.auth-card[data-v-7d9a6591]{position:relative;width:100%;max-width:440px;padding:40px 36px 32px;background:#fff;border-radius:16px;box-shadow:0 24px 80px #00000040;z-index:1}.auth-header[data-v-7d9a6591]{text-align:center;margin-bottom:28px}.auth-icon[data-v-7d9a6591]{margin-bottom:12px}.auth-title[data-v-7d9a6591]{color:#1a1a2e;font-size:24px;font-weight:700;margin-bottom:6px}.auth-subtitle[data-v-7d9a6591]{color:#909399;font-size:14px}.auth-form[data-v-7d9a6591] .el-input__wrapper{border-radius:8px}.password-strength[data-v-7d9a6591]{height:4px;background:#e4e7ed;border-radius:2px;margin-top:8px;overflow:hidden}.strength-bar[data-v-7d9a6591]{height:100%;border-radius:2px;transition:width .3s ease,background .3s ease}.strength-bar.weak[data-v-7d9a6591]{background:#f56c6c}.strength-bar.medium[data-v-7d9a6591]{background:#e6a23c}.strength-bar.strong[data-v-7d9a6591]{background:#67c23a}.strength-text[data-v-7d9a6591]{font-size:12px;color:#909399;margin-top:4px}.auth-footer[data-v-7d9a6591]{text-align:center;margin-top:20px;color:#606266;font-size:14px}.auth-link[data-v-7d9a6591]{color:#409eff;margin-left:6px;text-decoration:none;font-weight:500}.auth-link[data-v-7d9a6591]:hover{text-decoration:underline}@media (max-width: 480px){.auth-card[data-v-7d9a6591]{padding:32px 24px 24px;border-radius:12px}.auth-title[data-v-7d9a6591]{font-size:22px}}
|
||||
@@ -0,0 +1 @@
|
||||
.agents-page[data-v-42322893]{max-width:1600px;margin:0 auto}.quota-row[data-v-42322893],.main-card[data-v-42322893]{margin-bottom:20px}.stat-card[data-v-42322893]{background:#fff;border-radius:12px;padding:24px;display:flex;align-items:center;gap:20px;box-shadow:0 2px 8px #0000000f;transition:all .3s ease}.stat-card[data-v-42322893]:hover{transform:translateY(-4px);box-shadow:0 8px 16px #0000001a}.stat-icon[data-v-42322893]{width:64px;height:64px;border-radius:12px;display:flex;align-items:center;justify-content:center;color:#fff;flex-shrink:0}.stat-total .stat-icon[data-v-42322893]{background:linear-gradient(135deg,#667eea,#764ba2)}.stat-used .stat-icon[data-v-42322893]{background:linear-gradient(135deg,#f093fb,#f5576c)}.stat-active .stat-icon[data-v-42322893]{background:linear-gradient(135deg,#43e97b,#38f9d7)}.stat-value[data-v-42322893]{font-size:32px;font-weight:700;color:#303133}.stat-label[data-v-42322893]{font-size:14px;color:#909399;margin-top:4px}.advanced-search[data-v-42322893]{padding:20px;background:#f5f7fa;border-radius:8px;margin-bottom:20px}.search-form[data-v-42322893]{display:flex;flex-wrap:wrap;gap:12px}.toolbar[data-v-42322893]{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:12px}.toolbar-left[data-v-42322893],.toolbar-right[data-v-42322893]{display:flex;gap:12px;flex-wrap:wrap}.data-table[data-v-42322893] .el-table__header th{font-weight:600;color:#303133}.text-success[data-v-42322893]{color:#67c23a}.text-danger[data-v-42322893]{color:#f56c6c}.pagination-wrapper[data-v-42322893]{margin-top:20px;display:flex;justify-content:flex-end}.column-settings[data-v-42322893]{padding:8px}.column-settings-title[data-v-42322893]{font-weight:600;margin-bottom:12px}.column-settings .el-checkbox[data-v-42322893]{display:block;margin-bottom:8px}.expand-enter-active[data-v-42322893],.expand-leave-active[data-v-42322893]{transition:all .3s ease}.expand-enter-from[data-v-42322893],.expand-leave-to[data-v-42322893]{opacity:0;max-height:0;overflow:hidden}.expand-enter-to[data-v-42322893],.expand-leave-from[data-v-42322893]{opacity:1;max-height:200px}@media (max-width:768px){.toolbar[data-v-42322893]{flex-direction:column;align-items:stretch}.toolbar-left[data-v-42322893],.toolbar-right[data-v-42322893]{width:100%}.search-form[data-v-42322893]{flex-direction:column}.search-form .el-form-item[data-v-42322893],.search-form .el-select[data-v-42322893],.search-form .el-input[data-v-42322893]{width:100%!important}}
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Ie,m as Le,o as s,c as E,b as l,w as t,K as c,P as u,D as se,l as p,a3 as Pe,a5 as Te,H as Ae,a4 as Be,a as n,E as Ne,n as o,aN as Me,C as m,aO as Ke,aP as Oe,T as Qe,a9 as Q,d as He,e as Ze,f as Ge,g as Je,aa as We,ab as Xe,h as Ye,ac as ea,i as r,ad as ne,ae as aa,af as re,S as ta,ag as la,ah as oa,U as sa,V as na,aj as ra,ak as ua,F as H,R as Z,t as da,al as ia,am as pa,an as ca,B as ma,Z as _a,ar as fa,as as ga,at as ue,au as va,k as j}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as ba}from"./user-KptFbP1d.js";import{u as ya,a as ha}from"./useColumnSettings-sXzip_cz.js";import{r as h}from"./index-CZCGMR8A.js";const wa={class:"agents-page"},ka={key:0,class:"quota-row"},Ca={class:"stat-card stat-total"},xa={class:"stat-icon"},Va={class:"stat-info"},Fa={class:"stat-value"},Ea={class:"stat-card stat-used"},Sa={class:"stat-icon"},qa={class:"stat-info"},za={class:"stat-value"},Ua={class:"stat-card stat-active"},ja={class:"stat-icon"},Ra={class:"stat-info"},Da={class:"stat-value"},$a={class:"advanced-search"},Ia={class:"toolbar"},La={class:"toolbar-left"},Pa={class:"toolbar-right"},Ta={class:"column-settings"},Aa={class:"pagination-wrapper"},Ba={__name:"Agents",setup(Na){const de=ba(),ie=se(()=>de.user),w=se(()=>{var i;return((i=ie.value)==null?void 0:i.role)==="admin"}),S=p(!0),G=p([]),k=p(null),J=p([]),R=p(!1),{list:pe,loading:ce,page:D,pageSize:$,total:me,selectedRows:q,filters:C,tableMaxHeight:_e,fetchData:I,handleSelectionChange:fe,handleSortChange:ge,handleSizeChange:ve,handleFilterChange:z,resetFilters:be,refreshData:ye}=ya({apiUrl:"/agents",defaultFilters:{keyword:"",status:""},defaultPageSize:20}),{columnOptions:he,visibleColumns:f,saveColumnSettings:we}=ha("agents_column_settings",[{prop:"id",label:"ID"},{prop:"username",label:"用户名"},{prop:"nickname",label:"昵称"},{prop:"total_quota",label:"总额度"},{prop:"used_quota",label:"已使用"},{prop:"remain_quota",label:"剩余额度"},{prop:"status",label:"状态"},{prop:"last_login_at",label:"最后登录"},{prop:"created_at",label:"创建时间"}]);Le(async()=>{if(w.value)I();else{W(),X();const i=await h.get("/projects/all");G.value=i.data}});async function W(){try{k.value=(await h.get("/agents/my-quota")).data}catch{}}async function X(){R.value=!0;try{J.value=(await h.get("/agents/quota-logs",{params:{page_size:50}})).data.list}finally{R.value=!1}}const x=p(!1),L=p(null),P=p(null),b=p({amount:0,remark:""}),ke={amount:[{required:!0,message:"请输入金额",trigger:"blur"}]},T=p(!1);function Y(i){L.value=i,b.value={amount:0,remark:""},x.value=!0}async function Ce(){P.value&&await P.value.validate(async i=>{var e;if(i){T.value=!0;try{await h.post("/agents/recharge",{agent_id:(e=L.value)==null?void 0:e.id,amount:b.value.amount,remark:b.value.remark}),j.success("充值成功"),x.value=!1,I()}catch{}finally{T.value=!1}}})}const ee=p(null),g=p({project_id:"",card_type_id:""}),xe={project_id:[{required:!0,message:"请选择项目",trigger:"change"}],card_type_id:[{required:!0,message:"请选择套餐",trigger:"change"}]},A=p([]),B=p(!1);async function Ve(i){if(g.value.card_type_id="",!i){A.value=[];return}A.value=(await h.get(`/projects/${i}/card-types`)).data||[]}async function Fe(){await ee.value.validate(async i=>{if(i){B.value=!0;try{const e=await h.post("/agents/authorize",g.value);j.success(`授权成功!卡密: ${e.data.card_key}`),W(),X(),g.value={project_id:"",card_type_id:""}}catch{}finally{B.value=!1}}})}function Ee(i){if(!q.value.length){j.warning("请先选择要导出的代理");return}const e=new URLSearchParams;e.set("ids",q.value.map(V=>V.id).join(",")),e.append("format",i);const y=localStorage.getItem("access_token");window.open(`/api/agents/export?${e.toString()}&token=${y}`,"_blank"),j.success("导出任务已启动")}return(i,e)=>{const y=Ne,V=Be,Se=Pe,N=Ge,v=Ze,U=Xe,M=We,_=Ye,K=He,ae=na,qe=sa,ze=ta,Ue=da,je=ua,d=ca,F=_a,te=pa,Re=ga,O=Te,De=va,$e=Ae,le=fa;return s(),E("div",wa,[!w.value&&k.value?(s(),E("div",ka,[l(Se,{gutter:20},{default:t(()=>[l(V,{xs:12,sm:8,md:8,lg:8},{default:t(()=>{var a;return[n("div",Ca,[n("div",xa,[l(y,{size:32},{default:t(()=>[l(o(Me))]),_:1})]),n("div",Va,[n("div",Fa,"¥"+m((a=k.value.total_quota)==null?void 0:a.toFixed(2)),1),e[12]||(e[12]=n("div",{class:"stat-label"},"总额度",-1))])])]}),_:1}),l(V,{xs:12,sm:8,md:8,lg:8},{default:t(()=>{var a;return[n("div",Ea,[n("div",Sa,[l(y,{size:32},{default:t(()=>[l(o(Ke))]),_:1})]),n("div",qa,[n("div",za,"¥"+m((a=k.value.used_quota)==null?void 0:a.toFixed(2)),1),e[13]||(e[13]=n("div",{class:"stat-label"},"已使用",-1))])])]}),_:1}),l(V,{xs:12,sm:8,md:8,lg:8},{default:t((Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Ie,m as Le,o as s,c as E,b as l,w as t,K as c,P as u,D as se,l as p,a4 as Pe,a6 as Te,H as Ae,a5 as Be,a as n,E as Ne,n as o,aN as Me,C as m,aO as Ke,aP as Oe,T as Qe,aa as Q,d as He,e as Ze,f as Ge,g as Je,ab as We,ac as Xe,h as Ye,ad as ea,i as r,ae as ne,af as aa,ag as re,S as ta,ah as la,ai as oa,U as sa,V as na,ak as ra,al as ua,F as H,R as Z,t as ia,am as da,an as pa,ao as ca,B as ma,Z as _a,as as fa,at as ga,au as ue,av as va,k as R}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as ba}from"./user-DvAOsLmR.js";import{u as ya,a as ha}from"./useColumnSettings-BO5PTaEn.js";import{r as h}from"./index-DpFNINBG.js";const wa={class:"agents-page"},ka={key:0,class:"quota-row"},Ca={class:"stat-card stat-total"},xa={class:"stat-icon"},Va={class:"stat-info"},Fa={class:"stat-value"},Ea={class:"stat-card stat-used"},Sa={class:"stat-icon"},qa={class:"stat-info"},za={class:"stat-value"},Ua={class:"stat-card stat-active"},Ra={class:"stat-icon"},ja={class:"stat-info"},Da={class:"stat-value"},$a={class:"advanced-search"},Ia={class:"toolbar"},La={class:"toolbar-left"},Pa={class:"toolbar-right"},Ta={class:"column-settings"},Aa={class:"pagination-wrapper"},Ba={__name:"Agents",setup(Na){const ie=ba(),de=se(()=>ie.user),w=se(()=>{var d;return((d=de.value)==null?void 0:d.role)==="admin"}),S=p(!0),G=p([]),k=p(null),J=p([]),j=p(!1),{list:pe,loading:ce,page:D,pageSize:$,total:me,selectedRows:q,filters:C,tableMaxHeight:_e,fetchData:I,handleSelectionChange:fe,handleSortChange:ge,handleSizeChange:ve,handleFilterChange:z,resetFilters:be,refreshData:ye}=ya({apiUrl:"/agents",defaultFilters:{keyword:"",status:""},defaultPageSize:20}),{columnOptions:he,visibleColumns:f,saveColumnSettings:we}=ha("agents_column_settings",[{prop:"id",label:"ID"},{prop:"username",label:"用户名"},{prop:"nickname",label:"昵称"},{prop:"total_quota",label:"总额度"},{prop:"used_quota",label:"已使用"},{prop:"remain_quota",label:"剩余额度"},{prop:"status",label:"状态"},{prop:"last_login_at",label:"最后登录"},{prop:"created_at",label:"创建时间"}]);Le(async()=>{if(w.value)I();else{W(),X();const d=await h.get("/projects/all");G.value=d.data}});async function W(){try{k.value=(await h.get("/agents/my-quota")).data}catch{}}async function X(){j.value=!0;try{J.value=(await h.get("/agents/quota-logs",{params:{page_size:50}})).data.list}finally{j.value=!1}}const x=p(!1),L=p(null),P=p(null),b=p({amount:0,remark:""}),ke={amount:[{required:!0,message:"请输入金额",trigger:"blur"}]},T=p(!1);function Y(d){L.value=d,b.value={amount:0,remark:""},x.value=!0}async function Ce(){P.value&&await P.value.validate(async d=>{var e;if(d){T.value=!0;try{await h.post("/agents/recharge",{agent_id:(e=L.value)==null?void 0:e.id,amount:b.value.amount,remark:b.value.remark}),R.success("充值成功"),x.value=!1,I()}catch{}finally{T.value=!1}}})}const ee=p(null),g=p({project_id:"",card_type_id:""}),xe={project_id:[{required:!0,message:"请选择项目",trigger:"change"}],card_type_id:[{required:!0,message:"请选择套餐",trigger:"change"}]},A=p([]),B=p(!1);async function Ve(d){if(g.value.card_type_id="",!d){A.value=[];return}A.value=(await h.get(`/projects/${d}/card-types`)).data||[]}async function Fe(){await ee.value.validate(async d=>{if(d){B.value=!0;try{const e=await h.post("/agents/authorize",g.value);R.success(`授权成功!卡密: ${e.data.card_key}`),W(),X(),g.value={project_id:"",card_type_id:""}}catch{}finally{B.value=!1}}})}function Ee(d){if(!q.value.length){R.warning("请先选择要导出的代理");return}const e=new URLSearchParams;e.set("ids",q.value.map(V=>V.id).join(",")),e.append("format",d);const y=localStorage.getItem("access_token");window.open(`/api/agents/export?${e.toString()}&token=${y}`,"_blank"),R.success("导出任务已启动")}return(d,e)=>{const y=Ne,V=Be,Se=Pe,N=Ge,v=Ze,U=Xe,M=We,_=Ye,K=He,ae=na,qe=sa,ze=ta,Ue=ia,Re=ua,i=ca,F=_a,te=pa,je=ga,O=Te,De=va,$e=Ae,le=fa;return s(),E("div",wa,[!w.value&&k.value?(s(),E("div",ka,[l(Se,{gutter:20},{default:t(()=>[l(V,{xs:12,sm:8,md:8,lg:8},{default:t(()=>{var a;return[n("div",Ca,[n("div",xa,[l(y,{size:32},{default:t(()=>[l(o(Me))]),_:1})]),n("div",Va,[n("div",Fa,"¥"+m((a=k.value.total_quota)==null?void 0:a.toFixed(2)),1),e[12]||(e[12]=n("div",{class:"stat-label"},"总额度",-1))])])]}),_:1}),l(V,{xs:12,sm:8,md:8,lg:8},{default:t(()=>{var a;return[n("div",Ea,[n("div",Sa,[l(y,{size:32},{default:t(()=>[l(o(Ke))]),_:1})]),n("div",qa,[n("div",za,"¥"+m((a=k.value.used_quota)==null?void 0:a.toFixed(2)),1),e[13]||(e[13]=n("div",{class:"stat-label"},"已使用",-1))])])]}),_:1}),l(V,{xs:12,sm:8,md:8,lg:8},{default:t((Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Le,o as i,c as L,b as a,w as t,a4 as Pe,a6 as Te,l as x,H as Ae,a5 as Me,a as s,E as Ne,n as o,s as He,C as d,a8 as Oe,ay as Ge,a9 as Ze,T as Je,aa as te,d as We,e as Xe,f as Ye,g as J,ab as et,ac as tt,h as at,ad as lt,i as n,ae,af as ot,ag as st,S as nt,ah as it,ai as dt,U as rt,V as ut,aj as ct,ak as _t,al as pt,F as mt,R as ft,P as u,t as vt,am as gt,an as bt,ao as yt,K as m,Z as kt,B as le,aG as ht,as as Ct,at as xt,au as oe,aH as qt,aI as wt,D as W,k as Q,aw as se,j as ne}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as Vt,a as zt}from"./useColumnSettings-BO5PTaEn.js";import{r as S}from"./index-DpFNINBG.js";const I={list(g){return S.get("/authorizations",{params:g})},stats(){return S.get("/authorizations/stats")},detail(g){return S.get(`/authorizations/${g}`)},create(g){return S.post("/authorizations",g)},revoke(g,z){return S.put(`/authorizations/${g}/revoke`,{reason:z})},delete(g){return S.delete(`/authorizations/${g}`)}},Et={class:"authorizations-page"},Qt={class:"stat-card stat-total"},St={class:"stat-icon"},Dt={class:"stat-info"},Ut={class:"stat-value"},$t={class:"stat-card stat-active"},Ft={class:"stat-icon"},It={class:"stat-info"},Rt={class:"stat-value"},jt={class:"stat-card stat-expired"},Bt={class:"stat-icon"},Kt={class:"stat-info"},Lt={class:"stat-value"},Pt={class:"stat-card stat-revoked"},Tt={class:"stat-icon"},At={class:"stat-info"},Mt={class:"stat-value"},Nt={class:"advanced-search"},Ht={class:"toolbar"},Ot={class:"toolbar-left"},Gt={class:"toolbar-right"},Zt={class:"column-settings"},Jt={class:"mono-text"},Wt={class:"mono-text"},Xt={key:0,class:"text-success"},Yt={class:"pagination-wrapper"},ea={class:"mono-text"},ta={class:"mono-text"},aa={class:"mono-text"},la={__name:"Authorizations",setup(g){const z=x(!0),{list:R,loading:ie,page:P,pageSize:T,total:X,selectedRows:k,filters:h,tableMaxHeight:de,stats:j,fetchData:D,fetchStats:B,handleSelectionChange:re,handleSortChange:ue,handleSizeChange:ce,handleFilterChange:q,resetFilters:_e,refreshData:pe}=Vt({apiUrl:"/authorizations",statsUrl:"/authorizations/stats",defaultFilters:{bot_qq:"",contact_qq:"",status:"",card_key:""},defaultPageSize:20}),{columnOptions:me,visibleColumns:b,saveColumnSettings:fe}=zt("authorizations_column_settings",[{prop:"id",label:"ID"},{prop:"bot_qq",label:"机器人QQ"},{prop:"contact_qq",label:"联系人QQ"},{prop:"contact_name",label:"联系人"},{prop:"card_key",label:"卡密"},{prop:"project_name",label:"项目"},{prop:"duration_days",label:"有效天数"},{prop:"status",label:"状态"},{prop:"expire_time",label:"过期时间"},{prop:"authorized_at",label:"授权时间"}]),ve=W(()=>R.value.filter(c=>c.status==="active"&&!c.is_expired).length),ge=W(()=>R.value.filter(c=>c.is_expired).length),be=W(()=>R.value.filter(c=>c.status==="revoked").length),U=x(!1),A=x(!1),M=x(null),p=ne({card_key:"",bot_qq:"",contact_qq:"",contact_name:""}),ye={card_key:[{required:!0,message:"请输入卡密",trigger:"blur"}],bot_qq:[{required:!0,message:"请输入机器人QQ",trigger:"blur"},{pattern:/^\d{5,15}$/,message:"请输入5-15位数字",trigger:"blur"}],contact_qq:[{required:!0,message:"请输入联系人QQ",trigger:"blur"},{pattern:/^\d{5,15}$/,message:"请输入5-15位数字",trigger:"blur"}]};function ke(){U.value=!0}function he(){var c;p.card_key="",p.bot_qq="",p.contact_qq="",p.contact_name="",(c=M.value)==null||c.resetFields()}async function Ce(){if(await M.value.validate().catch(()=>!1)){A.value=!0;try{await I.create({...p}),Q.success("授权成功"),U.value=!1,D(),B()}finally{A.value=!1}}}const N=x(!1),r=x(null);async function xe(c){try{const e=await I.detail(c.id);r.value=e.data,N.value=!0}catch{}}const $=x(!1),H=x(!1),Y=x(null),F=ne({reason:""});function qe(c){Y.value=c.id,F.reason="",$.value=!0}async function we(){H.value=!0;try{await I.revoke(Y.value,F.reason),Q.success("授权已撤销"),$.value=!1,D(),B()}finally{H.value=!1}}async function Ve(c){try{await se.confirm("确定要删除此授权记录吗?此操作不可恢复。","确认删除",{type:"warning"}),await I.delete(c),Q.success("已删除"),D(),B()}catch{}}async function ze(){if(k.value.length)try{await se.confirm(`确定删除选中的 ${k.value.length} 条授权记录吗?`,"批量删除",{type:"warning"});for(const c of k.value)await I.delete(c.id);Q.success("批量删除成功"),D(),B()}catch{}}function Ee(c){if(!k.value.length){Q.warning("请先选择要导出的授权");return}const e=new URLSearchParams;e.set("ids",k.value.map(E=>E.id).join(",")),e.append("format",c);const V=localStorage.getItem("access_token");window.open(`/api/authorizations/export?${e.toString()}&to
Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
.authorizations-page[data-v-6bd70485]{max-width:1600px;margin:0 auto}.stats-row[data-v-6bd70485]{margin-bottom:20px}.stat-card[data-v-6bd70485]{background:#fff;border-radius:12px;padding:24px;display:flex;align-items:center;gap:20px;box-shadow:0 2px 8px #0000000f;transition:all .3s ease}.stat-card[data-v-6bd70485]:hover{transform:translateY(-4px);box-shadow:0 8px 16px #0000001a}.stat-icon[data-v-6bd70485]{width:64px;height:64px;border-radius:12px;display:flex;align-items:center;justify-content:center;color:#fff;flex-shrink:0}.stat-total .stat-icon[data-v-6bd70485]{background:linear-gradient(135deg,#667eea,#764ba2)}.stat-active .stat-icon[data-v-6bd70485]{background:linear-gradient(135deg,#43e97b,#38f9d7)}.stat-expired .stat-icon[data-v-6bd70485]{background:linear-gradient(135deg,#f093fb,#f5576c)}.stat-revoked .stat-icon[data-v-6bd70485]{background:linear-gradient(135deg,#4facfe,#00f2fe)}.stat-value[data-v-6bd70485]{font-size:32px;font-weight:700;color:#303133}.stat-label[data-v-6bd70485]{font-size:14px;color:#909399;margin-top:4px}.advanced-search[data-v-6bd70485]{padding:20px;background:#f5f7fa;border-radius:8px;margin-bottom:20px}.search-form[data-v-6bd70485]{display:flex;flex-wrap:wrap;gap:12px}.toolbar[data-v-6bd70485]{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:12px}.toolbar-left[data-v-6bd70485],.toolbar-right[data-v-6bd70485]{display:flex;gap:12px;flex-wrap:wrap}.data-table[data-v-6bd70485] .el-table__header th{font-weight:600;color:#303133}.mono-text[data-v-6bd70485]{font-family:Courier New,monospace}.text-success[data-v-6bd70485]{color:#67c23a}.text-danger[data-v-6bd70485]{color:#f56c6c}.pagination-wrapper[data-v-6bd70485]{margin-top:20px;display:flex;justify-content:flex-end}.column-settings[data-v-6bd70485]{padding:8px}.column-settings-title[data-v-6bd70485]{font-weight:600;margin-bottom:12px}.column-settings .el-checkbox[data-v-6bd70485]{display:block;margin-bottom:8px}.expand-enter-active[data-v-6bd70485],.expand-leave-active[data-v-6bd70485]{transition:all .3s ease}.expand-enter-from[data-v-6bd70485],.expand-leave-to[data-v-6bd70485]{opacity:0;max-height:0;overflow:hidden}.expand-enter-to[data-v-6bd70485],.expand-leave-from[data-v-6bd70485]{opacity:1;max-height:200px}@media (max-width:768px){.toolbar[data-v-6bd70485]{flex-direction:column;align-items:stretch}.toolbar-left[data-v-6bd70485],.toolbar-right[data-v-6bd70485]{width:100%}.search-form[data-v-6bd70485]{flex-direction:column}.search-form .el-form-item[data-v-6bd70485],.search-form .el-select[data-v-6bd70485],.search-form .el-input[data-v-6bd70485]{width:100%!important}}
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Le,o as i,c as L,b as a,w as t,a3 as Pe,a5 as Te,l as C,H as Ae,a4 as Me,a as s,E as Ne,n as o,s as He,C as d,a7 as Oe,ax as Ge,a8 as Ze,T as Je,a9 as te,d as We,e as Xe,f as Ye,g as J,aa as et,ab as tt,h as at,ac as lt,i as n,ad as ae,ae as ot,af as st,S as nt,ag as it,ah as dt,U as rt,V as ut,ai as ct,aj as _t,ak as pt,F as mt,R as ft,P as u,t as vt,al as gt,am as bt,an as yt,K as m,Z as kt,B as le,aF as ht,ar as xt,as as Ct,at as oe,aG as qt,aH as wt,D as W,k as Q,av as se,j as ne}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as Vt,a as zt}from"./useColumnSettings-sXzip_cz.js";import{r as S}from"./index-CZCGMR8A.js";const I={list(g){return S.get("/authorizations",{params:g})},stats(){return S.get("/authorizations/stats")},detail(g){return S.get(`/authorizations/${g}`)},create(g){return S.post("/authorizations",g)},revoke(g,z){return S.put(`/authorizations/${g}/revoke`,{reason:z})},delete(g){return S.delete(`/authorizations/${g}`)}},Et={class:"authorizations-page"},Qt={class:"stat-card stat-total"},St={class:"stat-icon"},Dt={class:"stat-info"},Ut={class:"stat-value"},Ft={class:"stat-card stat-active"},$t={class:"stat-icon"},It={class:"stat-info"},Rt={class:"stat-value"},jt={class:"stat-card stat-expired"},Bt={class:"stat-icon"},Kt={class:"stat-info"},Lt={class:"stat-value"},Pt={class:"stat-card stat-revoked"},Tt={class:"stat-icon"},At={class:"stat-info"},Mt={class:"stat-value"},Nt={class:"advanced-search"},Ht={class:"toolbar"},Ot={class:"toolbar-left"},Gt={class:"toolbar-right"},Zt={class:"column-settings"},Jt={class:"mono-text"},Wt={class:"mono-text"},Xt={key:0,class:"text-success"},Yt={class:"pagination-wrapper"},ea={class:"mono-text"},ta={class:"mono-text"},aa={class:"mono-text"},la={__name:"Authorizations",setup(g){const z=C(!0),{list:R,loading:ie,page:P,pageSize:T,total:X,selectedRows:k,filters:h,tableMaxHeight:de,stats:j,fetchData:D,fetchStats:B,handleSelectionChange:re,handleSortChange:ue,handleSizeChange:ce,handleFilterChange:q,resetFilters:_e,refreshData:pe}=Vt({apiUrl:"/authorizations",statsUrl:"/authorizations/stats",defaultFilters:{bot_qq:"",contact_qq:"",status:"",card_key:""},defaultPageSize:20}),{columnOptions:me,visibleColumns:b,saveColumnSettings:fe}=zt("authorizations_column_settings",[{prop:"id",label:"ID"},{prop:"bot_qq",label:"机器人QQ"},{prop:"contact_qq",label:"联系人QQ"},{prop:"contact_name",label:"联系人"},{prop:"card_key",label:"卡密"},{prop:"project_name",label:"项目"},{prop:"duration_days",label:"有效天数"},{prop:"status",label:"状态"},{prop:"expire_time",label:"过期时间"},{prop:"authorized_at",label:"授权时间"}]),ve=W(()=>R.value.filter(c=>c.status==="active"&&!c.is_expired).length),ge=W(()=>R.value.filter(c=>c.is_expired).length),be=W(()=>R.value.filter(c=>c.status==="revoked").length),U=C(!1),A=C(!1),M=C(null),p=ne({card_key:"",bot_qq:"",contact_qq:"",contact_name:""}),ye={card_key:[{required:!0,message:"请输入卡密",trigger:"blur"}],bot_qq:[{required:!0,message:"请输入机器人QQ",trigger:"blur"},{pattern:/^\d{5,15}$/,message:"请输入5-15位数字",trigger:"blur"}],contact_qq:[{required:!0,message:"请输入联系人QQ",trigger:"blur"},{pattern:/^\d{5,15}$/,message:"请输入5-15位数字",trigger:"blur"}]};function ke(){U.value=!0}function he(){var c;p.card_key="",p.bot_qq="",p.contact_qq="",p.contact_name="",(c=M.value)==null||c.resetFields()}async function xe(){if(await M.value.validate().catch(()=>!1)){A.value=!0;try{await I.create({...p}),Q.success("授权成功"),U.value=!1,D(),B()}finally{A.value=!1}}}const N=C(!1),r=C(null);async function Ce(c){try{const e=await I.detail(c.id);r.value=e.data,N.value=!0}catch{}}const F=C(!1),H=C(!1),Y=C(null),$=ne({reason:""});function qe(c){Y.value=c.id,$.reason="",F.value=!0}async function we(){H.value=!0;try{await I.revoke(Y.value,$.reason),Q.success("授权已撤销"),F.value=!1,D(),B()}finally{H.value=!1}}async function Ve(c){try{await se.confirm("确定要删除此授权记录吗?此操作不可恢复。","确认删除",{type:"warning"}),await I.delete(c),Q.success("已删除"),D(),B()}catch{}}async function ze(){if(k.value.length)try{await se.confirm(`确定删除选中的 ${k.value.length} 条授权记录吗?`,"批量删除",{type:"warning"});for(const c of k.value)await I.delete(c.id);Q.success("批量删除成功"),D(),B()}catch{}}function Ee(c){if(!k.value.length){Q.warning("请先选择要导出的授权");return}const e=new URLSearchParams;e.set("ids",k.value.map(E=>E.id).join(",")),e.append("format",c);const V=localStorage.getItem("access_token");window.open(`/api/authorizations/export?${e.toStringLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Te,o as u,c as A,b as t,w as a,a4 as Me,a6 as Le,l as _,H as je,a5 as qe,a as i,E as He,n as l,aQ as Ke,C as b,a8 as Ne,ay as Ye,T as Ae,aa as O,d as Oe,e as Ge,ab as Qe,ac as Ze,f as Je,g as We,h as Xe,ad as et,i as r,ae as G,af as tt,ag as at,aj as Q,S as lt,ah as ot,ai as nt,U as st,V as it,aE as Z,ak as rt,al as dt,F as ut,R as pt,P as c,t as ct,am as mt,an as _t,ao as ft,K as y,Z as gt,aq as vt,ar as bt,as as yt,at as kt,au as J,aS as ht,aT as wt,aD as Ct,a3 as xt,D as W,aw as X,k as f,j as Vt}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as Et,a as St}from"./useColumnSettings-BO5PTaEn.js";import{r as V}from"./index-DpFNINBG.js";const Dt={class:"blacklist-page"},Ut={class:"stat-card stat-total"},It={class:"stat-icon"},zt={class:"stat-info"},Ft={class:"stat-value"},Rt={class:"stat-card stat-active"},$t={class:"stat-icon"},Pt={class:"stat-info"},Bt={class:"stat-value"},Tt={class:"stat-card stat-expired"},Mt={class:"stat-icon"},Lt={class:"stat-info"},jt={class:"stat-value"},qt={class:"advanced-search"},Ht={class:"toolbar"},Kt={class:"toolbar-left"},Nt={class:"toolbar-right"},Yt={class:"column-settings"},At={class:"pagination-wrapper"},Ot={__name:"Blacklist",setup(Gt){const I=_(!0),R=_(!1),$=_(!1),C=_(!1),E=_(!1),x=_(!1),P=_(null),z=_(null),S=_(null),{list:B,loading:ee,page:T,pageSize:M,total:q,selectedRows:m,filters:k,tableMaxHeight:te,fetchData:D,handleSelectionChange:ae,handleSortChange:le,handleSizeChange:oe,handleFilterChange:U,resetFilters:ne,refreshData:se}=Et({apiUrl:"/blacklists",defaultFilters:{target_type:"",status:"",keyword:""},defaultPageSize:20}),{columnOptions:ie,visibleColumns:g,saveColumnSettings:re}=St("blacklist_column_settings",[{prop:"id",label:"ID"},{prop:"target_type",label:"类型"},{prop:"target_value",label:"目标值"},{prop:"status",label:"状态"},{prop:"expire_time",label:"过期时间"},{prop:"operator_name",label:"操作人"},{prop:"remark",label:"备注"},{prop:"created_at",label:"添加时间"}]),de=W(()=>B.value.filter(n=>n.status===1).length),ue=W(()=>B.value.filter(n=>n.expire_time&&new Date(n.expire_time)<new Date).length),s=Vt({id:null,target_type:"ip",target_value:"",expire_time:"",remark:""}),pe={target_type:[{required:!0,message:"请选择目标类型",trigger:"change"}],target_value:[{required:!0,message:"请输入目标值",trigger:"blur"}]};function ce(){s.id=null,s.target_type="ip",s.target_value="",s.expire_time="",s.remark="",S.value&&S.value.resetFields()}function me(){x.value=!1,ce(),C.value=!0}function _e(n){x.value=!0,s.id=n.id,s.target_type=n.target_type,s.target_value=n.target_value,s.expire_time=n.expire_time||"",s.remark=n.remark||"",C.value=!0}async function fe(){S.value&&await S.value.validate(async n=>{if(n){R.value=!0;try{x.value?(await V.put(`/blacklists/${s.id}`,{expire_time:s.expire_time||null,remark:s.remark}),f.success("黑名单更新成功")):(await V.post("/blacklists",{target_type:s.target_type,target_value:s.target_value,expire_time:s.expire_time||null,remark:s.remark}),f.success("黑名单添加成功")),C.value=!1,D()}catch{}finally{R.value=!1}}})}async function ge(n,e){try{await V.put(`/blacklists/${n.id}`,{status:e}),f.success("状态更新成功")}catch{n.status=e===1?0:1}}async function ve(n){try{await X.confirm("确定删除该黑名单吗?","提示",{type:"warning"}),await V.delete(`/blacklists/${n.id}`),f.success("删除成功"),D()}catch(e){e!=="cancel"&&console.error(e)}}async function be(){if(m.value.length)try{await X.confirm(`确定删除选中的 ${m.value.length} 条黑名单吗?`,"警告",{type:"warning"});const n=m.value.map(e=>e.id);await V.post("/blacklists/batch-delete",{ids:n}),f.success("批量删除成功"),D()}catch(n){n!=="cancel"&&console.error(n)}}function ye(){if(!m.value.length){f.warning("请先选择要导出的记录");return}const n=new URLSearchParams;n.set("ids",m.value.map(h=>h.id).join(","));const e=localStorage.getItem("access_token");window.open(`/api/blacklists/export?${n.toString()}&token=${e}`,"_blank"),f.success("导出任务已启动")}function ke(n){z.value=n.raw}async function he(){if(!z.value){f.warning("请选择 CSV 文件");return}const n=new FormData;n.append("file",z.value),$.value=!0;try{const e=await V.post("/blacklists/import",n,{headers:{"Content-Type":"multipart/form-data"}});f.success(e.message||"导入完成"),E.value=!1,z.value=null,P.value&&P.value.clearFiles(),D()}catch{}finally{$.value=!1}}return(n,e)=>{const h=He,L=qe,we=Me,F=Ze,H=Qe,v=Ge,j=Je,d=Xe,K=Oe,Ce=it,xe=st,Ve=lt,Ee=ct,Se=dt,p=ft,De=gt,Ue=vt,Ie=_t,ze=kt,Fe=Le,N=wt,ReLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
.el-radio{--el-radio-font-size:var(--el-font-size-base);--el-radio-text-color:var(--el-text-color-regular);--el-radio-font-weight:var(--el-font-weight-primary);--el-radio-input-height:14px;--el-radio-input-width:14px;--el-radio-input-border-radius:var(--el-border-radius-circle);--el-radio-input-bg-color:var(--el-fill-color-blank);--el-radio-input-border:var(--el-border);--el-radio-input-border-color:var(--el-border-color);--el-radio-input-border-color-hover:var(--el-color-primary);color:var(--el-radio-text-color);font-weight:var(--el-radio-font-weight);cursor:pointer;white-space:nowrap;font-size:var(--el-font-size-base);-webkit-user-select:none;user-select:none;outline:none;align-items:center;height:32px;margin-right:30px;display:inline-flex;position:relative}.el-radio.el-radio--large{height:40px}.el-radio.el-radio--small{height:24px}.el-radio.is-bordered{border-radius:var(--el-border-radius-base);border:var(--el-border);box-sizing:border-box;padding:0 15px 0 9px}.el-radio.is-bordered.is-checked{border-color:var(--el-color-primary)}.el-radio.is-bordered.is-disabled{cursor:not-allowed;border-color:var(--el-border-color-lighter)}.el-radio.is-bordered.el-radio--large{border-radius:var(--el-border-radius-base);padding:0 19px 0 11px}.el-radio.is-bordered.el-radio--large .el-radio__label{font-size:var(--el-font-size-base)}.el-radio.is-bordered.el-radio--large .el-radio__inner{width:14px;height:14px}.el-radio.is-bordered.el-radio--small{border-radius:var(--el-border-radius-base);padding:0 11px 0 7px}.el-radio.is-bordered.el-radio--small .el-radio__label{font-size:12px}.el-radio.is-bordered.el-radio--small .el-radio__inner{width:12px;height:12px}.el-radio:last-child{margin-right:0}.el-radio__input{white-space:nowrap;cursor:pointer;vertical-align:middle;outline:none;display:inline-flex;position:relative}.el-radio__input.is-disabled .el-radio__inner{background-color:var(--el-disabled-bg-color);border-color:var(--el-disabled-border-color);cursor:not-allowed}.el-radio__input.is-disabled .el-radio__inner:after{cursor:not-allowed;background-color:var(--el-disabled-bg-color)}.el-radio__input.is-disabled .el-radio__inner+.el-radio__label{cursor:not-allowed}.el-radio__input.is-disabled.is-checked .el-radio__inner{background-color:var(--el-disabled-bg-color);border-color:var(--el-disabled-border-color)}.el-radio__input.is-disabled.is-checked .el-radio__inner:after{background-color:var(--el-text-color-placeholder)}.el-radio__input.is-disabled+span.el-radio__label{color:var(--el-text-color-placeholder);cursor:not-allowed}.el-radio__input.is-checked .el-radio__inner{border-color:var(--el-color-primary);background:var(--el-color-primary)}.el-radio__input.is-checked .el-radio__inner:after{background-color:var(--el-color-white);transform:translate(-50%,-50%)scale(1)}.el-radio__input.is-checked+.el-radio__label{color:var(--el-color-primary)}.el-radio__input.is-focus .el-radio__inner{border-color:var(--el-radio-input-border-color-hover)}.el-radio__inner{border:var(--el-radio-input-border);border-radius:var(--el-radio-input-border-radius);width:var(--el-radio-input-width);height:var(--el-radio-input-height);background-color:var(--el-radio-input-bg-color);cursor:pointer;box-sizing:border-box;transition:all .3s;display:inline-block;position:relative}.el-radio__inner:hover{border-color:var(--el-radio-input-border-color-hover)}.el-radio__inner:after{border-radius:var(--el-radio-input-border-radius);content:"";width:4px;height:4px;transition:transform .15s ease-in;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)scale(0)}.el-radio__original{opacity:0;z-index:-1;outline:none;margin:0;position:absolute;top:0;bottom:0;left:0;right:0}.el-radio__original:focus-visible+.el-radio__inner{outline:2px solid var(--el-radio-input-border-color-hover);outline-offset:1px;border-radius:var(--el-radio-input-border-radius)}.el-radio:focus:not(:focus-visible):not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner{box-shadow:0 0 2px 2px var(--el-radio-input-border-color-hover)}.el-radio__label{font-size:var(--el-radio-font-size);padding-left:8px}.el-radio.el-radio--large .el-radio__label{font-size:14px}.el-radio.el-radio--large .el-radio__inner{width:14px;height:14px}.el-radio.el-radio--small .el-radio__label{font-size:12px}.el-radio.el-radio--small .el-radio__inner{width:12px;height:12px}.el-radio-group{flex-wrap:wrap;align-items:center;font-size:0;display:inline-flex}.el-radio-button{--el-radio-button-checked-bg-color:var(--el-color-primary);--el-radio-button-checked-text-color:var(--el-color-white);--el-radio-button-checked-border-color:var(--el-color-primary);--el-radio-button-disabled-checked-fill:var(--el-border-color-extra-light);outline:none;display:inline-block;position:relative}.el-radio-button__inner{white-space:nowrap;vertical-align:middle;background:var(--el-button-bg-color,var(--el-fill-color-blank));outline:var(--el-border);line-height:1;font-weight:var(--el-button-font-weight,var(--el-font-weight-primary));color:var(-Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Te,o as u,c as A,b as t,w as a,a3 as Me,a5 as Le,l as _,H as je,a4 as qe,a as i,E as He,n as l,aQ as Ke,C as b,a7 as Ne,ax as Ye,T as Ae,a9 as O,d as Oe,e as Ge,aa as Qe,ab as Ze,f as Je,g as We,h as Xe,ac as et,i as r,ad as G,ae as tt,af as at,ai as Q,S as lt,ag as ot,ah as nt,U as st,V as it,aD as Z,aj as rt,ak as dt,F as ut,R as pt,P as c,t as ct,al as mt,am as _t,an as ft,K as y,Z as gt,ap as vt,aq as bt,ar as yt,as as kt,at as J,aS as ht,aT as wt,aC as Ct,aI as xt,D as W,av as X,k as f,j as Vt}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as Et,a as St}from"./useColumnSettings-sXzip_cz.js";import{r as V}from"./index-CZCGMR8A.js";const Dt={class:"blacklist-page"},Ut={class:"stat-card stat-total"},It={class:"stat-icon"},zt={class:"stat-info"},Ft={class:"stat-value"},Rt={class:"stat-card stat-active"},$t={class:"stat-icon"},Pt={class:"stat-info"},Bt={class:"stat-value"},Tt={class:"stat-card stat-expired"},Mt={class:"stat-icon"},Lt={class:"stat-info"},jt={class:"stat-value"},qt={class:"advanced-search"},Ht={class:"toolbar"},Kt={class:"toolbar-left"},Nt={class:"toolbar-right"},Yt={class:"column-settings"},At={class:"pagination-wrapper"},Ot={__name:"Blacklist",setup(Gt){const I=_(!0),R=_(!1),$=_(!1),C=_(!1),E=_(!1),x=_(!1),P=_(null),z=_(null),S=_(null),{list:B,loading:ee,page:T,pageSize:M,total:q,selectedRows:m,filters:k,tableMaxHeight:te,fetchData:D,handleSelectionChange:ae,handleSortChange:le,handleSizeChange:oe,handleFilterChange:U,resetFilters:ne,refreshData:se}=Et({apiUrl:"/blacklists",defaultFilters:{target_type:"",status:"",keyword:""},defaultPageSize:20}),{columnOptions:ie,visibleColumns:g,saveColumnSettings:re}=St("blacklist_column_settings",[{prop:"id",label:"ID"},{prop:"target_type",label:"类型"},{prop:"target_value",label:"目标值"},{prop:"status",label:"状态"},{prop:"expire_time",label:"过期时间"},{prop:"operator_name",label:"操作人"},{prop:"remark",label:"备注"},{prop:"created_at",label:"添加时间"}]),de=W(()=>B.value.filter(n=>n.status===1).length),ue=W(()=>B.value.filter(n=>n.expire_time&&new Date(n.expire_time)<new Date).length),s=Vt({id:null,target_type:"ip",target_value:"",expire_time:"",remark:""}),pe={target_type:[{required:!0,message:"请选择目标类型",trigger:"change"}],target_value:[{required:!0,message:"请输入目标值",trigger:"blur"}]};function ce(){s.id=null,s.target_type="ip",s.target_value="",s.expire_time="",s.remark="",S.value&&S.value.resetFields()}function me(){x.value=!1,ce(),C.value=!0}function _e(n){x.value=!0,s.id=n.id,s.target_type=n.target_type,s.target_value=n.target_value,s.expire_time=n.expire_time||"",s.remark=n.remark||"",C.value=!0}async function fe(){S.value&&await S.value.validate(async n=>{if(n){R.value=!0;try{x.value?(await V.put(`/blacklists/${s.id}`,{expire_time:s.expire_time||null,remark:s.remark}),f.success("黑名单更新成功")):(await V.post("/blacklists",{target_type:s.target_type,target_value:s.target_value,expire_time:s.expire_time||null,remark:s.remark}),f.success("黑名单添加成功")),C.value=!1,D()}catch{}finally{R.value=!1}}})}async function ge(n,e){try{await V.put(`/blacklists/${n.id}`,{status:e}),f.success("状态更新成功")}catch{n.status=e===1?0:1}}async function ve(n){try{await X.confirm("确定删除该黑名单吗?","提示",{type:"warning"}),await V.delete(`/blacklists/${n.id}`),f.success("删除成功"),D()}catch(e){e!=="cancel"&&console.error(e)}}async function be(){if(m.value.length)try{await X.confirm(`确定删除选中的 ${m.value.length} 条黑名单吗?`,"警告",{type:"warning"});const n=m.value.map(e=>e.id);await V.post("/blacklists/batch-delete",{ids:n}),f.success("批量删除成功"),D()}catch(n){n!=="cancel"&&console.error(n)}}function ye(){if(!m.value.length){f.warning("请先选择要导出的记录");return}const n=new URLSearchParams;n.set("ids",m.value.map(h=>h.id).join(","));const e=localStorage.getItem("access_token");window.open(`/api/blacklists/export?${n.toString()}&token=${e}`,"_blank"),f.success("导出任务已启动")}function ke(n){z.value=n.raw}async function he(){if(!z.value){f.warning("请选择 CSV 文件");return}const n=new FormData;n.append("file",z.value),$.value=!0;try{const e=await V.post("/blacklists/import",n,{headers:{"Content-Type":"multipart/form-data"}});f.success(e.message||"导入完成"),E.value=!1,z.value=null,P.value&&P.value.clearFiles(),D()}catch{}finally{$.value=!1}}return(n,e)=>{const h=He,L=qe,we=Me,F=Ze,H=Qe,v=Ge,j=Je,d=Xe,K=Oe,Ce=it,xe=st,Ve=lt,Ee=ct,Se=dt,p=ft,De=gt,Ue=vt,Ie=_t,ze=kt,Fe=Le,N=wt,ReLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
.cards-page[data-v-8d2be4a9]{max-width:1600px;margin:0 auto}.stats-row[data-v-8d2be4a9]{margin-bottom:20px}.stat-card[data-v-8d2be4a9]{background:#fff;border-radius:12px;padding:24px;display:flex;align-items:center;gap:20px;box-shadow:0 2px 8px #0000000f;transition:all .3s ease;cursor:pointer}.stat-card[data-v-8d2be4a9]:hover{transform:translateY(-4px);box-shadow:0 8px 16px #0000001a}.stat-icon[data-v-8d2be4a9]{width:64px;height:64px;border-radius:12px;display:flex;align-items:center;justify-content:center;color:#fff;flex-shrink:0}.stat-total .stat-icon[data-v-8d2be4a9]{background:linear-gradient(135deg,#667eea,#764ba2)}.stat-unused .stat-icon[data-v-8d2be4a9]{background:linear-gradient(135deg,#f093fb,#f5576c)}.stat-used .stat-icon[data-v-8d2be4a9]{background:linear-gradient(135deg,#4facfe,#00f2fe)}.stat-disabled .stat-icon[data-v-8d2be4a9]{background:linear-gradient(135deg,#43e97b,#38f9d7)}.stat-info[data-v-8d2be4a9]{flex:1}.stat-value[data-v-8d2be4a9]{font-size:32px;font-weight:700;color:#303133;line-height:1.2}.stat-label[data-v-8d2be4a9]{font-size:14px;color:#909399;margin-top:4px}.main-card[data-v-8d2be4a9]{margin-bottom:20px}.advanced-search[data-v-8d2be4a9]{padding:20px;background:#f5f7fa;border-radius:8px;margin-bottom:20px}.search-form[data-v-8d2be4a9]{display:flex;flex-wrap:wrap;gap:12px}.toolbar[data-v-8d2be4a9]{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:12px}.toolbar-left[data-v-8d2be4a9],.toolbar-right[data-v-8d2be4a9]{display:flex;gap:12px;flex-wrap:wrap}.cards-table[data-v-8d2be4a9]{width:100%}.cards-table[data-v-8d2be4a9] .el-table__header{background:#f5f7fa}.cards-table[data-v-8d2be4a9] .el-table__header th{font-weight:600;color:#303133}.cards-table[data-v-8d2be4a9] .el-table__row{transition:background .2s ease}.cards-table[data-v-8d2be4a9] .el-table__row:hover>td{background:#ecf5ff!important}.card-key-cell[data-v-8d2be4a9]{display:flex;align-items:center;gap:8px}.copy-icon[data-v-8d2be4a9]{cursor:pointer;color:#409eff;transition:color .2s ease}.copy-icon[data-v-8d2be4a9]:hover{color:#66b1ff}.card-key-text[data-v-8d2be4a9]{font-family:Courier New,monospace;font-size:13px}.mono-text[data-v-8d2be4a9]{font-family:Courier New,monospace}.text-muted[data-v-8d2be4a9]{color:#c0c4cc}.text-success[data-v-8d2be4a9]{color:#67c23a}.text-danger[data-v-8d2be4a9]{color:#f56c6c}.card-key-detail[data-v-8d2be4a9]{display:flex;align-items:center;gap:12px}.bind-info-pre[data-v-8d2be4a9]{font-size:12px;max-height:200px;overflow:auto;background:#f5f7fa;padding:12px;border-radius:4px;margin:0}.pagination-wrapper[data-v-8d2be4a9]{margin-top:20px;display:flex;justify-content:flex-end}.column-settings[data-v-8d2be4a9]{padding:8px}.column-settings-title[data-v-8d2be4a9]{font-weight:600;margin-bottom:12px;color:#303133}.column-settings .el-checkbox[data-v-8d2be4a9]{display:block;margin-bottom:8px}.expand-enter-active[data-v-8d2be4a9],.expand-leave-active[data-v-8d2be4a9]{transition:all .3s ease}.expand-enter-from[data-v-8d2be4a9],.expand-leave-to[data-v-8d2be4a9]{opacity:0;max-height:0;overflow:hidden}.expand-enter-to[data-v-8d2be4a9],.expand-leave-from[data-v-8d2be4a9]{opacity:1;max-height:200px}@media (max-width: 768px){.toolbar[data-v-8d2be4a9]{flex-direction:column;align-items:stretch}.toolbar-left[data-v-8d2be4a9],.toolbar-right[data-v-8d2be4a9]{width:100%;justify-content:flex-start}.stat-card[data-v-8d2be4a9]{margin-bottom:12px}.search-form[data-v-8d2be4a9]{flex-direction:column}.search-form .el-form-item[data-v-8d2be4a9]{width:100%}.search-form .el-select[data-v-8d2be4a9],.search-form .el-input[data-v-8d2be4a9],.search-form .el-date-picker[data-v-8d2be4a9]{width:100%!important}}@media (max-width: 480px){.stats-row[data-v-8d2be4a9] .el-col{margin-bottom:12px}.stat-value[data-v-8d2be4a9]{font-size:24px}.stat-icon[data-v-8d2be4a9]{width:48px;height:48px}}
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as tt,m as at,ay as lt,az as st,o,c as v,b as l,w as t,l as u,j as ot,a3 as nt,a5 as dt,H as ut,a4 as it,a as d,E as rt,n as m,aA as ct,C as i,a7 as pt,a8 as _t,aB as mt,T as ft,a9 as pe,d as vt,e as yt,aa as bt,F as N,R as O,P as r,ab as gt,f as kt,g as wt,aC as ht,h as xt,ac as Ct,i as n,ad as _e,ae as Vt,af as St,aD as me,S as Et,ag as jt,ah as Dt,U as zt,V as Ut,ai as It,aE as $t,aj as qt,ak as Ft,t as Bt,al as Tt,am as Rt,an as Mt,K as x,ao as fe,Z as Nt,B as Ot,aF as Lt,ar as Pt,as as Ht,au as Qt,aG as Jt,aH as Yt,aI as Gt,k as C,av as ve,D as Kt}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{r as V}from"./index-CZCGMR8A.js";const At={class:"cards-page"},Zt={class:"stat-card stat-total"},Wt={class:"stat-icon"},Xt={class:"stat-info"},ea={class:"stat-value"},ta={class:"stat-card stat-unused"},aa={class:"stat-icon"},la={class:"stat-info"},sa={class:"stat-value"},oa={class:"stat-card stat-used"},na={class:"stat-icon"},da={class:"stat-info"},ua={class:"stat-value"},ia={class:"stat-card stat-disabled"},ra={class:"stat-icon"},ca={class:"stat-info"},pa={class:"stat-value"},_a={class:"advanced-search"},ma={class:"toolbar"},fa={class:"toolbar-left"},va={class:"toolbar-right"},ya={class:"column-settings"},ba={class:"card-key-cell"},ga={class:"card-key-text"},ka={key:0,class:"mono-text"},wa={key:1,class:"text-muted"},ha={key:0,class:"text-success"},xa={class:"pagination-wrapper"},Ca={class:"card-key-detail"},Va={class:"mono-text"},Sa={key:0,class:"text-success"},Ea={key:1},ja={key:0,class:"mono-text"},Da={key:1,class:"text-muted"},za={key:0,class:"bind-info-pre"},Ua={key:1,class:"text-muted"},Ia={__name:"Cards",setup($a){const ne=u([]),Z=u(!1),q=u(1),L=u(20),de=u(0),F=u(null),P=u([]),y=u([]),W=u([]),H=u(!0),ye=u(null),ue=u(500),_=ot({project_id:"",status:"",keyword:"",start_date:"",end_date:""}),Q=u([{prop:"id",label:"ID",visible:!0},{prop:"card_key",label:"卡密",visible:!0},{prop:"project_name",label:"项目",visible:!0},{prop:"card_type_name",label:"类型",visible:!0},{prop:"bot_qq",label:"机器人QQ",visible:!0},{prop:"duration_days",label:"有效天数",visible:!0},{prop:"status",label:"状态",visible:!0},{prop:"expire_time",label:"过期时间",visible:!0},{prop:"created_at",label:"生成时间",visible:!0}]),S=Kt(()=>{const s={};return Q.value.forEach(e=>{s[e.prop]=e.visible}),s}),B=u(!1),X=u(null),b=u({project_id:"",card_type_id:"",count:10,remark:""}),be={project_id:[{required:!0,message:"请选择项目",trigger:"change"}],card_type_id:[{required:!0,message:"请选择套餐",trigger:"change"}],count:[{required:!0,message:"请输入数量",trigger:"blur"}]},ee=u(!1),J=u([]),te=u(!1),c=u(null),T=u(!1),ae=u(!1),R=u(null),I=u(""),le=u(null),M=u(!1),se=u(!1),Y=u("unused");at(()=>{Me(),Oe(),ge(),k(),z(),oe(),window.addEventListener("resize",oe)}),lt(()=>{window.removeEventListener("resize",oe)});async function ge(){try{const s=await V.get("/projects/all");P.value=s.data}catch(s){console.error("获取项目列表失败:",s)}}async function k(){Z.value=!0,Ne();try{const s={page:q.value,page_size:L.value,..._};Object.keys(s).forEach(f=>{(s[f]===""||s[f]===null||s[f]===void 0)&&delete s[f]});const e=await V.get("/cards",{params:s});ne.value=e.data.list,de.value=e.data.total}catch(s){console.error("获取卡密列表失败:",s)}finally{Z.value=!1}}async function z(){try{const s=await V.get("/cards/stats");F.value=s.data}catch(s){console.error("获取统计数据失败:",s)}}function ke(){k(),z(),C.success("刷新成功")}function we(s){y.value=s}function he({prop:s,order:e}){k()}function xe(s){L.value=s,q.value=1,k()}function U(){q.value=1,k()}function Ce(s){s?(_.start_date=s[0],_.end_date=s[1]):(_.start_date="",_.end_date=""),U()}function Ve(){_.project_id="",_.status="",_.keyword="",_.start_date="",_.end_date="",W.value=[],U()}function Se(){b.value={project_id:"",card_type_id:"",count:10,remark:""},J.value=[],B.value=!0}st(()=>b.value.project_id,async s=>{if(!s){J.value=[];return}try{const e=await V.get(`/projects/${s}/card-types`);J.value=e.data||[]}catch(e){console.error("获取套餐列表失败:",e)}});async function Ee(){X.value&&await X.value.validate(async s=>{if(s){ee.value=!0;try{const e=await V.post("/cards/generate",b.value);C.success(e.message||"生成成功"),B.value=!1,k(),z()}catch(e){console.error("生成卡密失败:",e)}finally{ee.value=!1}}})}async function je(s){const e=s.status==="disabled"?"unused":"disabled",f=e==="disabled"?"禁用":"启用";try{await ve.confirm(`确定要${f}该卡密吗?`,"提示",{Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as tt,m as at,az as lt,aA as st,o,c as v,b as l,w as t,l as u,j as ot,a4 as nt,a6 as dt,H as ut,a5 as it,a as d,E as rt,n as m,aB as ct,C as i,a8 as pt,a9 as _t,aC as mt,T as ft,aa as pe,d as vt,e as yt,ab as bt,F as N,R as O,P as r,ac as gt,f as kt,g as wt,aD as ht,h as xt,ad as Ct,i as n,ae as _e,af as Vt,ag as St,aE as me,S as Et,ah as jt,ai as Dt,U as zt,V as Ut,aj as It,aF as $t,ak as qt,al as Ft,t as Bt,am as Tt,an as Rt,ao as Mt,K as x,ap as fe,Z as Nt,B as Ot,aG as Lt,as as Pt,at as Ht,av as Qt,aH as Jt,aI as Yt,a3 as Gt,k as C,aw as ve,D as Kt}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{r as V}from"./index-DpFNINBG.js";const At={class:"cards-page"},Zt={class:"stat-card stat-total"},Wt={class:"stat-icon"},Xt={class:"stat-info"},ea={class:"stat-value"},ta={class:"stat-card stat-unused"},aa={class:"stat-icon"},la={class:"stat-info"},sa={class:"stat-value"},oa={class:"stat-card stat-used"},na={class:"stat-icon"},da={class:"stat-info"},ua={class:"stat-value"},ia={class:"stat-card stat-disabled"},ra={class:"stat-icon"},ca={class:"stat-info"},pa={class:"stat-value"},_a={class:"advanced-search"},ma={class:"toolbar"},fa={class:"toolbar-left"},va={class:"toolbar-right"},ya={class:"column-settings"},ba={class:"card-key-cell"},ga={class:"card-key-text"},ka={key:0,class:"mono-text"},wa={key:1,class:"text-muted"},ha={key:0,class:"text-success"},xa={class:"pagination-wrapper"},Ca={class:"card-key-detail"},Va={class:"mono-text"},Sa={key:0,class:"text-success"},Ea={key:1},ja={key:0,class:"mono-text"},Da={key:1,class:"text-muted"},za={key:0,class:"bind-info-pre"},Ua={key:1,class:"text-muted"},Ia={__name:"Cards",setup($a){const ne=u([]),Z=u(!1),q=u(1),L=u(20),de=u(0),F=u(null),P=u([]),y=u([]),W=u([]),H=u(!0),ye=u(null),ue=u(500),_=ot({project_id:"",status:"",keyword:"",start_date:"",end_date:""}),Q=u([{prop:"id",label:"ID",visible:!0},{prop:"card_key",label:"卡密",visible:!0},{prop:"project_name",label:"项目",visible:!0},{prop:"card_type_name",label:"类型",visible:!0},{prop:"bot_qq",label:"机器人QQ",visible:!0},{prop:"duration_days",label:"有效天数",visible:!0},{prop:"status",label:"状态",visible:!0},{prop:"expire_time",label:"过期时间",visible:!0},{prop:"created_at",label:"生成时间",visible:!0}]),S=Kt(()=>{const s={};return Q.value.forEach(e=>{s[e.prop]=e.visible}),s}),B=u(!1),X=u(null),b=u({project_id:"",card_type_id:"",count:10,remark:""}),be={project_id:[{required:!0,message:"请选择项目",trigger:"change"}],card_type_id:[{required:!0,message:"请选择套餐",trigger:"change"}],count:[{required:!0,message:"请输入数量",trigger:"blur"}]},ee=u(!1),J=u([]),te=u(!1),c=u(null),T=u(!1),ae=u(!1),R=u(null),I=u(""),le=u(null),M=u(!1),se=u(!1),Y=u("unused");at(()=>{Me(),Oe(),ge(),k(),z(),oe(),window.addEventListener("resize",oe)}),lt(()=>{window.removeEventListener("resize",oe)});async function ge(){try{const s=await V.get("/projects/all");P.value=s.data}catch(s){console.error("获取项目列表失败:",s)}}async function k(){Z.value=!0,Ne();try{const s={page:q.value,page_size:L.value,..._};Object.keys(s).forEach(f=>{(s[f]===""||s[f]===null||s[f]===void 0)&&delete s[f]});const e=await V.get("/cards",{params:s});ne.value=e.data.list,de.value=e.data.total}catch(s){console.error("获取卡密列表失败:",s)}finally{Z.value=!1}}async function z(){try{const s=await V.get("/cards/stats");F.value=s.data}catch(s){console.error("获取统计数据失败:",s)}}function ke(){k(),z(),C.success("刷新成功")}function we(s){y.value=s}function he({prop:s,order:e}){k()}function xe(s){L.value=s,q.value=1,k()}function U(){q.value=1,k()}function Ce(s){s?(_.start_date=s[0],_.end_date=s[1]):(_.start_date="",_.end_date=""),U()}function Ve(){_.project_id="",_.status="",_.keyword="",_.start_date="",_.end_date="",W.value=[],U()}function Se(){b.value={project_id:"",card_type_id:"",count:10,remark:""},J.value=[],B.value=!0}st(()=>b.value.project_id,async s=>{if(!s){J.value=[];return}try{const e=await V.get(`/projects/${s}/card-types`);J.value=e.data||[]}catch(e){console.error("获取套餐列表失败:",e)}});async function Ee(){X.value&&await X.value.validate(async s=>{if(s){ee.value=!0;try{const e=await V.post("/cards/generate",b.value);C.success(e.message||"生成成功"),B.value=!1,k(),z()}catch(e){console.error("生成卡密失败:",e)}finally{ee.value=!1}}})}async function je(s){const e=s.status==="disabled"?"unused":"disabled",f=e==="disabled"?"禁用":"启用";try{await ve.confirm(`确定要${f}该卡密吗?`,"提示",{Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
.coupons-page[data-v-897497d8]{max-width:1600px;margin:0 auto}.stats-row[data-v-897497d8]{margin-bottom:20px}.stat-card[data-v-897497d8]{background:#fff;border-radius:12px;padding:24px;display:flex;align-items:center;gap:20px;box-shadow:0 2px 8px #0000000f;transition:all .3s ease}.stat-card[data-v-897497d8]:hover{transform:translateY(-4px);box-shadow:0 8px 16px #0000001a}.stat-icon[data-v-897497d8]{width:64px;height:64px;border-radius:12px;display:flex;align-items:center;justify-content:center;color:#fff;flex-shrink:0}.stat-total .stat-icon[data-v-897497d8]{background:linear-gradient(135deg,#667eea,#764ba2)}.stat-active .stat-icon[data-v-897497d8]{background:linear-gradient(135deg,#43e97b,#38f9d7)}.stat-used .stat-icon[data-v-897497d8]{background:linear-gradient(135deg,#f093fb,#f5576c)}.stat-value[data-v-897497d8]{font-size:32px;font-weight:700;color:#303133}.stat-label[data-v-897497d8]{font-size:14px;color:#909399;margin-top:4px}.advanced-search[data-v-897497d8]{padding:20px;background:#f5f7fa;border-radius:8px;margin-bottom:20px}.search-form[data-v-897497d8]{display:flex;flex-wrap:wrap;gap:12px}.toolbar[data-v-897497d8]{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:12px}.toolbar-left[data-v-897497d8],.toolbar-right[data-v-897497d8]{display:flex;gap:12px;flex-wrap:wrap}.data-table[data-v-897497d8] .el-table__header th{font-weight:600;color:#303133}.pagination-wrapper[data-v-897497d8]{margin-top:20px;display:flex;justify-content:flex-end}.column-settings[data-v-897497d8]{padding:8px}.column-settings-title[data-v-897497d8]{font-weight:600;margin-bottom:12px}.column-settings .el-checkbox[data-v-897497d8]{display:block;margin-bottom:8px}.expand-enter-active[data-v-897497d8],.expand-leave-active[data-v-897497d8]{transition:all .3s ease}.expand-enter-from[data-v-897497d8],.expand-leave-to[data-v-897497d8]{opacity:0;max-height:0;overflow:hidden}.expand-enter-to[data-v-897497d8],.expand-leave-from[data-v-897497d8]{opacity:1;max-height:200px}@media (max-width:768px){.toolbar[data-v-897497d8]{flex-direction:column;align-items:stretch}.toolbar-left[data-v-897497d8],.toolbar-right[data-v-897497d8]{width:100%}.search-form[data-v-897497d8]{flex-direction:column}.search-form .el-form-item[data-v-897497d8],.search-form .el-select[data-v-897497d8],.search-form .el-input[data-v-897497d8]{width:100%!important}}
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as ze,m as De,o as d,c as h,b as t,w as a,l as x,a4 as Ue,a6 as je,H as $e,a5 as Fe,a as i,E as Ie,n as o,z as Me,C as r,a8 as Re,aR as Be,T as Ye,aa as G,d as Pe,e as He,f as Te,g as Ne,ab as qe,ac as Ke,F as T,R as N,P as p,h as Le,ad as Ae,i as u,ae as J,af as Oe,ag as Ze,S as Ge,ah as Je,ai as Qe,U as We,V as Xe,ak as et,al as tt,t as lt,am as at,an as ot,ao as nt,K as v,Z as st,as as it,at as dt,au as Q,av as ut,aD as rt,aq as pt,D as W,k as C,aw as X,j as ct}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as mt,a as _t}from"./useColumnSettings-BO5PTaEn.js";import{r as S}from"./index-DpFNINBG.js";const ft={class:"coupons-page"},gt={class:"stat-card stat-total"},vt={class:"stat-icon"},bt={class:"stat-info"},xt={class:"stat-value"},yt={class:"stat-card stat-active"},ht={class:"stat-icon"},Ct={class:"stat-info"},kt={class:"stat-value"},wt={class:"stat-card stat-used"},Vt={class:"stat-icon"},Et={class:"stat-info"},St={class:"stat-value"},zt={class:"advanced-search"},Dt={class:"toolbar"},Ut={class:"toolbar-left"},jt={class:"toolbar-right"},$t={class:"column-settings"},Ft={style:{color:"#67C23A","font-weight":"600"}},It={key:0},Mt={key:1},Rt={class:"pagination-wrapper"},Bt={__name:"Coupons",setup(Yt){const z=x(!0),D=x([]),{list:$,loading:ee,page:F,pageSize:I,total:q,selectedRows:f,filters:b,tableMaxHeight:te,fetchData:U,handleSelectionChange:le,handleSortChange:ae,handleSizeChange:oe,handleFilterChange:k,resetFilters:ne,refreshData:se}=mt({apiUrl:"/coupons",defaultFilters:{keyword:"",status:"",project_id:""},defaultPageSize:20}),{columnOptions:ie,visibleColumns:g,saveColumnSettings:de}=_t("coupons_column_settings",[{prop:"id",label:"ID"},{prop:"code",label:"优惠码"},{prop:"name",label:"名称/备注"},{prop:"discount_percent",label:"省钱%"},{prop:"usage",label:"使用情况"},{prop:"min_amount",label:"最低消费"},{prop:"status",label:"状态"},{prop:"expire_at",label:"过期时间"},{prop:"created_at",label:"创建时间"}]),ue=W(()=>$.value.filter(s=>s.status===1).length),re=W(()=>$.value.reduce((s,e)=>s+(e.used_count||0),0));De(async()=>{var s;try{const e=await S.get("/projects");D.value=((s=e.data)==null?void 0:s.list)||e.data||[]}catch{D.value=[]}});const w=x(!1),V=x(!1),M=x(null),K=x(null),R=x(!1),n=ct({code:"",name:"",discount_percent:10,max_use_count:0,min_amount:0,project_ids:[],expire_at:"",status:1}),pe={code:[{required:!0,message:"请输入优惠码",trigger:"blur"}],discount_percent:[{required:!0,message:"请输入省钱百分比",trigger:"blur"}]};function L(s){s?(V.value=!0,M.value=s.id,n.code=s.code,n.name=s.name,n.discount_percent=parseFloat(s.discount_percent),n.max_use_count=s.max_use_count,n.min_amount=parseFloat(s.min_amount),n.project_ids=s.project_ids&&s.project_ids.trim()?s.project_ids.split(",").filter(Boolean):[],n.expire_at=s.expire_at||"",n.status=s.status):(V.value=!1,M.value=null,n.code="",n.name="",n.discount_percent=10,n.max_use_count=0,n.min_amount=0,n.project_ids=[],n.expire_at="",n.status=1),w.value=!0}async function ce(){if(await K.value.validate().catch(()=>!1)){R.value=!0;try{const e={code:n.code.toUpperCase(),name:n.name,discount_percent:n.discount_percent,max_use_count:n.max_use_count,min_amount:n.min_amount,project_ids:n.project_ids.join(","),expire_at:n.expire_at||null,status:n.status};V.value?(await S.put(`/coupons/${M.value}`,e),C.success("更新成功")):(await S.post("/coupons",e),C.success("创建成功")),w.value=!1,U()}catch{}finally{R.value=!1}}}async function me(s){try{await X.confirm(`确定删除优惠码「${s.code}」吗?`,"确认删除",{type:"warning"}),await S.delete(`/coupons/${s.id}`),C.success("删除成功"),U()}catch{}}async function _e(){if(f.value.length)try{await X.confirm(`确定删除选中的 ${f.value.length} 个优惠码吗?`,"批量删除",{type:"warning"});for(const s of f.value)await S.delete(`/coupons/${s.id}`);C.success("批量删除成功"),U()}catch{}}function fe(s){if(!f.value.length){C.warning("请先选择要导出的优惠码");return}const e=new URLSearchParams;e.set("ids",f.value.map(E=>E.id).join(",")),e.append("format",s);const y=localStorage.getItem("access_token");window.open(`/api/coupons/export?${e.toString()}&token=${y}`,"_blank"),C.success("导出任务已启动")}return(s,e)=>{const y=Ie,E=Fe,ge=Ue,B=Te,c=He,j=Ke,Y=qe,m=Le,A=Pe,O=Xe,ve=We,be=Ge,xe=lt,ye=tt,_=nt,Z=st,he=ot,Ce=dt,ke=je,P=ut,we=rt,Ve=pt,Ee=$e,Se=it;return d(),h("div",ft,[t(ge,{gutter:20,class:"stats-row"},{default:a(()=>[t(E,{xs:12,sm:8,md:8,lg:8},{default:a(()=>[i("div",gt,[i("div",vt,[t(y,{size:Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
.coupons-page[data-v-a2be1759]{max-width:1600px;margin:0 auto}.stats-row[data-v-a2be1759]{margin-bottom:20px}.stat-card[data-v-a2be1759]{background:#fff;border-radius:12px;padding:24px;display:flex;align-items:center;gap:20px;box-shadow:0 2px 8px #0000000f;transition:all .3s ease}.stat-card[data-v-a2be1759]:hover{transform:translateY(-4px);box-shadow:0 8px 16px #0000001a}.stat-icon[data-v-a2be1759]{width:64px;height:64px;border-radius:12px;display:flex;align-items:center;justify-content:center;color:#fff;flex-shrink:0}.stat-total .stat-icon[data-v-a2be1759]{background:linear-gradient(135deg,#667eea,#764ba2)}.stat-active .stat-icon[data-v-a2be1759]{background:linear-gradient(135deg,#43e97b,#38f9d7)}.stat-used .stat-icon[data-v-a2be1759]{background:linear-gradient(135deg,#f093fb,#f5576c)}.stat-value[data-v-a2be1759]{font-size:32px;font-weight:700;color:#303133}.stat-label[data-v-a2be1759]{font-size:14px;color:#909399;margin-top:4px}.advanced-search[data-v-a2be1759]{padding:20px;background:#f5f7fa;border-radius:8px;margin-bottom:20px}.search-form[data-v-a2be1759]{display:flex;flex-wrap:wrap;gap:12px}.toolbar[data-v-a2be1759]{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:12px}.toolbar-left[data-v-a2be1759],.toolbar-right[data-v-a2be1759]{display:flex;gap:12px;flex-wrap:wrap}.data-table[data-v-a2be1759] .el-table__header th{font-weight:600;color:#303133}.pagination-wrapper[data-v-a2be1759]{margin-top:20px;display:flex;justify-content:flex-end}.column-settings[data-v-a2be1759]{padding:8px}.column-settings-title[data-v-a2be1759]{font-weight:600;margin-bottom:12px}.column-settings .el-checkbox[data-v-a2be1759]{display:block;margin-bottom:8px}.expand-enter-active[data-v-a2be1759],.expand-leave-active[data-v-a2be1759]{transition:all .3s ease}.expand-enter-from[data-v-a2be1759],.expand-leave-to[data-v-a2be1759]{opacity:0;max-height:0;overflow:hidden}.expand-enter-to[data-v-a2be1759],.expand-leave-from[data-v-a2be1759]{opacity:1;max-height:200px}@media (max-width:768px){.toolbar[data-v-a2be1759]{flex-direction:column;align-items:stretch}.toolbar-left[data-v-a2be1759],.toolbar-right[data-v-a2be1759]{width:100%}.search-form[data-v-a2be1759]{flex-direction:column}.search-form .el-form-item[data-v-a2be1759],.search-form .el-select[data-v-a2be1759],.search-form .el-input[data-v-a2be1759]{width:100%!important}}
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as ze,m as Ue,o as d,c as h,b as t,w as a,l as x,a3 as De,a5 as je,H as $e,a4 as Fe,a as i,E as Ie,n as o,z as Me,C as r,a7 as Re,aR as Ye,T as Be,a9 as G,d as Pe,e as He,f as Ne,g as Te,aa as Ke,ab as Le,F as N,R as T,P as p,h as qe,ac as Ae,i as u,ad as J,ae as Oe,af as Ze,S as Ge,ag as Je,ah as Qe,U as We,V as Xe,aj as et,ak as tt,t as lt,al as at,am as ot,an as nt,K as v,Z as st,ar as it,as as dt,at as Q,au as ut,aC as rt,ap as pt,D as W,k as C,av as X,j as ct}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as mt,a as _t}from"./useColumnSettings-sXzip_cz.js";import{r as S}from"./index-CZCGMR8A.js";const ft={class:"coupons-page"},gt={class:"stat-card stat-total"},vt={class:"stat-icon"},bt={class:"stat-info"},xt={class:"stat-value"},yt={class:"stat-card stat-active"},ht={class:"stat-icon"},Ct={class:"stat-info"},kt={class:"stat-value"},wt={class:"stat-card stat-used"},Vt={class:"stat-icon"},Et={class:"stat-info"},St={class:"stat-value"},zt={class:"advanced-search"},Ut={class:"toolbar"},Dt={class:"toolbar-left"},jt={class:"toolbar-right"},$t={class:"column-settings"},Ft={style:{color:"#67C23A","font-weight":"600"}},It={key:0},Mt={key:1},Rt={class:"pagination-wrapper"},Yt={__name:"Coupons",setup(Bt){const z=x(!0),j=x([]),{list:$,loading:ee,page:F,pageSize:I,total:K,selectedRows:f,filters:b,tableMaxHeight:te,fetchData:U,handleSelectionChange:le,handleSortChange:ae,handleSizeChange:oe,handleFilterChange:k,resetFilters:ne,refreshData:se}=mt({apiUrl:"/coupons",defaultFilters:{keyword:"",status:"",project_id:""},defaultPageSize:20}),{columnOptions:ie,visibleColumns:g,saveColumnSettings:de}=_t("coupons_column_settings",[{prop:"id",label:"ID"},{prop:"code",label:"优惠码"},{prop:"name",label:"名称/备注"},{prop:"discount_percent",label:"省钱%"},{prop:"usage",label:"使用情况"},{prop:"min_amount",label:"最低消费"},{prop:"status",label:"状态"},{prop:"expire_at",label:"过期时间"},{prop:"created_at",label:"创建时间"}]),ue=W(()=>$.value.filter(s=>s.status===1).length),re=W(()=>$.value.reduce((s,e)=>s+(e.used_count||0),0));Ue(async()=>{const s=await S.get("/projects");j.value=s.data||[]});const w=x(!1),V=x(!1),M=x(null),L=x(null),R=x(!1),n=ct({code:"",name:"",discount_percent:10,max_use_count:0,min_amount:0,project_ids:[],expire_at:"",status:1}),pe={code:[{required:!0,message:"请输入优惠码",trigger:"blur"}],discount_percent:[{required:!0,message:"请输入省钱百分比",trigger:"blur"}]};function q(s){s?(V.value=!0,M.value=s.id,n.code=s.code,n.name=s.name,n.discount_percent=parseFloat(s.discount_percent),n.max_use_count=s.max_use_count,n.min_amount=parseFloat(s.min_amount),n.project_ids=s.project_ids?s.project_ids.split(",").map(Number):[],n.expire_at=s.expire_at||"",n.status=s.status):(V.value=!1,M.value=null,n.code="",n.name="",n.discount_percent=10,n.max_use_count=0,n.min_amount=0,n.project_ids=[],n.expire_at="",n.status=1),w.value=!0}async function ce(){if(await L.value.validate().catch(()=>!1)){R.value=!0;try{const e={code:n.code.toUpperCase(),name:n.name,discount_percent:n.discount_percent,max_use_count:n.max_use_count,min_amount:n.min_amount,project_ids:n.project_ids.join(","),expire_at:n.expire_at||null,status:n.status};V.value?(await S.put(`/coupons/${M.value}`,e),C.success("更新成功")):(await S.post("/coupons",e),C.success("创建成功")),w.value=!1,U()}catch{}finally{R.value=!1}}}async function me(s){try{await X.confirm(`确定删除优惠码「${s.code}」吗?`,"确认删除",{type:"warning"}),await S.delete(`/coupons/${s.id}`),C.success("删除成功"),U()}catch{}}async function _e(){if(f.value.length)try{await X.confirm(`确定删除选中的 ${f.value.length} 个优惠码吗?`,"批量删除",{type:"warning"});for(const s of f.value)await S.delete(`/coupons/${s.id}`);C.success("批量删除成功"),U()}catch{}}function fe(s){if(!f.value.length){C.warning("请先选择要导出的优惠码");return}const e=new URLSearchParams;e.set("ids",f.value.map(E=>E.id).join(",")),e.append("format",s);const y=localStorage.getItem("access_token");window.open(`/api/coupons/export?${e.toString()}&token=${y}`,"_blank"),C.success("导出任务已启动")}return(s,e)=>{const y=Ie,E=Fe,ge=De,Y=Ne,c=He,D=Le,B=Ke,m=qe,A=Pe,O=Xe,ve=We,be=Ge,xe=lt,ye=tt,_=nt,Z=st,he=ot,Ce=dt,ke=je,P=ut,we=rt,Ve=pt,Ee=$e,Se=it;return d(),h("div",ft,[t(ge,{gutter:20,class:"stats-row"},{default:a(()=>[t(E,{xs:12,sm:8,md:8,lg:8},{default:a(()=>[i("div",gt,[i("div",vt,[t(y,{size:32},{default:a(()=>[t(o(Me))]),_:1})]),i("div",bt,[i("div",xt,r(o(K)),1),e[17]||(e[17]=iLine truncated
|
||||
@@ -0,0 +1,60 @@
|
||||
import{_ as $I,m as qI,o as Io,c as nm,b as rn,w as $r,P as Nh,K as KI,l as im,a4 as JI,r as QI,F as jI,R as tL,a5 as eL,a6 as rL,A as om,a as yi,E as aL,a1 as nL,C as sm,i as iL,D as lm}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css */import{u as oL}from"./user-DvAOsLmR.js";import{r as sL}from"./index-DpFNINBG.js";/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
***************************************************************************** */var op=function(r,e){return op=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,a){t.__proto__=a}||function(t,a){for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(t[n]=a[n])},op(r,e)};function k(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");op(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var lL=function(){function r(){this.firefox=!1,this.ie=!1,this.edge=!1,this.newEdge=!1,this.weChat=!1}return r}(),uL=function(){function r(){this.browser=new lL,this.node=!1,this.wxa=!1,this.worker=!1,this.svgSupported=!1,this.touchEventsSupported=!1,this.pointerEventsSupported=!1,this.domSupported=!1,this.transformSupported=!1,this.transform3dSupported=!1,this.hasGlobalWindow=typeof window<"u"}return r}(),yt=new uL;typeof wx=="object"&&typeof wx.getSystemInfoSync=="function"?(yt.wxa=!0,yt.touchEventsSupported=!0):typeof document>"u"&&typeof self<"u"?yt.worker=!0:!yt.hasGlobalWindow||"Deno"in window?(yt.node=!0,yt.svgSupported=!0):fL(navigator.userAgent,yt);function fL(r,e){var t=e.browser,a=r.match(/Firefox\/([\d.]+)/),n=r.match(/MSIE\s([\d.]+)/)||r.match(/Trident\/.+?rv:(([\d.]+))/),i=r.match(/Edge?\/([\d.]+)/),o=/micromessenger/i.test(r);a&&(t.firefox=!0,t.version=a[1]),n&&(t.ie=!0,t.version=n[1]),i&&(t.edge=!0,t.version=i[1],t.newEdge=+i[1].split(".")[0]>18),o&&(t.weChat=!0),e.svgSupported=typeof SVGRect<"u",e.touchEventsSupported="ontouchstart"in window&&!t.ie&&!t.edge,e.pointerEventsSupported="onpointerdown"in window&&(t.edge||t.ie&&+t.version>=11),e.domSupported=typeof document<"u";var s=document.documentElement.style;e.transform3dSupported=(t.ie&&"transition"in s||t.edge||"WebKitCSSMatrix"in window&&"m11"in new WebKitCSSMatrix||"MozPerspective"in s)&&!("OTransition"in s),e.transformSupported=e.transform3dSupported||t.ie&&+t.version>=9}var qd=12,cw="sans-serif",Ya=qd+"px "+cw,hL=20,vL=100,cL="007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";function pL(r){var e={};if(typeof JSON>"u")return e;for(var t=0;t<r.length;t++){var a=String.fromCharCode(t+32),n=(r.charCodeAt(t)-hL)/vL;e[a]=n}return e}var dL=pL(cL),Xa={createCanvas:function(){return typeof document<"u"&&document.createElement("canvas")},measureText:function(){var r,e;return function(t,a){if(!r){var n=Xa.createCanvas();r=n&&n.getContext("2d")}if(r)return e!==a&&(e=r.font=a||Ya),r.measureText(t);t=t||"",a=a||Ya;var i=/((?:\d+)?\.?\d*)px/.exec(a),o=i&&+i[1]||qd,s=0;if(a.indexOf("mono")>=0)s=o*t.length;else for(var l=0;l<t.length;l++){var u=dL[t[l]];s+=u==null?o:u*o}return{width:s}}}(),loadImage:function(r,e,t){var a=new Image;return a.onload=e,a.onerror=t,a.src=r,a}},pw=Gr(["Function","RegExp","Date","Error","CanvasGradient","CanvasPattern","Image","Canvas"],function(r,e){return r["[object "+e+"]"]=!0,r},{}),dw=Gr(["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64"],function(r,e){return r["[object "+e+"Array]"]=!0,r},{}),vo=Object.prototype.toString,$f=Array.prototype,gL=$f.forEach,yL=$f.filter,Kd=$f.slice,mL=$f.map,um=(function(){}).constructor,Ll=um?um.prototype:null,Jd="__proto__",_L=2311;function gw(){return _L++}function Qd(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];typeof console<"u"&&console.error.apply(console,r)}function rt(r){if(r==null||typeof r!="object")return r;var e=r,t=vo.call(r);if(t==="[object Array]"){if(!ys(r)){e=[];for(var a=0,n=r.length;a<n;a++)e[a]=rt(r[a])}}else if(dw[t]){if(!ys(r)){var i=r.constructor;if(i.from)e=i.from(r);else{e=new i(r.length);for(var a=0,n=r.length;a<n;a++)e[a]=r[a]}}}else if(!pw[t]&&!ys(r)&&!eo(r)){e={};for(var o in r)r.hasOwnProperty(o)&&o!==Jd&&(e[o]=rt(r[o]))}return e}function ut(r,e,t){if(!et(e)||!et(r))return t?rt(e):r;for(var a in e)if(e.hasOwnProperty(a)&&a!==Jd){var n=r[a],i=e[a];et(i)&&et(n)&&!z(i)&&!z(n)&&!eo(i)&&!eo(n)&&!fm(i)&&!fm(n)&&!ys(i)&&!ys(n)?ut(n,i,t):(t||!(a in r))&&(r[a]=rt(e[a]))}return r}function jd(r,e){for(var t=r[0],a=1,n=r.length;a<n;a++)t=ut(t,r[a],e);return t}function V(r,e){if(Object.assign)Object.assign(r,e);else for(var t in e)e.hasOwnProperty(t)&&t!==Jd&&(r[t]=e[t]);return r}function j(r,e,t){for(var a=_t(e),n=0,i=a.length;n<i;n++){var o=a[n];(t?e[o]!=null:r[o]==null)&&(r[o]=e[o])}return r}function ct(r,e){if(r){if(r.indexOf)return r.indexOf(e);for(var t=0,a=r.length;t<a;t++)if(r[t]===e)return t}return-1}function SL(r,e){var t=r.prototype;function a(){}a.prototype=e.prototype,r.prototype=new a;for(var n in t)t.hasOwnProperty(n)&&(r.prototype[n]=t[n]);r.prototype.constructor=r,r.superClass=e}function Kt(r,e,t){if(r="prototype"in r?r.prototype:r,e="prototype"in e?e.prototype:e,Object.getOwnPropertyNames)for(var a=Object.getOwnPropertyNames(e),n=0;n<a.length;n++){var i=a[n];i!=="constructor"&&(t?e[i]!=null:r[i]==null)&&(r[i]=e[i])}else j(r,eLine truncated
|
||||
`),i=n.length;if(i===1)return Nm(n[0],e,t,a);for(var o=new ht(0,0,0,0),s=0;s<n.length;s++){var l=Nm(n[s],e,t,a);s===0?o.copy(l):o.union(l)}return o}function ss(r,e,t){return t==="right"?r-=e:t==="center"&&(r-=e/2),r}function Fi(r,e,t){return t==="middle"?r-=e/2:t==="bottom"&&(r-=e),r}function jf(r){return Ue("国",r)}function Sr(r,e){return typeof r=="string"?r.lastIndexOf("%")>=0?parseFloat(r)/100*e:parseFloat(r):r}function lf(r,e,t){var a=e.position||"inside",n=e.distance!=null?e.distance:5,i=t.height,o=t.width,s=i/2,l=t.x,u=t.y,f="left",h="top";if(a instanceof Array)l+=Sr(a[0],t.width),u+=Sr(a[1],t.height),f=null,h=null;else switch(a){case"left":l-=n,u+=s,f="right",h="middle";break;case"right":l+=n+o,u+=s,h="middle";break;case"top":l+=o/2,u-=n,f="center",h="bottom";break;case"bottom":l+=o/2,u+=i+n,f="center";break;case"inside":l+=o/2,u+=s,f="center",h="middle";break;case"insideLeft":l+=n,u+=s,h="middle";break;case"insideRight":l+=o-n,u+=s,f="right",h="middle";break;case"insideTop":l+=o/2,u+=n,f="center";break;case"insideBottom":l+=o/2,u+=i-n,f="center",h="bottom";break;case"insideTopLeft":l+=n,u+=n;break;case"insideTopRight":l+=o-n,u+=n,f="right";break;case"insideBottomLeft":l+=n,u+=i-n,h="bottom";break;case"insideBottomRight":l+=o-n,u+=i-n,f="right",h="bottom";break}return r=r||{},r.x=l,r.y=u,r.align=f,r.verticalAlign=h,r}var tv="__zr_normal__",ev=Hr.concat(["ignore"]),L2=Gr(Hr,function(r,e){return r[e]=!0,r},{ignore:!1}),xi={},P2=new ht(0,0,0,0),th=function(){function r(e){this.id=gw(),this.animators=[],this.currentStates=[],this.states={},this._init(e)}return r.prototype._init=function(e){this.attr(e)},r.prototype.drift=function(e,t,a){switch(this.draggable){case"horizontal":t=0;break;case"vertical":e=0;break}var n=this.transform;n||(n=this.transform=[1,0,0,1,0,0]),n[4]+=e,n[5]+=t,this.decomposeTransform(),this.markRedraw()},r.prototype.beforeUpdate=function(){},r.prototype.afterUpdate=function(){},r.prototype.update=function(){this.updateTransform(),this.__dirty&&this.updateInnerText()},r.prototype.updateInnerText=function(e){var t=this._textContent;if(t&&(!t.ignore||e)){this.textConfig||(this.textConfig={});var a=this.textConfig,n=a.local,i=t.innerTransformable,o=void 0,s=void 0,l=!1;i.parent=n?this:null;var u=!1;if(i.copyTransform(t),a.position!=null){var f=P2;a.layoutRect?f.copy(a.layoutRect):f.copy(this.getBoundingRect()),n||f.applyTransform(this.transform),this.calculateTextPosition?this.calculateTextPosition(xi,a,f):lf(xi,a,f),i.x=xi.x,i.y=xi.y,o=xi.align,s=xi.verticalAlign;var h=a.origin;if(h&&a.rotation!=null){var v=void 0,c=void 0;h==="center"?(v=f.width*.5,c=f.height*.5):(v=Sr(h[0],f.width),c=Sr(h[1],f.height)),u=!0,i.originX=-i.x+v+(n?0:f.x),i.originY=-i.y+c+(n?0:f.y)}}a.rotation!=null&&(i.rotation=a.rotation);var p=a.offset;p&&(i.x+=p[0],i.y+=p[1],u||(i.originX=-p[0],i.originY=-p[1]));var d=a.inside==null?typeof a.position=="string"&&a.position.indexOf("inside")>=0:a.inside,g=this._innerTextDefaultStyle||(this._innerTextDefaultStyle={}),y=void 0,m=void 0,_=void 0;d&&this.canBeInsideText()?(y=a.insideFill,m=a.insideStroke,(y==null||y==="auto")&&(y=this.getInsideTextFill()),(m==null||m==="auto")&&(m=this.getInsideTextStroke(y),_=!0)):(y=a.outsideFill,m=a.outsideStroke,(y==null||y==="auto")&&(y=this.getOutsideFill()),(m==null||m==="auto")&&(m=this.getOutsideStroke(y),_=!0)),y=y||"#000",(y!==g.fill||m!==g.stroke||_!==g.autoStroke||o!==g.align||s!==g.verticalAlign)&&(l=!0,g.fill=y,g.stroke=m,g.autoStroke=_,g.align=o,g.verticalAlign=s,t.setDefaultTextStyle(g)),t.__dirty|=Ge,l&&t.dirtyStyle(!0)}},r.prototype.canBeInsideText=function(){return!0},r.prototype.getInsideTextFill=function(){return"#fff"},r.prototype.getInsideTextStroke=function(e){return"#000"},r.prototype.getOutsideFill=function(){return this.__zr&&this.__zr.isDarkMode()?Mp:Dp},r.prototype.getOutsideStroke=function(e){var t=this.__zr&&this.__zr.getBackgroundColor(),a=typeof t=="string"&&We(t);a||(a=[255,255,255,1]);for(var n=a[3],i=this.__zr.isDarkMode(),o=0;o<3;o++)a[o]=a[o]*n+(i?0:255)*(1-n);return a[3]=1,na(a,"rgba")},r.prototype.traverse=function(e,t){},r.prototype.attrKV=function(e,t){e==="textConfig"?this.setTextConfig(t):e==="textContent"?this.setTextContent(t):e==="clipPath"?this.setClipPath(t):e==="extra"?(this.extra=this.extra||{},V(this.extra,t)):this[e]=t},r.prototype.hide=function(){this.ignore=!0,this.markRedraw()},r.prototype.show=function(){this.ignore=!1,this.markRedraw()},r.prototype.attr=function(e,t){if(typeof e=="string")this.attrKV(e,t);else if(et(e))for(var a=e,n=_t(a),i=0;i<n.length;i++){var o=n[i];this.attrKV(o,e[o])}return this.markRedraw(),this},r.prototype.saveCurrentToNormalState=function(e){this._innerSaveToNormal(e);for(var t=this._normalState,a=0;a<this.animators.length;a++){var n=this.animators[a],i=n.__fromStateTransition;if(!(n.getLoop()||i&&i!==tv)){var o=n.targetName,s=o?t[o]:t;n.saveTo(s)}}},r.prototype._innerSaveToNormal=function(e){var t=this._normalState;t||(t=this._normalState={}),e.textConf
Line truncated
|
||||
* ZRender, a high performance 2d drawing library.
|
||||
*
|
||||
* Copyright (c) 2013, Baidu Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* LICENSE
|
||||
* https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
|
||||
*/var zu={},Uw={};function N2(r){delete Uw[r]}function B2(r){if(!r)return!1;if(typeof r=="string")return nf(r,1)<Cp;if(r.colorStops){for(var e=r.colorStops,t=0,a=e.length,n=0;n<a;n++)t+=nf(e[n].color,1);return t/=a,t<Cp}return!1}var V2=function(){function r(e,t,a){var n=this;this._sleepAfterStill=10,this._stillFrameAccum=0,this._needsRefresh=!0,this._needsRefreshHover=!0,this._darkMode=!1,a=a||{},this.dom=t,this.id=e;var i=new jL,o=a.renderer||"canvas";zu[o]||(o=_t(zu)[0]),a.useDirtyRect=a.useDirtyRect==null?!1:a.useDirtyRect;var s=new zu[o](t,i,a,e),l=a.ssr||s.ssrOnly;this.storage=i,this.painter=s;var u=!yt.node&&!yt.worker&&!l?new M2(s.getViewportRoot(),s.root):null,f=a.useCoarsePointer,h=f==null||f==="auto"?yt.touchEventsSupported:!!f,v=44,c;h&&(c=st(a.pointerSize,v)),this.handler=new bw(i,s,u,s.root,c),this.animation=new x2({stage:{update:l?null:function(){return n._flush(!0)}}}),l||this.animation.start()}return r.prototype.add=function(e){this._disposed||!e||(this.storage.addRoot(e),e.addSelfToZr(this),this.refresh())},r.prototype.remove=function(e){this._disposed||!e||(this.storage.delRoot(e),e.removeSelfFromZr(this),this.refresh())},r.prototype.configLayer=function(e,t){this._disposed||(this.painter.configLayer&&this.painter.configLayer(e,t),this.refresh())},r.prototype.setBackgroundColor=function(e){this._disposed||(this.painter.setBackgroundColor&&this.painter.setBackgroundColor(e),this.refresh(),this._backgroundColor=e,this._darkMode=B2(e))},r.prototype.getBackgroundColor=function(){return this._backgroundColor},r.prototype.setDarkMode=function(e){this._darkMode=e},r.prototype.isDarkMode=function(){return this._darkMode},r.prototype.refreshImmediately=function(e){this._disposed||(e||this.animation.update(!0),this._needsRefresh=!1,this.painter.refresh(),this._needsRefresh=!1)},r.prototype.refresh=function(){this._disposed||(this._needsRefresh=!0,this.animation.start())},r.prototype.flush=function(){this._disposed||this._flush(!1)},r.prototype._flush=function(e){var t,a=Yi();this._needsRefresh&&(t=!0,this.refreshImmediately(e)),this._needsRefreshHover&&(t=!0,this.refreshHoverImmediately());var n=Yi();t?(this._stillFrameAccum=0,this.trigger("rendered",{elapsedTime:n-a})):this._sleepAfterStill>0&&(this._stillFrameAccum++,this._stillFrameAccum>this._sleepAfterStill&&this.animation.stop())},r.prototype.setSleepAfterStill=function(e){this._sleepAfterStill=e},r.prototype.wakeUp=function(){this._disposed||(this.animation.start(),this._stillFrameAccum=0)},r.prototype.refreshHover=function(){this._needsRefreshHover=!0},r.prototype.refreshHoverImmediately=function(){this._disposed||(this._needsRefreshHover=!1,this.painter.refreshHover&&this.painter.getType()==="canvas"&&this.painter.refreshHover())},r.prototype.resize=function(e){this._disposed||(e=e||{},this.painter.resize(e.width,e.height),this.handler.resize())},r.prototype.clearAnimation=function(){this._disposed||this.animation.clear()},r.prototype.getWidth=function(){if(!this._disposed)return this.painter.getWidth()},r.prototype.getHeight=function(){if(!this._disposed)return this.painter.getHeight()},r.prototype.setCursorStyle=function(e){this._disposed||this.handler.setCursorStyle(e)},r.prototype.findHover=function(e,t){if(!this._disposed)return this.handler.findHover(e,t)},r.prototype.on=function(e,t,a){return this._disposed||this.handler.on(e,t,a),this},r.prototype.off=function(e,t){this._disposed||this.handler.off(e,t)},r.prototype.trigger=function(e,t){this._disposed||this.handler.trigger(e,t)},r.prototype.clear=function(){if(!this._disposed){for(var e=this.storage.getRoots(),t=0;t<e.length;t++)e[t]instanceof at&&e[t].removeSelfFromZr(this);this.storage.delAllRoots(),this.painter.clear()}},r.prototype.dispose=function(){this._disposed||(this.animation.stop(),this.clear(),this.storage.dispose(),this.painter.dispose(),this.handler.dispose(),this.animation=this.storage=this.painter=this.handler=null,this._disposed=!0,N2(this.id))},r}();function Bm(r,e){var t=new V2(gw(),r,e);return Uw[t.id]=t,t}function z2(r,e){zu[r]=e}var Ip;function G2(r){if(typeof Ip=="function")return Ip(r)}function F2(r){Ip=r}var Vm=1e-4,Yw=20;function H2(r){return r.replace(/^\s+|\s+$/g,"")}function Dt(r,e,t,a){var n=e[0],i=e[1],o=t[0],s=t[1],l=i-n,u=s-o;if(l===0)return u===0?o:(o+s)/2;if(a)if(l>0){if(r<=n)return o;if(r>=i)return s}else{if(r>=n)return o;if(r<=i)return s}else{if(r===n)return o;if(r===i)return s}return(r-n)/l*u+o}function W(r,e){switch(r){case"center":case"middle":r="50%";break;case"left":case"top":r="0%";break;case"right":case"bottom":r="100%";break}return Y(r)?H2(r).match(/%$/)?parseFloat(r)/100*e:parseFloat(r):r==null?NaN:+r}function Ut(r,e,t){return e==null&&(e=10),e=Math.min(Math.max(0,e),Yw),r=(+r).toFixed(e),t?r:+r}function nr(r){return r.sort(function(e,t){return e-t}),r}function kr(r){if(r=+r,isNaN(r))return 0;if(r>1e-14){for(var e=1,t=0;t<15;t++,e*=10)if(Math.round(r*e)/e===r)return t}return W2(r)}function W2(r){var e=r.toString().toLowerCase(),t=e.indeLine truncated
|
||||
`);i=oT(t,a,n,i);for(var s=!1,l={},u=0,f=o.length;u<f;u++)sT(l,o[u],i),o[u]=l.textLine,s=s||l.isTruncated;r.text=o.join(`
|
||||
`),r.isTruncated=s}function oT(r,e,t,a){a=a||{};var n=V({},a);n.font=e,t=st(t,"..."),n.maxIterations=st(a.maxIterations,2);var i=n.minChar=st(a.minChar,0);n.cnCharWidth=Ue("国",e);var o=n.ascCharWidth=Ue("a",e);n.placeholder=st(a.placeholder,"");for(var s=r=Math.max(0,r-1),l=0;l<i&&s>=o;l++)s-=o;var u=Ue(t,e);return u>s&&(t="",u=0),s=r-u,n.ellipsis=t,n.ellipsisWidth=u,n.contentWidth=s,n.containerWidth=r,n}function sT(r,e,t){var a=t.containerWidth,n=t.font,i=t.contentWidth;if(!a){r.textLine="",r.isTruncated=!1;return}var o=Ue(e,n);if(o<=a){r.textLine=e,r.isTruncated=!1;return}for(var s=0;;s++){if(o<=i||s>=t.maxIterations){e+=t.ellipsis;break}var l=s===0?bP(e,i,t.ascCharWidth,t.cnCharWidth):o>0?Math.floor(e.length*i/o):0;e=e.substr(0,l),o=Ue(e,n)}e===""&&(e=t.placeholder),r.textLine=e,r.isTruncated=!0}function bP(r,e,t,a){for(var n=0,i=0,o=r.length;i<o&&n<e;i++){var s=r.charCodeAt(i);n+=0<=s&&s<=127?t:a}return i}function wP(r,e){r!=null&&(r+="");var t=e.overflow,a=e.padding,n=e.font,i=t==="truncate",o=jf(n),s=st(e.lineHeight,o),l=!!e.backgroundColor,u=e.lineOverflow==="truncate",f=!1,h=e.width,v;h!=null&&(t==="break"||t==="breakAll")?v=r?lT(r,e.font,h,t==="breakAll",0).lines:[]:v=r?r.split(`
|
||||
`):[];var c=v.length*s,p=st(e.height,c);if(c>p&&u){var d=Math.floor(p/s);f=f||v.length>d,v=v.slice(0,d)}if(r&&i&&h!=null)for(var g=oT(h,n,e.ellipsis,{minChar:e.truncateMinChar,placeholder:e.placeholder}),y={},m=0;m<v.length;m++)sT(y,v[m],g),v[m]=y.textLine,f=f||y.isTruncated;for(var _=p,S=0,m=0;m<v.length;m++)S=Math.max(Ue(v[m],n),S);h==null&&(h=S);var b=S;return a&&(_+=a[0]+a[2],b+=a[1]+a[3],h+=a[1]+a[3]),l&&(b=h),{lines:v,height:p,outerWidth:b,outerHeight:_,lineHeight:s,calculatedLineHeight:o,contentWidth:S,contentHeight:c,width:h,isTruncated:f}}var TP=function(){function r(){}return r}(),Ym=function(){function r(e){this.tokens=[],e&&(this.tokens=e)}return r}(),AP=function(){function r(){this.width=0,this.height=0,this.contentWidth=0,this.contentHeight=0,this.outerWidth=0,this.outerHeight=0,this.lines=[],this.isTruncated=!1}return r}();function CP(r,e){var t=new AP;if(r!=null&&(r+=""),!r)return t;for(var a=e.width,n=e.height,i=e.overflow,o=(i==="break"||i==="breakAll")&&a!=null?{width:a,accumWidth:0,breakAll:i==="breakAll"}:null,s=iv.lastIndex=0,l;(l=iv.exec(r))!=null;){var u=l.index;u>s&&ov(t,r.substring(s,u),e,o),ov(t,l[2],e,o,l[1]),s=iv.lastIndex}s<r.length&&ov(t,r.substring(s,r.length),e,o);var f=[],h=0,v=0,c=e.padding,p=i==="truncate",d=e.lineOverflow==="truncate",g={};function y(F,H,U){F.width=H,F.lineHeight=U,h+=U,v=Math.max(v,H)}t:for(var m=0;m<t.lines.length;m++){for(var _=t.lines[m],S=0,b=0,x=0;x<_.tokens.length;x++){var w=_.tokens[x],T=w.styleName&&e.rich[w.styleName]||{},A=w.textPadding=T.padding,C=A?A[1]+A[3]:0,M=w.font=T.font||e.font;w.contentHeight=jf(M);var I=st(T.height,w.contentHeight);if(w.innerHeight=I,A&&(I+=A[0]+A[2]),w.height=I,w.lineHeight=Vr(T.lineHeight,e.lineHeight,I),w.align=T&&T.align||e.align,w.verticalAlign=T&&T.verticalAlign||"middle",d&&n!=null&&h+w.lineHeight>n){var L=t.lines.length;x>0?(_.tokens=_.tokens.slice(0,x),y(_,b,S),t.lines=t.lines.slice(0,m+1)):t.lines=t.lines.slice(0,m),t.isTruncated=t.isTruncated||t.lines.length<L;break t}var P=T.width,R=P==null||P==="auto";if(typeof P=="string"&&P.charAt(P.length-1)==="%")w.percentWidth=P,f.push(w),w.contentWidth=Ue(w.text,M);else{if(R){var E=T.backgroundColor,N=E&&E.image;N&&(N=SP(N),rh(N)&&(w.width=Math.max(w.width,N.width*I/N.height)))}var O=p&&a!=null?a-b:null;O!=null&&O<w.width?!R||O<C?(w.text="",w.width=w.contentWidth=0):(xP(g,w.text,O-C,M,e.ellipsis,{minChar:e.truncateMinChar}),w.text=g.text,t.isTruncated=t.isTruncated||g.isTruncated,w.width=w.contentWidth=Ue(w.text,M)):w.contentWidth=Ue(w.text,M)}w.width+=C,b+=w.width,T&&(S=Math.max(S,w.lineHeight))}y(_,b,S)}t.outerWidth=t.width=st(a,v),t.outerHeight=t.height=st(n,h),t.contentHeight=h,t.contentWidth=v,c&&(t.outerWidth+=c[1]+c[3],t.outerHeight+=c[0]+c[2]);for(var m=0;m<f.length;m++){var w=f[m],B=w.percentWidth;w.width=parseInt(B,10)/100*t.width}return t}function ov(r,e,t,a,n){var i=e==="",o=n&&t.rich[n]||{},s=r.lines,l=o.font||t.font,u=!1,f,h;if(a){var v=o.padding,c=v?v[1]+v[3]:0;if(o.width!=null&&o.width!=="auto"){var p=Sr(o.width,a.width)+c;s.length>0&&p+a.accumWidth>a.width&&(f=e.split(`
|
||||
`),u=!0),a.accumWidth=p}else{var d=lT(e,l,a.width,a.breakAll,a.accumWidth);a.accumWidth=d.accumWidth+c,h=d.linesWidths,f=d.lines}}else f=e.split(`
|
||||
`);for(var g=0;g<f.length;g++){var y=f[g],m=new TP;if(m.styleName=n,m.text=y,m.isLineHolder=!y&&!i,typeof o.width=="number"?m.width=o.width:m.width=h?h[g]:Ue(y,l),!g&&!u){var _=(s[s.length-1]||(s[0]=new Ym)).tokens,S=_.length;S===1&&_[0].isLineHolder?_[0]=m:(y||!S||i)&&_.push(m)}else s.push(new Ym([m]))}}function DP(r){var e=r.charCodeAt(0);return e>=32&&e<=591||e>=880&&e<=4351||e>=4608&&e<=5119||e>=7680&&e<=8303}var MP=Gr(",&?/;] ".split(""),function(r,e){return r[e]=!0,r},{});function IP(r){return DP(r)?!!MP[r]:!0}function lT(r,e,t,a,n){for(var i=[],o=[],s="",l="",u=0,f=0,h=0;h<r.length;h++){var v=r.charAt(h);if(v===`
|
||||
`){l&&(s+=l,f+=u),i.push(s),o.push(f),s="",l="",u=0,f=0;continue}var c=Ue(v,e),p=a?!1:!IP(v);if(i.length?f+c>t:n+f+c>t){f?(s||l)&&(p?(s||(s=l,l="",u=0,f=u),i.push(s),o.push(f-u),l+=v,u+=c,s="",f=u):(l&&(s+=l,l="",u=0),i.push(s),o.push(f),s=v,f=c)):p?(i.push(l),o.push(u),l=v,u=c):(i.push(v),o.push(c));continue}f+=c,p?(l+=v,u+=c):(l&&(s+=l,l="",u=0),s+=v)}return!i.length&&!s&&(s=r,l="",u=0),l&&(s+=l),s&&(i.push(s),o.push(f)),i.length===1&&(f+=n),{accumWidth:f,lines:i,linesWidths:o}}var Rp="__zr_style_"+Math.round(Math.random()*10),$n={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"#000",opacity:1,blend:"source-over"},ah={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};$n[Rp]=!0;var Xm=["z","z2","invisible"],LP=["invisible"],or=function(r){k(e,r);function e(t){return r.call(this,t)||this}return e.prototype._init=function(t){for(var a=_t(t),n=0;n<a.length;n++){var i=a[n];i==="style"?this.useStyle(t[i]):r.prototype.attrKV.call(this,i,t[i])}this.style||this.useStyle({})},e.prototype.beforeBrush=function(){},e.prototype.afterBrush=function(){},e.prototype.innerBeforeBrush=function(){},e.prototype.innerAfterBrush=function(){},e.prototype.shouldBePainted=function(t,a,n,i){var o=this.transform;if(this.ignore||this.invisible||this.style.opacity===0||this.culling&&PP(this,t,a)||o&&!o[0]&&!o[3])return!1;if(n&&this.__clipPaths){for(var s=0;s<this.__clipPaths.length;++s)if(this.__clipPaths[s].isZeroArea())return!1}if(i&&this.parent)for(var l=this.parent;l;){if(l.ignore)return!1;l=l.parent}return!0},e.prototype.contain=function(t,a){return this.rectContain(t,a)},e.prototype.traverse=function(t,a){t.call(a,this)},e.prototype.rectContain=function(t,a){var n=this.transformCoordToLocal(t,a),i=this.getBoundingRect();return i.contain(n[0],n[1])},e.prototype.getPaintRect=function(){var t=this._paintRect;if(!this._paintRect||this.__dirty){var a=this.transform,n=this.getBoundingRect(),i=this.style,o=i.shadowBlur||0,s=i.shadowOffsetX||0,l=i.shadowOffsetY||0;t=this._paintRect||(this._paintRect=new ht(0,0,0,0)),a?ht.applyTransform(t,n,a):t.copy(n),(o||s||l)&&(t.width+=o*2+Math.abs(s),t.height+=o*2+Math.abs(l),t.x=Math.min(t.x,t.x+s-o),t.y=Math.min(t.y,t.y+l-o));var u=this.dirtyRectTolerance;t.isZero()||(t.x=Math.floor(t.x-u),t.y=Math.floor(t.y-u),t.width=Math.ceil(t.width+1+u*2),t.height=Math.ceil(t.height+1+u*2))}return t},e.prototype.setPrevPaintRect=function(t){t?(this._prevPaintRect=this._prevPaintRect||new ht(0,0,0,0),this._prevPaintRect.copy(t)):this._prevPaintRect=null},e.prototype.getPrevPaintRect=function(){return this._prevPaintRect},e.prototype.animateStyle=function(t){return this.animate("style",t)},e.prototype.updateDuringAnimation=function(t){t==="style"?this.dirtyStyle():this.markRedraw()},e.prototype.attrKV=function(t,a){t!=="style"?r.prototype.attrKV.call(this,t,a):this.style?this.setStyle(a):this.useStyle(a)},e.prototype.setStyle=function(t,a){return typeof t=="string"?this.style[t]=a:V(this.style,t),this.dirtyStyle(),this},e.prototype.dirtyStyle=function(t){t||this.markRedraw(),this.__dirty|=is,this._rect&&(this._rect=null)},e.prototype.dirty=function(){this.dirtyStyle()},e.prototype.styleChanged=function(){return!!(this.__dirty&is)},e.prototype.styleUpdated=function(){this.__dirty&=~is},e.prototype.createStyle=function(t){return Kf($n,t)},e.prototype.useStyle=function(t){t[Rp]||(t=this.createStyle(t)),this.__inHover?this.__hoverStyle=t:this.style=t,this.dirtyStyle()},e.prototype.isStyleObject=function(t){return t[Rp]},e.prototype._innerSaveToNormal=function(t){r.prototype._innerSaveToNormal.call(this,t);var a=this._normalState;t.style&&!a.style&&(a.style=this._mergeStyle(this.createStyle(),this.style)),this._savePrimaryToNormal(t,a,Xm)},e.prototype._applyStateObj=function(t,a,n,i,o,s){r.prototype._applyStateObj.call(this,t,a,n,i,o,s);var l=!(a&&i),u;if(a&&a.style?o?i?u=a.style:(u=this._mergeStyle(this.createStyle(),n.style),this._mergeStyle(u,a.style)):(u=this._mergeStyle(this.createStyle(),i?this.style:n.style),this._mergeStyle(u,a.style)):l&&(u=n.style),u)if(o){var f=this.style;if(this.style=this.createStyle(l?{}:f),l)for(var h=_t(f),v=0;v<h.length;v++){var c=h[v];c in u&&(u[c]=u[c],this.style[c]=f[c])}for(var p=_t(u),v=0;v<p.length;v++){var c=p[v];this.style[c]=this.style[c]}this._transitionState(t,{style:u},s,this.getAnimationStyleProps())}else this.useStyle(u);for(var d=this.__inHover?LP:Xm,v=0;v<d.length;v++){var c=d[v];a&&a[c]!=null?this[c]=a[c]:l&&n[c]!=null&&(this[c]=n[c])}},e.prototype._mergeStates=function(t){for(var a=r.prototype._mergeStates.call(this,t),n,i=0;i<t.length;i++){var o=t[i];o.style&&(n=n||{},this._mergeStyle(n,o.style))}return n&&(a.style=n),a},e.prototype._mergeStyle=function(t,a){return V(t,a),t},e.prototype.getAnimationStyleProps=function(){return ah},e.initDefaultProps=function(){var t=e.prototype;t.type="displayable",t.invisible=!1,t.z=0,t.z2=0,t.zlevel=0,t.culling=!1,t.cursor="pointer",t.rectHover=!1,t.incremental=!1,t._rect=null,t.dirty
Line truncated
|
||||
`,`
|
||||
|
||||
`,`
|
||||
|
||||
|
||||
`];function ie(r,e){return e.type=r,e}function $p(r){return r.type==="section"}function PA(r){return $p(r)?wk:Tk}function RA(r){if($p(r)){var e=0,t=r.blocks.length,a=t>1||t>0&&!r.noHeader;return D(r.blocks,function(n){var i=RA(n);i>=e&&(e=i+ +(a&&(!i||$p(n)&&!n.noHeader)))}),e}return 0}function wk(r,e,t,a){var n=e.noHeader,i=Ak(RA(e)),o=[],s=e.blocks||[];Ce(!s||z(s)),s=s||[];var l=r.orderMode;if(e.sortBlocks&&l){s=s.slice();var u={valueAsc:"asc",valueDesc:"desc"};if(Z(u,l)){var f=new TA(u[l],null);s.sort(function(d,g){return f.evaluate(d.sortParam,g.sortParam)})}else l==="seriesDesc"&&s.reverse()}D(s,function(d,g){var y=e.valueFormatter,m=PA(d)(y?V(V({},r),{valueFormatter:y}):r,d,g>0?i.html:0,a);m!=null&&o.push(m)});var h=r.renderMode==="richText"?o.join(i.richText):qp(a,o.join(""),n?t:i.html);if(n)return h;var v=Wp(e.header,"ordinal",r.useUTC),c=LA(a,r.renderMode).nameStyle,p=IA(a);return r.renderMode==="richText"?EA(r,v,c)+i.richText+h:qp(a,'<div style="'+c+";"+p+';">'+we(v)+"</div>"+h,t)}function Tk(r,e,t,a){var n=r.renderMode,i=e.noName,o=e.noValue,s=!e.markerType,l=e.name,u=r.useUTC,f=e.valueFormatter||r.valueFormatter||function(S){return S=z(S)?S:[S],G(S,function(b,x){return Wp(b,z(c)?c[x]:c,u)})};if(!(i&&o)){var h=s?"":r.markupStyleCreator.makeTooltipMarker(e.markerType,e.markerColor||"#333",n),v=i?"":Wp(l,"ordinal",u),c=e.valueType,p=o?[]:f(e.value,e.dataIndex),d=!s||!i,g=!s&&i,y=LA(a,n),m=y.nameStyle,_=y.valueStyle;return n==="richText"?(s?"":h)+(i?"":EA(r,v,m))+(o?"":Mk(r,p,d,g,_)):qp(a,(s?"":h)+(i?"":Ck(v,!s,m))+(o?"":Dk(p,d,g,_)),t)}}function t_(r,e,t,a,n,i){if(r){var o=PA(r),s={useUTC:n,renderMode:t,orderMode:a,markupStyleCreator:e,valueFormatter:r.valueFormatter};return o(s,r,0,i)}}function Ak(r){return{html:xk[r],richText:bk[r]}}function qp(r,e,t){var a='<div style="clear:both"></div>',n="margin: "+t+"px 0 0",i=IA(r);return'<div style="'+n+";"+i+';">'+e+a+"</div>"}function Ck(r,e,t){var a=e?"margin-left:2px":"";return'<span style="'+t+";"+a+'">'+we(r)+"</span>"}function Dk(r,e,t,a){var n=t?"10px":"20px",i=e?"float:right;margin-left:"+n:"";return r=z(r)?r:[r],'<span style="'+i+";"+a+'">'+G(r,function(o){return we(o)}).join(" ")+"</span>"}function EA(r,e,t){return r.markupStyleCreator.wrapRichTextStyle(e,t)}function Mk(r,e,t,a,n){var i=[n],o=a?10:20;return t&&i.push({padding:[0,0,0,o],align:"right"}),r.markupStyleCreator.wrapRichTextStyle(z(e)?e.join(" "):e,i)}function kA(r,e){var t=r.getData().getItemVisual(e,"style"),a=t[r.visualDrawType];return ii(a)}function OA(r,e){var t=r.get("padding");return t??(e==="richText"?[8,10]:10)}var Lv=function(){function r(){this.richTextStyles={},this._nextStyleNameId=Kw()}return r.prototype._generateStyleName=function(){return"__EC_aUTo_"+this._nextStyleNameId++},r.prototype.makeTooltipMarker=function(e,t,a){var n=a==="richText"?this._generateStyleName():null,i=mE({color:t,type:e,renderMode:a,markerId:n});return Y(i)?i:(this.richTextStyles[n]=i.style,i.content)},r.prototype.wrapRichTextStyle=function(e,t){var a={};z(t)?D(t,function(i){return V(a,i)}):V(a,t);var n=this._generateStyleName();return this.richTextStyles[n]=a,"{"+n+"|"+e+"}"},r}();function NA(r){var e=r.series,t=r.dataIndex,a=r.multipleSeries,n=e.getData(),i=n.mapDimensionsAll("defaultedTooltip"),o=i.length,s=e.getRawValue(t),l=z(s),u=kA(e,t),f,h,v,c;if(o>1||l&&!o){var p=Ik(s,e,t,i,u);f=p.inlineValues,h=p.inlineValueTypes,v=p.blocks,c=p.inlineValues[0]}else if(o){var d=n.getDimensionInfo(i[0]);c=f=no(n,t,i[0]),h=d.type}else c=f=l?s[0]:s;var g=ug(e),y=g&&e.name||"",m=n.getName(t),_=a?y:m;return ie("section",{header:y,noHeader:a||!g,sortParam:c,blocks:[ie("nameValue",{markerType:"item",markerColor:u,name:_,noName:!gr(_),value:f,valueType:h,dataIndex:t})].concat(v||[])})}function Ik(r,e,t,a,n){var i=e.getData(),o=Gr(r,function(h,v,c){var p=i.getDimensionInfo(c);return h=h||p&&p.tooltip!==!1&&p.displayName!=null},!1),s=[],l=[],u=[];a.length?D(a,function(h){f(no(i,t,h),h)}):D(r,f);function f(h,v){var c=i.getDimensionInfo(v);!c||c.otherDims.tooltip===!1||(o?u.push(ie("nameValue",{markerType:"subItem",markerColor:n,name:c.displayName,value:h,valueType:c.type})):(s.push(h),l.push(c.type)))}return{inlineValues:s,inlineValueTypes:l,blocks:u}}var ba=xt();function Jl(r,e){return r.getName(e)||r.getId(e)}var Yu="__universalTransitionEnabled",Vt=function(r){k(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t._selectedDataIndicesMap={},t}return e.prototype.init=function(t,a,n){this.seriesIndex=this.componentIndex,this.dataTask=Ds({count:Pk,reset:Rk}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n);var i=ba(this).sourceManager=new MA(this);i.prepareSource();var o=this.getInitialData(t,n);r_(o,this),this.dataTask.context.data=o,ba(this).dataBeforeProcessed=o,e_(this),this._initSelectedMapFromData(o)},e.prototype.mergeDefaultAndTheme=function(t,a){var n=Us(this),i=n?bo(t):{},o=this.subType;mt.hasClass(o)&&(o+="Series"),ut(t,a.getTheme().get(this.subType)),ut(t,t
Line truncated
|
||||
`:"";function a(n){var i=n.children,o=n.tag,s=n.attrs,l=n.text;return OB(o,s)+(o!=="style"?we(l):l||"")+(i?""+t+G(i,function(u){return a(u)}).join(t)+t:"")+NB(o)}return a(r)}function BB(r,e,t){t=t||{};var a=t.newline?`
|
||||
`:"",n=" {"+a,i=a+"}",o=G(_t(r),function(l){return l+n+G(_t(r[l]),function(u){return u+":"+r[l][u]+";"}).join(a)+i}).join(a),s=G(_t(e),function(l){return"@keyframes "+l+n+G(_t(e[l]),function(u){return u+n+G(_t(e[l][u]),function(f){var h=e[l][u][f];return f==="d"&&(h='path("'+h+'")'),f+":"+h+";"}).join(a)+i}).join(a)+i}).join(a);return!o&&!s?"":["<![CDATA[",o,s,"]]>"].join(a)}function sd(r){return{zrId:r,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssStyleCache:{},cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function K_(r,e,t,a){return re("svg","root",{width:r,height:e,xmlns:jC,"xmlns:xlink":tD,version:"1.1",baseProfile:"full",viewBox:a?"0 0 "+r+" "+e:!1},t)}var VB=0;function rD(){return VB++}var J_={cubicIn:"0.32,0,0.67,0",cubicOut:"0.33,1,0.68,1",cubicInOut:"0.65,0,0.35,1",quadraticIn:"0.11,0,0.5,0",quadraticOut:"0.5,1,0.89,1",quadraticInOut:"0.45,0,0.55,1",quarticIn:"0.5,0,0.75,0",quarticOut:"0.25,1,0.5,1",quarticInOut:"0.76,0,0.24,1",quinticIn:"0.64,0,0.78,0",quinticOut:"0.22,1,0.36,1",quinticInOut:"0.83,0,0.17,1",sinusoidalIn:"0.12,0,0.39,0",sinusoidalOut:"0.61,1,0.88,1",sinusoidalInOut:"0.37,0,0.63,1",exponentialIn:"0.7,0,0.84,0",exponentialOut:"0.16,1,0.3,1",exponentialInOut:"0.87,0,0.13,1",circularIn:"0.55,0,1,0.45",circularOut:"0,0.55,0.45,1",circularInOut:"0.85,0,0.15,1"},Mn="transform-origin";function zB(r,e,t){var a=V({},r.shape);V(a,e),r.buildPath(t,a);var n=new QC;return n.reset(Bw(r)),t.rebuildPath(n,1),n.generateStr(),n.getStr()}function GB(r,e){var t=e.originX,a=e.originY;(t||a)&&(r[Mn]=t+"px "+a+"px")}var FB={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function aD(r,e){var t=e.zrId+"-ani-"+e.cssAnimIdx++;return e.cssAnims[t]=r,t}function HB(r,e,t){var a=r.shape.paths,n={},i,o;if(D(a,function(l){var u=sd(t.zrId);u.animation=!0,Dh(l,{},u,!0);var f=u.cssAnims,h=u.cssNodes,v=_t(f),c=v.length;if(c){o=v[c-1];var p=f[o];for(var d in p){var g=p[d];n[d]=n[d]||{d:""},n[d].d+=g.d||""}for(var y in h){var m=h[y].animation;m.indexOf(o)>=0&&(i=m)}}}),!!i){e.d=!1;var s=aD(n,t);return i.replace(o,s)}}function Q_(r){return Y(r)?J_[r]?"cubic-bezier("+J_[r]+")":ig(r)?r:"":""}function Dh(r,e,t,a){var n=r.animators,i=n.length,o=[];if(r instanceof Sg){var s=HB(r,e,t);if(s)o.push(s);else if(!i)return}else if(!i)return;for(var l={},u=0;u<i;u++){var f=n[u],h=[f.getMaxTime()/1e3+"s"],v=Q_(f.getClip().easing),c=f.getDelay();v?h.push(v):h.push("linear"),c&&h.push(c/1e3+"s"),f.getLoop()&&h.push("infinite");var p=h.join(" ");l[p]=l[p]||[p,[]],l[p][1].push(f)}function d(m){var _=m[1],S=_.length,b={},x={},w={},T="animation-timing-function";function A(vt,tt,pt){for(var q=vt.getTracks(),ot=vt.getMaxTime(),Ot=0;Ot<q.length;Ot++){var It=q[Ot];if(It.needsAnimate()){var Et=It.keyframes,Gt=It.propName;if(pt&&(Gt=pt(Gt)),Gt)for(var jt=0;jt<Et.length;jt++){var Ve=Et[jt],Pe=Math.round(Ve.time/ot*100)+"%",en=Q_(Ve.easing),ma=Ve.rawValue;(Y(ma)||wt(ma))&&(tt[Pe]=tt[Pe]||{},tt[Pe][Gt]=Ve.rawValue,en&&(tt[Pe][T]=en))}}}}for(var C=0;C<S;C++){var M=_[C],I=M.targetName;I?I==="shape"&&A(M,x):!a&&A(M,b)}for(var L in b){var P={};Hw(P,r),V(P,b[L]);var R=Vw(P),E=b[L][T];w[L]=R?{transform:R}:{},GB(w[L],P),E&&(w[L][T]=E)}var N,O=!0;for(var L in x){w[L]=w[L]||{};var B=!N,E=x[L][T];B&&(N=new Ur);var F=N.len();N.reset(),w[L].d=zB(r,x[L],N);var H=N.len();if(!B&&F!==H){O=!1;break}E&&(w[L][T]=E)}if(!O)for(var L in w)delete w[L].d;if(!a)for(var C=0;C<S;C++){var M=_[C],I=M.targetName;I==="style"&&A(M,w,function(q){return FB[q]})}for(var U=_t(w),K=!0,Q,C=1;C<U.length;C++){var it=U[C-1],Lt=U[C];if(w[it][Mn]!==w[Lt][Mn]){K=!1;break}Q=w[it][Mn]}if(K&&Q){for(var L in w)w[L][Mn]&&delete w[L][Mn];e[Mn]=Q}if(Ct(U,function(vt){return _t(w[vt]).length>0}).length){var Wt=aD(w,t);return Wt+" "+m[0]+" both"}}for(var g in l){var s=d(l[g]);s&&o.push(s)}if(o.length){var y=t.zrId+"-cls-"+rD();t.cssNodes["."+y]={animation:o.join(",")},e.class=y}}function WB(r,e,t){if(!r.ignore)if(r.isSilent()){var a={"pointer-events":"none"};j_(a,e,t)}else{var n=r.states.emphasis&&r.states.emphasis.style?r.states.emphasis.style:{},i=n.fill;if(!i){var o=r.style&&r.style.fill,s=r.states.select&&r.states.select.style&&r.states.select.style.fill,l=r.currentStates.indexOf("select")>=0&&s||o;l&&(i=_p(l))}var u=n.lineWidth;if(u){var f=!n.strokeNoScale&&r.transform?r.transform[0]:1;u=u/f}var a={cursor:"pointer"};i&&(a.fill=i),n.stroke&&(a.stroke=n.stroke),u&&(a["stroke-width"]=u),j_(a,e,t)}}function j_(r,e,t,a){var n=JSON.stringify(r),i=t.cssStyleCache[n];i||(i=t.zrId+"-cls-"+rD(),t.cssStyleCache[n]=i,t.cssNodes["."+i+":hover"]=r),e.class=e.class?e.class+" "+i:i}var Ks=Math.round;function nD(r){return r&&Y(r.src)}function iD(r){return r&&J(r.toDataURL)}function ey(r,e,t,a){RB(function(n,i){var o=n==="fill"||n==="stroke";o&&Nw(i)?sD(e,r,n,a):o&&og(i)?lD(t,r,n,a):r[n]=i,o&&a.ssr&&i==="none"&&(r["pointer-events"]="visible")},e,t,!1),KB(t,r,a)}function ry(r,e){var t=G2(e);t&&(t.e
Line truncated
|
||||
`+g.message)}var n=new at;n.add(a),n.isGeoSVGGraphicRoot=!0;var i=t.width,o=t.height,s=t.viewBoxRect,l=this._boundingRect;if(!l){var u=void 0,f=void 0,h=void 0,v=void 0;if(i!=null?(u=0,h=i):s&&(u=s.x,h=s.width),o!=null?(f=0,v=o):s&&(f=s.y,v=s.height),u==null||f==null){var c=a.getBoundingRect();u==null&&(u=c.x,h=c.width),f==null&&(f=c.y,v=c.height)}l=this._boundingRect=new ht(u,f,h,v)}if(s){var p=GD(s,l);a.scaleX=a.scaleY=p.scale,a.x=p.x,a.y=p.y}n.setClipPath(new St({shape:l.plain()}));var d=[];return D(t.named,function(g){i5.get(g.svgNodeTagLower)!=null&&(d.push(g),s5(g.el))}),{root:n,boundingRect:l,named:d}},r.prototype.useGraphic=function(e){var t=this._usedGraphicMap,a=t.get(e);return a||(a=this._freedGraphics.pop()||this._buildGraphic(this._parsedXML),t.set(e,a),a)},r.prototype.freeGraphic=function(e){var t=this._usedGraphicMap,a=t.get(e);a&&(t.removeKey(e),this._freedGraphics.push(a))},r}();function s5(r){r.silent=!1,r.isGroup&&r.traverse(function(e){e.silent=!1})}function l5(r){var e=[],t=$();return D(r,function(a){if(a.namedFrom==null){var n=new rB(a.name,a.el);e.push(n),t.set(a.name,n)}}),{regions:e,regionsMap:t}}var dd=[126,25],Q1="南海诸岛",In=[[[0,3.5],[7,11.2],[15,11.9],[30,7],[42,.7],[52,.7],[56,7.7],[59,.7],[64,.7],[64,0],[5,0],[0,3.5]],[[13,16.1],[19,14.7],[16,21.7],[11,23.1],[13,16.1]],[[12,32.2],[14,38.5],[15,38.5],[13,32.2],[12,32.2]],[[16,47.6],[12,53.2],[13,53.2],[18,47.6],[16,47.6]],[[6,64.4],[8,70],[9,70],[8,64.4],[6,64.4]],[[23,82.6],[29,79.8],[30,79.8],[25,82.6],[23,82.6]],[[37,70.7],[43,62.3],[44,62.3],[39,70.7],[37,70.7]],[[48,51.1],[51,45.5],[53,45.5],[50,51.1],[48,51.1]],[[51,35],[51,28.7],[53,28.7],[53,35],[51,35]],[[52,22.4],[55,17.5],[56,17.5],[53,22.4],[52,22.4]],[[58,12.6],[62,7],[63,7],[60,12.6],[58,12.6]],[[0,3.5],[0,93.1],[64,93.1],[64,0],[63,0],[63,92.4],[1,92.4],[1,3.5],[0,3.5]]];for(var Dn=0;Dn<In.length;Dn++)for(var Pi=0;Pi<In[Dn].length;Pi++)In[Dn][Pi][0]/=10.5,In[Dn][Pi][1]/=-10.5/.75,In[Dn][Pi][0]+=dd[0],In[Dn][Pi][1]+=dd[1];function u5(r,e){if(r==="china"){for(var t=0;t<e.length;t++)if(e[t].name===Q1)return;e.push(new NC(Q1,G(In,function(a){return{type:"polygon",exterior:a}}),dd))}}var f5={南海诸岛:[32,80],广东:[0,-10],香港:[10,5],澳门:[-10,10],天津:[5,5]};function h5(r,e){if(r==="china"){var t=f5[e.name];if(t){var a=e.getCenter();a[0]+=t[0]/10.5,a[1]+=-t[1]/(10.5/.75),e.setCenter(a)}}}var v5=[[[123.45165252685547,25.73527164402261],[123.49731445312499,25.73527164402261],[123.49731445312499,25.750734064600884],[123.45165252685547,25.750734064600884],[123.45165252685547,25.73527164402261]]];function c5(r,e){r==="china"&&e.name==="台湾"&&e.geometries.push({type:"polygon",exterior:v5[0]})}var p5="name",d5=function(){function r(e,t,a){this.type="geoJSON",this._parsedMap=$(),this._mapName=e,this._specialAreas=a,this._geoJSON=y5(t)}return r.prototype.load=function(e,t){t=t||p5;var a=this._parsedMap.get(t);if(!a){var n=this._parseToRegions(t);a=this._parsedMap.set(t,{regions:n,boundingRect:g5(n)})}var i=$(),o=[];return D(a.regions,function(s){var l=s.name;e&&Z(e,l)&&(s=s.cloneShallow(l=e[l])),o.push(s),i.set(l,s)}),{regions:o,boundingRect:a.boundingRect||new ht(0,0,0,0),regionsMap:i}},r.prototype._parseToRegions=function(e){var t=this._mapName,a=this._geoJSON,n;try{n=a?nB(a,e):[]}catch(i){throw new Error(`Invalid geoJson format
|
||||
`+i.message)}return u5(t,n),D(n,function(i){var o=i.name;h5(t,i),c5(t,i);var s=this._specialAreas&&this._specialAreas[o];s&&i.transformTo(s.left,s.top,s.width,s.height)},this),n},r.prototype.getMapForUser=function(){return{geoJson:this._geoJSON,geoJSON:this._geoJSON,specialAreas:this._specialAreas}},r}();function g5(r){for(var e,t=0;t<r.length;t++){var a=r[t].getBoundingRect();e=e||a.clone(),e.union(a)}return e}function y5(r){return Y(r)?typeof JSON<"u"&&JSON.parse?JSON.parse(r):new Function("return ("+r+");")():r}var Ko=$();const ca={registerMap:function(r,e,t){if(e.svg){var a=new o5(r,e.svg);Ko.set(r,a)}else{var n=e.geoJson||e.geoJSON;n&&!e.features?t=e.specialAreas:n=e;var a=new d5(r,n,t);Ko.set(r,a)}},getGeoResource:function(r){return Ko.get(r)},getMapForUser:function(r){var e=Ko.get(r);return e&&e.type==="geoJSON"&&e.getMapForUser()},load:function(r,e,t){var a=Ko.get(r);if(a)return a.load(e,t)}};var fy=["rect","circle","line","ellipse","polygon","polyline","path"],m5=$(fy),_5=$(fy.concat(["g"])),S5=$(fy.concat(["g"])),FD=xt();function gu(r){var e=r.getItemStyle(),t=r.get("areaColor");return t!=null&&(e.fill=t),e}function j1(r){var e=r.style;e&&(e.stroke=e.stroke||e.fill,e.fill=null)}var HD=function(){function r(e){var t=new at;this.uid=So("ec_map_draw"),this._controller=new Dl(e.getZr()),this._controllerHost={target:t},this.group=t,t.add(this._regionsGroup=new at),t.add(this._svgGroup=new at)}return r.prototype.draw=function(e,t,a,n,i){var o=e.mainType==="geo",s=e.getData&&e.getData();o&&t.eachComponent({mainType:"series",subType:"map"},function(y){!s&&y.getHostGeoModel()===e&&(s=y.getData())});var l=e.coordinateSystem,u=this._regionsGroup,f=this.group,h=l.getTransformInfo(),v=h.raw,c=h.roam,p=!u.childAt(0)||i;p?(f.x=c.x,f.y=c.y,f.scaleX=c.scaleX,f.scaleY=c.scaleY,f.dirty()):Tt(f,c,e);var d=s&&s.getVisual("visualMeta")&&s.getVisual("visualMeta").length>0,g={api:a,geo:l,mapOrGeoModel:e,data:s,isVisualEncodedByVisualMap:d,isGeo:o,transformInfoRaw:v};l.resourceType==="geoJSON"?this._buildGeoJSON(g):l.resourceType==="geoSVG"&&this._buildSVG(g),this._updateController(e,t,a),this._updateMapSelectHandler(e,u,a,n)},r.prototype._buildGeoJSON=function(e){var t=this._regionsGroupByName=$(),a=$(),n=this._regionsGroup,i=e.transformInfoRaw,o=e.mapOrGeoModel,s=e.data,l=e.geo.projection,u=l&&l.stream;function f(c,p){return p&&(c=p(c)),c&&[c[0]*i.scaleX+i.x,c[1]*i.scaleY+i.y]}function h(c){for(var p=[],d=!u&&l&&l.project,g=0;g<c.length;++g){var y=f(c[g],d);y&&p.push(y)}return p}function v(c){return{shape:{points:h(c)}}}n.removeAll(),D(e.geo.regions,function(c){var p=c.name,d=t.get(p),g=a.get(p)||{},y=g.dataIdx,m=g.regionModel;if(!d){d=t.set(p,new at),n.add(d),y=s?s.indexOfName(p):null,m=e.isGeo?o.getRegionModel(p):s?s.getItemModel(y):null;var _=m.get("silent",!0);_!=null&&(d.silent=_),a.set(p,{dataIdx:y,regionModel:m})}var S=[],b=[];D(c.geometries,function(T){if(T.type==="polygon"){var A=[T.exterior].concat(T.interiors||[]);u&&(A=iS(A,u)),D(A,function(M){S.push(new Ie(v(M)))})}else{var C=T.points;u&&(C=iS(C,u,!0)),D(C,function(M){b.push(new Le(v(M)))})}});var x=f(c.getCenter(),l&&l.project);function w(T,A){if(T.length){var C=new Sg({culling:!0,segmentIgnoreThreshold:1,shape:{paths:T}});d.add(C),tS(e,C,y,m),eS(e,C,p,m,o,y,x),A&&(j1(C),D(C.states,j1))}}w(S),w(b,!0)}),t.each(function(c,p){var d=a.get(p),g=d.dataIdx,y=d.regionModel;rS(e,c,p,y,o,g),aS(e,c,p,y,o),nS(e,c,p,y,o)},this)},r.prototype._buildSVG=function(e){var t=e.geo.map,a=e.transformInfoRaw;this._svgGroup.x=a.x,this._svgGroup.y=a.y,this._svgGroup.scaleX=a.scaleX,this._svgGroup.scaleY=a.scaleY,this._svgResourceChanged(t)&&(this._freeSVG(),this._useSVG(t));var n=this._svgDispatcherMap=$(),i=!1;D(this._svgGraphicRecord.named,function(o){var s=o.name,l=e.mapOrGeoModel,u=e.data,f=o.svgNodeTagLower,h=o.el,v=u?u.indexOfName(s):null,c=l.getRegionModel(s);m5.get(f)!=null&&h instanceof or&&tS(e,h,v,c),h instanceof or&&(h.culling=!0);var p=c.get("silent",!0);if(p!=null&&(h.silent=p),h.z2EmphasisLift=0,!o.namedFrom&&(S5.get(f)!=null&&eS(e,h,s,c,l,v,null),rS(e,h,s,c,l,v),aS(e,h,s,c,l),_5.get(f)!=null)){var d=nS(e,h,s,c,l);d==="self"&&(i=!0);var g=n.get(s)||n.set(s,[]);g.push(h)}},this),this._enableBlurEntireSVG(i,e)},r.prototype._enableBlurEntireSVG=function(e,t){if(e&&t.isGeo){var a=t.mapOrGeoModel.getModel(["blur","itemStyle"]).getItemStyle(),n=a.opacity;this._svgGraphicRecord.root.traverse(function(i){if(!i.isGroup){ni(i);var o=i.ensureState("blur").style||{};o.opacity==null&&n!=null&&(o.opacity=n),i.ensureState("emphasis")}})}},r.prototype.remove=function(){this._regionsGroup.removeAll(),this._regionsGroupByName=null,this._svgGroup.removeAll(),this._freeSVG(),this._controller.dispose(),this._controllerHost=null},r.prototype.findHighDownDispatchers=function(e,t){if(e==null)return[];var a=t.coordinateSystem;if(a.resourceType==="geoJSON"){var n=this._regionsGroupByName;if(n){var i=n.get(e);return i?[i]:[]}}else if(a.resourceType==="geoSVG")return this._svgDispatcherMap&&t
Line truncated
|
||||
`))}),e.join(`
|
||||
|
||||
`+kh+`
|
||||
|
||||
`)}function R6(r){return G(r,function(e){var t=e.getRawData(),a=[e.name],n=[];return t.each(t.dimensions,function(){for(var i=arguments.length,o=arguments[i-1],s=t.getName(o),l=0;l<i-1;l++)n[l]=arguments[l];a.push((s?s+ho:"")+n.join(ho))}),a.join(`
|
||||
`)}).join(`
|
||||
|
||||
`+kh+`
|
||||
|
||||
`)}function E6(r){var e=L6(r);return{value:Ct([P6(e.seriesGroupByCategoryAxis),R6(e.other)],function(t){return!!t.replace(/[\n\t\s]/g,"")}).join(`
|
||||
|
||||
`+kh+`
|
||||
|
||||
`),meta:e.meta}}function Gf(r){return r.replace(/^\s\s*/,"").replace(/\s\s*$/,"")}function k6(r){var e=r.slice(0,r.indexOf(`
|
||||
`));if(e.indexOf(ho)>=0)return!0}var Nd=new RegExp("["+ho+"]+","g");function O6(r){for(var e=r.split(/\n+/g),t=Gf(e.shift()).split(Nd),a=[],n=G(t,function(l){return{name:l,data:[]}}),i=0;i<e.length;i++){var o=Gf(e[i]).split(Nd);a.push(o.shift());for(var s=0;s<o.length;s++)n[s]&&(n[s].data[i]=o[s])}return{series:n,categories:a}}function N6(r){for(var e=r.split(/\n+/g),t=Gf(e.shift()),a=[],n=0;n<e.length;n++){var i=Gf(e[n]);if(i){var o=i.split(Nd),s="",l=void 0,u=!1;isNaN(o[0])?(u=!0,s=o[0],o=o.slice(1),a[n]={name:s,value:[]},l=a[n].value):l=a[n]=[];for(var f=0;f<o.length;f++)l.push(+o[f]);l.length===1&&(u?a[n].value=l[0]:a[n]=l[0])}}return{name:t,data:a}}function B6(r,e){var t=r.split(new RegExp(`
|
||||
*`+kh+`
|
||||
*`,"g")),a={series:[]};return D(t,function(n,i){if(k6(n)){var o=O6(n),s=e[i],l=s.axisDim+"Axis";s&&(a[l]=a[l]||[],a[l][s.axisIndex]={data:o.categories},a.series=a.series.concat(o.series))}else{var o=N6(n);a.series.push(o)}}),a}var V6=function(r){k(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.onclick=function(t,a){setTimeout(function(){a.dispatchAction({type:"hideTip"})});var n=a.getDom(),i=this.model;this._dom&&n.removeChild(this._dom);var o=document.createElement("div");o.style.cssText="position:absolute;top:0;bottom:0;left:0;right:0;padding:5px",o.style.backgroundColor=i.get("backgroundColor")||"#fff";var s=document.createElement("h4"),l=i.get("lang")||[];s.innerHTML=l[0]||i.get("title"),s.style.cssText="margin:10px 20px",s.style.color=i.get("textColor");var u=document.createElement("div"),f=document.createElement("textarea");u.style.cssText="overflow:auto";var h=i.get("optionToContent"),v=i.get("contentToOption"),c=E6(t);if(J(h)){var p=h(a.getOption());Y(p)?u.innerHTML=p:eo(p)&&u.appendChild(p)}else{f.readOnly=i.get("readOnly");var d=f.style;d.cssText="display:block;width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;resize:none;box-sizing:border-box;outline:none",d.color=i.get("textColor"),d.borderColor=i.get("textareaBorderColor"),d.backgroundColor=i.get("textareaColor"),f.value=c.value,u.appendChild(f)}var g=c.meta,y=document.createElement("div");y.style.cssText="position:absolute;bottom:5px;left:0;right:0";var m="float:right;margin-right:20px;border:none;cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px",_=document.createElement("div"),S=document.createElement("div");m+=";background-color:"+i.get("buttonColor"),m+=";color:"+i.get("buttonTextColor");var b=this;function x(){n.removeChild(o),b._dom=null}pp(_,"click",x),pp(S,"click",function(){if(v==null&&h!=null||v!=null&&h==null){x();return}var w;try{J(v)?w=v(u,a.getOption()):w=B6(f.value,g)}catch(T){throw x(),new Error("Data view format error "+T)}w&&a.dispatchAction({type:"changeDataView",newOption:w}),x()}),_.innerHTML=l[1],S.innerHTML=l[2],S.style.cssText=_.style.cssText=m,!i.get("readOnly")&&y.appendChild(S),y.appendChild(_),o.appendChild(s),o.appendChild(u),o.appendChild(y),u.style.height=n.clientHeight-80+"px",n.appendChild(o),this._dom=o},e.prototype.remove=function(t,a){this._dom&&a.getDom().removeChild(this._dom)},e.prototype.dispose=function(t,a){this.remove(t,a)},e.getDefaultOption=function(t){var a={show:!0,readOnly:!1,optionToContent:null,contentToOption:null,icon:"M17.5,17.3H33 M17.5,17.3H33 M45.4,29.5h-28 M11.5,2v56H51V14.8L38.4,2H11.5z M38.4,2.2v12.7H51 M45.4,41.7h-28",title:t.getLocaleModel().get(["toolbox","dataView","title"]),lang:t.getLocaleModel().get(["toolbox","dataView","lang"]),backgroundColor:"#fff",textColor:"#000",textareaColor:"#fff",textareaBorderColor:"#333",buttonColor:"#c23531",buttonTextColor:"#fff"};return a},e}(er);function z6(r,e){return G(r,function(t,a){var n=e&&e[a];if(et(n)&&!z(n)){var i=et(t)&&!z(t);i||(t={value:t});var o=n.name!=null&&t.name==null;return t=j(t,n),o&&delete t.name,t}else return t})}Xr({type:"changeDataView",event:"dataViewChanged",update:"prepareAndUpdate"},function(r,e){var t=[];D(r.newOption.series,function(a){var n=e.getSeriesByName(a.name)[0];if(!n)t.push(V({type:"scatter"},a));else{var i=n.get("data");t.push({name:a.name,data:z6(a.data,i)})}}),e.mergeOption(j({series:t},r.newOption))});var mI=D,_I=xt();function G6(r,e){var t=Zy(r);mI(e,function(a,n){for(var i=t.length-1;i>=0;i--){var o=t[i];if(o[n])break}if(i<0){var s=r.queryComponents({mainType:"dataZoom",subType:"select",id:n})[0];if(s){var l=s.getPercentRange();t[0][n]={dataZoomId:n,start:l[0],end:l[1]}}}}),t.push(e)}function F6(r){var e=Zy(r),t=e[e.length-1];e.length>1&&e.pop();var a={};return mI(t,function(n,i){for(var o=e.length-1;o>=0;o--)if(n=e[o][i],n){a[i]=n;break}}),a}function H6(r){_I(r).snapshots=null}function W6(r){return Zy(r).length}function Zy(r){var e=_I(r);return e.snapshots||(e.snapshots=[{}]),e.snapshots}var U6=function(r){k(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.onclick=function(t,a){H6(t),a.dispatchAction({type:"restore",from:this.uid})},e.getDefaultOption=function(t){var a={show:!0,icon:"M3.8,33.4 M47,18.9h9.8V8.7 M56.3,20.1 C52.1,9,40.5,0.6,26.8,2.1C12.6,3.7,1.6,16.2,2.1,30.6 M13,41.1H3.1v10.2 M3.7,39.9c4.2,11.1,15.8,19.5,29.5,18 c14.2-1.6,25.2-14.1,24.7-28.5",title:t.getLocaleModel().get(["toolbox","restore","title"])};return a},e}(er);Xr({type:"restore",event:"restore",update:"prepareAndUpdate"},function(r,e){e.resetOption("recreate")});var Y6=["grid","xAxis","yAxis","geo","graph","polar","radiusAxis","angleAxis","bmap"],$y=function(){function r(e,t,a){var n=this;this._targetInfoList=[];var i=Qx(t,e);D(X6,function(o,s){(!a||!a.include||ct(a.include,s)>=0)&&o(i,n._targetInfoList)})}return r.prototype.setOutputRanges=function(e,t){return this.matchOutputRanges(e,t,function(a,n,i){if((a.coor
Line truncated
|
||||
|
||||
`:"<br/>",y=h.join(g);this._showOrMove(s,function(){this._updateContentNotChangedOnAxis(t,u)?this._updatePosition(s,c,o[0],o[1],this._tooltipContent,u):this._showTooltipContent(s,y,u,Math.random()+"",o[0],o[1],c,null,v)})},e.prototype._showSeriesItemTooltip=function(t,a,n){var i=this._ecModel,o=nt(a),s=o.seriesIndex,l=i.getSeriesByIndex(s),u=o.dataModel||l,f=o.dataIndex,h=o.dataType,v=u.getData(h),c=this._renderMode,p=t.positionDefault,d=ts([v.getItemModel(f),u,l&&(l.coordinateSystem||{}).model],this._tooltipModel,p?{position:p}:null),g=d.get("trigger");if(!(g!=null&&g!=="item")){var y=u.getDataParams(f,h),m=new Lv;y.marker=m.makeTooltipMarker("item",ii(y.color),c);var _=$0(u.formatTooltip(f,!1,h)),S=d.get("order"),b=d.get("valueFormatter"),x=_.frag,w=x?t_(b?V({valueFormatter:b},x):x,m,c,S,i.get("useUTC"),d.get("textStyle")):_.text,T="item_"+u.name+"_"+f;this._showOrMove(d,function(){this._showTooltipContent(d,w,y,T,t.offsetX,t.offsetY,t.position,t.target,m)}),n({type:"showTip",dataIndexInside:f,dataIndex:v.getRawIndex(f),seriesIndex:s,from:this.uid})}},e.prototype._showComponentItemTooltip=function(t,a,n){var i=this._renderMode==="html",o=nt(a),s=o.tooltipConfig,l=s.option||{},u=l.encodeHTMLContent;if(Y(l)){var f=l;l={content:f,formatter:f},u=!0}u&&i&&l.content&&(l=rt(l),l.content=we(l.content));var h=[l],v=this._ecModel.getComponent(o.componentMainType,o.componentIndex);v&&h.push(v),h.push({formatter:l.content});var c=t.positionDefault,p=ts(h,this._tooltipModel,c?{position:c}:null),d=p.get("content"),g=Math.random()+"",y=new Lv;this._showOrMove(p,function(){var m=rt(p.get("formatterParams")||{});this._showTooltipContent(p,d,m,g,t.offsetX,t.offsetY,t.position,a,y)}),n({type:"showTip",from:this.uid})},e.prototype._showTooltipContent=function(t,a,n,i,o,s,l,u,f){if(this._ticket="",!(!t.get("showContent")||!t.get("show"))){var h=this._tooltipContent;h.setEnterable(t.get("enterable"));var v=t.get("formatter");l=l||t.get("position");var c=a,p=this._getNearestPoint([o,s],n,t.get("trigger"),t.get("borderColor")),d=p.color;if(v)if(Y(v)){var g=t.ecModel.get("useUTC"),y=z(n)?n[0]:n,m=y&&y.axisType&&y.axisType.indexOf("time")>=0;c=v,m&&(c=vh(y.axisValue,c,g)),c=rA(c,n,!0)}else if(J(v)){var _=X(function(S,b){S===this._ticket&&(h.setContent(b,f,t,d,l),this._updatePosition(t,l,o,s,h,n,u))},this);this._ticket=i,c=v(n,i,_)}else c=v;h.setContent(c,f,t,d,l),h.show(t,d),this._updatePosition(t,l,o,s,h,n,u)}},e.prototype._getNearestPoint=function(t,a,n,i){if(n==="axis"||z(a))return{color:i||(this._renderMode==="html"?"#fff":"none")};if(!z(a))return{color:i||a.color||a.borderColor}},e.prototype._updatePosition=function(t,a,n,i,o,s,l){var u=this._api.getWidth(),f=this._api.getHeight();a=a||t.get("position");var h=o.getSize(),v=t.get("align"),c=t.get("verticalAlign"),p=l&&l.getBoundingRect().clone();if(l&&p.applyTransform(l.transform),J(a)&&(a=a([n,i],s,o.el,p,{viewSize:[u,f],contentSize:h.slice()})),z(a))n=W(a[0],u),i=W(a[1],f);else if(et(a)){var d=a;d.width=h[0],d.height=h[1];var g=Qt(d,{width:u,height:f});n=g.x,i=g.y,v=null,c=null}else if(Y(a)&&l){var y=gU(a,p,h,t.get("borderWidth"));n=y[0],i=y[1]}else{var y=pU(n,i,o,u,f,v?null:20,c?null:20);n=y[0],i=y[1]}if(v&&(n-=fb(v)?h[0]/2:v==="right"?h[0]:0),c&&(i-=fb(c)?h[1]/2:c==="bottom"?h[1]:0),SI(t)){var y=dU(n,i,o,u,f);n=y[0],i=y[1]}o.moveTo(n,i)},e.prototype._updateContentNotChangedOnAxis=function(t,a){var n=this._lastDataByCoordSys,i=this._cbParamsList,o=!!n&&n.length===t.length;return o&&D(n,function(s,l){var u=s.dataByAxis||[],f=t[l]||{},h=f.dataByAxis||[];o=o&&u.length===h.length,o&&D(u,function(v,c){var p=h[c]||{},d=v.seriesDataIndices||[],g=p.seriesDataIndices||[];o=o&&v.value===p.value&&v.axisType===p.axisType&&v.axisId===p.axisId&&d.length===g.length,o&&D(d,function(y,m){var _=g[m];o=o&&y.seriesIndex===_.seriesIndex&&y.dataIndex===_.dataIndex}),i&&D(v.seriesDataIndices,function(y){var m=y.seriesIndex,_=a[m],S=i[m];_&&S&&S.data!==_.data&&(o=!1)})})}),this._lastDataByCoordSys=t,this._cbParamsList=a,!!o},e.prototype._hide=function(t){this._lastDataByCoordSys=null,t({type:"hideTip",from:this.uid})},e.prototype.dispose=function(t,a){yt.node||!a.getDom()||(Xs(this,"_updatePosition"),this._tooltipContent.dispose(),Ed("itemTooltip",a))},e.type="tooltip",e}(Ft);function ts(r,e,t){var a=e.ecModel,n;t?(n=new Mt(t,a,a),n=new Mt(e.option,n,a)):n=e;for(var i=r.length-1;i>=0;i--){var o=r[i];o&&(o instanceof Mt&&(o=o.get("tooltip",!0)),Y(o)&&(o={formatter:o}),o&&(n=new Mt(o,n,a)))}return n}function ub(r,e){return r.dispatchAction||X(e.dispatchAction,e)}function pU(r,e,t,a,n,i,o){var s=t.getSize(),l=s[0],u=s[1];return i!=null&&(r+l+i+2>a?r-=l+i:r+=i),o!=null&&(e+u+o>n?e-=u+o:e+=o),[r,e]}function dU(r,e,t,a,n){var i=t.getSize(),o=i[0],s=i[1];return r=Math.min(r+o,a)-o,e=Math.min(e+s,n)-s,r=Math.max(r,0),e=Math.max(e,0),[r,e]}function gU(r,e,t,a){var n=t[0],i=t[1],o=Math.ceil(Math.SQRT2*a)+8,s=0,l=0,u=e.width,f=e.height;switch(r){case"inside":s=e.x+u/2-n/2,l=e.y+f/2-i/2;break;case"top":s=e.x
Line truncated
|
||||
`)){var g=new Pu;g.newline=!0,u.add(g);return}var y=n.getSeriesByName(d)[0];if(!f.get(d))if(y){var m=y.getData(),_=m.getVisual("legendLineStyle")||{},S=m.getVisual("legendIcon"),b=m.getVisual("style"),x=this._createItem(y,d,p,c,a,t,_,b,S,h,i);x.on("click",Ni(Ib,d,null,i,v)).on("mouseover",Ni(Ud,y.name,null,i,v)).on("mouseout",Ni(Yd,y.name,null,i,v)),n.ssr&&x.eachChild(function(w){var T=nt(w);T.seriesIndex=y.seriesIndex,T.dataIndex=p,T.ssrType="legend"}),f.set(d,!0)}else n.eachRawSeries(function(w){if(!f.get(d)&&w.legendVisualProvider){var T=w.legendVisualProvider;if(!T.containName(d))return;var A=T.indexOfName(d),C=T.getItemVisual(A,"style"),M=T.getItemVisual(A,"legendIcon"),I=We(C.fill);I&&I[3]===0&&(I[3]=.2,C=V(V({},C),{fill:na(I,"rgba")}));var L=this._createItem(w,d,p,c,a,t,{},C,M,h,i);L.on("click",Ni(Ib,null,d,i,v)).on("mouseover",Ni(Ud,null,d,i,v)).on("mouseout",Ni(Yd,null,d,i,v)),n.ssr&&L.eachChild(function(P){var R=nt(P);R.seriesIndex=w.seriesIndex,R.dataIndex=p,R.ssrType="legend"}),f.set(d,!0)}},this)},this),o&&this._createSelector(o,a,i,s,l)},e.prototype._createSelector=function(t,a,n,i,o){var s=this.getSelectorGroup();Wd(t,function(u){var f=u.type,h=new bt({style:{x:0,y:0,align:"center",verticalAlign:"middle"},onclick:function(){n.dispatchAction({type:f==="all"?"legendAllSelect":"legendInverseSelect",legendId:a.id})}});s.add(h);var v=a.getModel("selectorLabel"),c=a.getModel(["emphasis","selectorLabel"]);ve(h,{normal:v,emphasis:c},{defaultText:u.title}),Kn(h)})},e.prototype._createItem=function(t,a,n,i,o,s,l,u,f,h,v){var c=t.visualDrawType,p=o.get("itemWidth"),d=o.get("itemHeight"),g=o.isSelected(a),y=i.get("symbolRotate"),m=i.get("symbolKeepAspect"),_=i.get("icon");f=_||f||"roundRect";var S=d8(f,i,l,u,c,g,v),b=new Pu,x=i.getModel("textStyle");if(J(t.getLegendIcon)&&(!_||_==="inherit"))b.add(t.getLegendIcon({itemWidth:p,itemHeight:d,icon:f,iconRotate:y,itemStyle:S.itemStyle,lineStyle:S.lineStyle,symbolKeepAspect:m}));else{var w=_==="inherit"&&t.getData().getVisual("symbol")?y==="inherit"?t.getData().getVisual("symbolRotate"):y:0;b.add(g8({itemWidth:p,itemHeight:d,icon:f,iconRotate:w,itemStyle:S.itemStyle,symbolKeepAspect:m}))}var T=s==="left"?p+5:-5,A=s,C=o.get("formatter"),M=a;Y(C)&&C?M=C.replace("{name}",a??""):J(C)&&(M=C(a));var I=g?x.getTextColor():i.get("inactiveColor");b.add(new bt({style:Bt(x,{text:M,x:T,y:d/2,fill:I,align:A,verticalAlign:"middle"},{inheritColor:I})}));var L=new St({shape:b.getBoundingRect(),style:{fill:"transparent"}}),P=i.getModel("tooltip");return P.get("show")&&fi({el:L,componentModel:o,itemName:a,itemTooltipOption:P.option}),b.add(L),b.eachChild(function(R){R.silent=!0}),L.silent=!h,this.getContentGroup().add(b),Kn(b),b.__legendDataIndex=n,b},e.prototype.layoutInner=function(t,a,n,i,o,s){var l=this.getContentGroup(),u=this.getSelectorGroup();Qn(t.get("orient"),l,t.get("itemGap"),n.width,n.height);var f=l.getBoundingRect(),h=[-f.x,-f.y];if(u.markRedraw(),l.markRedraw(),o){Qn("horizontal",u,t.get("selectorItemGap",!0));var v=u.getBoundingRect(),c=[-v.x,-v.y],p=t.get("selectorButtonGap",!0),d=t.getOrient().index,g=d===0?"width":"height",y=d===0?"height":"width",m=d===0?"y":"x";s==="end"?c[d]+=f[g]+p:h[d]+=v[g]+p,c[1-d]+=f[y]/2-v[y]/2,u.x=c[0],u.y=c[1],l.x=h[0],l.y=h[1];var _={x:0,y:0};return _[g]=f[g]+p+v[g],_[y]=Math.max(f[y],v[y]),_[m]=Math.min(0,v[m]+c[1-d]),_}else return l.x=h[0],l.y=h[1],this.group.getBoundingRect()},e.prototype.remove=function(){this.getContentGroup().removeAll(),this._isFirstRender=!0},e.type="legend.plain",e}(Ft);function d8(r,e,t,a,n,i,o){function s(g,y){g.lineWidth==="auto"&&(g.lineWidth=y.lineWidth>0?2:0),Wd(g,function(m,_){g[_]==="inherit"&&(g[_]=y[_])})}var l=e.getModel("itemStyle"),u=l.getItemStyle(),f=r.lastIndexOf("empty",0)===0?"fill":"stroke",h=l.getShallow("decal");u.decal=!h||h==="inherit"?a.decal:io(h,o),u.fill==="inherit"&&(u.fill=a[n]),u.stroke==="inherit"&&(u.stroke=a[f]),u.opacity==="inherit"&&(u.opacity=(n==="fill"?a:t).opacity),s(u,a);var v=e.getModel("lineStyle"),c=v.getLineStyle();if(s(c,t),u.fill==="auto"&&(u.fill=a.fill),u.stroke==="auto"&&(u.stroke=a.fill),c.stroke==="auto"&&(c.stroke=a.fill),!i){var p=e.get("inactiveBorderWidth"),d=u[f];u.lineWidth=p==="auto"?a.lineWidth>0&&d?2:0:u.lineWidth,u.fill=e.get("inactiveColor"),u.stroke=e.get("inactiveBorderColor"),c.stroke=v.get("inactiveColor"),c.lineWidth=v.get("inactiveWidth")}return{itemStyle:u,lineStyle:c}}function g8(r){var e=r.icon||"roundRect",t=qt(e,0,0,r.itemWidth,r.itemHeight,r.itemStyle.fill,r.symbolKeepAspect);return t.setStyle(r.itemStyle),t.rotation=(r.iconRotate||0)*Math.PI/180,t.setOrigin([r.itemWidth/2,r.itemHeight/2]),e.indexOf("empty")>-1&&(t.style.stroke=t.style.fill,t.style.fill="#fff",t.style.lineWidth=2),t}function Ib(r,e,t,a){Yd(r,e,t,a),t.dispatchAction({type:"legendToggleSelect",name:r??e}),Ud(r,e,t,a)}function LI(r){for(var e=r.getZr().storage.getDisplayList(),t,a=0,n=e.length;a<n&&!(t=e[a].states.emphasis);)a++;return t&&t.hoverLayer}function Ud(r,e,
Line truncated
|
||||
`||n==="")){var i=r.isSelected(n);Z(t,n)?t[n]=t[n]&&i:t[n]=i}}),t}function m8(r){r.registerAction("legendToggleSelect","legendselectchanged",lt(rs,"toggleSelected")),r.registerAction("legendAllSelect","legendselectall",lt(rs,"allSelect")),r.registerAction("legendInverseSelect","legendinverseselect",lt(rs,"inverseSelect")),r.registerAction("legendSelect","legendselected",lt(rs,"select")),r.registerAction("legendUnSelect","legendunselected",lt(rs,"unSelect"))}function PI(r){r.registerComponentModel(Hd),r.registerComponentView(II),r.registerProcessor(r.PRIORITY.PROCESSOR.SERIES_FILTER,y8),r.registerSubTypeDefaulter("legend",function(){return"plain"}),m8(r)}var _8=function(r){k(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.setScrollDataIndex=function(t){this.option.scrollDataIndex=t},e.prototype.init=function(t,a,n){var i=bo(t);r.prototype.init.call(this,t,a,n),Pb(this,t,i)},e.prototype.mergeOption=function(t,a){r.prototype.mergeOption.call(this,t,a),Pb(this,this.option,t)},e.type="legend.scroll",e.defaultOption=tn(Hd.defaultOption,{scrollDataIndex:0,pageButtonItemGap:5,pageButtonGap:null,pageButtonPosition:"end",pageFormatter:"{current}/{total}",pageIcons:{horizontal:["M0,0L12,-10L12,10z","M0,0L-12,-10L-12,10z"],vertical:["M0,0L20,0L10,-20z","M0,0L20,0L10,20z"]},pageIconColor:"#2f4554",pageIconInactiveColor:"#aaa",pageIconSize:15,pageTextStyle:{color:"#333"},animationDurationUpdate:800}),e}(Hd);function Pb(r,e,t){var a=r.getOrient(),n=[1,1];n[a.index]=0,qa(e,t,{type:"box",ignoreSize:!!n})}var Rb=at,Jc=["width","height"],Qc=["x","y"],S8=function(r){k(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.newlineDisabled=!0,t._currentIndex=0,t}return e.prototype.init=function(){r.prototype.init.call(this),this.group.add(this._containerGroup=new Rb),this._containerGroup.add(this.getContentGroup()),this.group.add(this._controllerGroup=new Rb)},e.prototype.resetInner=function(){r.prototype.resetInner.call(this),this._controllerGroup.removeAll(),this._containerGroup.removeClipPath(),this._containerGroup.__rectSize=null},e.prototype.renderInner=function(t,a,n,i,o,s,l){var u=this;r.prototype.renderInner.call(this,t,a,n,i,o,s,l);var f=this._controllerGroup,h=a.get("pageIconSize",!0),v=z(h)?h:[h,h];p("pagePrev",0);var c=a.getModel("pageTextStyle");f.add(new bt({name:"pageText",style:{text:"xx/xx",fill:c.getTextColor(),font:c.getFont(),verticalAlign:"middle",align:"center"},silent:!0})),p("pageNext",1);function p(d,g){var y=d+"DataIndex",m=gl(a.get("pageIcons",!0)[a.getOrient().name][g],{onclick:X(u._pageGo,u,y,a,i)},{x:-v[0]/2,y:-v[1]/2,width:v[0],height:v[1]});m.name=d,f.add(m)}},e.prototype.layoutInner=function(t,a,n,i,o,s){var l=this.getSelectorGroup(),u=t.getOrient().index,f=Jc[u],h=Qc[u],v=Jc[1-u],c=Qc[1-u];o&&Qn("horizontal",l,t.get("selectorItemGap",!0));var p=t.get("selectorButtonGap",!0),d=l.getBoundingRect(),g=[-d.x,-d.y],y=rt(n);o&&(y[f]=n[f]-d[f]-p);var m=this._layoutContentAndController(t,i,y,u,f,v,c,h);if(o){if(s==="end")g[u]+=m[f]+p;else{var _=d[f]+p;g[u]-=_,m[h]-=_}m[f]+=d[f]+p,g[1-u]+=m[c]+m[v]/2-d[v]/2,m[v]=Math.max(m[v],d[v]),m[c]=Math.min(m[c],d[c]+g[1-u]),l.x=g[0],l.y=g[1],l.markRedraw()}return m},e.prototype._layoutContentAndController=function(t,a,n,i,o,s,l,u){var f=this.getContentGroup(),h=this._containerGroup,v=this._controllerGroup;Qn(t.get("orient"),f,t.get("itemGap"),i?n.width:null,i?null:n.height),Qn("horizontal",v,t.get("pageButtonItemGap",!0));var c=f.getBoundingRect(),p=v.getBoundingRect(),d=this._showController=c[o]>n[o],g=[-c.x,-c.y];a||(g[i]=f[u]);var y=[0,0],m=[-p.x,-p.y],_=st(t.get("pageButtonGap",!0),t.get("itemGap",!0));if(d){var S=t.get("pageButtonPosition",!0);S==="end"?m[i]+=n[o]-p[o]:y[i]+=p[o]+_}m[1-i]+=c[s]/2-p[s]/2,f.setPosition(g),h.setPosition(y),v.setPosition(m);var b={x:0,y:0};if(b[o]=d?n[o]:c[o],b[s]=Math.max(c[s],p[s]),b[l]=Math.min(0,p[l]+m[1-i]),h.__rectSize=n[o],d){var x={x:0,y:0};x[o]=Math.max(n[o]-p[o]-_,0),x[s]=b[s],h.setClipPath(new St({shape:x})),h.__rectSize=x[o]}else v.eachChild(function(T){T.attr({invisible:!0,silent:!0})});var w=this._getPageInfo(t);return w.pageIndex!=null&&Tt(f,{x:w.contentPosition[0],y:w.contentPosition[1]},d?t:null),this._updatePageInfoView(t,w),b},e.prototype._pageGo=function(t,a,n){var i=this._getPageInfo(a)[t];i!=null&&n.dispatchAction({type:"legendScroll",scrollDataIndex:i,legendId:a.id})},e.prototype._updatePageInfoView=function(t,a){var n=this._controllerGroup;D(["pagePrev","pageNext"],function(f){var h=f+"DataIndex",v=a[h]!=null,c=n.childOfName(f);c&&(c.setStyle("fill",v?t.get("pageIconColor",!0):t.get("pageIconInactiveColor",!0)),c.cursor=v?"pointer":"default")});var i=n.childOfName("pageText"),o=t.get("pageFormatter"),s=a.pageIndex,l=s!=null?s+1:0,u=a.pageCount;i&&o&&i.setStyle("text",Y(o)?o.replace("{current}",l==null?"":l+"").replace("{total}",u==null?"":u+""):o({current:l,total:u}))},e.prototype._getPageInfo=function(t){var a=t.get("
Line truncated
|
||||
@@ -0,0 +1,60 @@
|
||||
import{_ as $I,m as qI,o as Io,c as nm,b as rn,w as $r,P as Nh,K as KI,l as im,a3 as JI,r as QI,F as jI,R as tL,a4 as eL,a5 as rL,A as om,a as yi,E as aL,a1 as nL,C as sm,i as iL,D as lm}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css */import{u as oL}from"./user-KptFbP1d.js";import{r as sL}from"./index-CZCGMR8A.js";/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
***************************************************************************** */var op=function(r,e){return op=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,a){t.__proto__=a}||function(t,a){for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(t[n]=a[n])},op(r,e)};function k(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");op(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var lL=function(){function r(){this.firefox=!1,this.ie=!1,this.edge=!1,this.newEdge=!1,this.weChat=!1}return r}(),uL=function(){function r(){this.browser=new lL,this.node=!1,this.wxa=!1,this.worker=!1,this.svgSupported=!1,this.touchEventsSupported=!1,this.pointerEventsSupported=!1,this.domSupported=!1,this.transformSupported=!1,this.transform3dSupported=!1,this.hasGlobalWindow=typeof window<"u"}return r}(),yt=new uL;typeof wx=="object"&&typeof wx.getSystemInfoSync=="function"?(yt.wxa=!0,yt.touchEventsSupported=!0):typeof document>"u"&&typeof self<"u"?yt.worker=!0:!yt.hasGlobalWindow||"Deno"in window?(yt.node=!0,yt.svgSupported=!0):fL(navigator.userAgent,yt);function fL(r,e){var t=e.browser,a=r.match(/Firefox\/([\d.]+)/),n=r.match(/MSIE\s([\d.]+)/)||r.match(/Trident\/.+?rv:(([\d.]+))/),i=r.match(/Edge?\/([\d.]+)/),o=/micromessenger/i.test(r);a&&(t.firefox=!0,t.version=a[1]),n&&(t.ie=!0,t.version=n[1]),i&&(t.edge=!0,t.version=i[1],t.newEdge=+i[1].split(".")[0]>18),o&&(t.weChat=!0),e.svgSupported=typeof SVGRect<"u",e.touchEventsSupported="ontouchstart"in window&&!t.ie&&!t.edge,e.pointerEventsSupported="onpointerdown"in window&&(t.edge||t.ie&&+t.version>=11),e.domSupported=typeof document<"u";var s=document.documentElement.style;e.transform3dSupported=(t.ie&&"transition"in s||t.edge||"WebKitCSSMatrix"in window&&"m11"in new WebKitCSSMatrix||"MozPerspective"in s)&&!("OTransition"in s),e.transformSupported=e.transform3dSupported||t.ie&&+t.version>=9}var qd=12,cw="sans-serif",Ya=qd+"px "+cw,hL=20,vL=100,cL="007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";function pL(r){var e={};if(typeof JSON>"u")return e;for(var t=0;t<r.length;t++){var a=String.fromCharCode(t+32),n=(r.charCodeAt(t)-hL)/vL;e[a]=n}return e}var dL=pL(cL),Xa={createCanvas:function(){return typeof document<"u"&&document.createElement("canvas")},measureText:function(){var r,e;return function(t,a){if(!r){var n=Xa.createCanvas();r=n&&n.getContext("2d")}if(r)return e!==a&&(e=r.font=a||Ya),r.measureText(t);t=t||"",a=a||Ya;var i=/((?:\d+)?\.?\d*)px/.exec(a),o=i&&+i[1]||qd,s=0;if(a.indexOf("mono")>=0)s=o*t.length;else for(var l=0;l<t.length;l++){var u=dL[t[l]];s+=u==null?o:u*o}return{width:s}}}(),loadImage:function(r,e,t){var a=new Image;return a.onload=e,a.onerror=t,a.src=r,a}},pw=Gr(["Function","RegExp","Date","Error","CanvasGradient","CanvasPattern","Image","Canvas"],function(r,e){return r["[object "+e+"]"]=!0,r},{}),dw=Gr(["Int8","Uint8","Uint8Clamped","Int16","Uint16","Int32","Uint32","Float32","Float64"],function(r,e){return r["[object "+e+"Array]"]=!0,r},{}),vo=Object.prototype.toString,$f=Array.prototype,gL=$f.forEach,yL=$f.filter,Kd=$f.slice,mL=$f.map,um=(function(){}).constructor,Ll=um?um.prototype:null,Jd="__proto__",_L=2311;function gw(){return _L++}function Qd(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];typeof console<"u"&&console.error.apply(console,r)}function rt(r){if(r==null||typeof r!="object")return r;var e=r,t=vo.call(r);if(t==="[object Array]"){if(!ys(r)){e=[];for(var a=0,n=r.length;a<n;a++)e[a]=rt(r[a])}}else if(dw[t]){if(!ys(r)){var i=r.constructor;if(i.from)e=i.from(r);else{e=new i(r.length);for(var a=0,n=r.length;a<n;a++)e[a]=r[a]}}}else if(!pw[t]&&!ys(r)&&!eo(r)){e={};for(var o in r)r.hasOwnProperty(o)&&o!==Jd&&(e[o]=rt(r[o]))}return e}function ut(r,e,t){if(!et(e)||!et(r))return t?rt(e):r;for(var a in e)if(e.hasOwnProperty(a)&&a!==Jd){var n=r[a],i=e[a];et(i)&&et(n)&&!z(i)&&!z(n)&&!eo(i)&&!eo(n)&&!fm(i)&&!fm(n)&&!ys(i)&&!ys(n)?ut(n,i,t):(t||!(a in r))&&(r[a]=rt(e[a]))}return r}function jd(r,e){for(var t=r[0],a=1,n=r.length;a<n;a++)t=ut(t,r[a],e);return t}function V(r,e){if(Object.assign)Object.assign(r,e);else for(var t in e)e.hasOwnProperty(t)&&t!==Jd&&(r[t]=e[t]);return r}function j(r,e,t){for(var a=_t(e),n=0,i=a.length;n<i;n++){var o=a[n];(t?e[o]!=null:r[o]==null)&&(r[o]=e[o])}return r}function ct(r,e){if(r){if(r.indexOf)return r.indexOf(e);for(var t=0,a=r.length;t<a;t++)if(r[t]===e)return t}return-1}function SL(r,e){var t=r.prototype;function a(){}a.prototype=e.prototype,r.prototype=new a;for(var n in t)t.hasOwnProperty(n)&&(r.prototype[n]=t[n]);r.prototype.constructor=r,r.superClass=e}function Kt(r,e,t){if(r="prototype"in r?r.prototype:r,e="prototype"in e?e.prototype:e,Object.getOwnPropertyNames)for(var a=Object.getOwnPropertyNames(e),n=0;n<a.length;n++){var i=a[n];i!=="constructor"&&(t?e[i]!=null:r[i]==null)&&(r[i]=e[i])}else j(r,eLine truncated
|
||||
`),i=n.length;if(i===1)return Nm(n[0],e,t,a);for(var o=new ht(0,0,0,0),s=0;s<n.length;s++){var l=Nm(n[s],e,t,a);s===0?o.copy(l):o.union(l)}return o}function ss(r,e,t){return t==="right"?r-=e:t==="center"&&(r-=e/2),r}function Fi(r,e,t){return t==="middle"?r-=e/2:t==="bottom"&&(r-=e),r}function jf(r){return Ue("国",r)}function Sr(r,e){return typeof r=="string"?r.lastIndexOf("%")>=0?parseFloat(r)/100*e:parseFloat(r):r}function lf(r,e,t){var a=e.position||"inside",n=e.distance!=null?e.distance:5,i=t.height,o=t.width,s=i/2,l=t.x,u=t.y,f="left",h="top";if(a instanceof Array)l+=Sr(a[0],t.width),u+=Sr(a[1],t.height),f=null,h=null;else switch(a){case"left":l-=n,u+=s,f="right",h="middle";break;case"right":l+=n+o,u+=s,h="middle";break;case"top":l+=o/2,u-=n,f="center",h="bottom";break;case"bottom":l+=o/2,u+=i+n,f="center";break;case"inside":l+=o/2,u+=s,f="center",h="middle";break;case"insideLeft":l+=n,u+=s,h="middle";break;case"insideRight":l+=o-n,u+=s,f="right",h="middle";break;case"insideTop":l+=o/2,u+=n,f="center";break;case"insideBottom":l+=o/2,u+=i-n,f="center",h="bottom";break;case"insideTopLeft":l+=n,u+=n;break;case"insideTopRight":l+=o-n,u+=n,f="right";break;case"insideBottomLeft":l+=n,u+=i-n,h="bottom";break;case"insideBottomRight":l+=o-n,u+=i-n,f="right",h="bottom";break}return r=r||{},r.x=l,r.y=u,r.align=f,r.verticalAlign=h,r}var tv="__zr_normal__",ev=Hr.concat(["ignore"]),L2=Gr(Hr,function(r,e){return r[e]=!0,r},{ignore:!1}),xi={},P2=new ht(0,0,0,0),th=function(){function r(e){this.id=gw(),this.animators=[],this.currentStates=[],this.states={},this._init(e)}return r.prototype._init=function(e){this.attr(e)},r.prototype.drift=function(e,t,a){switch(this.draggable){case"horizontal":t=0;break;case"vertical":e=0;break}var n=this.transform;n||(n=this.transform=[1,0,0,1,0,0]),n[4]+=e,n[5]+=t,this.decomposeTransform(),this.markRedraw()},r.prototype.beforeUpdate=function(){},r.prototype.afterUpdate=function(){},r.prototype.update=function(){this.updateTransform(),this.__dirty&&this.updateInnerText()},r.prototype.updateInnerText=function(e){var t=this._textContent;if(t&&(!t.ignore||e)){this.textConfig||(this.textConfig={});var a=this.textConfig,n=a.local,i=t.innerTransformable,o=void 0,s=void 0,l=!1;i.parent=n?this:null;var u=!1;if(i.copyTransform(t),a.position!=null){var f=P2;a.layoutRect?f.copy(a.layoutRect):f.copy(this.getBoundingRect()),n||f.applyTransform(this.transform),this.calculateTextPosition?this.calculateTextPosition(xi,a,f):lf(xi,a,f),i.x=xi.x,i.y=xi.y,o=xi.align,s=xi.verticalAlign;var h=a.origin;if(h&&a.rotation!=null){var v=void 0,c=void 0;h==="center"?(v=f.width*.5,c=f.height*.5):(v=Sr(h[0],f.width),c=Sr(h[1],f.height)),u=!0,i.originX=-i.x+v+(n?0:f.x),i.originY=-i.y+c+(n?0:f.y)}}a.rotation!=null&&(i.rotation=a.rotation);var p=a.offset;p&&(i.x+=p[0],i.y+=p[1],u||(i.originX=-p[0],i.originY=-p[1]));var d=a.inside==null?typeof a.position=="string"&&a.position.indexOf("inside")>=0:a.inside,g=this._innerTextDefaultStyle||(this._innerTextDefaultStyle={}),y=void 0,m=void 0,_=void 0;d&&this.canBeInsideText()?(y=a.insideFill,m=a.insideStroke,(y==null||y==="auto")&&(y=this.getInsideTextFill()),(m==null||m==="auto")&&(m=this.getInsideTextStroke(y),_=!0)):(y=a.outsideFill,m=a.outsideStroke,(y==null||y==="auto")&&(y=this.getOutsideFill()),(m==null||m==="auto")&&(m=this.getOutsideStroke(y),_=!0)),y=y||"#000",(y!==g.fill||m!==g.stroke||_!==g.autoStroke||o!==g.align||s!==g.verticalAlign)&&(l=!0,g.fill=y,g.stroke=m,g.autoStroke=_,g.align=o,g.verticalAlign=s,t.setDefaultTextStyle(g)),t.__dirty|=Ge,l&&t.dirtyStyle(!0)}},r.prototype.canBeInsideText=function(){return!0},r.prototype.getInsideTextFill=function(){return"#fff"},r.prototype.getInsideTextStroke=function(e){return"#000"},r.prototype.getOutsideFill=function(){return this.__zr&&this.__zr.isDarkMode()?Mp:Dp},r.prototype.getOutsideStroke=function(e){var t=this.__zr&&this.__zr.getBackgroundColor(),a=typeof t=="string"&&We(t);a||(a=[255,255,255,1]);for(var n=a[3],i=this.__zr.isDarkMode(),o=0;o<3;o++)a[o]=a[o]*n+(i?0:255)*(1-n);return a[3]=1,na(a,"rgba")},r.prototype.traverse=function(e,t){},r.prototype.attrKV=function(e,t){e==="textConfig"?this.setTextConfig(t):e==="textContent"?this.setTextContent(t):e==="clipPath"?this.setClipPath(t):e==="extra"?(this.extra=this.extra||{},V(this.extra,t)):this[e]=t},r.prototype.hide=function(){this.ignore=!0,this.markRedraw()},r.prototype.show=function(){this.ignore=!1,this.markRedraw()},r.prototype.attr=function(e,t){if(typeof e=="string")this.attrKV(e,t);else if(et(e))for(var a=e,n=_t(a),i=0;i<n.length;i++){var o=n[i];this.attrKV(o,e[o])}return this.markRedraw(),this},r.prototype.saveCurrentToNormalState=function(e){this._innerSaveToNormal(e);for(var t=this._normalState,a=0;a<this.animators.length;a++){var n=this.animators[a],i=n.__fromStateTransition;if(!(n.getLoop()||i&&i!==tv)){var o=n.targetName,s=o?t[o]:t;n.saveTo(s)}}},r.prototype._innerSaveToNormal=function(e){var t=this._normalState;t||(t=this._normalState={}),e.textConf
Line truncated
|
||||
* ZRender, a high performance 2d drawing library.
|
||||
*
|
||||
* Copyright (c) 2013, Baidu Inc.
|
||||
* All rights reserved.
|
||||
*
|
||||
* LICENSE
|
||||
* https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
|
||||
*/var zu={},Uw={};function N2(r){delete Uw[r]}function B2(r){if(!r)return!1;if(typeof r=="string")return nf(r,1)<Cp;if(r.colorStops){for(var e=r.colorStops,t=0,a=e.length,n=0;n<a;n++)t+=nf(e[n].color,1);return t/=a,t<Cp}return!1}var V2=function(){function r(e,t,a){var n=this;this._sleepAfterStill=10,this._stillFrameAccum=0,this._needsRefresh=!0,this._needsRefreshHover=!0,this._darkMode=!1,a=a||{},this.dom=t,this.id=e;var i=new jL,o=a.renderer||"canvas";zu[o]||(o=_t(zu)[0]),a.useDirtyRect=a.useDirtyRect==null?!1:a.useDirtyRect;var s=new zu[o](t,i,a,e),l=a.ssr||s.ssrOnly;this.storage=i,this.painter=s;var u=!yt.node&&!yt.worker&&!l?new M2(s.getViewportRoot(),s.root):null,f=a.useCoarsePointer,h=f==null||f==="auto"?yt.touchEventsSupported:!!f,v=44,c;h&&(c=st(a.pointerSize,v)),this.handler=new bw(i,s,u,s.root,c),this.animation=new x2({stage:{update:l?null:function(){return n._flush(!0)}}}),l||this.animation.start()}return r.prototype.add=function(e){this._disposed||!e||(this.storage.addRoot(e),e.addSelfToZr(this),this.refresh())},r.prototype.remove=function(e){this._disposed||!e||(this.storage.delRoot(e),e.removeSelfFromZr(this),this.refresh())},r.prototype.configLayer=function(e,t){this._disposed||(this.painter.configLayer&&this.painter.configLayer(e,t),this.refresh())},r.prototype.setBackgroundColor=function(e){this._disposed||(this.painter.setBackgroundColor&&this.painter.setBackgroundColor(e),this.refresh(),this._backgroundColor=e,this._darkMode=B2(e))},r.prototype.getBackgroundColor=function(){return this._backgroundColor},r.prototype.setDarkMode=function(e){this._darkMode=e},r.prototype.isDarkMode=function(){return this._darkMode},r.prototype.refreshImmediately=function(e){this._disposed||(e||this.animation.update(!0),this._needsRefresh=!1,this.painter.refresh(),this._needsRefresh=!1)},r.prototype.refresh=function(){this._disposed||(this._needsRefresh=!0,this.animation.start())},r.prototype.flush=function(){this._disposed||this._flush(!1)},r.prototype._flush=function(e){var t,a=Yi();this._needsRefresh&&(t=!0,this.refreshImmediately(e)),this._needsRefreshHover&&(t=!0,this.refreshHoverImmediately());var n=Yi();t?(this._stillFrameAccum=0,this.trigger("rendered",{elapsedTime:n-a})):this._sleepAfterStill>0&&(this._stillFrameAccum++,this._stillFrameAccum>this._sleepAfterStill&&this.animation.stop())},r.prototype.setSleepAfterStill=function(e){this._sleepAfterStill=e},r.prototype.wakeUp=function(){this._disposed||(this.animation.start(),this._stillFrameAccum=0)},r.prototype.refreshHover=function(){this._needsRefreshHover=!0},r.prototype.refreshHoverImmediately=function(){this._disposed||(this._needsRefreshHover=!1,this.painter.refreshHover&&this.painter.getType()==="canvas"&&this.painter.refreshHover())},r.prototype.resize=function(e){this._disposed||(e=e||{},this.painter.resize(e.width,e.height),this.handler.resize())},r.prototype.clearAnimation=function(){this._disposed||this.animation.clear()},r.prototype.getWidth=function(){if(!this._disposed)return this.painter.getWidth()},r.prototype.getHeight=function(){if(!this._disposed)return this.painter.getHeight()},r.prototype.setCursorStyle=function(e){this._disposed||this.handler.setCursorStyle(e)},r.prototype.findHover=function(e,t){if(!this._disposed)return this.handler.findHover(e,t)},r.prototype.on=function(e,t,a){return this._disposed||this.handler.on(e,t,a),this},r.prototype.off=function(e,t){this._disposed||this.handler.off(e,t)},r.prototype.trigger=function(e,t){this._disposed||this.handler.trigger(e,t)},r.prototype.clear=function(){if(!this._disposed){for(var e=this.storage.getRoots(),t=0;t<e.length;t++)e[t]instanceof at&&e[t].removeSelfFromZr(this);this.storage.delAllRoots(),this.painter.clear()}},r.prototype.dispose=function(){this._disposed||(this.animation.stop(),this.clear(),this.storage.dispose(),this.painter.dispose(),this.handler.dispose(),this.animation=this.storage=this.painter=this.handler=null,this._disposed=!0,N2(this.id))},r}();function Bm(r,e){var t=new V2(gw(),r,e);return Uw[t.id]=t,t}function z2(r,e){zu[r]=e}var Ip;function G2(r){if(typeof Ip=="function")return Ip(r)}function F2(r){Ip=r}var Vm=1e-4,Yw=20;function H2(r){return r.replace(/^\s+|\s+$/g,"")}function Dt(r,e,t,a){var n=e[0],i=e[1],o=t[0],s=t[1],l=i-n,u=s-o;if(l===0)return u===0?o:(o+s)/2;if(a)if(l>0){if(r<=n)return o;if(r>=i)return s}else{if(r>=n)return o;if(r<=i)return s}else{if(r===n)return o;if(r===i)return s}return(r-n)/l*u+o}function W(r,e){switch(r){case"center":case"middle":r="50%";break;case"left":case"top":r="0%";break;case"right":case"bottom":r="100%";break}return Y(r)?H2(r).match(/%$/)?parseFloat(r)/100*e:parseFloat(r):r==null?NaN:+r}function Ut(r,e,t){return e==null&&(e=10),e=Math.min(Math.max(0,e),Yw),r=(+r).toFixed(e),t?r:+r}function nr(r){return r.sort(function(e,t){return e-t}),r}function kr(r){if(r=+r,isNaN(r))return 0;if(r>1e-14){for(var e=1,t=0;t<15;t++,e*=10)if(Math.round(r*e)/e===r)return t}return W2(r)}function W2(r){var e=r.toString().toLowerCase(),t=e.indeLine truncated
|
||||
`);i=oT(t,a,n,i);for(var s=!1,l={},u=0,f=o.length;u<f;u++)sT(l,o[u],i),o[u]=l.textLine,s=s||l.isTruncated;r.text=o.join(`
|
||||
`),r.isTruncated=s}function oT(r,e,t,a){a=a||{};var n=V({},a);n.font=e,t=st(t,"..."),n.maxIterations=st(a.maxIterations,2);var i=n.minChar=st(a.minChar,0);n.cnCharWidth=Ue("国",e);var o=n.ascCharWidth=Ue("a",e);n.placeholder=st(a.placeholder,"");for(var s=r=Math.max(0,r-1),l=0;l<i&&s>=o;l++)s-=o;var u=Ue(t,e);return u>s&&(t="",u=0),s=r-u,n.ellipsis=t,n.ellipsisWidth=u,n.contentWidth=s,n.containerWidth=r,n}function sT(r,e,t){var a=t.containerWidth,n=t.font,i=t.contentWidth;if(!a){r.textLine="",r.isTruncated=!1;return}var o=Ue(e,n);if(o<=a){r.textLine=e,r.isTruncated=!1;return}for(var s=0;;s++){if(o<=i||s>=t.maxIterations){e+=t.ellipsis;break}var l=s===0?bP(e,i,t.ascCharWidth,t.cnCharWidth):o>0?Math.floor(e.length*i/o):0;e=e.substr(0,l),o=Ue(e,n)}e===""&&(e=t.placeholder),r.textLine=e,r.isTruncated=!0}function bP(r,e,t,a){for(var n=0,i=0,o=r.length;i<o&&n<e;i++){var s=r.charCodeAt(i);n+=0<=s&&s<=127?t:a}return i}function wP(r,e){r!=null&&(r+="");var t=e.overflow,a=e.padding,n=e.font,i=t==="truncate",o=jf(n),s=st(e.lineHeight,o),l=!!e.backgroundColor,u=e.lineOverflow==="truncate",f=!1,h=e.width,v;h!=null&&(t==="break"||t==="breakAll")?v=r?lT(r,e.font,h,t==="breakAll",0).lines:[]:v=r?r.split(`
|
||||
`):[];var c=v.length*s,p=st(e.height,c);if(c>p&&u){var d=Math.floor(p/s);f=f||v.length>d,v=v.slice(0,d)}if(r&&i&&h!=null)for(var g=oT(h,n,e.ellipsis,{minChar:e.truncateMinChar,placeholder:e.placeholder}),y={},m=0;m<v.length;m++)sT(y,v[m],g),v[m]=y.textLine,f=f||y.isTruncated;for(var _=p,S=0,m=0;m<v.length;m++)S=Math.max(Ue(v[m],n),S);h==null&&(h=S);var b=S;return a&&(_+=a[0]+a[2],b+=a[1]+a[3],h+=a[1]+a[3]),l&&(b=h),{lines:v,height:p,outerWidth:b,outerHeight:_,lineHeight:s,calculatedLineHeight:o,contentWidth:S,contentHeight:c,width:h,isTruncated:f}}var TP=function(){function r(){}return r}(),Ym=function(){function r(e){this.tokens=[],e&&(this.tokens=e)}return r}(),AP=function(){function r(){this.width=0,this.height=0,this.contentWidth=0,this.contentHeight=0,this.outerWidth=0,this.outerHeight=0,this.lines=[],this.isTruncated=!1}return r}();function CP(r,e){var t=new AP;if(r!=null&&(r+=""),!r)return t;for(var a=e.width,n=e.height,i=e.overflow,o=(i==="break"||i==="breakAll")&&a!=null?{width:a,accumWidth:0,breakAll:i==="breakAll"}:null,s=iv.lastIndex=0,l;(l=iv.exec(r))!=null;){var u=l.index;u>s&&ov(t,r.substring(s,u),e,o),ov(t,l[2],e,o,l[1]),s=iv.lastIndex}s<r.length&&ov(t,r.substring(s,r.length),e,o);var f=[],h=0,v=0,c=e.padding,p=i==="truncate",d=e.lineOverflow==="truncate",g={};function y(F,H,U){F.width=H,F.lineHeight=U,h+=U,v=Math.max(v,H)}t:for(var m=0;m<t.lines.length;m++){for(var _=t.lines[m],S=0,b=0,x=0;x<_.tokens.length;x++){var w=_.tokens[x],T=w.styleName&&e.rich[w.styleName]||{},A=w.textPadding=T.padding,C=A?A[1]+A[3]:0,M=w.font=T.font||e.font;w.contentHeight=jf(M);var I=st(T.height,w.contentHeight);if(w.innerHeight=I,A&&(I+=A[0]+A[2]),w.height=I,w.lineHeight=Vr(T.lineHeight,e.lineHeight,I),w.align=T&&T.align||e.align,w.verticalAlign=T&&T.verticalAlign||"middle",d&&n!=null&&h+w.lineHeight>n){var L=t.lines.length;x>0?(_.tokens=_.tokens.slice(0,x),y(_,b,S),t.lines=t.lines.slice(0,m+1)):t.lines=t.lines.slice(0,m),t.isTruncated=t.isTruncated||t.lines.length<L;break t}var P=T.width,R=P==null||P==="auto";if(typeof P=="string"&&P.charAt(P.length-1)==="%")w.percentWidth=P,f.push(w),w.contentWidth=Ue(w.text,M);else{if(R){var E=T.backgroundColor,N=E&&E.image;N&&(N=SP(N),rh(N)&&(w.width=Math.max(w.width,N.width*I/N.height)))}var O=p&&a!=null?a-b:null;O!=null&&O<w.width?!R||O<C?(w.text="",w.width=w.contentWidth=0):(xP(g,w.text,O-C,M,e.ellipsis,{minChar:e.truncateMinChar}),w.text=g.text,t.isTruncated=t.isTruncated||g.isTruncated,w.width=w.contentWidth=Ue(w.text,M)):w.contentWidth=Ue(w.text,M)}w.width+=C,b+=w.width,T&&(S=Math.max(S,w.lineHeight))}y(_,b,S)}t.outerWidth=t.width=st(a,v),t.outerHeight=t.height=st(n,h),t.contentHeight=h,t.contentWidth=v,c&&(t.outerWidth+=c[1]+c[3],t.outerHeight+=c[0]+c[2]);for(var m=0;m<f.length;m++){var w=f[m],B=w.percentWidth;w.width=parseInt(B,10)/100*t.width}return t}function ov(r,e,t,a,n){var i=e==="",o=n&&t.rich[n]||{},s=r.lines,l=o.font||t.font,u=!1,f,h;if(a){var v=o.padding,c=v?v[1]+v[3]:0;if(o.width!=null&&o.width!=="auto"){var p=Sr(o.width,a.width)+c;s.length>0&&p+a.accumWidth>a.width&&(f=e.split(`
|
||||
`),u=!0),a.accumWidth=p}else{var d=lT(e,l,a.width,a.breakAll,a.accumWidth);a.accumWidth=d.accumWidth+c,h=d.linesWidths,f=d.lines}}else f=e.split(`
|
||||
`);for(var g=0;g<f.length;g++){var y=f[g],m=new TP;if(m.styleName=n,m.text=y,m.isLineHolder=!y&&!i,typeof o.width=="number"?m.width=o.width:m.width=h?h[g]:Ue(y,l),!g&&!u){var _=(s[s.length-1]||(s[0]=new Ym)).tokens,S=_.length;S===1&&_[0].isLineHolder?_[0]=m:(y||!S||i)&&_.push(m)}else s.push(new Ym([m]))}}function DP(r){var e=r.charCodeAt(0);return e>=32&&e<=591||e>=880&&e<=4351||e>=4608&&e<=5119||e>=7680&&e<=8303}var MP=Gr(",&?/;] ".split(""),function(r,e){return r[e]=!0,r},{});function IP(r){return DP(r)?!!MP[r]:!0}function lT(r,e,t,a,n){for(var i=[],o=[],s="",l="",u=0,f=0,h=0;h<r.length;h++){var v=r.charAt(h);if(v===`
|
||||
`){l&&(s+=l,f+=u),i.push(s),o.push(f),s="",l="",u=0,f=0;continue}var c=Ue(v,e),p=a?!1:!IP(v);if(i.length?f+c>t:n+f+c>t){f?(s||l)&&(p?(s||(s=l,l="",u=0,f=u),i.push(s),o.push(f-u),l+=v,u+=c,s="",f=u):(l&&(s+=l,l="",u=0),i.push(s),o.push(f),s=v,f=c)):p?(i.push(l),o.push(u),l=v,u=c):(i.push(v),o.push(c));continue}f+=c,p?(l+=v,u+=c):(l&&(s+=l,l="",u=0),s+=v)}return!i.length&&!s&&(s=r,l="",u=0),l&&(s+=l),s&&(i.push(s),o.push(f)),i.length===1&&(f+=n),{accumWidth:f,lines:i,linesWidths:o}}var Rp="__zr_style_"+Math.round(Math.random()*10),$n={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"#000",opacity:1,blend:"source-over"},ah={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};$n[Rp]=!0;var Xm=["z","z2","invisible"],LP=["invisible"],or=function(r){k(e,r);function e(t){return r.call(this,t)||this}return e.prototype._init=function(t){for(var a=_t(t),n=0;n<a.length;n++){var i=a[n];i==="style"?this.useStyle(t[i]):r.prototype.attrKV.call(this,i,t[i])}this.style||this.useStyle({})},e.prototype.beforeBrush=function(){},e.prototype.afterBrush=function(){},e.prototype.innerBeforeBrush=function(){},e.prototype.innerAfterBrush=function(){},e.prototype.shouldBePainted=function(t,a,n,i){var o=this.transform;if(this.ignore||this.invisible||this.style.opacity===0||this.culling&&PP(this,t,a)||o&&!o[0]&&!o[3])return!1;if(n&&this.__clipPaths){for(var s=0;s<this.__clipPaths.length;++s)if(this.__clipPaths[s].isZeroArea())return!1}if(i&&this.parent)for(var l=this.parent;l;){if(l.ignore)return!1;l=l.parent}return!0},e.prototype.contain=function(t,a){return this.rectContain(t,a)},e.prototype.traverse=function(t,a){t.call(a,this)},e.prototype.rectContain=function(t,a){var n=this.transformCoordToLocal(t,a),i=this.getBoundingRect();return i.contain(n[0],n[1])},e.prototype.getPaintRect=function(){var t=this._paintRect;if(!this._paintRect||this.__dirty){var a=this.transform,n=this.getBoundingRect(),i=this.style,o=i.shadowBlur||0,s=i.shadowOffsetX||0,l=i.shadowOffsetY||0;t=this._paintRect||(this._paintRect=new ht(0,0,0,0)),a?ht.applyTransform(t,n,a):t.copy(n),(o||s||l)&&(t.width+=o*2+Math.abs(s),t.height+=o*2+Math.abs(l),t.x=Math.min(t.x,t.x+s-o),t.y=Math.min(t.y,t.y+l-o));var u=this.dirtyRectTolerance;t.isZero()||(t.x=Math.floor(t.x-u),t.y=Math.floor(t.y-u),t.width=Math.ceil(t.width+1+u*2),t.height=Math.ceil(t.height+1+u*2))}return t},e.prototype.setPrevPaintRect=function(t){t?(this._prevPaintRect=this._prevPaintRect||new ht(0,0,0,0),this._prevPaintRect.copy(t)):this._prevPaintRect=null},e.prototype.getPrevPaintRect=function(){return this._prevPaintRect},e.prototype.animateStyle=function(t){return this.animate("style",t)},e.prototype.updateDuringAnimation=function(t){t==="style"?this.dirtyStyle():this.markRedraw()},e.prototype.attrKV=function(t,a){t!=="style"?r.prototype.attrKV.call(this,t,a):this.style?this.setStyle(a):this.useStyle(a)},e.prototype.setStyle=function(t,a){return typeof t=="string"?this.style[t]=a:V(this.style,t),this.dirtyStyle(),this},e.prototype.dirtyStyle=function(t){t||this.markRedraw(),this.__dirty|=is,this._rect&&(this._rect=null)},e.prototype.dirty=function(){this.dirtyStyle()},e.prototype.styleChanged=function(){return!!(this.__dirty&is)},e.prototype.styleUpdated=function(){this.__dirty&=~is},e.prototype.createStyle=function(t){return Kf($n,t)},e.prototype.useStyle=function(t){t[Rp]||(t=this.createStyle(t)),this.__inHover?this.__hoverStyle=t:this.style=t,this.dirtyStyle()},e.prototype.isStyleObject=function(t){return t[Rp]},e.prototype._innerSaveToNormal=function(t){r.prototype._innerSaveToNormal.call(this,t);var a=this._normalState;t.style&&!a.style&&(a.style=this._mergeStyle(this.createStyle(),this.style)),this._savePrimaryToNormal(t,a,Xm)},e.prototype._applyStateObj=function(t,a,n,i,o,s){r.prototype._applyStateObj.call(this,t,a,n,i,o,s);var l=!(a&&i),u;if(a&&a.style?o?i?u=a.style:(u=this._mergeStyle(this.createStyle(),n.style),this._mergeStyle(u,a.style)):(u=this._mergeStyle(this.createStyle(),i?this.style:n.style),this._mergeStyle(u,a.style)):l&&(u=n.style),u)if(o){var f=this.style;if(this.style=this.createStyle(l?{}:f),l)for(var h=_t(f),v=0;v<h.length;v++){var c=h[v];c in u&&(u[c]=u[c],this.style[c]=f[c])}for(var p=_t(u),v=0;v<p.length;v++){var c=p[v];this.style[c]=this.style[c]}this._transitionState(t,{style:u},s,this.getAnimationStyleProps())}else this.useStyle(u);for(var d=this.__inHover?LP:Xm,v=0;v<d.length;v++){var c=d[v];a&&a[c]!=null?this[c]=a[c]:l&&n[c]!=null&&(this[c]=n[c])}},e.prototype._mergeStates=function(t){for(var a=r.prototype._mergeStates.call(this,t),n,i=0;i<t.length;i++){var o=t[i];o.style&&(n=n||{},this._mergeStyle(n,o.style))}return n&&(a.style=n),a},e.prototype._mergeStyle=function(t,a){return V(t,a),t},e.prototype.getAnimationStyleProps=function(){return ah},e.initDefaultProps=function(){var t=e.prototype;t.type="displayable",t.invisible=!1,t.z=0,t.z2=0,t.zlevel=0,t.culling=!1,t.cursor="pointer",t.rectHover=!1,t.incremental=!1,t._rect=null,t.dirty
Line truncated
|
||||
`,`
|
||||
|
||||
`,`
|
||||
|
||||
|
||||
`];function ie(r,e){return e.type=r,e}function $p(r){return r.type==="section"}function PA(r){return $p(r)?wk:Tk}function RA(r){if($p(r)){var e=0,t=r.blocks.length,a=t>1||t>0&&!r.noHeader;return D(r.blocks,function(n){var i=RA(n);i>=e&&(e=i+ +(a&&(!i||$p(n)&&!n.noHeader)))}),e}return 0}function wk(r,e,t,a){var n=e.noHeader,i=Ak(RA(e)),o=[],s=e.blocks||[];Ce(!s||z(s)),s=s||[];var l=r.orderMode;if(e.sortBlocks&&l){s=s.slice();var u={valueAsc:"asc",valueDesc:"desc"};if(Z(u,l)){var f=new TA(u[l],null);s.sort(function(d,g){return f.evaluate(d.sortParam,g.sortParam)})}else l==="seriesDesc"&&s.reverse()}D(s,function(d,g){var y=e.valueFormatter,m=PA(d)(y?V(V({},r),{valueFormatter:y}):r,d,g>0?i.html:0,a);m!=null&&o.push(m)});var h=r.renderMode==="richText"?o.join(i.richText):qp(a,o.join(""),n?t:i.html);if(n)return h;var v=Wp(e.header,"ordinal",r.useUTC),c=LA(a,r.renderMode).nameStyle,p=IA(a);return r.renderMode==="richText"?EA(r,v,c)+i.richText+h:qp(a,'<div style="'+c+";"+p+';">'+we(v)+"</div>"+h,t)}function Tk(r,e,t,a){var n=r.renderMode,i=e.noName,o=e.noValue,s=!e.markerType,l=e.name,u=r.useUTC,f=e.valueFormatter||r.valueFormatter||function(S){return S=z(S)?S:[S],G(S,function(b,x){return Wp(b,z(c)?c[x]:c,u)})};if(!(i&&o)){var h=s?"":r.markupStyleCreator.makeTooltipMarker(e.markerType,e.markerColor||"#333",n),v=i?"":Wp(l,"ordinal",u),c=e.valueType,p=o?[]:f(e.value,e.dataIndex),d=!s||!i,g=!s&&i,y=LA(a,n),m=y.nameStyle,_=y.valueStyle;return n==="richText"?(s?"":h)+(i?"":EA(r,v,m))+(o?"":Mk(r,p,d,g,_)):qp(a,(s?"":h)+(i?"":Ck(v,!s,m))+(o?"":Dk(p,d,g,_)),t)}}function t_(r,e,t,a,n,i){if(r){var o=PA(r),s={useUTC:n,renderMode:t,orderMode:a,markupStyleCreator:e,valueFormatter:r.valueFormatter};return o(s,r,0,i)}}function Ak(r){return{html:xk[r],richText:bk[r]}}function qp(r,e,t){var a='<div style="clear:both"></div>',n="margin: "+t+"px 0 0",i=IA(r);return'<div style="'+n+";"+i+';">'+e+a+"</div>"}function Ck(r,e,t){var a=e?"margin-left:2px":"";return'<span style="'+t+";"+a+'">'+we(r)+"</span>"}function Dk(r,e,t,a){var n=t?"10px":"20px",i=e?"float:right;margin-left:"+n:"";return r=z(r)?r:[r],'<span style="'+i+";"+a+'">'+G(r,function(o){return we(o)}).join(" ")+"</span>"}function EA(r,e,t){return r.markupStyleCreator.wrapRichTextStyle(e,t)}function Mk(r,e,t,a,n){var i=[n],o=a?10:20;return t&&i.push({padding:[0,0,0,o],align:"right"}),r.markupStyleCreator.wrapRichTextStyle(z(e)?e.join(" "):e,i)}function kA(r,e){var t=r.getData().getItemVisual(e,"style"),a=t[r.visualDrawType];return ii(a)}function OA(r,e){var t=r.get("padding");return t??(e==="richText"?[8,10]:10)}var Lv=function(){function r(){this.richTextStyles={},this._nextStyleNameId=Kw()}return r.prototype._generateStyleName=function(){return"__EC_aUTo_"+this._nextStyleNameId++},r.prototype.makeTooltipMarker=function(e,t,a){var n=a==="richText"?this._generateStyleName():null,i=mE({color:t,type:e,renderMode:a,markerId:n});return Y(i)?i:(this.richTextStyles[n]=i.style,i.content)},r.prototype.wrapRichTextStyle=function(e,t){var a={};z(t)?D(t,function(i){return V(a,i)}):V(a,t);var n=this._generateStyleName();return this.richTextStyles[n]=a,"{"+n+"|"+e+"}"},r}();function NA(r){var e=r.series,t=r.dataIndex,a=r.multipleSeries,n=e.getData(),i=n.mapDimensionsAll("defaultedTooltip"),o=i.length,s=e.getRawValue(t),l=z(s),u=kA(e,t),f,h,v,c;if(o>1||l&&!o){var p=Ik(s,e,t,i,u);f=p.inlineValues,h=p.inlineValueTypes,v=p.blocks,c=p.inlineValues[0]}else if(o){var d=n.getDimensionInfo(i[0]);c=f=no(n,t,i[0]),h=d.type}else c=f=l?s[0]:s;var g=ug(e),y=g&&e.name||"",m=n.getName(t),_=a?y:m;return ie("section",{header:y,noHeader:a||!g,sortParam:c,blocks:[ie("nameValue",{markerType:"item",markerColor:u,name:_,noName:!gr(_),value:f,valueType:h,dataIndex:t})].concat(v||[])})}function Ik(r,e,t,a,n){var i=e.getData(),o=Gr(r,function(h,v,c){var p=i.getDimensionInfo(c);return h=h||p&&p.tooltip!==!1&&p.displayName!=null},!1),s=[],l=[],u=[];a.length?D(a,function(h){f(no(i,t,h),h)}):D(r,f);function f(h,v){var c=i.getDimensionInfo(v);!c||c.otherDims.tooltip===!1||(o?u.push(ie("nameValue",{markerType:"subItem",markerColor:n,name:c.displayName,value:h,valueType:c.type})):(s.push(h),l.push(c.type)))}return{inlineValues:s,inlineValueTypes:l,blocks:u}}var ba=xt();function Jl(r,e){return r.getName(e)||r.getId(e)}var Yu="__universalTransitionEnabled",Vt=function(r){k(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t._selectedDataIndicesMap={},t}return e.prototype.init=function(t,a,n){this.seriesIndex=this.componentIndex,this.dataTask=Ds({count:Pk,reset:Rk}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n);var i=ba(this).sourceManager=new MA(this);i.prepareSource();var o=this.getInitialData(t,n);r_(o,this),this.dataTask.context.data=o,ba(this).dataBeforeProcessed=o,e_(this),this._initSelectedMapFromData(o)},e.prototype.mergeDefaultAndTheme=function(t,a){var n=Us(this),i=n?bo(t):{},o=this.subType;mt.hasClass(o)&&(o+="Series"),ut(t,a.getTheme().get(this.subType)),ut(t,t
Line truncated
|
||||
`:"";function a(n){var i=n.children,o=n.tag,s=n.attrs,l=n.text;return OB(o,s)+(o!=="style"?we(l):l||"")+(i?""+t+G(i,function(u){return a(u)}).join(t)+t:"")+NB(o)}return a(r)}function BB(r,e,t){t=t||{};var a=t.newline?`
|
||||
`:"",n=" {"+a,i=a+"}",o=G(_t(r),function(l){return l+n+G(_t(r[l]),function(u){return u+":"+r[l][u]+";"}).join(a)+i}).join(a),s=G(_t(e),function(l){return"@keyframes "+l+n+G(_t(e[l]),function(u){return u+n+G(_t(e[l][u]),function(f){var h=e[l][u][f];return f==="d"&&(h='path("'+h+'")'),f+":"+h+";"}).join(a)+i}).join(a)+i}).join(a);return!o&&!s?"":["<![CDATA[",o,s,"]]>"].join(a)}function sd(r){return{zrId:r,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssStyleCache:{},cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function K_(r,e,t,a){return re("svg","root",{width:r,height:e,xmlns:jC,"xmlns:xlink":tD,version:"1.1",baseProfile:"full",viewBox:a?"0 0 "+r+" "+e:!1},t)}var VB=0;function rD(){return VB++}var J_={cubicIn:"0.32,0,0.67,0",cubicOut:"0.33,1,0.68,1",cubicInOut:"0.65,0,0.35,1",quadraticIn:"0.11,0,0.5,0",quadraticOut:"0.5,1,0.89,1",quadraticInOut:"0.45,0,0.55,1",quarticIn:"0.5,0,0.75,0",quarticOut:"0.25,1,0.5,1",quarticInOut:"0.76,0,0.24,1",quinticIn:"0.64,0,0.78,0",quinticOut:"0.22,1,0.36,1",quinticInOut:"0.83,0,0.17,1",sinusoidalIn:"0.12,0,0.39,0",sinusoidalOut:"0.61,1,0.88,1",sinusoidalInOut:"0.37,0,0.63,1",exponentialIn:"0.7,0,0.84,0",exponentialOut:"0.16,1,0.3,1",exponentialInOut:"0.87,0,0.13,1",circularIn:"0.55,0,1,0.45",circularOut:"0,0.55,0.45,1",circularInOut:"0.85,0,0.15,1"},Mn="transform-origin";function zB(r,e,t){var a=V({},r.shape);V(a,e),r.buildPath(t,a);var n=new QC;return n.reset(Bw(r)),t.rebuildPath(n,1),n.generateStr(),n.getStr()}function GB(r,e){var t=e.originX,a=e.originY;(t||a)&&(r[Mn]=t+"px "+a+"px")}var FB={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function aD(r,e){var t=e.zrId+"-ani-"+e.cssAnimIdx++;return e.cssAnims[t]=r,t}function HB(r,e,t){var a=r.shape.paths,n={},i,o;if(D(a,function(l){var u=sd(t.zrId);u.animation=!0,Dh(l,{},u,!0);var f=u.cssAnims,h=u.cssNodes,v=_t(f),c=v.length;if(c){o=v[c-1];var p=f[o];for(var d in p){var g=p[d];n[d]=n[d]||{d:""},n[d].d+=g.d||""}for(var y in h){var m=h[y].animation;m.indexOf(o)>=0&&(i=m)}}}),!!i){e.d=!1;var s=aD(n,t);return i.replace(o,s)}}function Q_(r){return Y(r)?J_[r]?"cubic-bezier("+J_[r]+")":ig(r)?r:"":""}function Dh(r,e,t,a){var n=r.animators,i=n.length,o=[];if(r instanceof Sg){var s=HB(r,e,t);if(s)o.push(s);else if(!i)return}else if(!i)return;for(var l={},u=0;u<i;u++){var f=n[u],h=[f.getMaxTime()/1e3+"s"],v=Q_(f.getClip().easing),c=f.getDelay();v?h.push(v):h.push("linear"),c&&h.push(c/1e3+"s"),f.getLoop()&&h.push("infinite");var p=h.join(" ");l[p]=l[p]||[p,[]],l[p][1].push(f)}function d(m){var _=m[1],S=_.length,b={},x={},w={},T="animation-timing-function";function A(vt,tt,pt){for(var q=vt.getTracks(),ot=vt.getMaxTime(),Ot=0;Ot<q.length;Ot++){var It=q[Ot];if(It.needsAnimate()){var Et=It.keyframes,Gt=It.propName;if(pt&&(Gt=pt(Gt)),Gt)for(var jt=0;jt<Et.length;jt++){var Ve=Et[jt],Pe=Math.round(Ve.time/ot*100)+"%",en=Q_(Ve.easing),ma=Ve.rawValue;(Y(ma)||wt(ma))&&(tt[Pe]=tt[Pe]||{},tt[Pe][Gt]=Ve.rawValue,en&&(tt[Pe][T]=en))}}}}for(var C=0;C<S;C++){var M=_[C],I=M.targetName;I?I==="shape"&&A(M,x):!a&&A(M,b)}for(var L in b){var P={};Hw(P,r),V(P,b[L]);var R=Vw(P),E=b[L][T];w[L]=R?{transform:R}:{},GB(w[L],P),E&&(w[L][T]=E)}var N,O=!0;for(var L in x){w[L]=w[L]||{};var B=!N,E=x[L][T];B&&(N=new Ur);var F=N.len();N.reset(),w[L].d=zB(r,x[L],N);var H=N.len();if(!B&&F!==H){O=!1;break}E&&(w[L][T]=E)}if(!O)for(var L in w)delete w[L].d;if(!a)for(var C=0;C<S;C++){var M=_[C],I=M.targetName;I==="style"&&A(M,w,function(q){return FB[q]})}for(var U=_t(w),K=!0,Q,C=1;C<U.length;C++){var it=U[C-1],Lt=U[C];if(w[it][Mn]!==w[Lt][Mn]){K=!1;break}Q=w[it][Mn]}if(K&&Q){for(var L in w)w[L][Mn]&&delete w[L][Mn];e[Mn]=Q}if(Ct(U,function(vt){return _t(w[vt]).length>0}).length){var Wt=aD(w,t);return Wt+" "+m[0]+" both"}}for(var g in l){var s=d(l[g]);s&&o.push(s)}if(o.length){var y=t.zrId+"-cls-"+rD();t.cssNodes["."+y]={animation:o.join(",")},e.class=y}}function WB(r,e,t){if(!r.ignore)if(r.isSilent()){var a={"pointer-events":"none"};j_(a,e,t)}else{var n=r.states.emphasis&&r.states.emphasis.style?r.states.emphasis.style:{},i=n.fill;if(!i){var o=r.style&&r.style.fill,s=r.states.select&&r.states.select.style&&r.states.select.style.fill,l=r.currentStates.indexOf("select")>=0&&s||o;l&&(i=_p(l))}var u=n.lineWidth;if(u){var f=!n.strokeNoScale&&r.transform?r.transform[0]:1;u=u/f}var a={cursor:"pointer"};i&&(a.fill=i),n.stroke&&(a.stroke=n.stroke),u&&(a["stroke-width"]=u),j_(a,e,t)}}function j_(r,e,t,a){var n=JSON.stringify(r),i=t.cssStyleCache[n];i||(i=t.zrId+"-cls-"+rD(),t.cssStyleCache[n]=i,t.cssNodes["."+i+":hover"]=r),e.class=e.class?e.class+" "+i:i}var Ks=Math.round;function nD(r){return r&&Y(r.src)}function iD(r){return r&&J(r.toDataURL)}function ey(r,e,t,a){RB(function(n,i){var o=n==="fill"||n==="stroke";o&&Nw(i)?sD(e,r,n,a):o&&og(i)?lD(t,r,n,a):r[n]=i,o&&a.ssr&&i==="none"&&(r["pointer-events"]="visible")},e,t,!1),KB(t,r,a)}function ry(r,e){var t=G2(e);t&&(t.e
Line truncated
|
||||
`+g.message)}var n=new at;n.add(a),n.isGeoSVGGraphicRoot=!0;var i=t.width,o=t.height,s=t.viewBoxRect,l=this._boundingRect;if(!l){var u=void 0,f=void 0,h=void 0,v=void 0;if(i!=null?(u=0,h=i):s&&(u=s.x,h=s.width),o!=null?(f=0,v=o):s&&(f=s.y,v=s.height),u==null||f==null){var c=a.getBoundingRect();u==null&&(u=c.x,h=c.width),f==null&&(f=c.y,v=c.height)}l=this._boundingRect=new ht(u,f,h,v)}if(s){var p=GD(s,l);a.scaleX=a.scaleY=p.scale,a.x=p.x,a.y=p.y}n.setClipPath(new St({shape:l.plain()}));var d=[];return D(t.named,function(g){i5.get(g.svgNodeTagLower)!=null&&(d.push(g),s5(g.el))}),{root:n,boundingRect:l,named:d}},r.prototype.useGraphic=function(e){var t=this._usedGraphicMap,a=t.get(e);return a||(a=this._freedGraphics.pop()||this._buildGraphic(this._parsedXML),t.set(e,a),a)},r.prototype.freeGraphic=function(e){var t=this._usedGraphicMap,a=t.get(e);a&&(t.removeKey(e),this._freedGraphics.push(a))},r}();function s5(r){r.silent=!1,r.isGroup&&r.traverse(function(e){e.silent=!1})}function l5(r){var e=[],t=$();return D(r,function(a){if(a.namedFrom==null){var n=new rB(a.name,a.el);e.push(n),t.set(a.name,n)}}),{regions:e,regionsMap:t}}var dd=[126,25],Q1="南海诸岛",In=[[[0,3.5],[7,11.2],[15,11.9],[30,7],[42,.7],[52,.7],[56,7.7],[59,.7],[64,.7],[64,0],[5,0],[0,3.5]],[[13,16.1],[19,14.7],[16,21.7],[11,23.1],[13,16.1]],[[12,32.2],[14,38.5],[15,38.5],[13,32.2],[12,32.2]],[[16,47.6],[12,53.2],[13,53.2],[18,47.6],[16,47.6]],[[6,64.4],[8,70],[9,70],[8,64.4],[6,64.4]],[[23,82.6],[29,79.8],[30,79.8],[25,82.6],[23,82.6]],[[37,70.7],[43,62.3],[44,62.3],[39,70.7],[37,70.7]],[[48,51.1],[51,45.5],[53,45.5],[50,51.1],[48,51.1]],[[51,35],[51,28.7],[53,28.7],[53,35],[51,35]],[[52,22.4],[55,17.5],[56,17.5],[53,22.4],[52,22.4]],[[58,12.6],[62,7],[63,7],[60,12.6],[58,12.6]],[[0,3.5],[0,93.1],[64,93.1],[64,0],[63,0],[63,92.4],[1,92.4],[1,3.5],[0,3.5]]];for(var Dn=0;Dn<In.length;Dn++)for(var Pi=0;Pi<In[Dn].length;Pi++)In[Dn][Pi][0]/=10.5,In[Dn][Pi][1]/=-10.5/.75,In[Dn][Pi][0]+=dd[0],In[Dn][Pi][1]+=dd[1];function u5(r,e){if(r==="china"){for(var t=0;t<e.length;t++)if(e[t].name===Q1)return;e.push(new NC(Q1,G(In,function(a){return{type:"polygon",exterior:a}}),dd))}}var f5={南海诸岛:[32,80],广东:[0,-10],香港:[10,5],澳门:[-10,10],天津:[5,5]};function h5(r,e){if(r==="china"){var t=f5[e.name];if(t){var a=e.getCenter();a[0]+=t[0]/10.5,a[1]+=-t[1]/(10.5/.75),e.setCenter(a)}}}var v5=[[[123.45165252685547,25.73527164402261],[123.49731445312499,25.73527164402261],[123.49731445312499,25.750734064600884],[123.45165252685547,25.750734064600884],[123.45165252685547,25.73527164402261]]];function c5(r,e){r==="china"&&e.name==="台湾"&&e.geometries.push({type:"polygon",exterior:v5[0]})}var p5="name",d5=function(){function r(e,t,a){this.type="geoJSON",this._parsedMap=$(),this._mapName=e,this._specialAreas=a,this._geoJSON=y5(t)}return r.prototype.load=function(e,t){t=t||p5;var a=this._parsedMap.get(t);if(!a){var n=this._parseToRegions(t);a=this._parsedMap.set(t,{regions:n,boundingRect:g5(n)})}var i=$(),o=[];return D(a.regions,function(s){var l=s.name;e&&Z(e,l)&&(s=s.cloneShallow(l=e[l])),o.push(s),i.set(l,s)}),{regions:o,boundingRect:a.boundingRect||new ht(0,0,0,0),regionsMap:i}},r.prototype._parseToRegions=function(e){var t=this._mapName,a=this._geoJSON,n;try{n=a?nB(a,e):[]}catch(i){throw new Error(`Invalid geoJson format
|
||||
`+i.message)}return u5(t,n),D(n,function(i){var o=i.name;h5(t,i),c5(t,i);var s=this._specialAreas&&this._specialAreas[o];s&&i.transformTo(s.left,s.top,s.width,s.height)},this),n},r.prototype.getMapForUser=function(){return{geoJson:this._geoJSON,geoJSON:this._geoJSON,specialAreas:this._specialAreas}},r}();function g5(r){for(var e,t=0;t<r.length;t++){var a=r[t].getBoundingRect();e=e||a.clone(),e.union(a)}return e}function y5(r){return Y(r)?typeof JSON<"u"&&JSON.parse?JSON.parse(r):new Function("return ("+r+");")():r}var Ko=$();const ca={registerMap:function(r,e,t){if(e.svg){var a=new o5(r,e.svg);Ko.set(r,a)}else{var n=e.geoJson||e.geoJSON;n&&!e.features?t=e.specialAreas:n=e;var a=new d5(r,n,t);Ko.set(r,a)}},getGeoResource:function(r){return Ko.get(r)},getMapForUser:function(r){var e=Ko.get(r);return e&&e.type==="geoJSON"&&e.getMapForUser()},load:function(r,e,t){var a=Ko.get(r);if(a)return a.load(e,t)}};var fy=["rect","circle","line","ellipse","polygon","polyline","path"],m5=$(fy),_5=$(fy.concat(["g"])),S5=$(fy.concat(["g"])),FD=xt();function gu(r){var e=r.getItemStyle(),t=r.get("areaColor");return t!=null&&(e.fill=t),e}function j1(r){var e=r.style;e&&(e.stroke=e.stroke||e.fill,e.fill=null)}var HD=function(){function r(e){var t=new at;this.uid=So("ec_map_draw"),this._controller=new Dl(e.getZr()),this._controllerHost={target:t},this.group=t,t.add(this._regionsGroup=new at),t.add(this._svgGroup=new at)}return r.prototype.draw=function(e,t,a,n,i){var o=e.mainType==="geo",s=e.getData&&e.getData();o&&t.eachComponent({mainType:"series",subType:"map"},function(y){!s&&y.getHostGeoModel()===e&&(s=y.getData())});var l=e.coordinateSystem,u=this._regionsGroup,f=this.group,h=l.getTransformInfo(),v=h.raw,c=h.roam,p=!u.childAt(0)||i;p?(f.x=c.x,f.y=c.y,f.scaleX=c.scaleX,f.scaleY=c.scaleY,f.dirty()):Tt(f,c,e);var d=s&&s.getVisual("visualMeta")&&s.getVisual("visualMeta").length>0,g={api:a,geo:l,mapOrGeoModel:e,data:s,isVisualEncodedByVisualMap:d,isGeo:o,transformInfoRaw:v};l.resourceType==="geoJSON"?this._buildGeoJSON(g):l.resourceType==="geoSVG"&&this._buildSVG(g),this._updateController(e,t,a),this._updateMapSelectHandler(e,u,a,n)},r.prototype._buildGeoJSON=function(e){var t=this._regionsGroupByName=$(),a=$(),n=this._regionsGroup,i=e.transformInfoRaw,o=e.mapOrGeoModel,s=e.data,l=e.geo.projection,u=l&&l.stream;function f(c,p){return p&&(c=p(c)),c&&[c[0]*i.scaleX+i.x,c[1]*i.scaleY+i.y]}function h(c){for(var p=[],d=!u&&l&&l.project,g=0;g<c.length;++g){var y=f(c[g],d);y&&p.push(y)}return p}function v(c){return{shape:{points:h(c)}}}n.removeAll(),D(e.geo.regions,function(c){var p=c.name,d=t.get(p),g=a.get(p)||{},y=g.dataIdx,m=g.regionModel;if(!d){d=t.set(p,new at),n.add(d),y=s?s.indexOfName(p):null,m=e.isGeo?o.getRegionModel(p):s?s.getItemModel(y):null;var _=m.get("silent",!0);_!=null&&(d.silent=_),a.set(p,{dataIdx:y,regionModel:m})}var S=[],b=[];D(c.geometries,function(T){if(T.type==="polygon"){var A=[T.exterior].concat(T.interiors||[]);u&&(A=iS(A,u)),D(A,function(M){S.push(new Ie(v(M)))})}else{var C=T.points;u&&(C=iS(C,u,!0)),D(C,function(M){b.push(new Le(v(M)))})}});var x=f(c.getCenter(),l&&l.project);function w(T,A){if(T.length){var C=new Sg({culling:!0,segmentIgnoreThreshold:1,shape:{paths:T}});d.add(C),tS(e,C,y,m),eS(e,C,p,m,o,y,x),A&&(j1(C),D(C.states,j1))}}w(S),w(b,!0)}),t.each(function(c,p){var d=a.get(p),g=d.dataIdx,y=d.regionModel;rS(e,c,p,y,o,g),aS(e,c,p,y,o),nS(e,c,p,y,o)},this)},r.prototype._buildSVG=function(e){var t=e.geo.map,a=e.transformInfoRaw;this._svgGroup.x=a.x,this._svgGroup.y=a.y,this._svgGroup.scaleX=a.scaleX,this._svgGroup.scaleY=a.scaleY,this._svgResourceChanged(t)&&(this._freeSVG(),this._useSVG(t));var n=this._svgDispatcherMap=$(),i=!1;D(this._svgGraphicRecord.named,function(o){var s=o.name,l=e.mapOrGeoModel,u=e.data,f=o.svgNodeTagLower,h=o.el,v=u?u.indexOfName(s):null,c=l.getRegionModel(s);m5.get(f)!=null&&h instanceof or&&tS(e,h,v,c),h instanceof or&&(h.culling=!0);var p=c.get("silent",!0);if(p!=null&&(h.silent=p),h.z2EmphasisLift=0,!o.namedFrom&&(S5.get(f)!=null&&eS(e,h,s,c,l,v,null),rS(e,h,s,c,l,v),aS(e,h,s,c,l),_5.get(f)!=null)){var d=nS(e,h,s,c,l);d==="self"&&(i=!0);var g=n.get(s)||n.set(s,[]);g.push(h)}},this),this._enableBlurEntireSVG(i,e)},r.prototype._enableBlurEntireSVG=function(e,t){if(e&&t.isGeo){var a=t.mapOrGeoModel.getModel(["blur","itemStyle"]).getItemStyle(),n=a.opacity;this._svgGraphicRecord.root.traverse(function(i){if(!i.isGroup){ni(i);var o=i.ensureState("blur").style||{};o.opacity==null&&n!=null&&(o.opacity=n),i.ensureState("emphasis")}})}},r.prototype.remove=function(){this._regionsGroup.removeAll(),this._regionsGroupByName=null,this._svgGroup.removeAll(),this._freeSVG(),this._controller.dispose(),this._controllerHost=null},r.prototype.findHighDownDispatchers=function(e,t){if(e==null)return[];var a=t.coordinateSystem;if(a.resourceType==="geoJSON"){var n=this._regionsGroupByName;if(n){var i=n.get(e);return i?[i]:[]}}else if(a.resourceType==="geoSVG")return this._svgDispatcherMap&&t
Line truncated
|
||||
`))}),e.join(`
|
||||
|
||||
`+kh+`
|
||||
|
||||
`)}function R6(r){return G(r,function(e){var t=e.getRawData(),a=[e.name],n=[];return t.each(t.dimensions,function(){for(var i=arguments.length,o=arguments[i-1],s=t.getName(o),l=0;l<i-1;l++)n[l]=arguments[l];a.push((s?s+ho:"")+n.join(ho))}),a.join(`
|
||||
`)}).join(`
|
||||
|
||||
`+kh+`
|
||||
|
||||
`)}function E6(r){var e=L6(r);return{value:Ct([P6(e.seriesGroupByCategoryAxis),R6(e.other)],function(t){return!!t.replace(/[\n\t\s]/g,"")}).join(`
|
||||
|
||||
`+kh+`
|
||||
|
||||
`),meta:e.meta}}function Gf(r){return r.replace(/^\s\s*/,"").replace(/\s\s*$/,"")}function k6(r){var e=r.slice(0,r.indexOf(`
|
||||
`));if(e.indexOf(ho)>=0)return!0}var Nd=new RegExp("["+ho+"]+","g");function O6(r){for(var e=r.split(/\n+/g),t=Gf(e.shift()).split(Nd),a=[],n=G(t,function(l){return{name:l,data:[]}}),i=0;i<e.length;i++){var o=Gf(e[i]).split(Nd);a.push(o.shift());for(var s=0;s<o.length;s++)n[s]&&(n[s].data[i]=o[s])}return{series:n,categories:a}}function N6(r){for(var e=r.split(/\n+/g),t=Gf(e.shift()),a=[],n=0;n<e.length;n++){var i=Gf(e[n]);if(i){var o=i.split(Nd),s="",l=void 0,u=!1;isNaN(o[0])?(u=!0,s=o[0],o=o.slice(1),a[n]={name:s,value:[]},l=a[n].value):l=a[n]=[];for(var f=0;f<o.length;f++)l.push(+o[f]);l.length===1&&(u?a[n].value=l[0]:a[n]=l[0])}}return{name:t,data:a}}function B6(r,e){var t=r.split(new RegExp(`
|
||||
*`+kh+`
|
||||
*`,"g")),a={series:[]};return D(t,function(n,i){if(k6(n)){var o=O6(n),s=e[i],l=s.axisDim+"Axis";s&&(a[l]=a[l]||[],a[l][s.axisIndex]={data:o.categories},a.series=a.series.concat(o.series))}else{var o=N6(n);a.series.push(o)}}),a}var V6=function(r){k(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.onclick=function(t,a){setTimeout(function(){a.dispatchAction({type:"hideTip"})});var n=a.getDom(),i=this.model;this._dom&&n.removeChild(this._dom);var o=document.createElement("div");o.style.cssText="position:absolute;top:0;bottom:0;left:0;right:0;padding:5px",o.style.backgroundColor=i.get("backgroundColor")||"#fff";var s=document.createElement("h4"),l=i.get("lang")||[];s.innerHTML=l[0]||i.get("title"),s.style.cssText="margin:10px 20px",s.style.color=i.get("textColor");var u=document.createElement("div"),f=document.createElement("textarea");u.style.cssText="overflow:auto";var h=i.get("optionToContent"),v=i.get("contentToOption"),c=E6(t);if(J(h)){var p=h(a.getOption());Y(p)?u.innerHTML=p:eo(p)&&u.appendChild(p)}else{f.readOnly=i.get("readOnly");var d=f.style;d.cssText="display:block;width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;resize:none;box-sizing:border-box;outline:none",d.color=i.get("textColor"),d.borderColor=i.get("textareaBorderColor"),d.backgroundColor=i.get("textareaColor"),f.value=c.value,u.appendChild(f)}var g=c.meta,y=document.createElement("div");y.style.cssText="position:absolute;bottom:5px;left:0;right:0";var m="float:right;margin-right:20px;border:none;cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px",_=document.createElement("div"),S=document.createElement("div");m+=";background-color:"+i.get("buttonColor"),m+=";color:"+i.get("buttonTextColor");var b=this;function x(){n.removeChild(o),b._dom=null}pp(_,"click",x),pp(S,"click",function(){if(v==null&&h!=null||v!=null&&h==null){x();return}var w;try{J(v)?w=v(u,a.getOption()):w=B6(f.value,g)}catch(T){throw x(),new Error("Data view format error "+T)}w&&a.dispatchAction({type:"changeDataView",newOption:w}),x()}),_.innerHTML=l[1],S.innerHTML=l[2],S.style.cssText=_.style.cssText=m,!i.get("readOnly")&&y.appendChild(S),y.appendChild(_),o.appendChild(s),o.appendChild(u),o.appendChild(y),u.style.height=n.clientHeight-80+"px",n.appendChild(o),this._dom=o},e.prototype.remove=function(t,a){this._dom&&a.getDom().removeChild(this._dom)},e.prototype.dispose=function(t,a){this.remove(t,a)},e.getDefaultOption=function(t){var a={show:!0,readOnly:!1,optionToContent:null,contentToOption:null,icon:"M17.5,17.3H33 M17.5,17.3H33 M45.4,29.5h-28 M11.5,2v56H51V14.8L38.4,2H11.5z M38.4,2.2v12.7H51 M45.4,41.7h-28",title:t.getLocaleModel().get(["toolbox","dataView","title"]),lang:t.getLocaleModel().get(["toolbox","dataView","lang"]),backgroundColor:"#fff",textColor:"#000",textareaColor:"#fff",textareaBorderColor:"#333",buttonColor:"#c23531",buttonTextColor:"#fff"};return a},e}(er);function z6(r,e){return G(r,function(t,a){var n=e&&e[a];if(et(n)&&!z(n)){var i=et(t)&&!z(t);i||(t={value:t});var o=n.name!=null&&t.name==null;return t=j(t,n),o&&delete t.name,t}else return t})}Xr({type:"changeDataView",event:"dataViewChanged",update:"prepareAndUpdate"},function(r,e){var t=[];D(r.newOption.series,function(a){var n=e.getSeriesByName(a.name)[0];if(!n)t.push(V({type:"scatter"},a));else{var i=n.get("data");t.push({name:a.name,data:z6(a.data,i)})}}),e.mergeOption(j({series:t},r.newOption))});var mI=D,_I=xt();function G6(r,e){var t=Zy(r);mI(e,function(a,n){for(var i=t.length-1;i>=0;i--){var o=t[i];if(o[n])break}if(i<0){var s=r.queryComponents({mainType:"dataZoom",subType:"select",id:n})[0];if(s){var l=s.getPercentRange();t[0][n]={dataZoomId:n,start:l[0],end:l[1]}}}}),t.push(e)}function F6(r){var e=Zy(r),t=e[e.length-1];e.length>1&&e.pop();var a={};return mI(t,function(n,i){for(var o=e.length-1;o>=0;o--)if(n=e[o][i],n){a[i]=n;break}}),a}function H6(r){_I(r).snapshots=null}function W6(r){return Zy(r).length}function Zy(r){var e=_I(r);return e.snapshots||(e.snapshots=[{}]),e.snapshots}var U6=function(r){k(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.onclick=function(t,a){H6(t),a.dispatchAction({type:"restore",from:this.uid})},e.getDefaultOption=function(t){var a={show:!0,icon:"M3.8,33.4 M47,18.9h9.8V8.7 M56.3,20.1 C52.1,9,40.5,0.6,26.8,2.1C12.6,3.7,1.6,16.2,2.1,30.6 M13,41.1H3.1v10.2 M3.7,39.9c4.2,11.1,15.8,19.5,29.5,18 c14.2-1.6,25.2-14.1,24.7-28.5",title:t.getLocaleModel().get(["toolbox","restore","title"])};return a},e}(er);Xr({type:"restore",event:"restore",update:"prepareAndUpdate"},function(r,e){e.resetOption("recreate")});var Y6=["grid","xAxis","yAxis","geo","graph","polar","radiusAxis","angleAxis","bmap"],$y=function(){function r(e,t,a){var n=this;this._targetInfoList=[];var i=Qx(t,e);D(X6,function(o,s){(!a||!a.include||ct(a.include,s)>=0)&&o(i,n._targetInfoList)})}return r.prototype.setOutputRanges=function(e,t){return this.matchOutputRanges(e,t,function(a,n,i){if((a.coor
Line truncated
|
||||
|
||||
`:"<br/>",y=h.join(g);this._showOrMove(s,function(){this._updateContentNotChangedOnAxis(t,u)?this._updatePosition(s,c,o[0],o[1],this._tooltipContent,u):this._showTooltipContent(s,y,u,Math.random()+"",o[0],o[1],c,null,v)})},e.prototype._showSeriesItemTooltip=function(t,a,n){var i=this._ecModel,o=nt(a),s=o.seriesIndex,l=i.getSeriesByIndex(s),u=o.dataModel||l,f=o.dataIndex,h=o.dataType,v=u.getData(h),c=this._renderMode,p=t.positionDefault,d=ts([v.getItemModel(f),u,l&&(l.coordinateSystem||{}).model],this._tooltipModel,p?{position:p}:null),g=d.get("trigger");if(!(g!=null&&g!=="item")){var y=u.getDataParams(f,h),m=new Lv;y.marker=m.makeTooltipMarker("item",ii(y.color),c);var _=$0(u.formatTooltip(f,!1,h)),S=d.get("order"),b=d.get("valueFormatter"),x=_.frag,w=x?t_(b?V({valueFormatter:b},x):x,m,c,S,i.get("useUTC"),d.get("textStyle")):_.text,T="item_"+u.name+"_"+f;this._showOrMove(d,function(){this._showTooltipContent(d,w,y,T,t.offsetX,t.offsetY,t.position,t.target,m)}),n({type:"showTip",dataIndexInside:f,dataIndex:v.getRawIndex(f),seriesIndex:s,from:this.uid})}},e.prototype._showComponentItemTooltip=function(t,a,n){var i=this._renderMode==="html",o=nt(a),s=o.tooltipConfig,l=s.option||{},u=l.encodeHTMLContent;if(Y(l)){var f=l;l={content:f,formatter:f},u=!0}u&&i&&l.content&&(l=rt(l),l.content=we(l.content));var h=[l],v=this._ecModel.getComponent(o.componentMainType,o.componentIndex);v&&h.push(v),h.push({formatter:l.content});var c=t.positionDefault,p=ts(h,this._tooltipModel,c?{position:c}:null),d=p.get("content"),g=Math.random()+"",y=new Lv;this._showOrMove(p,function(){var m=rt(p.get("formatterParams")||{});this._showTooltipContent(p,d,m,g,t.offsetX,t.offsetY,t.position,a,y)}),n({type:"showTip",from:this.uid})},e.prototype._showTooltipContent=function(t,a,n,i,o,s,l,u,f){if(this._ticket="",!(!t.get("showContent")||!t.get("show"))){var h=this._tooltipContent;h.setEnterable(t.get("enterable"));var v=t.get("formatter");l=l||t.get("position");var c=a,p=this._getNearestPoint([o,s],n,t.get("trigger"),t.get("borderColor")),d=p.color;if(v)if(Y(v)){var g=t.ecModel.get("useUTC"),y=z(n)?n[0]:n,m=y&&y.axisType&&y.axisType.indexOf("time")>=0;c=v,m&&(c=vh(y.axisValue,c,g)),c=rA(c,n,!0)}else if(J(v)){var _=X(function(S,b){S===this._ticket&&(h.setContent(b,f,t,d,l),this._updatePosition(t,l,o,s,h,n,u))},this);this._ticket=i,c=v(n,i,_)}else c=v;h.setContent(c,f,t,d,l),h.show(t,d),this._updatePosition(t,l,o,s,h,n,u)}},e.prototype._getNearestPoint=function(t,a,n,i){if(n==="axis"||z(a))return{color:i||(this._renderMode==="html"?"#fff":"none")};if(!z(a))return{color:i||a.color||a.borderColor}},e.prototype._updatePosition=function(t,a,n,i,o,s,l){var u=this._api.getWidth(),f=this._api.getHeight();a=a||t.get("position");var h=o.getSize(),v=t.get("align"),c=t.get("verticalAlign"),p=l&&l.getBoundingRect().clone();if(l&&p.applyTransform(l.transform),J(a)&&(a=a([n,i],s,o.el,p,{viewSize:[u,f],contentSize:h.slice()})),z(a))n=W(a[0],u),i=W(a[1],f);else if(et(a)){var d=a;d.width=h[0],d.height=h[1];var g=Qt(d,{width:u,height:f});n=g.x,i=g.y,v=null,c=null}else if(Y(a)&&l){var y=gU(a,p,h,t.get("borderWidth"));n=y[0],i=y[1]}else{var y=pU(n,i,o,u,f,v?null:20,c?null:20);n=y[0],i=y[1]}if(v&&(n-=fb(v)?h[0]/2:v==="right"?h[0]:0),c&&(i-=fb(c)?h[1]/2:c==="bottom"?h[1]:0),SI(t)){var y=dU(n,i,o,u,f);n=y[0],i=y[1]}o.moveTo(n,i)},e.prototype._updateContentNotChangedOnAxis=function(t,a){var n=this._lastDataByCoordSys,i=this._cbParamsList,o=!!n&&n.length===t.length;return o&&D(n,function(s,l){var u=s.dataByAxis||[],f=t[l]||{},h=f.dataByAxis||[];o=o&&u.length===h.length,o&&D(u,function(v,c){var p=h[c]||{},d=v.seriesDataIndices||[],g=p.seriesDataIndices||[];o=o&&v.value===p.value&&v.axisType===p.axisType&&v.axisId===p.axisId&&d.length===g.length,o&&D(d,function(y,m){var _=g[m];o=o&&y.seriesIndex===_.seriesIndex&&y.dataIndex===_.dataIndex}),i&&D(v.seriesDataIndices,function(y){var m=y.seriesIndex,_=a[m],S=i[m];_&&S&&S.data!==_.data&&(o=!1)})})}),this._lastDataByCoordSys=t,this._cbParamsList=a,!!o},e.prototype._hide=function(t){this._lastDataByCoordSys=null,t({type:"hideTip",from:this.uid})},e.prototype.dispose=function(t,a){yt.node||!a.getDom()||(Xs(this,"_updatePosition"),this._tooltipContent.dispose(),Ed("itemTooltip",a))},e.type="tooltip",e}(Ft);function ts(r,e,t){var a=e.ecModel,n;t?(n=new Mt(t,a,a),n=new Mt(e.option,n,a)):n=e;for(var i=r.length-1;i>=0;i--){var o=r[i];o&&(o instanceof Mt&&(o=o.get("tooltip",!0)),Y(o)&&(o={formatter:o}),o&&(n=new Mt(o,n,a)))}return n}function ub(r,e){return r.dispatchAction||X(e.dispatchAction,e)}function pU(r,e,t,a,n,i,o){var s=t.getSize(),l=s[0],u=s[1];return i!=null&&(r+l+i+2>a?r-=l+i:r+=i),o!=null&&(e+u+o>n?e-=u+o:e+=o),[r,e]}function dU(r,e,t,a,n){var i=t.getSize(),o=i[0],s=i[1];return r=Math.min(r+o,a)-o,e=Math.min(e+s,n)-s,r=Math.max(r,0),e=Math.max(e,0),[r,e]}function gU(r,e,t,a){var n=t[0],i=t[1],o=Math.ceil(Math.SQRT2*a)+8,s=0,l=0,u=e.width,f=e.height;switch(r){case"inside":s=e.x+u/2-n/2,l=e.y+f/2-i/2;break;case"top":s=e.x
Line truncated
|
||||
`)){var g=new Pu;g.newline=!0,u.add(g);return}var y=n.getSeriesByName(d)[0];if(!f.get(d))if(y){var m=y.getData(),_=m.getVisual("legendLineStyle")||{},S=m.getVisual("legendIcon"),b=m.getVisual("style"),x=this._createItem(y,d,p,c,a,t,_,b,S,h,i);x.on("click",Ni(Ib,d,null,i,v)).on("mouseover",Ni(Ud,y.name,null,i,v)).on("mouseout",Ni(Yd,y.name,null,i,v)),n.ssr&&x.eachChild(function(w){var T=nt(w);T.seriesIndex=y.seriesIndex,T.dataIndex=p,T.ssrType="legend"}),f.set(d,!0)}else n.eachRawSeries(function(w){if(!f.get(d)&&w.legendVisualProvider){var T=w.legendVisualProvider;if(!T.containName(d))return;var A=T.indexOfName(d),C=T.getItemVisual(A,"style"),M=T.getItemVisual(A,"legendIcon"),I=We(C.fill);I&&I[3]===0&&(I[3]=.2,C=V(V({},C),{fill:na(I,"rgba")}));var L=this._createItem(w,d,p,c,a,t,{},C,M,h,i);L.on("click",Ni(Ib,null,d,i,v)).on("mouseover",Ni(Ud,null,d,i,v)).on("mouseout",Ni(Yd,null,d,i,v)),n.ssr&&L.eachChild(function(P){var R=nt(P);R.seriesIndex=w.seriesIndex,R.dataIndex=p,R.ssrType="legend"}),f.set(d,!0)}},this)},this),o&&this._createSelector(o,a,i,s,l)},e.prototype._createSelector=function(t,a,n,i,o){var s=this.getSelectorGroup();Wd(t,function(u){var f=u.type,h=new bt({style:{x:0,y:0,align:"center",verticalAlign:"middle"},onclick:function(){n.dispatchAction({type:f==="all"?"legendAllSelect":"legendInverseSelect",legendId:a.id})}});s.add(h);var v=a.getModel("selectorLabel"),c=a.getModel(["emphasis","selectorLabel"]);ve(h,{normal:v,emphasis:c},{defaultText:u.title}),Kn(h)})},e.prototype._createItem=function(t,a,n,i,o,s,l,u,f,h,v){var c=t.visualDrawType,p=o.get("itemWidth"),d=o.get("itemHeight"),g=o.isSelected(a),y=i.get("symbolRotate"),m=i.get("symbolKeepAspect"),_=i.get("icon");f=_||f||"roundRect";var S=d8(f,i,l,u,c,g,v),b=new Pu,x=i.getModel("textStyle");if(J(t.getLegendIcon)&&(!_||_==="inherit"))b.add(t.getLegendIcon({itemWidth:p,itemHeight:d,icon:f,iconRotate:y,itemStyle:S.itemStyle,lineStyle:S.lineStyle,symbolKeepAspect:m}));else{var w=_==="inherit"&&t.getData().getVisual("symbol")?y==="inherit"?t.getData().getVisual("symbolRotate"):y:0;b.add(g8({itemWidth:p,itemHeight:d,icon:f,iconRotate:w,itemStyle:S.itemStyle,symbolKeepAspect:m}))}var T=s==="left"?p+5:-5,A=s,C=o.get("formatter"),M=a;Y(C)&&C?M=C.replace("{name}",a??""):J(C)&&(M=C(a));var I=g?x.getTextColor():i.get("inactiveColor");b.add(new bt({style:Bt(x,{text:M,x:T,y:d/2,fill:I,align:A,verticalAlign:"middle"},{inheritColor:I})}));var L=new St({shape:b.getBoundingRect(),style:{fill:"transparent"}}),P=i.getModel("tooltip");return P.get("show")&&fi({el:L,componentModel:o,itemName:a,itemTooltipOption:P.option}),b.add(L),b.eachChild(function(R){R.silent=!0}),L.silent=!h,this.getContentGroup().add(b),Kn(b),b.__legendDataIndex=n,b},e.prototype.layoutInner=function(t,a,n,i,o,s){var l=this.getContentGroup(),u=this.getSelectorGroup();Qn(t.get("orient"),l,t.get("itemGap"),n.width,n.height);var f=l.getBoundingRect(),h=[-f.x,-f.y];if(u.markRedraw(),l.markRedraw(),o){Qn("horizontal",u,t.get("selectorItemGap",!0));var v=u.getBoundingRect(),c=[-v.x,-v.y],p=t.get("selectorButtonGap",!0),d=t.getOrient().index,g=d===0?"width":"height",y=d===0?"height":"width",m=d===0?"y":"x";s==="end"?c[d]+=f[g]+p:h[d]+=v[g]+p,c[1-d]+=f[y]/2-v[y]/2,u.x=c[0],u.y=c[1],l.x=h[0],l.y=h[1];var _={x:0,y:0};return _[g]=f[g]+p+v[g],_[y]=Math.max(f[y],v[y]),_[m]=Math.min(0,v[m]+c[1-d]),_}else return l.x=h[0],l.y=h[1],this.group.getBoundingRect()},e.prototype.remove=function(){this.getContentGroup().removeAll(),this._isFirstRender=!0},e.type="legend.plain",e}(Ft);function d8(r,e,t,a,n,i,o){function s(g,y){g.lineWidth==="auto"&&(g.lineWidth=y.lineWidth>0?2:0),Wd(g,function(m,_){g[_]==="inherit"&&(g[_]=y[_])})}var l=e.getModel("itemStyle"),u=l.getItemStyle(),f=r.lastIndexOf("empty",0)===0?"fill":"stroke",h=l.getShallow("decal");u.decal=!h||h==="inherit"?a.decal:io(h,o),u.fill==="inherit"&&(u.fill=a[n]),u.stroke==="inherit"&&(u.stroke=a[f]),u.opacity==="inherit"&&(u.opacity=(n==="fill"?a:t).opacity),s(u,a);var v=e.getModel("lineStyle"),c=v.getLineStyle();if(s(c,t),u.fill==="auto"&&(u.fill=a.fill),u.stroke==="auto"&&(u.stroke=a.fill),c.stroke==="auto"&&(c.stroke=a.fill),!i){var p=e.get("inactiveBorderWidth"),d=u[f];u.lineWidth=p==="auto"?a.lineWidth>0&&d?2:0:u.lineWidth,u.fill=e.get("inactiveColor"),u.stroke=e.get("inactiveBorderColor"),c.stroke=v.get("inactiveColor"),c.lineWidth=v.get("inactiveWidth")}return{itemStyle:u,lineStyle:c}}function g8(r){var e=r.icon||"roundRect",t=qt(e,0,0,r.itemWidth,r.itemHeight,r.itemStyle.fill,r.symbolKeepAspect);return t.setStyle(r.itemStyle),t.rotation=(r.iconRotate||0)*Math.PI/180,t.setOrigin([r.itemWidth/2,r.itemHeight/2]),e.indexOf("empty")>-1&&(t.style.stroke=t.style.fill,t.style.fill="#fff",t.style.lineWidth=2),t}function Ib(r,e,t,a){Yd(r,e,t,a),t.dispatchAction({type:"legendToggleSelect",name:r??e}),Ud(r,e,t,a)}function LI(r){for(var e=r.getZr().storage.getDisplayList(),t,a=0,n=e.length;a<n&&!(t=e[a].states.emphasis);)a++;return t&&t.hoverLayer}function Ud(r,e,
Line truncated
|
||||
`||n==="")){var i=r.isSelected(n);Z(t,n)?t[n]=t[n]&&i:t[n]=i}}),t}function m8(r){r.registerAction("legendToggleSelect","legendselectchanged",lt(rs,"toggleSelected")),r.registerAction("legendAllSelect","legendselectall",lt(rs,"allSelect")),r.registerAction("legendInverseSelect","legendinverseselect",lt(rs,"inverseSelect")),r.registerAction("legendSelect","legendselected",lt(rs,"select")),r.registerAction("legendUnSelect","legendunselected",lt(rs,"unSelect"))}function PI(r){r.registerComponentModel(Hd),r.registerComponentView(II),r.registerProcessor(r.PRIORITY.PROCESSOR.SERIES_FILTER,y8),r.registerSubTypeDefaulter("legend",function(){return"plain"}),m8(r)}var _8=function(r){k(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t}return e.prototype.setScrollDataIndex=function(t){this.option.scrollDataIndex=t},e.prototype.init=function(t,a,n){var i=bo(t);r.prototype.init.call(this,t,a,n),Pb(this,t,i)},e.prototype.mergeOption=function(t,a){r.prototype.mergeOption.call(this,t,a),Pb(this,this.option,t)},e.type="legend.scroll",e.defaultOption=tn(Hd.defaultOption,{scrollDataIndex:0,pageButtonItemGap:5,pageButtonGap:null,pageButtonPosition:"end",pageFormatter:"{current}/{total}",pageIcons:{horizontal:["M0,0L12,-10L12,10z","M0,0L-12,-10L-12,10z"],vertical:["M0,0L20,0L10,-20z","M0,0L20,0L10,20z"]},pageIconColor:"#2f4554",pageIconInactiveColor:"#aaa",pageIconSize:15,pageTextStyle:{color:"#333"},animationDurationUpdate:800}),e}(Hd);function Pb(r,e,t){var a=r.getOrient(),n=[1,1];n[a.index]=0,qa(e,t,{type:"box",ignoreSize:!!n})}var Rb=at,Jc=["width","height"],Qc=["x","y"],S8=function(r){k(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.type=e.type,t.newlineDisabled=!0,t._currentIndex=0,t}return e.prototype.init=function(){r.prototype.init.call(this),this.group.add(this._containerGroup=new Rb),this._containerGroup.add(this.getContentGroup()),this.group.add(this._controllerGroup=new Rb)},e.prototype.resetInner=function(){r.prototype.resetInner.call(this),this._controllerGroup.removeAll(),this._containerGroup.removeClipPath(),this._containerGroup.__rectSize=null},e.prototype.renderInner=function(t,a,n,i,o,s,l){var u=this;r.prototype.renderInner.call(this,t,a,n,i,o,s,l);var f=this._controllerGroup,h=a.get("pageIconSize",!0),v=z(h)?h:[h,h];p("pagePrev",0);var c=a.getModel("pageTextStyle");f.add(new bt({name:"pageText",style:{text:"xx/xx",fill:c.getTextColor(),font:c.getFont(),verticalAlign:"middle",align:"center"},silent:!0})),p("pageNext",1);function p(d,g){var y=d+"DataIndex",m=gl(a.get("pageIcons",!0)[a.getOrient().name][g],{onclick:X(u._pageGo,u,y,a,i)},{x:-v[0]/2,y:-v[1]/2,width:v[0],height:v[1]});m.name=d,f.add(m)}},e.prototype.layoutInner=function(t,a,n,i,o,s){var l=this.getSelectorGroup(),u=t.getOrient().index,f=Jc[u],h=Qc[u],v=Jc[1-u],c=Qc[1-u];o&&Qn("horizontal",l,t.get("selectorItemGap",!0));var p=t.get("selectorButtonGap",!0),d=l.getBoundingRect(),g=[-d.x,-d.y],y=rt(n);o&&(y[f]=n[f]-d[f]-p);var m=this._layoutContentAndController(t,i,y,u,f,v,c,h);if(o){if(s==="end")g[u]+=m[f]+p;else{var _=d[f]+p;g[u]-=_,m[h]-=_}m[f]+=d[f]+p,g[1-u]+=m[c]+m[v]/2-d[v]/2,m[v]=Math.max(m[v],d[v]),m[c]=Math.min(m[c],d[c]+g[1-u]),l.x=g[0],l.y=g[1],l.markRedraw()}return m},e.prototype._layoutContentAndController=function(t,a,n,i,o,s,l,u){var f=this.getContentGroup(),h=this._containerGroup,v=this._controllerGroup;Qn(t.get("orient"),f,t.get("itemGap"),i?n.width:null,i?null:n.height),Qn("horizontal",v,t.get("pageButtonItemGap",!0));var c=f.getBoundingRect(),p=v.getBoundingRect(),d=this._showController=c[o]>n[o],g=[-c.x,-c.y];a||(g[i]=f[u]);var y=[0,0],m=[-p.x,-p.y],_=st(t.get("pageButtonGap",!0),t.get("itemGap",!0));if(d){var S=t.get("pageButtonPosition",!0);S==="end"?m[i]+=n[o]-p[o]:y[i]+=p[o]+_}m[1-i]+=c[s]/2-p[s]/2,f.setPosition(g),h.setPosition(y),v.setPosition(m);var b={x:0,y:0};if(b[o]=d?n[o]:c[o],b[s]=Math.max(c[s],p[s]),b[l]=Math.min(0,p[l]+m[1-i]),h.__rectSize=n[o],d){var x={x:0,y:0};x[o]=Math.max(n[o]-p[o]-_,0),x[s]=b[s],h.setClipPath(new St({shape:x})),h.__rectSize=x[o]}else v.eachChild(function(T){T.attr({invisible:!0,silent:!0})});var w=this._getPageInfo(t);return w.pageIndex!=null&&Tt(f,{x:w.contentPosition[0],y:w.contentPosition[1]},d?t:null),this._updatePageInfoView(t,w),b},e.prototype._pageGo=function(t,a,n){var i=this._getPageInfo(a)[t];i!=null&&n.dispatchAction({type:"legendScroll",scrollDataIndex:i,legendId:a.id})},e.prototype._updatePageInfoView=function(t,a){var n=this._controllerGroup;D(["pagePrev","pageNext"],function(f){var h=f+"DataIndex",v=a[h]!=null,c=n.childOfName(f);c&&(c.setStyle("fill",v?t.get("pageIconColor",!0):t.get("pageIconInactiveColor",!0)),c.cursor=v?"pointer":"default")});var i=n.childOfName("pageText"),o=t.get("pageFormatter"),s=a.pageIndex,l=s!=null?s+1:0,u=a.pageCount;i&&o&&i.setStyle("text",Y(o)?o.replace("{current}",l==null?"":l+"").replace("{total}",u==null?"":u+""):o({current:l,total:u}))},e.prototype._getPageInfo=function(t){var a=t.get("
Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
.stat-card[data-v-a79a1efd]{text-align:center;border-radius:10px;transition:transform .2s;margin-bottom:12px}.stat-card[data-v-a79a1efd]:hover{transform:translateY(-2px)}.stat-icon[data-v-a79a1efd]{margin-bottom:8px}.stat-value[data-v-a79a1efd]{font-size:26px;font-weight:700;margin-bottom:6px;font-family:Helvetica Neue,Arial,sans-serif}.stat-label[data-v-a79a1efd]{color:#909399;font-size:13px}.chart-card[data-v-a79a1efd]{border-radius:10px}.chart-header[data-v-a79a1efd]{font-size:15px;font-weight:600;display:flex;align-items:center;gap:6px}
|
||||
@@ -0,0 +1 @@
|
||||
.login-container[data-v-a0131caf]{min-height:100vh;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#1a1a2e,#16213e,#0f3460);position:relative;overflow:hidden}.login-bg[data-v-a0131caf]{position:absolute;top:0;right:0;bottom:0;left:0;overflow:hidden}.bg-circle[data-v-a0131caf]{position:absolute;border-radius:50%;opacity:.06;background:#409eff}.bg-circle.c1[data-v-a0131caf]{width:500px;height:500px;top:-150px;right:-100px}.bg-circle.c2[data-v-a0131caf]{width:300px;height:300px;bottom:-80px;left:-80px}.bg-circle.c3[data-v-a0131caf]{width:200px;height:200px;top:40%;left:60%}.login-card[data-v-a0131caf]{position:relative;width:400px;padding:48px 40px 36px;background:#fff;border-radius:16px;box-shadow:0 24px 80px #00000040;z-index:1}.login-icon[data-v-a0131caf]{text-align:center;margin-bottom:12px}.login-title[data-v-a0131caf]{text-align:center;color:#1a1a2e;font-size:26px;font-weight:700;margin-bottom:4px;letter-spacing:2px}.login-subtitle[data-v-a0131caf]{text-align:center;color:#909399;font-size:14px;margin-bottom:32px}.login-form[data-v-a0131caf] .el-input__wrapper{border-radius:8px}
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as b,o as E,c as V,a as o,b as s,w as l,E as x,d as k,u as h,r as B,e as C,f as F,g as I,h as K,i as L,j as U,k as z,l as m}from"./index-oChIw9ZZ.js";/* empty css *//* empty css */import{u as N}from"./user-DvAOsLmR.js";import"./index-DpFNINBG.js";const R={class:"login-container"},q={class:"login-card"},S={class:"login-icon"},j={__name:"Login",setup(A){const p=h(),f=N(),r=m(!1),t=m(null),a=U({username:"",password:""}),_={username:[{required:!0,message:"请输入用户名",trigger:"blur"}],password:[{required:!0,message:"请输入密码",trigger:"blur"}]};async function u(){t.value&&await t.value.validate(async d=>{if(d){r.value=!0;try{await f.login(a.username,a.password,"admin"),z.success("登录成功"),p.push("/dashboard")}catch{}finally{r.value=!1}}})}return(d,e)=>{const g=B("Key"),v=x,c=F,n=C,w=K,y=k;return E(),V("div",R,[e[5]||(e[5]=o("div",{class:"login-bg"},[o("div",{class:"bg-circle c1"}),o("div",{class:"bg-circle c2"}),o("div",{class:"bg-circle c3"})],-1)),o("div",q,[o("div",S,[s(v,{size:48,color:"#409EFF"},{default:l(()=>[s(g)]),_:1})]),e[3]||(e[3]=o("h2",{class:"login-title"},"CardAuth",-1)),e[4]||(e[4]=o("p",{class:"login-subtitle"},"授权管理系统",-1)),s(y,{ref_key:"formRef",ref:t,model:a,rules:_,size:"large",class:"login-form"},{default:l(()=>[s(n,{prop:"username"},{default:l(()=>[s(c,{modelValue:a.username,"onUpdate:modelValue":e[0]||(e[0]=i=>a.username=i),placeholder:"用户名","prefix-icon":"User",clearable:""},null,8,["modelValue"])]),_:1}),s(n,{prop:"password"},{default:l(()=>[s(c,{modelValue:a.password,"onUpdate:modelValue":e[1]||(e[1]=i=>a.password=i),type:"password",placeholder:"密码","prefix-icon":"Lock","show-password":"",onKeyup:I(u,["enter"])},null,8,["modelValue"])]),_:1}),s(n,null,{default:l(()=>[s(w,{type:"primary",loading:r.value,style:{width:"100%"},size:"large",onClick:u},{default:l(()=>[...e[2]||(e[2]=[L(" 登 录 ",-1)])]),_:1},8,["loading"])]),_:1})]),_:1},8,["model"])])])}}},J=b(j,[["__scopeId","data-v-a0131caf"]]);export{J as default};
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as b,o as E,c as V,a as o,b as s,w as l,E as x,d as k,u as h,r as B,e as C,f as F,g as I,h as K,i as L,j as U,k as z,l as m}from"./index-BpUdMXzZ.js";/* empty css *//* empty css */import{u as N}from"./user-KptFbP1d.js";import"./index-CZCGMR8A.js";const R={class:"login-container"},q={class:"login-card"},S={class:"login-icon"},j={__name:"Login",setup(A){const p=h(),f=N(),r=m(!1),t=m(null),a=U({username:"",password:""}),_={username:[{required:!0,message:"请输入用户名",trigger:"blur"}],password:[{required:!0,message:"请输入密码",trigger:"blur"}]};async function u(){t.value&&await t.value.validate(async d=>{if(d){r.value=!0;try{await f.login(a.username,a.password,"admin"),z.success("登录成功"),p.push("/dashboard")}catch{}finally{r.value=!1}}})}return(d,e)=>{const g=B("Key"),v=x,c=F,n=C,w=K,y=k;return E(),V("div",R,[e[5]||(e[5]=o("div",{class:"login-bg"},[o("div",{class:"bg-circle c1"}),o("div",{class:"bg-circle c2"}),o("div",{class:"bg-circle c3"})],-1)),o("div",q,[o("div",S,[s(v,{size:48,color:"#409EFF"},{default:l(()=>[s(g)]),_:1})]),e[3]||(e[3]=o("h2",{class:"login-title"},"CardAuth",-1)),e[4]||(e[4]=o("p",{class:"login-subtitle"},"授权管理系统",-1)),s(y,{ref_key:"formRef",ref:t,model:a,rules:_,size:"large",class:"login-form"},{default:l(()=>[s(n,{prop:"username"},{default:l(()=>[s(c,{modelValue:a.username,"onUpdate:modelValue":e[0]||(e[0]=i=>a.username=i),placeholder:"用户名","prefix-icon":"User",clearable:""},null,8,["modelValue"])]),_:1}),s(n,{prop:"password"},{default:l(()=>[s(c,{modelValue:a.password,"onUpdate:modelValue":e[1]||(e[1]=i=>a.password=i),type:"password",placeholder:"密码","prefix-icon":"Lock","show-password":"",onKeyup:I(u,["enter"])},null,8,["modelValue"])]),_:1}),s(n,null,{default:l(()=>[s(w,{type:"primary",loading:r.value,style:{width:"100%"},size:"large",onClick:u},{default:l(()=>[...e[2]||(e[2]=[L(" 登 录 ",-1)])]),_:1},8,["loading"])]),_:1})]),_:1},8,["model"])])])}}},J=b(j,[["__scopeId","data-v-a0131caf"]]);export{J as default};
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as ue,o as n,c as I,b as a,w as l,a3 as ce,a5 as pe,a4 as _e,a as o,E as me,n as e,aQ as ge,C as g,aM as fe,q as he,T as be,a9 as U,d as ve,e as we,f as Ce,g as E,aC as ke,h as ye,ac as xe,i as p,ad as P,ae as Se,S as Ee,ag as Ve,ah as De,U as ze,V as Ie,aj as Ue,ak as Pe,F as Ke,R as Fe,P as d,t as Re,al as Le,am as Me,an as Te,K as _,Z as Be,ar as Ne,as as Ye,at as K,D as F,l as R,k as L}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as je,a as $e}from"./useColumnSettings-sXzip_cz.js";import"./index-CZCGMR8A.js";const qe={class:"logs-page"},Oe={class:"stat-card stat-total"},Ae={class:"stat-icon"},He={class:"stat-info"},Qe={class:"stat-value"},We={class:"stat-card stat-today"},Ze={class:"stat-icon"},Ge={class:"stat-info"},Je={class:"stat-value"},Xe={class:"stat-card stat-users"},et={class:"stat-icon"},tt={class:"stat-info"},at={class:"stat-value"},lt={class:"advanced-search"},ot={class:"toolbar"},st={class:"toolbar-left"},nt={class:"toolbar-right"},it={class:"column-settings"},dt={class:"pagination-wrapper"},rt={__name:"Logs",setup(ut){const w=R(!0),V=R([]),{list:k,loading:M,page:y,pageSize:x,total:D,selectedRows:C,filters:i,tableMaxHeight:T,fetchData:B,handleSelectionChange:N,handleSortChange:Y,handleSizeChange:j,handleFilterChange:m,resetFilters:$,refreshData:q}=je({apiUrl:"/logs",defaultFilters:{action:"",user_id:"",username:"",start_date:"",end_date:""},defaultPageSize:20}),{columnOptions:O,visibleColumns:c,saveColumnSettings:A}=$e("logs_column_settings",[{prop:"id",label:"ID"},{prop:"username",label:"操作用户"},{prop:"nickname",label:"昵称"},{prop:"action",label:"操作类型"},{prop:"target_type",label:"目标类型"},{prop:"target_id",label:"目标ID"},{prop:"detail",label:"详情"},{prop:"ip",label:"IP"},{prop:"created_at",label:"时间"}]),H=F(()=>{const r=new Date().toISOString().slice(0,10);return k.value.filter(t=>t.created_at&&t.created_at.startsWith(r)).length}),Q=F(()=>new Set(k.value.map(r=>r.user_id)).size);function W(r){r?(i.start_date=r[0],i.end_date=r[1]):(i.start_date="",i.end_date=""),m()}function Z(r){if(!C.value.length){L.warning("请先选择要导出的日志");return}const t=new URLSearchParams;t.set("ids",C.value.map(b=>b.id).join(",")),t.append("format",r);const f=localStorage.getItem("access_token");window.open(`/api/logs/export?${t.toString()}&token=${f}`,"_blank"),L.success("导出任务已启动")}return(r,t)=>{const f=me,b=_e,G=ce,S=Ce,v=we,J=ke,h=ye,X=ve,z=Ie,ee=ze,te=Ee,ae=Re,le=Pe,u=Te,oe=Be,se=Me,ne=Ye,ie=pe,de=Ne;return n(),I("div",qe,[a(G,{gutter:20,class:"stats-row"},{default:l(()=>[a(b,{xs:12,sm:8,md:8,lg:8},{default:l(()=>[o("div",Oe,[o("div",Ae,[a(f,{size:32},{default:l(()=>[a(e(ge))]),_:1})]),o("div",He,[o("div",Qe,g(e(D)),1),t[7]||(t[7]=o("div",{class:"stat-label"},"总日志数",-1))])])]),_:1}),a(b,{xs:12,sm:8,md:8,lg:8},{default:l(()=>[o("div",We,[o("div",Ze,[a(f,{size:32},{default:l(()=>[a(e(fe))]),_:1})]),o("div",Ge,[o("div",Je,g(H.value),1),t[8]||(t[8]=o("div",{class:"stat-label"},"今日日志",-1))])])]),_:1}),a(b,{xs:12,sm:8,md:8,lg:8},{default:l(()=>[o("div",Xe,[o("div",et,[a(f,{size:32},{default:l(()=>[a(e(he))]),_:1})]),o("div",tt,[o("div",at,g(Q.value),1),t[9]||(t[9]=o("div",{class:"stat-label"},"操作用户数",-1))])])]),_:1})]),_:1}),a(ie,{shadow:"never",class:"main-card"},{default:l(()=>[a(be,{name:"expand"},{default:l(()=>[U(o("div",lt,[a(X,{inline:!0,model:e(i),class:"search-form","label-width":"90px"},{default:l(()=>[a(v,{label:"操作类型"},{default:l(()=>[a(S,{modelValue:e(i).action,"onUpdate:modelValue":t[0]||(t[0]=s=>e(i).action=s),placeholder:"输入操作类型",clearable:"",style:{width:"160px"},onClear:e(m),onKeyup:E(e(m),["enter"])},null,8,["modelValue","onClear","onKeyup"])]),_:1}),a(v,{label:"用户ID"},{default:l(()=>[a(S,{modelValue:e(i).user_id,"onUpdate:modelValue":t[1]||(t[1]=s=>e(i).user_id=s),placeholder:"用户ID",clearable:"",style:{width:"130px"},onClear:e(m),onKeyup:E(e(m),["enter"])},null,8,["modelValue","onClear","onKeyup"])]),_:1}),a(v,{label:"用户名"},{default:l(()=>[a(S,{modelValue:e(i).username,"onUpdate:modelValue":t[2]||(t[2]=s=>e(i).username=s),placeholder:"用户名",clearable:"",style:{width:"150px"},onClear:e(m),onKeyup:E(e(m),["enter"])},null,8,["modelValue","onClear","onKeyup"])]),_:1}),a(v,{label:"日期范围"},{default:l(()=>[a(J,{modelValue:V.value,"onUpdate:modelValue":t[3]||(t[3]=s=>V.value=s),type:"daterange","range-separator":"至","start-placeholder":"开始日期","end-placeholder":"结束日期","value-format":"YYYY-MM-DD",style:{width:"260px"},onChange:W},null,8,["modelValue"])]),_:1}),a(v,null,{default:l(()=>[a(h,{type:"primary",onClicLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
.logs-page[data-v-b3e40e19]{max-width:1600px;margin:0 auto}.stats-row[data-v-b3e40e19]{margin-bottom:20px}.stat-card[data-v-b3e40e19]{background:#fff;border-radius:12px;padding:24px;display:flex;align-items:center;gap:20px;box-shadow:0 2px 8px #0000000f;transition:all .3s ease}.stat-card[data-v-b3e40e19]:hover{transform:translateY(-4px);box-shadow:0 8px 16px #0000001a}.stat-icon[data-v-b3e40e19]{width:64px;height:64px;border-radius:12px;display:flex;align-items:center;justify-content:center;color:#fff;flex-shrink:0}.stat-total .stat-icon[data-v-b3e40e19]{background:linear-gradient(135deg,#667eea,#764ba2)}.stat-today .stat-icon[data-v-b3e40e19]{background:linear-gradient(135deg,#43e97b,#38f9d7)}.stat-users .stat-icon[data-v-b3e40e19]{background:linear-gradient(135deg,#f093fb,#f5576c)}.stat-value[data-v-b3e40e19]{font-size:32px;font-weight:700;color:#303133}.stat-label[data-v-b3e40e19]{font-size:14px;color:#909399;margin-top:4px}.advanced-search[data-v-b3e40e19]{padding:20px;background:#f5f7fa;border-radius:8px;margin-bottom:20px}.search-form[data-v-b3e40e19]{display:flex;flex-wrap:wrap;gap:12px}.toolbar[data-v-b3e40e19]{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:12px}.toolbar-left[data-v-b3e40e19],.toolbar-right[data-v-b3e40e19]{display:flex;gap:12px;flex-wrap:wrap}.data-table[data-v-b3e40e19] .el-table__header th{font-weight:600;color:#303133}.pagination-wrapper[data-v-b3e40e19]{margin-top:20px;display:flex;justify-content:flex-end}.column-settings[data-v-b3e40e19]{padding:8px}.column-settings-title[data-v-b3e40e19]{font-weight:600;margin-bottom:12px}.column-settings .el-checkbox[data-v-b3e40e19]{display:block;margin-bottom:8px}.expand-enter-active[data-v-b3e40e19],.expand-leave-active[data-v-b3e40e19]{transition:all .3s ease}.expand-enter-from[data-v-b3e40e19],.expand-leave-to[data-v-b3e40e19]{opacity:0;max-height:0;overflow:hidden}.expand-enter-to[data-v-b3e40e19],.expand-leave-from[data-v-b3e40e19]{opacity:1;max-height:200px}@media (max-width:768px){.toolbar[data-v-b3e40e19]{flex-direction:column;align-items:stretch}.toolbar-left[data-v-b3e40e19],.toolbar-right[data-v-b3e40e19]{width:100%}.search-form[data-v-b3e40e19]{flex-direction:column}.search-form .el-form-item[data-v-b3e40e19],.search-form .el-select[data-v-b3e40e19],.search-form .el-input[data-v-b3e40e19],.search-form .el-date-picker[data-v-b3e40e19]{width:100%!important}}
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as ue,o as n,c as I,b as a,w as l,a4 as ce,a6 as pe,a5 as _e,a as o,E as me,n as e,aQ as ge,C as g,aM as fe,q as he,T as be,aa as U,d as ve,e as we,f as Ce,g as E,aD as ke,h as ye,ad as xe,i as p,ae as P,af as Se,S as Ee,ah as Ve,ai as De,U as ze,V as Ie,ak as Ue,al as Pe,F as Ke,R as Fe,P as d,t as Re,am as Le,an as Me,ao as Te,K as _,Z as Be,as as Ne,at as Ye,au as K,D as F,l as R,k as L}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as $e,a as je}from"./useColumnSettings-BO5PTaEn.js";import"./index-DpFNINBG.js";const qe={class:"logs-page"},Oe={class:"stat-card stat-total"},Ae={class:"stat-icon"},He={class:"stat-info"},Qe={class:"stat-value"},We={class:"stat-card stat-today"},Ze={class:"stat-icon"},Ge={class:"stat-info"},Je={class:"stat-value"},Xe={class:"stat-card stat-users"},et={class:"stat-icon"},tt={class:"stat-info"},at={class:"stat-value"},lt={class:"advanced-search"},ot={class:"toolbar"},st={class:"toolbar-left"},nt={class:"toolbar-right"},it={class:"column-settings"},dt={class:"pagination-wrapper"},rt={__name:"Logs",setup(ut){const w=R(!0),V=R([]),{list:k,loading:M,page:y,pageSize:x,total:D,selectedRows:C,filters:i,tableMaxHeight:T,fetchData:B,handleSelectionChange:N,handleSortChange:Y,handleSizeChange:$,handleFilterChange:m,resetFilters:j,refreshData:q}=$e({apiUrl:"/logs",defaultFilters:{action:"",user_id:"",username:"",start_date:"",end_date:""},defaultPageSize:20}),{columnOptions:O,visibleColumns:c,saveColumnSettings:A}=je("logs_column_settings",[{prop:"id",label:"ID"},{prop:"username",label:"操作用户"},{prop:"nickname",label:"昵称"},{prop:"action",label:"操作类型"},{prop:"target_type",label:"目标类型"},{prop:"target_id",label:"目标ID"},{prop:"detail",label:"详情"},{prop:"ip",label:"IP"},{prop:"created_at",label:"时间"}]),H=F(()=>{const r=new Date().toISOString().slice(0,10);return k.value.filter(t=>t.created_at&&t.created_at.startsWith(r)).length}),Q=F(()=>new Set(k.value.map(r=>r.user_id)).size);function W(r){r?(i.start_date=r[0],i.end_date=r[1]):(i.start_date="",i.end_date=""),m()}function Z(r){if(!C.value.length){L.warning("请先选择要导出的日志");return}const t=new URLSearchParams;t.set("ids",C.value.map(b=>b.id).join(",")),t.append("format",r);const f=localStorage.getItem("access_token");window.open(`/api/logs/export?${t.toString()}&token=${f}`,"_blank"),L.success("导出任务已启动")}return(r,t)=>{const f=me,b=_e,G=ce,S=Ce,v=we,J=ke,h=ye,X=ve,z=Ie,ee=ze,te=Ee,ae=Re,le=Pe,u=Te,oe=Be,se=Me,ne=Ye,ie=pe,de=Ne;return n(),I("div",qe,[a(G,{gutter:20,class:"stats-row"},{default:l(()=>[a(b,{xs:12,sm:8,md:8,lg:8},{default:l(()=>[o("div",Oe,[o("div",Ae,[a(f,{size:32},{default:l(()=>[a(e(ge))]),_:1})]),o("div",He,[o("div",Qe,g(e(D)),1),t[7]||(t[7]=o("div",{class:"stat-label"},"总日志数",-1))])])]),_:1}),a(b,{xs:12,sm:8,md:8,lg:8},{default:l(()=>[o("div",We,[o("div",Ze,[a(f,{size:32},{default:l(()=>[a(e(fe))]),_:1})]),o("div",Ge,[o("div",Je,g(H.value),1),t[8]||(t[8]=o("div",{class:"stat-label"},"今日日志",-1))])])]),_:1}),a(b,{xs:12,sm:8,md:8,lg:8},{default:l(()=>[o("div",Xe,[o("div",et,[a(f,{size:32},{default:l(()=>[a(e(he))]),_:1})]),o("div",tt,[o("div",at,g(Q.value),1),t[9]||(t[9]=o("div",{class:"stat-label"},"操作用户数",-1))])])]),_:1})]),_:1}),a(ie,{shadow:"never",class:"main-card"},{default:l(()=>[a(be,{name:"expand"},{default:l(()=>[U(o("div",lt,[a(X,{inline:!0,model:e(i),class:"search-form","label-width":"90px"},{default:l(()=>[a(v,{label:"操作类型"},{default:l(()=>[a(S,{modelValue:e(i).action,"onUpdate:modelValue":t[0]||(t[0]=s=>e(i).action=s),placeholder:"输入操作类型",clearable:"",style:{width:"160px"},onClear:e(m),onKeyup:E(e(m),["enter"])},null,8,["modelValue","onClear","onKeyup"])]),_:1}),a(v,{label:"用户ID"},{default:l(()=>[a(S,{modelValue:e(i).user_id,"onUpdate:modelValue":t[1]||(t[1]=s=>e(i).user_id=s),placeholder:"用户ID",clearable:"",style:{width:"130px"},onClear:e(m),onKeyup:E(e(m),["enter"])},null,8,["modelValue","onClear","onKeyup"])]),_:1}),a(v,{label:"用户名"},{default:l(()=>[a(S,{modelValue:e(i).username,"onUpdate:modelValue":t[2]||(t[2]=s=>e(i).username=s),placeholder:"用户名",clearable:"",style:{width:"150px"},onClear:e(m),onKeyup:E(e(m),["enter"])},null,8,["modelValue","onClear","onKeyup"])]),_:1}),a(v,{label:"日期范围"},{default:l(()=>[a(J,{modelValue:V.value,"onUpdate:modelValue":t[3]||(t[3]=s=>V.value=s),type:"daterange","range-separator":"至","start-placeholder":"开始日期","end-placeholder":"结束日期","value-format":"YYYY-MM-DD",style:{width:"260px"},onChange:W},null,8,["modelValue"])]),_:1}),a(v,null,{default:l(()=>[a(h,{type:"primary",onClicLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Ye,m as ee,o as u,c as v,b as e,w as l,F as T,l as g,G as qe,H as Je,u as Qe,I as We,r as d,J as Xe,B as N,a,n as Ze,E as el,T as le,K as b,L as ll,M as tl,N as ol,O as nl,P as i,Q as al,R as A,A as F,S as sl,U as dl,V as ul,i as _,C as S,W as rl,X as il,Y as pl,Z as ml,$ as cl,a0 as _l,a1 as fl,d as vl,a2 as bl,e as yl,f as gl,h as kl,D as p,k as wl}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as hl}from"./user-KptFbP1d.js";import{r as El}from"./index-CZCGMR8A.js";const xl={class:"logo-icon"},Cl={key:0,class:"logo-text"},Ml={key:0,class:"sidebar-footer"},Tl={class:"theme-label"},Fl={class:"theme-dots"},Sl=["title","onClick"],Bl={key:1,class:"sidebar-footer-collapse"},Vl=["title"],Dl={class:"header-left"},Al={class:"header-right"},Il=["title"],Ll={class:"user-info"},zl={class:"user-name"},te="cardauth_sidebar_theme",oe="cardauth_primary_theme",Ul={__name:"MainLayout",setup(Pl){const I=Qe(),L=We(),B=hl(),f=p(()=>B.user),m=g(!1),ne=p(()=>L.path),V=p(()=>{var o;return["admin","project_admin"].includes((o=f.value)==null?void 0:o.role)}),ae=p(()=>{var o;return((o=f.value)==null?void 0:o.role)==="agent"}),se=p(()=>V.value),de=p(()=>{var t,h;return{admin:"超级管理员",project_admin:"项目管理员",agent:"代理"}[(t=f.value)==null?void 0:t.role]||((h=f.value)==null?void 0:h.role)}),E=[{key:"dark-blue",label:"深海蓝",color:"#1a1a2e"},{key:"dark",label:"暗夜黑",color:"#141414"},{key:"light",label:"简约白",color:"#ffffff"},{key:"purple",label:"罗兰紫",color:"#2d1b4e"},{key:"green",label:"森林绿",color:"#0d2f23"}],k=g("dark-blue"),ue=p(()=>{var o;return((o=E.find(t=>t.key===k.value))==null?void 0:o.color)||"#1a1a2e"}),re=p(()=>{var o;return((o=E.find(t=>t.key===k.value))==null?void 0:o.label)||"深海蓝"});function O(o){k.value=o,localStorage.setItem(te,o)}ee(()=>{const o=localStorage.getItem(te);o&&E.some(t=>t.key===o)&&(k.value=o)});const x=[{key:"indigo",label:"靛蓝",color:"#6366f1"},{key:"blue",label:"天蓝",color:"#0ea5e9"},{key:"rose",label:"玫瑰",color:"#f43f5e"},{key:"amber",label:"琥珀",color:"#f59e0b"},{key:"emerald",label:"翠绿",color:"#10b981"}],w=g("indigo"),ie=p(()=>{var o;return((o=x.find(t=>t.key===w.value))==null?void 0:o.color)||"#6366f1"}),pe=p(()=>{var o;return((o=x.find(t=>t.key===w.value))==null?void 0:o.label)||"靛蓝"});function H(o){const t=document.body.classList;x.forEach(h=>t.remove(`theme-primary-${h.key}`)),t.add(`theme-primary-${o}`)}function me(o){w.value=o,localStorage.setItem(oe,o),H(o)}ee(()=>{const o=localStorage.getItem(oe);o&&x.some(t=>t.key===o)&&(w.value=o),H(w.value)});const ce={"/dashboard":[],"/projects":[{path:"/dashboard",title:"业务管理"}],"/products":[{path:"/dashboard",title:"业务管理"}],"/cards":[{path:"/dashboard",title:"业务管理"}],"/authorizations":[{path:"/dashboard",title:"业务管理"}],"/orders":[{path:"/dashboard",title:"订单与代理"}],"/coupons":[{path:"/dashboard",title:"订单与代理"}],"/blacklist":[{path:"/dashboard",title:"订单与代理"}],"/agents":[{path:"/dashboard",title:"订单与代理"}],"/users":[{path:"/dashboard",title:"系统管理"}],"/payment-config":[{path:"/dashboard",title:"系统管理"}],"/system":[{path:"/dashboard",title:"系统管理"}],"/logs":[{path:"/dashboard",title:"系统管理"}]},K=p(()=>[...ce[L.path]||[],{title:L.meta.title}]),C=g(!1),z=g(!1),U=g(null),y=g({old_password:"",new_password:""}),_e={old_password:[{required:!0,message:"请输入原密码",trigger:"blur"}],new_password:[{required:!0,min:6,message:"新密码至少6位",trigger:"blur"}]};function fe(o){o==="logout"?(B.logout(),I.push("/login")):o==="changePwd"&&(y.value={old_password:"",new_password:""},C.value=!0)}async function ve(){U.value&&await U.value.validate(async o=>{if(o){z.value=!0;try{await El.post("/auth/change-password",y.value),wl.success("密码修改成功,请重新登录"),C.value=!1,B.logout(),I.push("/login")}catch{}finally{z.value=!1}}})}return B.fetchUser().catch(()=>{}),(o,t)=>{const h=d("Key"),s=el,be=d("Odometer"),r=nl,ye=ol,G=d("Briefcase"),ge=d("FolderOpened"),ke=d("Goods"),j=d("Tickets"),P=d("Lock"),D=al,Y=d("Document"),we=d("Money"),he=d("Discount"),Ee=d("CircleClose"),xe=d("Avatar"),q=d("Setting"),Ce=d("UserFilled"),Me=d("CreditCard"),Te=d("Notebook"),Fe=tl,Se=ll,Be=d("Brush"),M=ul,R=dl,$=sl,Ve=Xe,De=d("Fold"),Ae=d("Expand"),Ie=d("HomeFilled"),J=pl,Le=il,ze=d("BrushFilled"),Ue=ml,Pe=cl,Re=d("ArrowDown"),$e=d("User"),Ne=d("SwitchButton"),Oe=rl,He=d("router-view"),Ke=_l,Q=qe,W=gl,X=yl,Ge=vl,Z=kl,je=Je;return u(),v(T,null,[e(Q,{class:"main-layout"},{default:l(()=>[e(Ve,{width:m.value?"72px":"240px",class:N(["sidebar",`theme-${k.value}`])},{default:l(()=>[a("div",{class:"logo",onClick:t[0]||(t[0]=n=>Ze(I).push("/dashboard"))},[a("div",xl,[e(s,{size:26},{default:l(()=Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
.el-aside{box-sizing:border-box;width:var(--el-aside-width,300px);flex-shrink:0;overflow:auto}.el-container{box-sizing:border-box;flex-direction:row;flex:auto;min-width:0;display:flex}.el-container.is-vertical{flex-direction:column}.el-footer{--el-footer-padding:0 20px;--el-footer-height:60px;padding:var(--el-footer-padding);box-sizing:border-box;height:var(--el-footer-height);flex-shrink:0}.el-header{--el-header-padding:0 20px;--el-header-height:60px;padding:var(--el-header-padding);box-sizing:border-box;height:var(--el-header-height);flex-shrink:0}.el-main{--el-main-padding:20px;box-sizing:border-box;padding:var(--el-main-padding);flex:auto;display:block;overflow:auto}.el-breadcrumb{font-size:14px;line-height:1}.el-breadcrumb:before,.el-breadcrumb:after{content:"";display:table}.el-breadcrumb:after{clear:both}.el-breadcrumb__separator{color:var(--el-text-color-placeholder);margin:0 9px;font-weight:700}.el-breadcrumb__separator.el-icon{margin:0 6px;font-weight:400}.el-breadcrumb__separator.el-icon svg{vertical-align:middle}.el-breadcrumb__item{float:left;align-items:center;display:inline-flex}.el-breadcrumb__inner{color:var(--el-text-color-regular)}.el-breadcrumb__inner.is-link,.el-breadcrumb__inner a{transition:var(--el-transition-color);color:var(--el-text-color-primary);font-weight:700;text-decoration:none}.el-breadcrumb__inner.is-link:hover,.el-breadcrumb__inner a:hover{color:var(--el-color-primary);cursor:pointer}.el-breadcrumb__item:last-child .el-breadcrumb__inner,.el-breadcrumb__item:last-child .el-breadcrumb__inner:hover,.el-breadcrumb__item:last-child .el-breadcrumb__inner a,.el-breadcrumb__item:last-child .el-breadcrumb__inner a:hover{color:var(--el-text-color-regular);cursor:text;font-weight:400}.el-breadcrumb__item:last-child .el-breadcrumb__separator{display:none}.fade-in-linear-enter-active,.fade-in-linear-leave-active{transition:var(--el-transition-fade-linear)}.fade-in-linear-enter-from,.fade-in-linear-leave-to{opacity:0}.el-fade-in-linear-enter-active,.el-fade-in-linear-leave-active{transition:var(--el-transition-fade-linear)}.el-fade-in-linear-enter-from,.el-fade-in-linear-leave-to{opacity:0}.el-fade-in-enter-active,.el-fade-in-leave-active{transition:all var(--el-transition-duration) cubic-bezier(.55,0,.1,1)}.el-fade-in-enter-from,.el-fade-in-leave-active{opacity:0}.el-zoom-in-center-enter-active,.el-zoom-in-center-leave-active{transition:all var(--el-transition-duration) cubic-bezier(.55,0,.1,1)}.el-zoom-in-center-enter-from,.el-zoom-in-center-leave-active{opacity:0;transform:scaleX(0)}.el-zoom-in-top-enter-active,.el-zoom-in-top-leave-active{opacity:1;transition:var(--el-transition-md-fade);transform-origin:top;transform:scaleY(1)}.el-zoom-in-top-enter-active[data-popper-placement^=top],.el-zoom-in-top-leave-active[data-popper-placement^=top]{transform-origin:bottom}.el-zoom-in-top-enter-from,.el-zoom-in-top-leave-active{opacity:0;transform:scaleY(0)}.el-zoom-in-bottom-enter-active,.el-zoom-in-bottom-leave-active{opacity:1;transition:var(--el-transition-md-fade);transform-origin:bottom;transform:scaleY(1)}.el-zoom-in-bottom-enter-from,.el-zoom-in-bottom-leave-active{opacity:0;transform:scaleY(0)}.el-zoom-in-left-enter-active,.el-zoom-in-left-leave-active{opacity:1;transition:var(--el-transition-md-fade);transform-origin:0 0;transform:scale(1)}.el-zoom-in-left-enter-from,.el-zoom-in-left-leave-active{opacity:0;transform:scale(.45)}.collapse-transition{transition:var(--el-transition-duration) height ease-in-out,var(--el-transition-duration) padding-top ease-in-out,var(--el-transition-duration) padding-bottom ease-in-out}.el-collapse-transition-leave-active,.el-collapse-transition-enter-active{transition:var(--el-transition-duration) max-height ease-in-out,var(--el-transition-duration) padding-top ease-in-out,var(--el-transition-duration) padding-bottom ease-in-out}.horizontal-collapse-transition{transition:var(--el-transition-duration) width ease-in-out,var(--el-transition-duration) padding-left ease-in-out,var(--el-transition-duration) padding-right ease-in-out}.el-list-enter-active,.el-list-leave-active{transition:all 1s}.el-list-enter-from,.el-list-leave-to{opacity:0;transform:translateY(-30px)}.el-list-leave-active{position:absolute!important}.el-opacity-transition{transition:opacity var(--el-transition-duration) cubic-bezier(.55,0,.1,1)}:root{--el-menu-active-color:var(--el-color-primary);--el-menu-text-color:var(--el-text-color-primary);--el-menu-hover-text-color:var(--el-color-primary);--el-menu-bg-color:var(--el-fill-color-blank);--el-menu-hover-bg-color:var(--el-color-primary-light-9);--el-menu-item-height:56px;--el-menu-sub-item-height:calc(var(--el-menu-item-height) - 6px);--el-menu-horizontal-height:60px;--el-menu-horizontal-sub-item-height:36px;--el-menu-item-font-size:var(--el-font-size-base);--el-menu-item-hover-fill:var(--el-color-primary-light-9);--el-menu-border-color:var(--el-border-color);--el-menu-base-level-padding:20px;--el-menu-level-padding:20px;--el-menu-icon-Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
.el-aside{box-sizing:border-box;width:var(--el-aside-width,300px);flex-shrink:0;overflow:auto}.el-container{box-sizing:border-box;flex-direction:row;flex:auto;min-width:0;display:flex}.el-container.is-vertical{flex-direction:column}.el-footer{--el-footer-padding:0 20px;--el-footer-height:60px;padding:var(--el-footer-padding);box-sizing:border-box;height:var(--el-footer-height);flex-shrink:0}.el-header{--el-header-padding:0 20px;--el-header-height:60px;padding:var(--el-header-padding);box-sizing:border-box;height:var(--el-header-height);flex-shrink:0}.el-main{--el-main-padding:20px;box-sizing:border-box;padding:var(--el-main-padding);flex:auto;display:block;overflow:auto}.el-breadcrumb{font-size:14px;line-height:1}.el-breadcrumb:before,.el-breadcrumb:after{content:"";display:table}.el-breadcrumb:after{clear:both}.el-breadcrumb__separator{color:var(--el-text-color-placeholder);margin:0 9px;font-weight:700}.el-breadcrumb__separator.el-icon{margin:0 6px;font-weight:400}.el-breadcrumb__separator.el-icon svg{vertical-align:middle}.el-breadcrumb__item{float:left;align-items:center;display:inline-flex}.el-breadcrumb__inner{color:var(--el-text-color-regular)}.el-breadcrumb__inner.is-link,.el-breadcrumb__inner a{transition:var(--el-transition-color);color:var(--el-text-color-primary);font-weight:700;text-decoration:none}.el-breadcrumb__inner.is-link:hover,.el-breadcrumb__inner a:hover{color:var(--el-color-primary);cursor:pointer}.el-breadcrumb__item:last-child .el-breadcrumb__inner,.el-breadcrumb__item:last-child .el-breadcrumb__inner:hover,.el-breadcrumb__item:last-child .el-breadcrumb__inner a,.el-breadcrumb__item:last-child .el-breadcrumb__inner a:hover{color:var(--el-text-color-regular);cursor:text;font-weight:400}.el-breadcrumb__item:last-child .el-breadcrumb__separator{display:none}.fade-in-linear-enter-active,.fade-in-linear-leave-active{transition:var(--el-transition-fade-linear)}.fade-in-linear-enter-from,.fade-in-linear-leave-to{opacity:0}.el-fade-in-linear-enter-active,.el-fade-in-linear-leave-active{transition:var(--el-transition-fade-linear)}.el-fade-in-linear-enter-from,.el-fade-in-linear-leave-to{opacity:0}.el-fade-in-enter-active,.el-fade-in-leave-active{transition:all var(--el-transition-duration) cubic-bezier(.55,0,.1,1)}.el-fade-in-enter-from,.el-fade-in-leave-active{opacity:0}.el-zoom-in-center-enter-active,.el-zoom-in-center-leave-active{transition:all var(--el-transition-duration) cubic-bezier(.55,0,.1,1)}.el-zoom-in-center-enter-from,.el-zoom-in-center-leave-active{opacity:0;transform:scaleX(0)}.el-zoom-in-top-enter-active,.el-zoom-in-top-leave-active{opacity:1;transition:var(--el-transition-md-fade);transform-origin:top;transform:scaleY(1)}.el-zoom-in-top-enter-active[data-popper-placement^=top],.el-zoom-in-top-leave-active[data-popper-placement^=top]{transform-origin:bottom}.el-zoom-in-top-enter-from,.el-zoom-in-top-leave-active{opacity:0;transform:scaleY(0)}.el-zoom-in-bottom-enter-active,.el-zoom-in-bottom-leave-active{opacity:1;transition:var(--el-transition-md-fade);transform-origin:bottom;transform:scaleY(1)}.el-zoom-in-bottom-enter-from,.el-zoom-in-bottom-leave-active{opacity:0;transform:scaleY(0)}.el-zoom-in-left-enter-active,.el-zoom-in-left-leave-active{opacity:1;transition:var(--el-transition-md-fade);transform-origin:0 0;transform:scale(1)}.el-zoom-in-left-enter-from,.el-zoom-in-left-leave-active{opacity:0;transform:scale(.45)}.collapse-transition{transition:var(--el-transition-duration) height ease-in-out,var(--el-transition-duration) padding-top ease-in-out,var(--el-transition-duration) padding-bottom ease-in-out}.el-collapse-transition-leave-active,.el-collapse-transition-enter-active{transition:var(--el-transition-duration) max-height ease-in-out,var(--el-transition-duration) padding-top ease-in-out,var(--el-transition-duration) padding-bottom ease-in-out}.horizontal-collapse-transition{transition:var(--el-transition-duration) width ease-in-out,var(--el-transition-duration) padding-left ease-in-out,var(--el-transition-duration) padding-right ease-in-out}.el-list-enter-active,.el-list-leave-active{transition:all 1s}.el-list-enter-from,.el-list-leave-to{opacity:0;transform:translateY(-30px)}.el-list-leave-active{position:absolute!important}.el-opacity-transition{transition:opacity var(--el-transition-duration) cubic-bezier(.55,0,.1,1)}:root{--el-menu-active-color:var(--el-color-primary);--el-menu-text-color:var(--el-text-color-primary);--el-menu-hover-text-color:var(--el-color-primary);--el-menu-bg-color:var(--el-fill-color-blank);--el-menu-hover-bg-color:var(--el-color-primary-light-9);--el-menu-item-height:56px;--el-menu-sub-item-height:calc(var(--el-menu-item-height) - 6px);--el-menu-horizontal-height:60px;--el-menu-horizontal-sub-item-height:36px;--el-menu-item-font-size:var(--el-font-size-base);--el-menu-item-hover-fill:var(--el-color-primary-light-9);--el-menu-border-color:var(--el-border-color);--el-menu-base-level-padding:20px;--el-menu-level-padding:20px;--el-menu-icon-Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as dl,m as ce,o as r,c as k,b as e,w as a,F as I,l as f,G as il,H as ml,u as pl,I as cl,r as u,J as fl,B as Q,a as n,n as _l,E as vl,T as fe,K as w,L as gl,M as bl,N as yl,O as kl,P as _,Q as wl,R as G,A as P,S as hl,U as xl,V as El,i as p,C as M,W as Cl,X as Vl,Y as Ml,Z as Fl,$ as Sl,a0 as zl,a1 as Bl,d as Tl,a2 as _e,e as Al,f as Il,h as Pl,a3 as Dl,D as c,k as F}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as Ll}from"./user-DvAOsLmR.js";import{r as ve}from"./index-DpFNINBG.js";const Ul={class:"logo-icon"},Rl={key:0,class:"logo-text"},Gl={key:0,class:"sidebar-footer"},$l={class:"theme-label"},Nl={class:"theme-dots"},Hl=["title","onClick"],Ol={key:1,class:"sidebar-footer-collapse"},jl=["title"],Kl={class:"header-left"},Yl={class:"header-right"},ql=["title"],Jl={class:"user-info"},Wl={class:"user-name"},Ql={class:"profile-avatar-section"},Xl={class:"avatar-overlay"},ge="cardauth_sidebar_theme",be="cardauth_primary_theme",Zl={__name:"MainLayout",setup(ea){const $=pl(),N=cl(),g=Ll(),m=c(()=>g.user),b=f(!1),ye=c(()=>N.path),D=c(()=>{var t;return["admin","project_admin"].includes((t=m.value)==null?void 0:t.role)}),ke=c(()=>{var t;return((t=m.value)==null?void 0:t.role)==="agent"}),we=c(()=>D.value),X=c(()=>{var l,v;return{admin:"超级管理员",project_admin:"项目管理员",agent:"代理"}[(l=m.value)==null?void 0:l.role]||((v=m.value)==null?void 0:v.role)}),S=[{key:"dark-blue",label:"深海蓝",color:"#1a1a2e"},{key:"dark",label:"暗夜黑",color:"#141414"},{key:"light",label:"简约白",color:"#ffffff"},{key:"purple",label:"罗兰紫",color:"#2d1b4e"},{key:"green",label:"森林绿",color:"#0d2f23"}],E=f("dark-blue"),he=c(()=>{var t;return((t=S.find(l=>l.key===E.value))==null?void 0:t.color)||"#1a1a2e"}),xe=c(()=>{var t;return((t=S.find(l=>l.key===E.value))==null?void 0:t.label)||"深海蓝"});function Z(t){E.value=t,localStorage.setItem(ge,t)}ce(()=>{const t=localStorage.getItem(ge);t&&S.some(l=>l.key===t)&&(E.value=t)});const z=[{key:"indigo",label:"靛蓝",color:"#6366f1"},{key:"blue",label:"天蓝",color:"#0ea5e9"},{key:"rose",label:"玫瑰",color:"#f43f5e"},{key:"amber",label:"琥珀",color:"#f59e0b"},{key:"emerald",label:"翠绿",color:"#10b981"}],C=f("indigo"),Ee=c(()=>{var t;return((t=z.find(l=>l.key===C.value))==null?void 0:t.color)||"#6366f1"}),Ce=c(()=>{var t;return((t=z.find(l=>l.key===C.value))==null?void 0:t.label)||"靛蓝"});function ee(t){const l=document.body.classList;z.forEach(v=>l.remove(`theme-primary-${v.key}`)),l.add(`theme-primary-${t}`)}function Ve(t){C.value=t,localStorage.setItem(be,t),ee(t)}ce(()=>{const t=localStorage.getItem(be);t&&z.some(l=>l.key===t)&&(C.value=t),ee(C.value)});const Me={"/dashboard":[],"/projects":[{path:"/dashboard",title:"业务管理"}],"/products":[{path:"/dashboard",title:"业务管理"}],"/cards":[{path:"/dashboard",title:"业务管理"}],"/authorizations":[{path:"/dashboard",title:"业务管理"}],"/orders":[{path:"/dashboard",title:"订单与代理"}],"/coupons":[{path:"/dashboard",title:"订单与代理"}],"/blacklist":[{path:"/dashboard",title:"订单与代理"}],"/agents":[{path:"/dashboard",title:"订单与代理"}],"/users":[{path:"/dashboard",title:"系统管理"}],"/payment-config":[{path:"/dashboard",title:"系统管理"}],"/system":[{path:"/dashboard",title:"系统管理"}],"/logs":[{path:"/dashboard",title:"系统管理"}]},le=c(()=>[...Me[N.path]||[],{title:N.meta.title}]),B=f(!1),H=f(!1),O=f(null),h=f({old_password:"",new_password:""}),Fe={old_password:[{required:!0,message:"请输入原密码",trigger:"blur"}],new_password:[{required:!0,min:6,message:"新密码至少6位",trigger:"blur"}]};function Se(t){var l,v,s,L;t==="logout"?(g.logout(),$.push("/login")):t==="changePwd"?(h.value={old_password:"",new_password:""},B.value=!0):t==="profile"&&(d.value={nickname:((l=m.value)==null?void 0:l.nickname)||"",email:((v=m.value)==null?void 0:v.email)||"",phone:((s=m.value)==null?void 0:s.phone)||"",avatar:((L=m.value)==null?void 0:L.avatar)||""},T.value=!0)}async function ze(){O.value&&await O.value.validate(async t=>{if(t){H.value=!0;try{await ve.post("/auth/change-password",h.value),F.success("密码修改成功,请重新登录"),B.value=!1,g.logout(),$.push("/login")}catch{}finally{H.value=!1}}})}const T=f(!1),j=f(!1),K=f(null),d=f({nickname:"",email:"",phone:"",avatar:""}),Be={nickname:[{max:50,message:"昵称最长50个字符",trigger:"blur"}],email:[{type:"email",message:"请输入正确的邮箱格式",trigger:"blur"}],phone:[{max:20,message:"手机号最长20位",trigger:"blur"}]},Te=c(()=>({Authorization:`Bearer ${g.token}`}));function Ae(t){return["image/jpeg","image/png","image/gif","image/webp"].includes(t.type)?t.size/1024/1024<2?!0:(F.error("图片大小不能超过 2MB"),!1):(FLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
.orders-page[data-v-554ed2ab]{max-width:1600px;margin:0 auto}.stats-row[data-v-554ed2ab]{margin-bottom:20px}.stat-card[data-v-554ed2ab]{background:#fff;border-radius:12px;padding:24px;display:flex;align-items:center;gap:20px;box-shadow:0 2px 8px #0000000f;transition:all .3s ease}.stat-card[data-v-554ed2ab]:hover{transform:translateY(-4px);box-shadow:0 8px 16px #0000001a}.stat-icon[data-v-554ed2ab]{width:64px;height:64px;border-radius:12px;display:flex;align-items:center;justify-content:center;color:#fff;flex-shrink:0}.stat-total .stat-icon[data-v-554ed2ab]{background:linear-gradient(135deg,#667eea,#764ba2)}.stat-paid .stat-icon[data-v-554ed2ab]{background:linear-gradient(135deg,#43e97b,#38f9d7)}.stat-pending .stat-icon[data-v-554ed2ab]{background:linear-gradient(135deg,#f093fb,#f5576c)}.stat-refunded .stat-icon[data-v-554ed2ab]{background:linear-gradient(135deg,#4facfe,#00f2fe)}.stat-value[data-v-554ed2ab]{font-size:32px;font-weight:700;color:#303133}.stat-label[data-v-554ed2ab]{font-size:14px;color:#909399;margin-top:4px}.advanced-search[data-v-554ed2ab]{padding:20px;background:#f5f7fa;border-radius:8px;margin-bottom:20px}.search-form[data-v-554ed2ab]{display:flex;flex-wrap:wrap;gap:12px}.toolbar[data-v-554ed2ab]{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:12px}.toolbar-left[data-v-554ed2ab],.toolbar-right[data-v-554ed2ab]{display:flex;gap:12px;flex-wrap:wrap}.data-table[data-v-554ed2ab] .el-table__header th{font-weight:600;color:#303133}.price-text[data-v-554ed2ab]{color:#f56c6c;font-weight:700}.mono-text[data-v-554ed2ab]{font-family:Courier New,monospace}.text-muted[data-v-554ed2ab]{color:#c0c4cc}.pagination-wrapper[data-v-554ed2ab]{margin-top:20px;display:flex;justify-content:flex-end}.column-settings[data-v-554ed2ab]{padding:8px}.column-settings-title[data-v-554ed2ab]{font-weight:600;margin-bottom:12px}.column-settings .el-checkbox[data-v-554ed2ab]{display:block;margin-bottom:8px}.expand-enter-active[data-v-554ed2ab],.expand-leave-active[data-v-554ed2ab]{transition:all .3s ease}.expand-enter-from[data-v-554ed2ab],.expand-leave-to[data-v-554ed2ab]{opacity:0;max-height:0;overflow:hidden}.expand-enter-to[data-v-554ed2ab],.expand-leave-from[data-v-554ed2ab]{opacity:1;max-height:200px}@media (max-width:768px){.toolbar[data-v-554ed2ab]{flex-direction:column;align-items:stretch}.toolbar-left[data-v-554ed2ab],.toolbar-right[data-v-554ed2ab]{width:100%}.search-form[data-v-554ed2ab]{flex-direction:column}.search-form .el-form-item[data-v-554ed2ab],.search-form .el-select[data-v-554ed2ab],.search-form .el-input[data-v-554ed2ab]{width:100%!important}}
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as ve,o,c as w,b as a,w as t,a3 as ge,a5 as be,l as I,H as ke,a4 as we,a as n,E as he,n as l,aQ as Ce,C as r,a7 as xe,ax as Ee,a8 as ze,T as Se,a9 as R,d as Ve,e as De,aa as Fe,ab as Ue,f as Ie,g as je,h as qe,ac as Qe,i as d,ad as T,ae as $e,S as Be,ag as Pe,ah as Re,U as Te,V as Ke,aj as Le,ak as Me,F as Ne,R as Oe,P as i,t as He,al as Ae,am as Ge,an as Ze,K as c,Z as Je,aF as We,ar as Xe,as as Ye,at as K,aG as et,aH as tt,D as j,k as q,av as at}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as lt,a as st}from"./useColumnSettings-sXzip_cz.js";import{r as L}from"./index-CZCGMR8A.js";const ot={class:"orders-page"},nt={class:"stat-card stat-total"},dt={class:"stat-icon"},it={class:"stat-info"},rt={class:"stat-value"},pt={class:"stat-card stat-paid"},ut={class:"stat-icon"},_t={class:"stat-info"},ct={class:"stat-value"},mt={class:"stat-card stat-pending"},ft={class:"stat-icon"},yt={class:"stat-info"},vt={class:"stat-value"},gt={class:"stat-card stat-refunded"},bt={class:"stat-icon"},kt={class:"stat-info"},wt={class:"stat-value"},ht={class:"advanced-search"},Ct={class:"toolbar"},xt={class:"toolbar-left"},Et={class:"toolbar-right"},zt={class:"column-settings"},St={class:"price-text"},Vt={key:3,class:"text-muted"},Dt={key:0,class:"mono-text"},Ft={key:1,class:"text-muted"},Ut={class:"pagination-wrapper"},It={class:"price-text"},jt={key:0,class:"mono-text"},qt={key:1,class:"text-muted"},Qt={__name:"Orders",setup($t){const x=I(!0),V=I(!1),p=I(null),{list:E,loading:M,page:D,pageSize:F,total:Q,selectedRows:z,filters:g,tableMaxHeight:N,fetchData:$,handleSelectionChange:O,handleSortChange:H,handleSizeChange:A,handleFilterChange:C,resetFilters:G,refreshData:Z}=lt({apiUrl:"/orders",defaultFilters:{status:"",pay_type:"",keyword:""},defaultPageSize:20}),{columnOptions:J,visibleColumns:f,saveColumnSettings:W}=st("orders_column_settings",[{prop:"id",label:"ID"},{prop:"order_no",label:"订单号"},{prop:"project_name",label:"项目"},{prop:"card_type_name",label:"套餐"},{prop:"amount",label:"金额"},{prop:"pay_type",label:"支付方式"},{prop:"status",label:"状态"},{prop:"trade_no",label:"交易号"},{prop:"card_key",label:"卡密"},{prop:"paid_at",label:"支付时间"},{prop:"created_at",label:"创建时间"}]),X=j(()=>E.value.filter(u=>u.status==="paid").reduce((u,e)=>u+parseFloat(e.amount||0),0).toFixed(2)),Y=j(()=>E.value.filter(u=>u.status==="pending").length),ee=j(()=>E.value.filter(u=>u.status==="refunded").length);async function te(u){try{const e=await L.get(`/orders/${u.id}`);p.value=e.data,V.value=!0}catch(e){console.error(e)}}async function ae(u){try{await at.confirm("确定手动补单?将自动发货卡密。","提示",{type:"warning"}),await L.post(`/orders/${u.id}/complete`),q.success("补单成功"),$()}catch(e){e!=="cancel"&&console.error(e)}}function le(u){if(!z.value.length){q.warning("请先选择要导出的订单");return}const e=new URLSearchParams;e.set("ids",z.value.map(h=>h.id).join(",")),e.append("format",u);const b=localStorage.getItem("access_token");window.open(`/api/orders/export?${e.toString()}&token=${b}`,"_blank"),q.success("导出任务已启动")}return(u,e)=>{const b=he,h=we,se=ge,k=Ue,B=Fe,S=De,oe=Ie,v=qe,ne=Ve,P=Ke,de=Te,ie=Be,re=He,pe=Me,_=Ze,y=Je,ue=Ge,_e=Ye,ce=be,m=tt,me=et,fe=ke,ye=Xe;return o(),w("div",ot,[a(se,{gutter:20,class:"stats-row"},{default:t(()=>[a(h,{xs:12,sm:6,md:6,lg:6},{default:t(()=>[n("div",nt,[n("div",dt,[a(b,{size:32},{default:t(()=>[a(l(Ce))]),_:1})]),n("div",it,[n("div",rt,r(l(Q)),1),e[7]||(e[7]=n("div",{class:"stat-label"},"总订单数",-1))])])]),_:1}),a(h,{xs:12,sm:6,md:6,lg:6},{default:t(()=>[n("div",pt,[n("div",ut,[a(b,{size:32},{default:t(()=>[a(l(xe))]),_:1})]),n("div",_t,[n("div",ct,"¥"+r(X.value),1),e[8]||(e[8]=n("div",{class:"stat-label"},"已支付金额",-1))])])]),_:1}),a(h,{xs:12,sm:6,md:6,lg:6},{default:t(()=>[n("div",mt,[n("div",ft,[a(b,{size:32},{default:t(()=>[a(l(Ee))]),_:1})]),n("div",yt,[n("div",vt,r(Y.value),1),e[9]||(e[9]=n("div",{class:"stat-label"},"待支付",-1))])])]),_:1}),a(h,{xs:12,sm:6,md:6,lg:6},{default:t(()=>[n("div",gt,[n("div",bt,[a(b,{size:32},{default:t(()=>[a(l(ze))]),_:1})]),n("div",kt,[n("div",wt,r(ee.value),1),e[10]||(e[10]=n("div",{class:"stat-label"},"已退款",-1))])])]),_:1})]),_:1}),a(ce,{shadow:"never",class:"main-card"},{default:t(()=>[a(Se,{name:"expand"},{default:t(()=>[R(n("div",ht,[a(ne,{inline:!0,model:l(g),class:"search-form","label-width":"80px"},{default:t(()=>[a(S,{label:"状态"},{default:t(()=>[a(B,{modelValue:l(g).status,"onUpdate:modelValue":e[0]||(e[0]=s=>l(g).status=s),placeholder:"全部状态",clearable:"",stLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as ve,o,c as w,b as a,w as t,a4 as ge,a6 as be,l as U,H as ke,a5 as we,a as n,E as he,n as l,aQ as Ce,C as r,a8 as xe,ay as Ee,a9 as ze,T as Se,aa as R,d as Ve,e as De,ab as Fe,ac as Ie,f as Ue,g as qe,h as Qe,ad as $e,i as d,ae as T,af as je,S as Be,ah as Pe,ai as Re,U as Te,V as Ke,ak as Le,al as Me,F as Ne,R as Oe,P as i,t as He,am as Ae,an as Ge,ao as Ze,K as c,Z as Je,aG as We,as as Xe,at as Ye,au as K,aH as et,aI as tt,D as q,k as Q,aw as at}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as lt,a as st}from"./useColumnSettings-BO5PTaEn.js";import{r as L}from"./index-DpFNINBG.js";const ot={class:"orders-page"},nt={class:"stat-card stat-total"},dt={class:"stat-icon"},it={class:"stat-info"},rt={class:"stat-value"},pt={class:"stat-card stat-paid"},ut={class:"stat-icon"},_t={class:"stat-info"},ct={class:"stat-value"},mt={class:"stat-card stat-pending"},ft={class:"stat-icon"},yt={class:"stat-info"},vt={class:"stat-value"},gt={class:"stat-card stat-refunded"},bt={class:"stat-icon"},kt={class:"stat-info"},wt={class:"stat-value"},ht={class:"advanced-search"},Ct={class:"toolbar"},xt={class:"toolbar-left"},Et={class:"toolbar-right"},zt={class:"column-settings"},St={class:"price-text"},Vt={key:3,class:"text-muted"},Dt={key:0,class:"mono-text"},Ft={key:1,class:"text-muted"},It={class:"pagination-wrapper"},Ut={class:"price-text"},qt={key:0,class:"mono-text"},Qt={key:1,class:"text-muted"},$t={__name:"Orders",setup(jt){const x=U(!0),V=U(!1),p=U(null),{list:E,loading:M,page:D,pageSize:F,total:$,selectedRows:z,filters:g,tableMaxHeight:N,fetchData:j,handleSelectionChange:O,handleSortChange:H,handleSizeChange:A,handleFilterChange:C,resetFilters:G,refreshData:Z}=lt({apiUrl:"/orders",defaultFilters:{status:"",pay_type:"",keyword:""},defaultPageSize:20}),{columnOptions:J,visibleColumns:f,saveColumnSettings:W}=st("orders_column_settings",[{prop:"id",label:"ID"},{prop:"order_no",label:"订单号"},{prop:"project_name",label:"项目"},{prop:"card_type_name",label:"套餐"},{prop:"amount",label:"金额"},{prop:"pay_type",label:"支付方式"},{prop:"status",label:"状态"},{prop:"trade_no",label:"交易号"},{prop:"card_key",label:"卡密"},{prop:"paid_at",label:"支付时间"},{prop:"created_at",label:"创建时间"}]),X=q(()=>E.value.filter(u=>u.status==="paid").reduce((u,e)=>u+parseFloat(e.amount||0),0).toFixed(2)),Y=q(()=>E.value.filter(u=>u.status==="pending").length),ee=q(()=>E.value.filter(u=>u.status==="refunded").length);async function te(u){try{const e=await L.get(`/orders/${u.id}`);p.value=e.data,V.value=!0}catch(e){console.error(e)}}async function ae(u){try{await at.confirm("确定手动补单?将自动发货卡密。","提示",{type:"warning"}),await L.post(`/orders/${u.id}/complete`),Q.success("补单成功"),j()}catch(e){e!=="cancel"&&console.error(e)}}function le(u){if(!z.value.length){Q.warning("请先选择要导出的订单");return}const e=new URLSearchParams;e.set("ids",z.value.map(h=>h.id).join(",")),e.append("format",u);const b=localStorage.getItem("access_token");window.open(`/api/orders/export?${e.toString()}&token=${b}`,"_blank"),Q.success("导出任务已启动")}return(u,e)=>{const b=he,h=we,se=ge,k=Ie,B=Fe,S=De,oe=Ue,v=Qe,ne=Ve,P=Ke,de=Te,ie=Be,re=He,pe=Me,_=Ze,y=Je,ue=Ge,_e=Ye,ce=be,m=tt,me=et,fe=ke,ye=Xe;return o(),w("div",ot,[a(se,{gutter:20,class:"stats-row"},{default:t(()=>[a(h,{xs:12,sm:6,md:6,lg:6},{default:t(()=>[n("div",nt,[n("div",dt,[a(b,{size:32},{default:t(()=>[a(l(Ce))]),_:1})]),n("div",it,[n("div",rt,r(l($)),1),e[7]||(e[7]=n("div",{class:"stat-label"},"总订单数",-1))])])]),_:1}),a(h,{xs:12,sm:6,md:6,lg:6},{default:t(()=>[n("div",pt,[n("div",ut,[a(b,{size:32},{default:t(()=>[a(l(xe))]),_:1})]),n("div",_t,[n("div",ct,"¥"+r(X.value),1),e[8]||(e[8]=n("div",{class:"stat-label"},"已支付金额",-1))])])]),_:1}),a(h,{xs:12,sm:6,md:6,lg:6},{default:t(()=>[n("div",mt,[n("div",ft,[a(b,{size:32},{default:t(()=>[a(l(Ee))]),_:1})]),n("div",yt,[n("div",vt,r(Y.value),1),e[9]||(e[9]=n("div",{class:"stat-label"},"待支付",-1))])])]),_:1}),a(h,{xs:12,sm:6,md:6,lg:6},{default:t(()=>[n("div",gt,[n("div",bt,[a(b,{size:32},{default:t(()=>[a(l(ze))]),_:1})]),n("div",kt,[n("div",wt,r(ee.value),1),e[10]||(e[10]=n("div",{class:"stat-label"},"已退款",-1))])])]),_:1})]),_:1}),a(ce,{shadow:"never",class:"main-card"},{default:t(()=>[a(Se,{name:"expand"},{default:t(()=>[R(n("div",ht,[a(ne,{inline:!0,model:l(g),class:"search-form","label-width":"80px"},{default:t(()=>[a(S,{label:"状态"},{default:t(()=>[a(B,{modelValue:l(g).status,"onUpdate:modelValue":e[0]||(e[0]=s=>l(g).status=s),placeholder:"全部状态",clearable:"",stLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as G,m as H,o as U,c as W,b as a,w as l,l as d,a6 as Z,H as A,r,aa as X,P as h,d as ee,aU as ae,E as le,i as n,e as te,f as oe,a as _,h as ne,aV as pe,t as se,as as ue,Z as ie,aW as re,D as I,k as v,j as de}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{r as D}from"./index-DpFNINBG.js";const me={class:"page-container"},_e={class:"card-header"},fe={__name:"PaymentConfig",setup(ye){const g=d(null),k=d(!1),b=d(!1),C=d(!1),f=d(!1),s=de({success:!1,message:""}),t=d({api_url:"",app_id:"",app_key:"",pay_types:["alipay","wxpay"]}),B={api_url:[{required:!0,message:"请输入支付网关地址",trigger:"blur"}],app_id:[{required:!0,message:"请输入商户ID",trigger:"blur"}],app_key:[{required:!0,message:"请输入商户密钥",trigger:"blur"}]},V=I(()=>(window.location.origin||"http://localhost:3000").replace(":3000",":8080")+"/api/public/payment/notify"),w=I(()=>(window.location.origin||"http://localhost:3000")+"/#/result");H(()=>R());async function R(){k.value=!0;try{const e=(await D.get("/system/configs?keys=payment_api_url,payment_app_id,payment_app_key,payment_pay_types")).data||{};t.value.api_url=e.payment_api_url||"",t.value.app_id=e.payment_app_id||"",t.value.app_key=e.payment_app_key||"",t.value.pay_types=e.payment_pay_types?JSON.parse(e.payment_pay_types):["alipay","wxpay"]}catch{}finally{k.value=!1}}async function q(){g.value&&await g.value.validate(async p=>{if(p){b.value=!0;try{await D.post("/system/configs",{configs:{payment_api_url:t.value.api_url,payment_app_id:t.value.app_id,payment_app_key:t.value.app_key,payment_pay_types:JSON.stringify(t.value.pay_types)}}),v.success("支付配置保存成功")}catch{}finally{b.value=!1}}})}async function L(){if(!t.value.api_url||!t.value.app_id||!t.value.app_key){v.warning("请先填写完整的接口参数");return}C.value=!0;try{const p=await D.post("/system/test-payment",{api_url:t.value.api_url,app_id:t.value.app_id,app_key:t.value.app_key});s.success=p.code===200,s.message=p.message||"连接测试完成",f.value=!0}catch{s.success=!1,s.message="连接测试失败,请检查参数",f.value=!0}finally{C.value=!1}}function x(p){navigator.clipboard.writeText(p).then(()=>{v.success("已复制到剪贴板")}).catch(()=>{v.info("复制失败,请手动复制")})}return(p,e)=>{const P=r("CreditCard"),u=le,N=ie,T=r("Connection"),y=ae,m=oe,i=te,S=r("Link"),c=ne,F=r("Coin"),J=r("BankCard"),E=se,K=r("ChatDotRound"),M=r("Chicken"),O=pe,Q=ee,Y=Z,$=re,j=A,z=ue;return U(),W("div",me,[a(Y,{shadow:"never",class:"config-card"},{header:l(()=>[_("div",_e,[_("span",null,[a(u,null,{default:l(()=>[a(P)]),_:1}),e[9]||(e[9]=n(" 支付配置",-1))]),a(N,{type:"warning",effect:"plain",size:"small"},{default:l(()=>[...e[10]||(e[10]=[n("易支付 (EPay) 接口",-1)])]),_:1})])]),default:l(()=>[X((U(),h(Q,{ref_key:"formRef",ref:g,model:t.value,rules:B,"label-width":"120px","label-position":"right"},{default:l(()=>[a(y,{"content-position":"left"},{default:l(()=>[a(u,null,{default:l(()=>[a(T)]),_:1}),e[11]||(e[11]=n(" 接口参数 ",-1))]),_:1}),a(i,{label:"支付网关",prop:"api_url"},{default:l(()=>[a(m,{modelValue:t.value.api_url,"onUpdate:modelValue":e[0]||(e[0]=o=>t.value.api_url=o),placeholder:"易支付网关地址,如 https://pay.example.com"},{prepend:l(()=>[...e[12]||(e[12]=[n("URL",-1)])]),_:1},8,["modelValue"]),e[13]||(e[13]=_("div",{class:"form-tip"},"易支付平台提供的支付网关地址,通常以 /submit.php 结尾",-1))]),_:1}),a(i,{label:"商户ID",prop:"app_id"},{default:l(()=>[a(m,{modelValue:t.value.app_id,"onUpdate:modelValue":e[1]||(e[1]=o=>t.value.app_id=o),placeholder:"易支付商户ID (PID)"},{prepend:l(()=>[...e[14]||(e[14]=[n("PID",-1)])]),_:1},8,["modelValue"])]),_:1}),a(i,{label:"商户密钥",prop:"app_key"},{default:l(()=>[a(m,{modelValue:t.value.app_key,"onUpdate:modelValue":e[2]||(e[2]=o=>t.value.app_key=o),type:"password","show-password":"",placeholder:"易支付商户密钥 (KEY)"},{'prepend"':l(()=>[...e[15]||(e[15]=[n("KEY",-1)])]),_:1},8,["modelValue"])]),_:1}),a(y,{"content-position":"left"},{default:l(()=>[a(u,null,{default:l(()=>[a(S)]),_:1}),e[16]||(e[16]=n(" 回调地址 ",-1))]),_:1}),a(i,{label:"异步通知地址"},{default:l(()=>[a(m,{modelValue:V.value,"onUpdate:modelValue":e[4]||(e[4]=o=>V.value=o),readonly:""},{append:l(()=>[a(c,{icon:p.CopyDocument,onClick:e[3]||(e[3]=o=>x(V.value))},{default:l(()=>[...e[17]||(e[17]=[n("复制",-1)])]),_:1},8,["icon"])]),_:1},8,["modelValue"]),e[18]||(e[18]=_("div",{class:"form-tip"},"将此地址填入易支付后台的「异步通知地址」",-1))]),_:1}),a(i,{label:"同步跳转地址"},{default:l(()=>[a(m,{modelValue:w.value,"onUpdate:modelValue":e[6]||(e[6]=o=>w.value=o),readonly:""},{append:l(()=>[a(c,{icon:p.CopyDocument,onClick:e[5]||(e[5]=o=>x(w.value))},{default:l(()=>[...eLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as G,m as H,o as U,c as W,b as a,w as l,l as d,a5 as Z,H as A,r,a9 as X,P as h,d as ee,aU as ae,E as le,i as n,e as te,f as oe,a as _,h as ne,aV as pe,t as se,ar as ue,Z as ie,aW as re,D as I,k as v,j as de}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{r as D}from"./index-CZCGMR8A.js";const me={class:"page-container"},_e={class:"card-header"},fe={__name:"PaymentConfig",setup(ye){const g=d(null),k=d(!1),b=d(!1),C=d(!1),f=d(!1),s=de({success:!1,message:""}),t=d({api_url:"",app_id:"",app_key:"",pay_types:["alipay","wxpay"]}),B={api_url:[{required:!0,message:"请输入支付网关地址",trigger:"blur"}],app_id:[{required:!0,message:"请输入商户ID",trigger:"blur"}],app_key:[{required:!0,message:"请输入商户密钥",trigger:"blur"}]},V=I(()=>(window.location.origin||"http://localhost:3000").replace(":3000",":8080")+"/api/public/payment/notify"),w=I(()=>(window.location.origin||"http://localhost:3000")+"/#/result");H(()=>R());async function R(){k.value=!0;try{const e=(await D.get("/system/configs?keys=payment_api_url,payment_app_id,payment_app_key,payment_pay_types")).data||{};t.value.api_url=e.payment_api_url||"",t.value.app_id=e.payment_app_id||"",t.value.app_key=e.payment_app_key||"",t.value.pay_types=e.payment_pay_types?JSON.parse(e.payment_pay_types):["alipay","wxpay"]}catch{}finally{k.value=!1}}async function q(){g.value&&await g.value.validate(async p=>{if(p){b.value=!0;try{await D.post("/system/configs",{configs:{payment_api_url:t.value.api_url,payment_app_id:t.value.app_id,payment_app_key:t.value.app_key,payment_pay_types:JSON.stringify(t.value.pay_types)}}),v.success("支付配置保存成功")}catch{}finally{b.value=!1}}})}async function L(){if(!t.value.api_url||!t.value.app_id||!t.value.app_key){v.warning("请先填写完整的接口参数");return}C.value=!0;try{const p=await D.post("/system/test-payment",{api_url:t.value.api_url,app_id:t.value.app_id,app_key:t.value.app_key});s.success=p.code===200,s.message=p.message||"连接测试完成",f.value=!0}catch{s.success=!1,s.message="连接测试失败,请检查参数",f.value=!0}finally{C.value=!1}}function x(p){navigator.clipboard.writeText(p).then(()=>{v.success("已复制到剪贴板")}).catch(()=>{v.info("复制失败,请手动复制")})}return(p,e)=>{const P=r("CreditCard"),u=le,N=ie,T=r("Connection"),y=ae,m=oe,i=te,S=r("Link"),c=ne,F=r("Coin"),J=r("BankCard"),E=se,K=r("ChatDotRound"),M=r("Chicken"),O=pe,Q=ee,Y=Z,$=re,j=A,z=ue;return U(),W("div",me,[a(Y,{shadow:"never",class:"config-card"},{header:l(()=>[_("div",_e,[_("span",null,[a(u,null,{default:l(()=>[a(P)]),_:1}),e[9]||(e[9]=n(" 支付配置",-1))]),a(N,{type:"warning",effect:"plain",size:"small"},{default:l(()=>[...e[10]||(e[10]=[n("易支付 (EPay) 接口",-1)])]),_:1})])]),default:l(()=>[X((U(),h(Q,{ref_key:"formRef",ref:g,model:t.value,rules:B,"label-width":"120px","label-position":"right"},{default:l(()=>[a(y,{"content-position":"left"},{default:l(()=>[a(u,null,{default:l(()=>[a(T)]),_:1}),e[11]||(e[11]=n(" 接口参数 ",-1))]),_:1}),a(i,{label:"支付网关",prop:"api_url"},{default:l(()=>[a(m,{modelValue:t.value.api_url,"onUpdate:modelValue":e[0]||(e[0]=o=>t.value.api_url=o),placeholder:"易支付网关地址,如 https://pay.example.com"},{prepend:l(()=>[...e[12]||(e[12]=[n("URL",-1)])]),_:1},8,["modelValue"]),e[13]||(e[13]=_("div",{class:"form-tip"},"易支付平台提供的支付网关地址,通常以 /submit.php 结尾",-1))]),_:1}),a(i,{label:"商户ID",prop:"app_id"},{default:l(()=>[a(m,{modelValue:t.value.app_id,"onUpdate:modelValue":e[1]||(e[1]=o=>t.value.app_id=o),placeholder:"易支付商户ID (PID)"},{prepend:l(()=>[...e[14]||(e[14]=[n("PID",-1)])]),_:1},8,["modelValue"])]),_:1}),a(i,{label:"商户密钥",prop:"app_key"},{default:l(()=>[a(m,{modelValue:t.value.app_key,"onUpdate:modelValue":e[2]||(e[2]=o=>t.value.app_key=o),type:"password","show-password":"",placeholder:"易支付商户密钥 (KEY)"},{'prepend"':l(()=>[...e[15]||(e[15]=[n("KEY",-1)])]),_:1},8,["modelValue"])]),_:1}),a(y,{"content-position":"left"},{default:l(()=>[a(u,null,{default:l(()=>[a(S)]),_:1}),e[16]||(e[16]=n(" 回调地址 ",-1))]),_:1}),a(i,{label:"异步通知地址"},{default:l(()=>[a(m,{modelValue:V.value,"onUpdate:modelValue":e[4]||(e[4]=o=>V.value=o),readonly:""},{append:l(()=>[a(c,{icon:p.CopyDocument,onClick:e[3]||(e[3]=o=>x(V.value))},{default:l(()=>[...e[17]||(e[17]=[n("复制",-1)])]),_:1},8,["icon"])]),_:1},8,["modelValue"]),e[18]||(e[18]=_("div",{class:"form-tip"},"将此地址填入易支付后台的「异步通知地址」",-1))]),_:1}),a(i,{label:"同步跳转地址"},{default:l(()=>[a(m,{modelValue:w.value,"onUpdate:modelValue":e[6]||(e[6]=o=>w.value=o),readonly:""},{append:l(()=>[a(c,{icon:p.CopyDocument,onClick:e[5]||(e[5]=o=>x(w.value))},{default:l(()=>[...eLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
.el-result{--el-result-padding:40px 30px;--el-result-icon-font-size:64px;--el-result-title-font-size:20px;--el-result-title-margin-top:20px;--el-result-subtitle-margin-top:10px;--el-result-extra-margin-top:30px;text-align:center;box-sizing:border-box;padding:var(--el-result-padding);flex-direction:column;justify-content:center;align-items:center;display:flex}.el-result__icon svg{width:var(--el-result-icon-font-size);height:var(--el-result-icon-font-size)}.el-result__title{margin-top:var(--el-result-title-margin-top)}.el-result__title p{font-size:var(--el-result-title-font-size);color:var(--el-text-color-primary);margin:0;line-height:1.3}.el-result__subtitle{margin-top:var(--el-result-subtitle-margin-top)}.el-result__subtitle p{font-size:var(--el-font-size-base);color:var(--el-text-color-regular);margin:0;line-height:1.3}.el-result__extra{margin-top:var(--el-result-extra-margin-top)}.el-result .icon-primary{--el-result-color:var(--el-color-primary);color:var(--el-result-color)}.el-result .icon-success{--el-result-color:var(--el-color-success);color:var(--el-result-color)}.el-result .icon-warning{--el-result-color:var(--el-color-warning);color:var(--el-result-color)}.el-result .icon-danger{--el-result-color:var(--el-color-danger);color:var(--el-result-color)}.el-result .icon-error{--el-result-color:var(--el-color-error);color:var(--el-result-color)}.el-result .icon-info{--el-result-color:var(--el-color-info);color:var(--el-result-color)}.el-checkbox-group{font-size:0;line-height:0}.el-divider{position:relative}.el-divider--horizontal{border-top:1px var(--el-border-color) var(--el-border-style);width:100%;height:1px;margin:24px 0;display:block}.el-divider--vertical{vertical-align:middle;border-left:1px var(--el-border-color) var(--el-border-style);width:1px;height:1em;margin:0 8px;display:inline-block;position:relative}.el-divider__text{background-color:var(--el-bg-color);color:var(--el-text-color-primary);padding:0 20px;font-size:14px;font-weight:500;position:absolute}.el-divider__text.is-left{left:20px;transform:translateY(-50%)}.el-divider__text.is-center{left:50%;transform:translate(-50%)translateY(-50%)}.el-divider__text.is-right{right:20px;transform:translateY(-50%)}.page-container[data-v-17922bec]{max-width:800px}.config-card[data-v-17922bec]{border-radius:8px}.card-header[data-v-17922bec]{display:flex;justify-content:space-between;align-items:center;font-size:16px;font-weight:600}.card-header .el-icon[data-v-17922bec]{margin-right:6px;vertical-align:middle}.form-tip[data-v-17922bec]{font-size:12px;color:#909399;margin-top:4px;line-height:1.5}.el-divider[data-v-17922bec]{margin:24px 0 20px}.el-divider .el-icon[data-v-17922bec]{margin-right:6px}
|
||||
@@ -0,0 +1 @@
|
||||
.products-page[data-v-de7333bd]{max-width:1600px;margin:0 auto}.stats-row[data-v-de7333bd]{margin-bottom:20px}.stat-card[data-v-de7333bd]{background:#fff;border-radius:12px;padding:24px;display:flex;align-items:center;gap:20px;box-shadow:0 2px 8px #0000000f;transition:all .3s ease}.stat-card[data-v-de7333bd]:hover{transform:translateY(-4px);box-shadow:0 8px 16px #0000001a}.stat-icon[data-v-de7333bd]{width:64px;height:64px;border-radius:12px;display:flex;align-items:center;justify-content:center;color:#fff;flex-shrink:0}.stat-total .stat-icon[data-v-de7333bd]{background:linear-gradient(135deg,#667eea,#764ba2)}.stat-active .stat-icon[data-v-de7333bd]{background:linear-gradient(135deg,#43e97b,#38f9d7)}.stat-inactive .stat-icon[data-v-de7333bd]{background:linear-gradient(135deg,#f093fb,#f5576c)}.stat-forever .stat-icon[data-v-de7333bd]{background:linear-gradient(135deg,#4facfe,#00f2fe)}.stat-value[data-v-de7333bd]{font-size:32px;font-weight:700;color:#303133}.stat-label[data-v-de7333bd]{font-size:14px;color:#909399;margin-top:4px}.advanced-search[data-v-de7333bd]{padding:20px;background:#f5f7fa;border-radius:8px;margin-bottom:20px}.search-form[data-v-de7333bd]{display:flex;flex-wrap:wrap;gap:12px}.toolbar[data-v-de7333bd]{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:12px}.toolbar-left[data-v-de7333bd],.toolbar-right[data-v-de7333bd]{display:flex;gap:12px;flex-wrap:wrap}.data-table[data-v-de7333bd] .el-table__header th{font-weight:600;color:#303133}.price-text[data-v-de7333bd]{color:#f56c6c;font-weight:700}.pagination-wrapper[data-v-de7333bd]{margin-top:20px;display:flex;justify-content:flex-end}.column-settings[data-v-de7333bd]{padding:8px}.column-settings-title[data-v-de7333bd]{font-weight:600;margin-bottom:12px}.column-settings .el-checkbox[data-v-de7333bd]{display:block;margin-bottom:8px}.expand-enter-active[data-v-de7333bd],.expand-leave-active[data-v-de7333bd]{transition:all .3s ease}.expand-enter-from[data-v-de7333bd],.expand-leave-to[data-v-de7333bd]{opacity:0;max-height:0;overflow:hidden}.expand-enter-to[data-v-de7333bd],.expand-leave-from[data-v-de7333bd]{opacity:1;max-height:200px}@media (max-width:768px){.toolbar[data-v-de7333bd]{flex-direction:column;align-items:stretch}.toolbar-left[data-v-de7333bd],.toolbar-right[data-v-de7333bd]{width:100%}.search-form[data-v-de7333bd]{flex-direction:column}.search-form .el-form-item[data-v-de7333bd],.search-form .el-select[data-v-de7333bd],.search-form .el-input[data-v-de7333bd]{width:100%!important}}
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Re,m as Pe,o as r,c as R,b as t,w as a,l as w,a4 as Be,a6 as Me,H as Te,a5 as qe,a as n,E as Le,n as l,ax as Ne,C as g,a8 as Ke,a9 as He,ay as Oe,T as Ae,aa as X,d as Ze,e as Ge,ab as Je,F as O,R as A,P as u,ac as Qe,f as We,g as Xe,h as Ye,ad as et,i as c,ae as Y,af as tt,ag as at,K as p,S as lt,ah as ot,ai as st,U as nt,V as it,aj as ee,ak as dt,al as rt,t as ut,am as ct,an as pt,ao as mt,Z as _t,aq as ft,ar as gt,as as vt,at as bt,au as te,av as yt,D as z,k as C,aw as ae}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as ht}from"./user-DvAOsLmR.js";import{u as wt,a as Ct}from"./useColumnSettings-BO5PTaEn.js";import{r as x}from"./index-DpFNINBG.js";const kt={class:"products-page"},Vt={class:"stat-card stat-total"},xt={class:"stat-icon"},Et={class:"stat-info"},jt={class:"stat-value"},St={class:"stat-card stat-active"},Ut={class:"stat-icon"},zt={class:"stat-info"},$t={class:"stat-value"},Dt={class:"stat-card stat-inactive"},Ft={class:"stat-icon"},It={class:"stat-info"},Rt={class:"stat-value"},Pt={class:"stat-card stat-forever"},Bt={class:"stat-icon"},Mt={class:"stat-info"},Tt={class:"stat-value"},qt={class:"advanced-search"},Lt={class:"toolbar"},Nt={class:"toolbar-left"},Kt={class:"toolbar-right"},Ht={class:"column-settings"},Ot={class:"price-text"},At={class:"pagination-wrapper"},Zt={__name:"Products",setup(Gt){const le=ht(),P=z(()=>le.user),B=z(()=>{var o;return["admin","project_admin"].includes((o=P.value)==null?void 0:o.role)}),M=w([]),$=w(!0),{list:D,loading:oe,page:T,pageSize:q,total:Z,selectedRows:b,filters:y,tableMaxHeight:se,fetchData:E,handleSelectionChange:ne,handleSortChange:ie,handleSizeChange:de,handleFilterChange:j,resetFilters:re,refreshData:ue}=wt({apiUrl:"/products",defaultFilters:{project_id:"",status:"",keyword:""},defaultPageSize:20}),{columnOptions:ce,visibleColumns:v,saveColumnSettings:pe}=Ct("products_column_settings",[{prop:"id",label:"ID"},{prop:"project_name",label:"所属项目"},{prop:"name",label:"商品名称"},{prop:"duration_days",label:"有效期"},{prop:"original_price",label:"原价"},{prop:"price",label:"售价"},{prop:"agent_cost",label:"代理成本"},{prop:"sort",label:"排序"},{prop:"status",label:"状态"},{prop:"created_at",label:"创建时间"}]),me=z(()=>D.value.filter(o=>o.status===1).length),_e=z(()=>D.value.filter(o=>o.status===0).length),fe=z(()=>D.value.filter(o=>o.duration_days==0).length);Pe(async()=>{const o=await x.get("/projects/all");M.value=o.data});const k=w(!1),S=w(!1),L=w(null),d=w({project_id:null,name:"",duration_days:30,price:0,original_price:0,agent_cost:0,sort:0,status:1}),ge={project_id:[{required:!0,message:"请选择项目",trigger:"change"}],name:[{required:!0,message:"请输入商品名称",trigger:"blur"}],price:[{required:!0,type:"number",message:"请输入价格",trigger:"blur"}]},N=w(!1);let K=null;function ve(){S.value=!1,K=null,d.value={project_id:null,name:"",duration_days:30,price:0,original_price:0,agent_cost:0,sort:0,status:1},k.value=!0}function be(o){S.value=!0,K=o.id,d.value={project_id:o.project_id,name:o.name,duration_days:o.duration_days,price:o.price,original_price:o.original_price??0,agent_cost:o.agent_cost,sort:o.sort,status:o.status},k.value=!0}async function ye(){L.value&&await L.value.validate(async o=>{if(o){N.value=!0;try{const e=d.value.project_id;S.value?(await x.put(`/projects/${e}/card-types/${K}`,d.value),C.success("更新成功")):(await x.post(`/projects/${e}/card-types`,d.value),C.success("创建成功")),k.value=!1,E()}catch(e){console.error(e)}finally{N.value=!1}}})}async function he(o){try{await ae.confirm("确定删除该商品?","提示",{type:"warning"}),await x.delete(`/projects/${o.project_id}/card-types/${o.id}`),C.success("删除成功"),E()}catch(e){e!=="cancel"&&console.error(e)}}async function we(){if(b.value.length)try{await ae.confirm(`确定删除选中的 ${b.value.length} 个商品吗?`,"批量删除",{type:"warning"});for(const o of b.value)await x.delete(`/projects/${o.project_id}/card-types/${o.id}`);C.success("批量删除成功"),E()}catch(o){o!=="cancel"&&console.error(o)}}async function Ce(o){try{await x.put(`/projects/${o.project_id}/card-types/${o.id}`,{status:o.status}),C.success("状态更新成功"),E()}catch(e){o.status=o.status===1?0:1,console.error(e)}}function ke(o){if(!b.value.length){C.warning("请先选择要导出的数据");return}const e=new URLSearchParams;e.set("ids",b.value.map(V=>V.id).join(",")),e.append("format",o);const h=localStorage.getItem("access_token");window.open(`/api/products/export?${e.toString()}&token=${h}`,"_blank"),C.success("导Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Re,m as Pe,o as r,c as R,b as t,w as a,l as w,a3 as Be,a5 as Me,H as Te,a4 as qe,a as n,E as Le,n as l,aw as Ne,C as g,a7 as Ke,a8 as He,ax as Oe,T as Ae,a9 as X,d as Ze,e as Ge,aa as Je,F as O,R as A,P as u,ab as Qe,f as We,g as Xe,h as Ye,ac as et,i as c,ad as Y,ae as tt,af as at,K as p,S as lt,ag as ot,ah as st,U as nt,V as it,ai as ee,aj as dt,ak as rt,t as ut,al as ct,am as pt,an as mt,Z as _t,ap as ft,aq as gt,ar as vt,as as bt,at as te,au as yt,D as z,k as C,av as ae}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as ht}from"./user-KptFbP1d.js";import{u as wt,a as Ct}from"./useColumnSettings-sXzip_cz.js";import{r as x}from"./index-CZCGMR8A.js";const kt={class:"products-page"},Vt={class:"stat-card stat-total"},xt={class:"stat-icon"},Et={class:"stat-info"},jt={class:"stat-value"},St={class:"stat-card stat-active"},Ut={class:"stat-icon"},zt={class:"stat-info"},$t={class:"stat-value"},Dt={class:"stat-card stat-inactive"},Ft={class:"stat-icon"},It={class:"stat-info"},Rt={class:"stat-value"},Pt={class:"stat-card stat-forever"},Bt={class:"stat-icon"},Mt={class:"stat-info"},Tt={class:"stat-value"},qt={class:"advanced-search"},Lt={class:"toolbar"},Nt={class:"toolbar-left"},Kt={class:"toolbar-right"},Ht={class:"column-settings"},Ot={class:"price-text"},At={class:"pagination-wrapper"},Zt={__name:"Products",setup(Gt){const le=ht(),P=z(()=>le.user),B=z(()=>{var o;return["admin","project_admin"].includes((o=P.value)==null?void 0:o.role)}),M=w([]),$=w(!0),{list:D,loading:oe,page:T,pageSize:q,total:Z,selectedRows:b,filters:y,tableMaxHeight:se,fetchData:E,handleSelectionChange:ne,handleSortChange:ie,handleSizeChange:de,handleFilterChange:j,resetFilters:re,refreshData:ue}=wt({apiUrl:"/products",defaultFilters:{project_id:"",status:"",keyword:""},defaultPageSize:20}),{columnOptions:ce,visibleColumns:v,saveColumnSettings:pe}=Ct("products_column_settings",[{prop:"id",label:"ID"},{prop:"project_name",label:"所属项目"},{prop:"name",label:"商品名称"},{prop:"duration_days",label:"有效期"},{prop:"original_price",label:"原价"},{prop:"price",label:"售价"},{prop:"agent_cost",label:"代理成本"},{prop:"sort",label:"排序"},{prop:"status",label:"状态"},{prop:"created_at",label:"创建时间"}]),me=z(()=>D.value.filter(o=>o.status===1).length),_e=z(()=>D.value.filter(o=>o.status===0).length),fe=z(()=>D.value.filter(o=>o.duration_days==0).length);Pe(async()=>{const o=await x.get("/projects/all");M.value=o.data});const k=w(!1),S=w(!1),L=w(null),d=w({project_id:null,name:"",duration_days:30,price:0,original_price:0,agent_cost:0,sort:0,status:1}),ge={project_id:[{required:!0,message:"请选择项目",trigger:"change"}],name:[{required:!0,message:"请输入商品名称",trigger:"blur"}],price:[{required:!0,type:"number",message:"请输入价格",trigger:"blur"}]},N=w(!1);let K=null;function ve(){S.value=!1,K=null,d.value={project_id:null,name:"",duration_days:30,price:0,original_price:0,agent_cost:0,sort:0,status:1},k.value=!0}function be(o){S.value=!0,K=o.id,d.value={project_id:o.project_id,name:o.name,duration_days:o.duration_days,price:o.price,original_price:o.original_price??0,agent_cost:o.agent_cost,sort:o.sort,status:o.status},k.value=!0}async function ye(){L.value&&await L.value.validate(async o=>{if(o){N.value=!0;try{const e=d.value.project_id;S.value?(await x.put(`/projects/${e}/card-types/${K}`,d.value),C.success("更新成功")):(await x.post(`/projects/${e}/card-types`,d.value),C.success("创建成功")),k.value=!1,E()}catch(e){console.error(e)}finally{N.value=!1}}})}async function he(o){try{await ae.confirm("确定删除该商品?","提示",{type:"warning"}),await x.delete(`/projects/${o.project_id}/card-types/${o.id}`),C.success("删除成功"),E()}catch(e){e!=="cancel"&&console.error(e)}}async function we(){if(b.value.length)try{await ae.confirm(`确定删除选中的 ${b.value.length} 个商品吗?`,"批量删除",{type:"warning"});for(const o of b.value)await x.delete(`/projects/${o.project_id}/card-types/${o.id}`);C.success("批量删除成功"),E()}catch(o){o!=="cancel"&&console.error(o)}}async function Ce(o){try{await x.put(`/projects/${o.project_id}/card-types/${o.id}`,{status:o.status}),C.success("状态更新成功"),E()}catch(e){o.status=o.status===1?0:1,console.error(e)}}function ke(o){if(!b.value.length){C.warning("请先选择要导出的数据");return}const e=new URLSearchParams;e.set("ids",b.value.map(V=>V.id).join(",")),e.append("format",o);const h=localStorage.getItem("access_token");window.open(`/api/products/export?${e.toString()}&token=${h}`,"_blank"),C.success("导Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Ze,o as c,c as ie,b as t,w as a,a3 as Ge,a5 as Je,l as p,H as Qe,a4 as We,a as n,E as Xe,n as o,a6 as Ye,C as g,a7 as et,a8 as tt,T as at,a9 as X,d as lt,e as ot,f as st,g as nt,aa as it,ab as dt,h as ut,ac as rt,i,ad as de,ae as pt,P as y,af as ue,K as k,S as ct,ag as mt,ah as ft,U as vt,V as _t,ai as re,aj as gt,ak as yt,F as bt,R as wt,t as kt,al as Ct,am as ht,an as Vt,ao as xt,ap as Et,aq as St,ar as $t,as as Ut,at as pe,Z as jt,au as zt,D as P,k as f,av as R}from"./index-BpUdMXzZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as Dt}from"./user-KptFbP1d.js";import{u as Ft,a as It}from"./useColumnSettings-sXzip_cz.js";import{r as b}from"./index-CZCGMR8A.js";const Pt={class:"projects-page"},Rt={class:"stat-card stat-total"},Tt={class:"stat-icon"},Kt={class:"stat-info"},Bt={class:"stat-value"},Lt={class:"stat-card stat-active"},At={class:"stat-icon"},qt={class:"stat-info"},Mt={class:"stat-value"},Nt={class:"stat-card stat-inactive"},Ht={class:"stat-icon"},Ot={class:"stat-info"},Zt={class:"stat-value"},Gt={class:"advanced-search"},Jt={class:"toolbar"},Qt={class:"toolbar-left"},Wt={class:"toolbar-right"},Xt={class:"column-settings"},Yt={class:"key-cell"},ea={class:"mono-text"},ta={class:"pagination-wrapper"},aa={style:{"margin-bottom":"12px"}},la={__name:"Projects",setup(oa){const ce=Dt(),me=P(()=>ce.user),T=P(()=>{var s;return["admin","project_admin"].includes((s=me.value)==null?void 0:s.role)}),j=p(!0),{list:K,loading:fe,page:B,pageSize:L,total:Y,selectedRows:w,filters:S,tableMaxHeight:ve,fetchData:h,handleSelectionChange:_e,handleSortChange:ge,handleSizeChange:ye,handleFilterChange:z,resetFilters:be,refreshData:we}=Ft({apiUrl:"/projects",defaultFilters:{keyword:"",status:""},defaultPageSize:20}),{columnOptions:ke,visibleColumns:V,saveColumnSettings:Ce}=It("projects_column_settings",[{prop:"id",label:"ID"},{prop:"name",label:"项目名称"},{prop:"description",label:"描述"},{prop:"api_key",label:"API Key"},{prop:"status",label:"状态"},{prop:"created_at",label:"创建时间"}]),he=P(()=>K.value.filter(s=>s.status===1).length),Ve=P(()=>K.value.filter(s=>s.status===0).length),x=p(!1),D=p(!1),A=p(null),v=p({name:"",description:"",status:1}),xe={name:[{required:!0,message:"请输入项目名称",trigger:"blur"}]},q=p(!1);let M=null;function Ee(){D.value=!1,M=null,v.value={name:"",description:"",status:1},x.value=!0}function Se(s){D.value=!0,M=s.id,v.value={name:s.name,description:s.description,status:s.status},x.value=!0}async function $e(){A.value&&await A.value.validate(async s=>{if(s){q.value=!0;try{if(D.value)await b.put(`/projects/${M}`,v.value),f.success("更新成功");else{const e=await b.post("/projects",v.value);f.success("创建成功,API Key: "+e.data.api_key)}x.value=!1,h()}catch{}finally{q.value=!1}}})}async function Ue(s){try{await b.put(`/projects/${s.id}`,{status:s.status}),f.success("状态更新成功"),h()}catch{s.status=s.status===1?0:1}}async function je(s){try{await R.confirm("确定重置API Key?旧Key将立即失效。","提示",{type:"warning"});const e=await b.post(`/projects/${s.id}/regenerate-key`);f.success("新API Key: "+e.data.api_key),h()}catch{}}async function ze(s){try{await R.confirm("确定删除该项目?","提示",{type:"warning"}),await b.delete(`/projects/${s.id}`),f.success("删除成功"),h()}catch{}}async function De(){if(w.value.length)try{await R.confirm(`确定删除选中的 ${w.value.length} 个项目吗?`,"批量删除",{type:"warning"});for(const s of w.value)await b.delete(`/projects/${s.id}`);f.success("批量删除成功"),h()}catch{}}function Fe(s){if(!w.value.length){f.warning("请先选择要导出的项目");return}const e=new URLSearchParams;e.set("ids",w.value.map(U=>U.id).join(",")),e.append("format",s);const C=localStorage.getItem("access_token");window.open(`/api/projects/export?${e.toString()}&token=${C}`,"_blank"),f.success("导出任务已启动")}function Ie(s){navigator.clipboard.writeText(s).then(()=>f.success("已复制")).catch(()=>f.error("复制失败"))}const N=p(!1),E=p(null),ee=p([]),H=p(!1),$=p(!1),O=p(null),d=p({name:"",duration_days:30,price:0,agent_cost:0,sort:0,status:1}),Pe={name:[{required:!0,message:"请输入名称",trigger:"blur"}],price:[{required:!0,type:"number",message:"请输入价格",trigger:"blur"}]},Z=p(!1);async function G(s){E.value=s,N.value=!0,H.value=!0;try{ee.value=(await b.get(`/projects/${s.id}/card-types`)).data}finally{H.value=!1}}function te(s){d.value=s?{...s}:{name:"",duration_days:30,price:0,agent_cost:0,sort:0,status:1},$.value=!0}async function Re(){O.value&&await O.value.validate(async s=>{if(s){ZLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
.projects-page[data-v-1c1317bf]{max-width:1600px;margin:0 auto}.stats-row[data-v-1c1317bf]{margin-bottom:20px}.stat-card[data-v-1c1317bf]{background:#fff;border-radius:12px;padding:24px;display:flex;align-items:center;gap:20px;box-shadow:0 2px 8px #0000000f;transition:all .3s ease}.stat-card[data-v-1c1317bf]:hover{transform:translateY(-4px);box-shadow:0 8px 16px #0000001a}.stat-icon[data-v-1c1317bf]{width:64px;height:64px;border-radius:12px;display:flex;align-items:center;justify-content:center;color:#fff;flex-shrink:0}.stat-total .stat-icon[data-v-1c1317bf]{background:linear-gradient(135deg,#667eea,#764ba2)}.stat-active .stat-icon[data-v-1c1317bf]{background:linear-gradient(135deg,#43e97b,#38f9d7)}.stat-inactive .stat-icon[data-v-1c1317bf]{background:linear-gradient(135deg,#f093fb,#f5576c)}.stat-value[data-v-1c1317bf]{font-size:32px;font-weight:700;color:#303133}.stat-label[data-v-1c1317bf]{font-size:14px;color:#909399;margin-top:4px}.advanced-search[data-v-1c1317bf]{padding:20px;background:#f5f7fa;border-radius:8px;margin-bottom:20px}.search-form[data-v-1c1317bf]{display:flex;flex-wrap:wrap;gap:12px}.toolbar[data-v-1c1317bf]{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:12px}.toolbar-left[data-v-1c1317bf],.toolbar-right[data-v-1c1317bf]{display:flex;gap:12px;flex-wrap:wrap}.data-table[data-v-1c1317bf] .el-table__header th{font-weight:600;color:#303133}.key-cell[data-v-1c1317bf]{display:flex;align-items:center;gap:8px}.copy-icon[data-v-1c1317bf]{color:#409eff;cursor:pointer}.mono-text[data-v-1c1317bf]{font-family:Courier New,monospace}.pagination-wrapper[data-v-1c1317bf]{margin-top:20px;display:flex;justify-content:flex-end}.column-settings[data-v-1c1317bf]{padding:8px}.column-settings-title[data-v-1c1317bf]{font-weight:600;margin-bottom:12px}.column-settings .el-checkbox[data-v-1c1317bf]{display:block;margin-bottom:8px}.expand-enter-active[data-v-1c1317bf],.expand-leave-active[data-v-1c1317bf]{transition:all .3s ease}.expand-enter-from[data-v-1c1317bf],.expand-leave-to[data-v-1c1317bf]{opacity:0;max-height:0;overflow:hidden}.expand-enter-to[data-v-1c1317bf],.expand-leave-from[data-v-1c1317bf]{opacity:1;max-height:200px}@media (max-width:768px){.toolbar[data-v-1c1317bf]{flex-direction:column;align-items:stretch}.toolbar-left[data-v-1c1317bf],.toolbar-right[data-v-1c1317bf]{width:100%}.search-form[data-v-1c1317bf]{flex-direction:column}.search-form .el-form-item[data-v-1c1317bf],.search-form .el-select[data-v-1c1317bf],.search-form .el-input[data-v-1c1317bf]{width:100%!important}}
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Ze,o as c,c as ie,b as t,w as a,a4 as Ge,a6 as Je,l as p,H as Qe,a5 as We,a as n,E as Xe,n as o,a7 as Ye,C as g,a8 as et,a9 as tt,T as at,aa as X,d as lt,e as ot,f as st,g as nt,ab as it,ac as dt,h as ut,ad as rt,i,ae as de,af as pt,P as y,ag as ue,K as k,S as ct,ah as mt,ai as ft,U as vt,V as _t,aj as re,ak as gt,al as yt,F as bt,R as wt,t as kt,am as Ct,an as ht,ao as Vt,ap as xt,aq as Et,ar as St,as as $t,at as Ut,au as pe,Z as jt,av as zt,D as P,k as f,aw as R}from"./index-oChIw9ZZ.js";/* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css *//* empty css */import{u as Dt}from"./user-DvAOsLmR.js";import{u as Ft,a as It}from"./useColumnSettings-BO5PTaEn.js";import{r as b}from"./index-DpFNINBG.js";const Pt={class:"projects-page"},Rt={class:"stat-card stat-total"},Tt={class:"stat-icon"},Kt={class:"stat-info"},Bt={class:"stat-value"},Lt={class:"stat-card stat-active"},At={class:"stat-icon"},qt={class:"stat-info"},Mt={class:"stat-value"},Nt={class:"stat-card stat-inactive"},Ht={class:"stat-icon"},Ot={class:"stat-info"},Zt={class:"stat-value"},Gt={class:"advanced-search"},Jt={class:"toolbar"},Qt={class:"toolbar-left"},Wt={class:"toolbar-right"},Xt={class:"column-settings"},Yt={class:"key-cell"},ea={class:"mono-text"},ta={class:"pagination-wrapper"},aa={style:{"margin-bottom":"12px"}},la={__name:"Projects",setup(oa){const ce=Dt(),me=P(()=>ce.user),T=P(()=>{var s;return["admin","project_admin"].includes((s=me.value)==null?void 0:s.role)}),j=p(!0),{list:K,loading:fe,page:B,pageSize:L,total:Y,selectedRows:w,filters:S,tableMaxHeight:ve,fetchData:h,handleSelectionChange:_e,handleSortChange:ge,handleSizeChange:ye,handleFilterChange:z,resetFilters:be,refreshData:we}=Ft({apiUrl:"/projects",defaultFilters:{keyword:"",status:""},defaultPageSize:20}),{columnOptions:ke,visibleColumns:V,saveColumnSettings:Ce}=It("projects_column_settings",[{prop:"id",label:"ID"},{prop:"name",label:"项目名称"},{prop:"description",label:"描述"},{prop:"api_key",label:"API Key"},{prop:"status",label:"状态"},{prop:"created_at",label:"创建时间"}]),he=P(()=>K.value.filter(s=>s.status===1).length),Ve=P(()=>K.value.filter(s=>s.status===0).length),x=p(!1),D=p(!1),A=p(null),v=p({name:"",description:"",status:1}),xe={name:[{required:!0,message:"请输入项目名称",trigger:"blur"}]},q=p(!1);let M=null;function Ee(){D.value=!1,M=null,v.value={name:"",description:"",status:1},x.value=!0}function Se(s){D.value=!0,M=s.id,v.value={name:s.name,description:s.description,status:s.status},x.value=!0}async function $e(){A.value&&await A.value.validate(async s=>{if(s){q.value=!0;try{if(D.value)await b.put(`/projects/${M}`,v.value),f.success("更新成功");else{const e=await b.post("/projects",v.value);f.success("创建成功,API Key: "+e.data.api_key)}x.value=!1,h()}catch{}finally{q.value=!1}}})}async function Ue(s){try{await b.put(`/projects/${s.id}`,{status:s.status}),f.success("状态更新成功"),h()}catch{s.status=s.status===1?0:1}}async function je(s){try{await R.confirm("确定重置API Key?旧Key将立即失效。","提示",{type:"warning"});const e=await b.post(`/projects/${s.id}/regenerate-key`);f.success("新API Key: "+e.data.api_key),h()}catch{}}async function ze(s){try{await R.confirm("确定删除该项目?","提示",{type:"warning"}),await b.delete(`/projects/${s.id}`),f.success("删除成功"),h()}catch{}}async function De(){if(w.value.length)try{await R.confirm(`确定删除选中的 ${w.value.length} 个项目吗?`,"批量删除",{type:"warning"});for(const s of w.value)await b.delete(`/projects/${s.id}`);f.success("批量删除成功"),h()}catch{}}function Fe(s){if(!w.value.length){f.warning("请先选择要导出的项目");return}const e=new URLSearchParams;e.set("ids",w.value.map(U=>U.id).join(",")),e.append("format",s);const C=localStorage.getItem("access_token");window.open(`/api/projects/export?${e.toString()}&token=${C}`,"_blank"),f.success("导出任务已启动")}function Ie(s){navigator.clipboard.writeText(s).then(()=>f.success("已复制")).catch(()=>f.error("复制失败"))}const N=p(!1),E=p(null),ee=p([]),H=p(!1),$=p(!1),O=p(null),d=p({name:"",duration_days:30,price:0,agent_cost:0,sort:0,status:1}),Pe={name:[{required:!0,message:"请输入名称",trigger:"blur"}],price:[{required:!0,type:"number",message:"请输入价格",trigger:"blur"}]},Z=p(!1);async function G(s){E.value=s,N.value=!0,H.value=!0;try{ee.value=(await b.get(`/projects/${s.id}/card-types`)).data}finally{H.value=!1}}function te(s){d.value=s?{...s}:{name:"",duration_days:30,price:0,agent_cost:0,sort:0,status:1},$.value=!0}async function Re(){O.value&&await O.value.validate(async s=>{if(s){ZLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
.glass-app[data-v-f4e96b6c]{--glass-bg: rgba(255,255,255,.12);--glass-bg-heavy: rgba(255,255,255,.18);--glass-border: rgba(255,255,255,.25);--glass-border-strong: rgba(255,255,255,.4);--glass-blur: 16px;--glass-blur-heavy: 20px;--radius: 16px;--radius-sm: 12px;--radius-xs: 8px;--c-white: rgba(255,255,255,.92);--c-white-70: rgba(255,255,255,.7);--c-white-50: rgba(255,255,255,.5);--c-white-30: rgba(255,255,255,.3);--c-primary: #60a5fa;--c-success: #34d399;--c-warning: #fbbf24;--c-danger: #f87171;--c-purple: #a78bfa;min-height:100vh;position:relative;overflow-x:hidden;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Microsoft YaHei,sans-serif;color:var(--c-white)}.bg-layer[data-v-f4e96b6c]{position:fixed;top:0;right:0;bottom:0;left:0;z-index:0;background:linear-gradient(135deg,#0f0c29,#302b63 40%,#24243e);overflow:hidden}.bg-blob[data-v-f4e96b6c]{position:absolute;border-radius:50%;filter:blur(80px);opacity:.5;will-change:transform;animation:blob-float-f4e96b6c 20s ease-in-out infinite alternate}.blob-1[data-v-f4e96b6c]{width:600px;height:600px;top:-10%;left:-5%;background:#6366f1;animation-duration:22s}.blob-2[data-v-f4e96b6c]{width:500px;height:500px;top:30%;right:-8%;background:#ec4899;animation-duration:18s;animation-delay:-5s}.blob-3[data-v-f4e96b6c]{width:400px;height:400px;bottom:-5%;left:20%;background:#06b6d4;animation-duration:25s;animation-delay:-10s}.blob-4[data-v-f4e96b6c]{width:350px;height:350px;top:50%;left:50%;background:#8b5cf6;animation-duration:20s;animation-delay:-7s}@keyframes blob-float-f4e96b6c{0%{transform:translate(0) scale(1)}33%{transform:translate(30px,-40px) scale(1.05)}66%{transform:translate(-20px,30px) scale(.95)}to{transform:translate(10px,-10px) scale(1.02)}}.bg-noise[data-v-f4e96b6c]{position:absolute;top:0;right:0;bottom:0;left:0;background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.04'/%3E%3C/svg%3E");background-size:256px;opacity:.4}.glass-header[data-v-f4e96b6c]{position:sticky;top:0;z-index:100;background:#0f0c2999;backdrop-filter:blur(var(--glass-blur-heavy));-webkit-backdrop-filter:blur(var(--glass-blur-heavy));border-bottom:1px solid var(--glass-border)}.header-inner[data-v-f4e96b6c]{max-width:1100px;margin:0 auto;padding:16px 24px 0}.header-brand[data-v-f4e96b6c]{display:flex;align-items:center;gap:12px;margin-bottom:14px;cursor:pointer}.brand-glass-icon[data-v-f4e96b6c]{width:44px;height:44px;border-radius:12px;background:var(--glass-bg);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);border:1px solid var(--glass-border);display:flex;align-items:center;justify-content:center;color:var(--c-primary)}.brand-text h1[data-v-f4e96b6c]{font-size:20px;font-weight:700;margin:0;color:var(--c-white);line-height:1.3}.brand-text p[data-v-f4e96b6c]{font-size:12px;color:var(--c-white-50);margin:0}.glass-nav[data-v-f4e96b6c]{display:flex;gap:4px}.glass-tab[data-v-f4e96b6c]{display:flex;align-items:center;gap:6px;padding:10px 18px;border:none;background:none;font-size:13px;color:var(--c-white-50);cursor:pointer;border-radius:var(--radius-sm) var(--radius-sm) 0 0;transition:all .3s ease;font-family:inherit;-webkit-user-select:none;user-select:none;position:relative}.glass-tab[data-v-f4e96b6c]:hover{color:var(--c-white-70);background:#ffffff0d}.glass-tab.active[data-v-f4e96b6c]{color:var(--c-white);background:var(--glass-bg);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);border:1px solid var(--glass-border);border-bottom-color:transparent}.glass-tab.active[data-v-f4e96b6c]:after{content:"";position:absolute;bottom:-1px;left:0;right:0;height:2px;background:var(--c-primary);border-radius:2px 2px 0 0}.tab-icon[data-v-f4e96b6c]{display:flex;align-items:center}.glass-main[data-v-f4e96b6c]{position:relative;z-index:1;max-width:1100px;margin:0 auto;padding:28px 24px 60px}.panel-fade-enter-active[data-v-f4e96b6c],.panel-fade-leave-active[data-v-f4e96b6c]{transition:opacity .25s ease,transform .25s ease}.panel-fade-enter-from[data-v-f4e96b6c]{opacity:0;transform:translateY(8px)}.panel-fade-leave-to[data-v-f4e96b6c]{opacity:0;transform:translateY(-8px)}.hero-glass[data-v-f4e96b6c]{display:flex;align-items:center;justify-content:space-between;padding:28px 32px;margin-bottom:24px;background:var(--glass-bg);backdrop-filter:blur(var(--glass-blur));-webkit-backdrop-filter:blur(var(--glass-blur));border:1px solid var(--glass-border);border-radius:var(--radius)}.hero-content h2[data-v-f4e96b6c]{font-size:24px;font-weight:700;margin:0 0 6px;color:var(--c-white)}.hero-content p[data-v-f4e96b6c]{font-size:14px;color:var(--c-white-50);margin:0}.hero-badge[data-v-f4e96b6c]{display:flex;align-items:baseline;gap:4px;padding:8px 16px;border-radius:20px;background:#60a5fa26;border:1px solid rgba(96,165,250,.3);font-sizLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Fs,m as $s,o as e,c as o,b1 as js,a as s,C as a,F as f,R as F,b as Y,w as G,T as J,P as is,b2 as Ts,j as ds,l as u,D as us,B as C,a1 as As,a9 as p,K as _,i as h,ae as D,b3 as k,g as rs,A as cs,a2 as vs,b4 as Us,b5 as H,k as y}from"./index-BpUdMXzZ.js";import{r as q}from"./index-CZCGMR8A.js";const Hs={class:"glass-app"},Is={class:"glass-header"},Ls={class:"header-inner"},Ps={class:"brand-text"},Rs={class:"glass-nav"},Ss=["onClick"],Ns={class:"glass-main"},Ds={key:"buy",class:"panel"},Ks={class:"hero-glass"},Es={class:"hero-content"},Os={class:"hero-badge"},Ys={class:"hero-count"},Gs={key:0,class:"glass-pill-group"},Js=["onClick"],Ws={key:1,class:"glass-grid"},Xs={key:2,class:"glass-empty"},Zs={key:3,class:"glass-grid"},sl={key:0,class:"discount-ribbon"},ll={key:1,class:"hot-tag"},tl={class:"product-top"},al={class:"product-name"},el={class:"duration-chip"},ol={class:"product-meta"},nl={class:"meta-tag"},il={class:"product-price-row"},dl={class:"price-block"},ul={class:"price-num"},rl={key:0,class:"price-old"},cl=["onClick"],vl={key:"activate",class:"panel"},pl={class:"glass-center-card"},_l={key:0,class:"glass-form"},yl={class:"glass-field"},bl={class:"glass-field"},ml={class:"glass-field"},gl={class:"glass-field"},hl={class:"glass-field"},fl={class:"coupon-row"},kl=["disabled"],wl={key:0,class:"spinner sm"},xl={key:1},Cl=["disabled"],ql={key:0,class:"spinner"},Ql={key:1},Bl={class:"success-rows"},Vl={class:"s-row"},Ml={class:"s-row"},zl={class:"s-row"},Fl={class:"mono"},$l={key:0,class:"s-row"},jl={key:"query",class:"panel"},Tl={class:"glass-sub-tabs"},Al=["onClick"],Ul={class:"glass-center-card"},Hl={class:"glass-search-bar"},Il=["disabled"],Ll=["disabled"],Pl={key:0,class:"spinner"},Rl={key:1},Sl={key:0,class:"glass-detail-card"},Nl={class:"detail-head"},Dl={class:"detail-rows"},Kl={class:"d-row"},El={class:"d-val mono"},Ol={class:"d-row"},Yl={class:"d-val"},Gl={class:"d-row"},Jl={class:"d-val"},Wl={class:"d-row"},Xl={class:"d-val"},Zl={class:"d-row"},st={class:"d-val bold mono"},lt={class:"d-row"},tt={class:"d-val bold mono"},at={key:0,class:"d-row"},et={class:"d-val mono"},ot={key:1,class:"d-row"},nt={class:"d-val"},it={class:"glass-center-card"},dt={class:"glass-search-bar"},ut=["disabled"],rt=["disabled"],ct={key:0,class:"spinner"},vt={key:1},pt={key:0,class:"auth-result"},_t={class:"auth-stats"},yt={class:"stat-glass"},bt={class:"stat-label"},mt={class:"stat-glass"},gt={class:"stat-num"},ht={class:"stat-glass"},ft={class:"stat-num",style:{color:"#67C23A"}},kt={class:"stat-glass"},wt={class:"stat-num",style:{color:"#E6A23C"}},xt={key:0,class:"auth-items"},Ct={class:"auth-item-head"},qt={class:"auth-qq"},Qt={class:"auth-item-body"},Bt={class:"auth-f"},Vt={class:"auth-f"},Mt={class:"auth-f"},zt={class:"mono"},Ft={class:"auth-f"},$t={class:"glass-footer"},jt={class:"modal-body"},Tt={class:"m-row"},At={class:"m-val"},Ut={class:"m-row"},Ht={class:"m-val"},It={class:"m-row"},Lt={class:"m-val"},Pt={class:"m-row"},Rt={class:"m-val"},St={class:"m-row"},Nt={class:"m-val"},Dt={class:"m-row"},Kt={class:"m-val"},Et={class:"coupon-row"},Ot=["disabled"],Yt={key:0,class:"spinner sm"},Gt={key:1},Jt={class:"m-row"},Wt={class:"m-val"},Xt={class:"pay-opts"},Zt=["value"],sa=["innerHTML"],la={class:"m-total"},ta={key:0,class:"m-old-price"},aa={class:"m-total-price"},ea={class:"modal-footer"},oa=["disabled"],na={key:0,class:"spinner"},ia={key:1},da={class:"glass-key-box"},ua={class:"mono"},ra={class:"success-rows"},ca={class:"s-row"},va={class:"mono"},pa={class:"s-row"},_a={class:"s-row"},ya={class:"mono"},ba={class:"s-row"},ma={class:"mono"},ga={class:"modal-footer"},ha={__name:"Shop",setup(fa){const ps=()=>H("svg",{viewBox:"0 0 16 16",width:16,height:16,fill:"currentColor"},[H("path",{d:"M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"})]),_s=()=>H("svg",{viewBox:"0 0 16 16",width:16,height:16,fill:"currentColor"},[H("path",{d:"M8 1a2 2 0 0 1 2 2v4H6V3a2 2 0 0 1 2-2zm3 6V3a3 3 0 0 0-6 0v4a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z"})]),ys=()=>H("svg",{viewBox:"0 0 16 16",width:16,height:16,fill:"currentColor"},[H("path",{d:"M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"})]),B=u("buy"),bs=[{key:"buy",label:"购买授权",icon:ps},{key:"activate",label:"在线授权",icon:_s},{key:"query",label:"授权查询",icon:ys}],d=ds({projects:!1,products:!1,query:!1,authQuery:!1,pay:!1,buyCoupon:!1,activate:!1,actCoupon:!1}),$=u([]),I=u(0),L=u([]),K=us(()=>$.value.find(i=>i.id===I.value)),j=u(!1),T=u("confirm"),w=u(null),A=u("alipay"),V=u(""),Q=u(""),P=u(""),U=u(null),M=u(""),m=u(nulLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{_ as Os,aA as Qs,m as Bs,o as l,c as o,b1 as js,a as s,C as a,A as $s,F as B,R as U,b as h,w as D,T as H,P as K,b2 as W,b3 as Vs,j as Ms,l as r,D as Rs,b4 as R,B as j,a1 as Ys,K as d,i as g,aa as w,b5 as C,g as zs,a2 as Q,b6 as Gs,k as E}from"./index-oChIw9ZZ.js";import{r as z}from"./index-DpFNINBG.js";const Js={class:"shop-app"},Ws={class:"shop-header"},Zs={class:"header-bar"},st={class:"brand-text"},tt={class:"brand-name"},lt=["onClick"],et={class:"shop-main"},at={key:0},ot={class:"hero"},nt={class:"hero-text"},it={class:"hero-stat"},rt={class:"stat-num"},ut=["onClick"],dt={key:1,class:"product-grid"},ct={key:2,class:"empty-state"},vt={key:0,class:"card-badge"},pt={class:"card-header"},yt={class:"card-name"},bt={class:"card-duration"},mt={class:"card-features"},ft={class:"card-price"},_t={class:"price-amount"},kt={key:0,class:"price-discount"},ht={key:1,class:"price-original"},gt=["onClick"],wt={key:1},qt={class:"center-card"},xt={key:0,class:"form-area"},Ct={class:"form-field"},Qt={class:"form-field"},Bt={class:"form-field"},jt={class:"form-field"},$t=["disabled"],Vt={key:0,class:"spinner white"},Mt={key:1},Rt={key:2},zt={class:"query-tabs"},Tt=["onClick"],Ft={key:"card",class:"center-card"},St={class:"form-field"},It=["disabled"],At=["disabled"],Ut={key:0,class:"spinner white"},Dt={key:1},Ht={key:"bot",class:"center-card"},Pt={class:"form-field"},Lt=["disabled"],Nt=["disabled"],Kt={key:0,class:"spinner white"},Et={key:1},Xt={class:"cr-status-text"},Ot={class:"cr-body"},Yt={class:"cr-row"},Gt={class:"mono"},Jt={class:"cr-row"},Wt={class:"cr-row"},Zt={class:"cr-row"},sl={class:"cr-row"},tl={class:"mono"},ll={class:"cr-row"},el={class:"mono"},al={key:0,class:"cr-row"},ol={class:"mono"},nl={key:1,class:"cr-row"},il={class:"modal-footer"},rl={class:"act-success-title"},ul={class:"act-success-sub"},dl={class:"act-success-body"},cl={class:"act-row"},vl={class:"act-row"},pl={class:"mono"},yl={class:"act-row"},bl={class:"mono"},ml={class:"act-row"},fl={class:"mono"},_l={key:0,class:"act-row"},kl={key:1,class:"act-row"},hl={class:"act-error-body"},gl={class:"modal-footer"},wl={class:"qr-summary"},ql={class:"qr-icon"},xl={class:"qr-text"},Cl={class:"qr-grid"},Ql={class:"qr-cell"},Bl={class:"qr-num"},jl={class:"qr-cell"},$l={class:"qr-num ok"},Vl={class:"qr-cell"},Ml={class:"qr-num warn"},Rl={key:0,class:"qr-list"},zl={class:"qr-item-head"},Tl={class:"qr-qq"},Fl={class:"qr-item-body"},Sl={class:"qr-row"},Il={class:"qr-row"},Al={class:"qr-row"},Ul={class:"modal-footer"},Dl={class:"shop-footer"},Hl={class:"modal-product-header"},Pl={class:"modal-product-icon"},Ll={class:"modal-product-info"},Nl={class:"modal-product-title"},Kl={class:"modal-product-meta"},El={class:"modal-product-price"},Xl={class:"mp-amount"},Ol={class:"modal-body"},Yl={class:"form-field modal-field"},Gl={class:"form-field modal-field"},Jl={class:"form-field modal-field"},Wl={class:"form-field modal-field"},Zl={class:"coupon-row"},se=["disabled"],te={key:0,class:"spinner sm white"},le={key:1},ee={class:"form-field modal-field"},ae={class:"pay-opts"},oe=["value"],ne=["innerHTML"],ie={class:"pay-label"},re={class:"m-total"},ue={class:"total-line"},de={key:0,class:"m-old-price"},ce={class:"m-total-price"},ve={class:"modal-footer"},pe=["disabled"],ye={key:0,class:"spinner white"},be={key:1},me={key:1,class:"success-block"},fe={class:"key-box"},_e={class:"mono"},ke={class:"success-rows"},he={class:"s-row"},ge={class:"mono"},we={class:"s-row"},qe={class:"s-row"},xe={class:"mono"},Ce={class:"s-row"},Qe={class:"mono"},Be={class:"modal-footer"},je={__name:"Shop",setup($e){const os=()=>R("svg",{viewBox:"0 0 16 16",width:16,height:16,fill:"currentColor"},[R("path",{d:"M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"})]),Ts=()=>R("svg",{viewBox:"0 0 16 16",width:16,height:16,fill:"currentColor"},[R("path",{d:"M8 1a2 2 0 0 1 2 2v4H6V3a2 2 0 0 1 2-2zm3 6V3a3 3 0 0 0-6 0v4a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z"})]),Fs=()=>R("svg",{viewBox:"0 0 16 16",width:16,height:16,fill:"currentColor"},[R("path",{d:"M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"})]),ts=()=>R("svg",{viewBox:"0 0 16 16",width:14,height:14,fill:"currentColor"},[R("path",{d:"M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0z"})]),q=r("buy"),ns=[{key:"buy",label:"购买授权",icon:os},{key:"activate",label:"在线授权",icon:Ts},{key:"query",label:"授权查询",icon:Fs}],is=r(null),rs=r([]),us=r({width:"0px",transform:"translateX(0px)",opacity:0});function ds(){Vs(()=>{coLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
.shop-app[data-v-c1b03ad0]{--bg-base: #f8fafc;--bg-surface: #ffffff;--bg-surface-solid: #ffffff;--bg-elevated: #f1f5f9;--bg-inset: #f1f5f9;--border: rgba(148, 163, 184, .25);--border-strong: rgba(148, 163, 184, .45);--shadow-sm: 0 1px 3px rgba(0, 0, 0, .06);--shadow-md: 0 4px 12px rgba(0, 0, 0, .08);--shadow-lg: 0 12px 32px rgba(0, 0, 0, .12);--shadow-glow: 0 0 24px rgba(99, 102, 241, .12);--text-primary: #0f172a;--text-secondary: #475569;--text-tertiary: #94a3b8;--accent: #6366f1;--accent-light: #6366f1;--accent-glow: rgba(99, 102, 241, .25);--success: #10b981;--warning: #f59e0b;--danger: #ef4444;--purple: #8b5cf6;--r-xl: 20px;--r-lg: 16px;--r-md: 10px;--r-sm: 8px;--ease: cubic-bezier(.4, 0, .2, 1);--ease-bounce: cubic-bezier(.34, 1.56, .64, 1);--dur: .3s;min-height:100vh;position:relative;overflow-x:hidden;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Microsoft YaHei,sans-serif;color:var(--text-primary);background:var(--bg-base);-webkit-font-smoothing:antialiased}.bg-canvas[data-v-c1b03ad0]{position:fixed;top:0;right:0;bottom:0;left:0;z-index:0;background:radial-gradient(ellipse 80% 50% at 20% 0%,rgba(99,102,241,.08) 0%,transparent 55%),radial-gradient(ellipse 60% 40% at 85% 15%,rgba(236,72,153,.05) 0%,transparent 50%),radial-gradient(ellipse 70% 50% at 50% 100%,rgba(6,182,212,.04) 0%,transparent 55%),linear-gradient(180deg,#f8fafc,#f1f5f9,#f8fafc)}.bg-grid[data-v-c1b03ad0]{position:absolute;top:0;right:0;bottom:0;left:0;background-image:linear-gradient(rgba(15,23,42,.03) 1px,transparent 1px),linear-gradient(90deg,rgba(15,23,42,.03) 1px,transparent 1px);background-size:48px 48px;-webkit-mask-image:radial-gradient(ellipse at center,black 20%,transparent 75%);mask-image:radial-gradient(ellipse at center,black 20%,transparent 75%)}.bg-orb[data-v-c1b03ad0]{position:absolute;border-radius:50%;filter:blur(140px);opacity:.18;will-change:transform;animation:orb-drift-c1b03ad0 25s ease-in-out infinite alternate}.orb-a[data-v-c1b03ad0]{width:520px;height:520px;top:-8%;left:-5%;background:#6366f1;animation-duration:30s}.orb-b[data-v-c1b03ad0]{width:420px;height:420px;top:30%;right:-8%;background:#ec4899;animation-duration:25s;animation-delay:-8s}.orb-c[data-v-c1b03ad0]{width:380px;height:380px;bottom:-5%;left:30%;background:#06b6d4;animation-duration:28s;animation-delay:-15s}@keyframes orb-drift-c1b03ad0{0%{transform:translate(0) scale(1)}50%{transform:translate(40px,-50px) scale(1.08)}to{transform:translate(-20px,30px) scale(.95)}}.shop-header[data-v-c1b03ad0]{position:sticky;top:0;z-index:100;background:#ffffffd1;backdrop-filter:blur(24px);-webkit-backdrop-filter:blur(24px);border-bottom:1px solid var(--border)}.header-bar[data-v-c1b03ad0]{max-width:1200px;margin:0 auto;padding:14px 28px;display:flex;align-items:center;justify-content:space-between;gap:24px;flex-wrap:wrap}.brand[data-v-c1b03ad0]{display:flex;align-items:center;gap:12px;cursor:pointer}.brand-logo[data-v-c1b03ad0]{width:42px;height:42px;border-radius:var(--r-md);background:linear-gradient(135deg,var(--accent),#8b5cf6);box-shadow:var(--shadow-sm),0 0 16px #6366f133;display:flex;align-items:center;justify-content:center;color:#fff;transition:all var(--dur) var(--ease)}.brand:hover .brand-logo[data-v-c1b03ad0]{box-shadow:var(--shadow-md),0 0 24px #6366f14d;transform:translateY(-2px)}.brand-text[data-v-c1b03ad0]{display:flex;flex-direction:column;gap:2px}.brand-name[data-v-c1b03ad0]{font-size:17px;font-weight:700;color:var(--text-primary);letter-spacing:-.2px}.brand-sub[data-v-c1b03ad0]{font-size:11px;color:var(--text-tertiary)}.nav-tabs[data-v-c1b03ad0]{display:flex;gap:4px;position:relative;padding:4px;background:var(--bg-inset);border-radius:var(--r-md);border:1px solid var(--border)}.nav-slider[data-v-c1b03ad0]{position:absolute;top:4px;left:0;height:calc(100% - 8px);border-radius:calc(var(--r-md) - 2px);background:linear-gradient(135deg,#6366f1,#8b5cf6);box-shadow:0 4px 14px #6366f140;transition:transform .4s cubic-bezier(.34,1.56,.64,1),width .35s cubic-bezier(.34,1.56,.64,1),opacity .3s ease;pointer-events:none;z-index:0}.nav-tab[data-v-c1b03ad0]{position:relative;z-index:1;display:flex;align-items:center;gap:6px;padding:9px 18px;border:none;background:transparent;font-size:14px;color:var(--text-secondary);cursor:pointer;border-radius:calc(var(--r-md) - 2px);font-family:inherit;-webkit-user-select:none;user-select:none;transition:color .3s ease,transform .2s ease}.nav-tab[data-v-c1b03ad0]:hover{color:var(--text-primary)}.nav-tab[data-v-c1b03ad0]:active{transform:scale(.97)}.nav-tab.active[data-v-c1b03ad0]{color:#fff}.nav-tab .tab-icon[data-v-c1b03ad0]{transition:transform .3s var(--ease-bounce);color:currentColor}.nav-tab.active .tab-icon[data-v-c1b03ad0]{transform:scale(1.1)}.tab-icon[data-v-c1b03ad0]{display:flex;align-items:center}.shop-main[data-v-c1b03ad0]{position:relative;z-index:1;max-width:1200px;margin:0 auto;padding:32px 28px 60px}.panel[data-v-c1b03ad0]{position:relative;width:100%}.panel-enter-active[data-v-c1b03Line truncated
|
||||
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user