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 = '
| 卡密 | 项目 | 类型 | 有效天数 | 状态 | 绑定时间 | 过期时间 | 生成时间 |
|---|---|---|---|---|---|---|---|
| ' . htmlspecialchars($card['card_key']) . ' | '; $html .= '' . htmlspecialchars($card['project_name'] ?? '') . ' | '; $html .= '' . htmlspecialchars($card['type']) . ' | '; $html .= '' . htmlspecialchars($card['duration_days'] == 0 ? '永久' : $card['duration_days'] . '天') . ' | '; $html .= '' . htmlspecialchars($statusMap[$card['status']] ?? $card['status']) . ' | '; $html .= '' . htmlspecialchars($card['bound_at'] ?? '') . ' | '; $html .= '' . htmlspecialchars($card['expire_time'] ?? '') . ' | '; $html .= '' . htmlspecialchars($card['created_at']) . ' | '; $html .= '