#feature: add ip operation log & sql generator

This commit is contained in:
2025-12-25 14:25:57 +08:00
parent 79889e1040
commit 3bcbd0661f
21 changed files with 1751 additions and 21 deletions

View File

@@ -103,3 +103,6 @@ MONO_TIMEOUT=30
# Git Monitor Configuration
GIT_MONITOR_PROJECTS="service,portal-be,agent-be"
# Admin IP whitelist (comma separated, supports wildcard: 192.168.* or 192.168.1.*)
TOOLBOX_ADMIN_IPS=

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Support\IpAccess;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class AdminMetaController extends Controller
{
public function show(Request $request): JsonResponse
{
$ipAddress = $request->ip();
return response()->json([
'success' => true,
'data' => [
'is_admin' => IpAccess::isAdmin($ipAddress),
'ip' => $ipAddress,
],
]);
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\IpUserMapping;
use App\Models\OperationLog;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
class IpUserMappingController extends Controller
{
public function index(): JsonResponse
{
$mappings = IpUserMapping::query()
->orderBy('ip_address')
->get();
$unmappedIps = OperationLog::query()
->select(
'operation_logs.ip_address',
DB::raw('COUNT(*) as logs_count'),
DB::raw('MAX(operation_logs.created_at) as last_seen_at')
)
->leftJoin('ip_user_mappings', 'operation_logs.ip_address', '=', 'ip_user_mappings.ip_address')
->whereNull('ip_user_mappings.id')
->where('operation_logs.ip_address', '!=', '')
->groupBy('operation_logs.ip_address')
->orderByDesc('last_seen_at')
->get();
return response()->json([
'success' => true,
'data' => [
'mappings' => $mappings,
'unmapped_ips' => $unmappedIps,
],
]);
}
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'ip_address' => ['required', 'ip', 'max:64', 'unique:ip_user_mappings,ip_address'],
'user_name' => ['required', 'string', 'max:128'],
'remark' => ['nullable', 'string', 'max:255'],
]);
$mapping = IpUserMapping::query()->create($data);
return response()->json([
'success' => true,
'data' => [
'mapping' => $mapping,
],
]);
}
public function update(Request $request, IpUserMapping $mapping): JsonResponse
{
$data = $request->validate([
'ip_address' => [
'required',
'ip',
'max:64',
Rule::unique('ip_user_mappings', 'ip_address')->ignore($mapping->id),
],
'user_name' => ['required', 'string', 'max:128'],
'remark' => ['nullable', 'string', 'max:255'],
]);
$mapping->update($data);
return response()->json([
'success' => true,
'data' => [
'mapping' => $mapping->refresh(),
],
]);
}
public function destroy(IpUserMapping $mapping): JsonResponse
{
$mapping->delete();
return response()->json([
'success' => true,
]);
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\OperationLog;
use App\Support\IpAccess;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class OperationLogController extends Controller
{
public function index(Request $request): JsonResponse
{
$data = $request->validate([
'page' => ['nullable', 'integer', 'min:1'],
'per_page' => ['nullable', 'integer', 'min:1', 'max:200'],
'q' => ['nullable', 'string', 'max:255'],
'method' => ['nullable', 'string', 'max:10'],
]);
$query = OperationLog::query()->orderByDesc('id');
$isAdmin = IpAccess::isAdmin($request->ip());
$search = trim((string) ($data['q'] ?? ''));
if ($search !== '') {
$query->where(function ($builder) use ($search, $isAdmin): void {
$builder->where('ip_address', 'like', "%{$search}%")
->orWhere('path', 'like', "%{$search}%")
->orWhere('route_name', 'like', "%{$search}%");
if ($isAdmin) {
$builder->orWhere('user_label', 'like', "%{$search}%");
}
});
}
$method = strtoupper((string) ($data['method'] ?? ''));
if ($method !== '') {
$query->where('method', $method);
}
$perPage = (int) ($data['per_page'] ?? 50);
$logs = $query->paginate($perPage);
$items = collect($logs->items())->map(function (OperationLog $log) use ($isAdmin): array {
$payload = $log->toArray();
if (!$isAdmin) {
$payload['user_label'] = null;
}
return $payload;
})->all();
return response()->json([
'success' => true,
'data' => [
'logs' => $items,
'pagination' => [
'current_page' => $logs->currentPage(),
'last_page' => $logs->lastPage(),
'per_page' => $logs->perPage(),
'total' => $logs->total(),
],
],
]);
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class SqlGeneratorController extends Controller
{
/**
* 查询 agentslave.case_extras 中已存在的 OB 外部 ID 记录。
*/
public function checkObExternalId(Request $request): JsonResponse
{
try {
$request->validate([
'case_codes' => 'required|array|min:1',
'case_codes.*' => 'required|string|max:255',
]);
$caseCodes = array_values(array_unique(array_filter(array_map('trim', $request->input('case_codes')))));
if (empty($caseCodes)) {
return response()->json([
'success' => false,
'message' => '请提供有效的 case_id 列表'
], 400);
}
$existingCaseCodes = [];
foreach (array_chunk($caseCodes, 1000) as $chunk) {
$results = DB::connection('agentslave')
->table('case_extras')
->where('source', 'ob')
->where('field', 'OB Case ID')
->whereIn('case_code', $chunk)
->pluck('case_code')
->all();
$existingCaseCodes = array_merge($existingCaseCodes, $results);
}
$existingCaseCodes = array_values(array_unique(array_map('strval', $existingCaseCodes)));
return response()->json([
'success' => true,
'data' => [
'existing_case_codes' => $existingCaseCodes,
],
]);
} catch (ValidationException $e) {
return response()->json([
'success' => false,
'message' => '请求参数验证失败',
'errors' => $e->errors(),
], 422);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => '查询 case_extras 失败: ' . $e->getMessage(),
], 500);
}
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Http\Middleware;
use App\Support\IpAccess;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class AdminIpMiddleware
{
/**
* @param Closure(Request): Response $next
*/
public function handle(Request $request, Closure $next): Response
{
if (!IpAccess::isAdmin($request->ip())) {
if ($request->expectsJson() || $request->is('api/*')) {
return response()->json([
'success' => false,
'message' => '无权限访问',
], 403);
}
abort(403);
}
return $next($request);
}
}

View File

@@ -0,0 +1,129 @@
<?php
namespace App\Http\Middleware;
use App\Models\IpUserMapping;
use App\Models\OperationLog;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
class OperationLogMiddleware
{
/**
* @param Closure(Request): Response $next
*/
public function handle(Request $request, Closure $next): Response
{
$startAt = microtime(true);
try {
$response = $next($request);
} catch (Throwable $exception) {
$this->recordLog($request, null, $startAt, 500);
throw $exception;
}
$this->recordLog($request, $response, $startAt, $response->getStatusCode());
return $response;
}
private function shouldLog(Request $request): bool
{
$methods = config('toolbox.operation_log.methods', []);
if (!in_array($request->method(), $methods, true)) {
return false;
}
return $request->is('api/*');
}
private function recordLog(Request $request, ?Response $response, float $startAt, int $statusCode): void
{
if (!$this->shouldLog($request)) {
return;
}
try {
$ipAddress = $request->ip() ?? '';
$mapping = $ipAddress !== ''
? IpUserMapping::query()->where('ip_address', $ipAddress)->first()
: null;
OperationLog::query()->create([
'ip_address' => $ipAddress,
'user_label' => $mapping?->user_name,
'method' => $request->method(),
'path' => '/' . ltrim($request->path(), '/'),
'route_name' => $request->route()?->getName(),
'status_code' => $statusCode,
'duration_ms' => (int) round((microtime(true) - $startAt) * 1000),
'request_payload' => $this->buildPayload($request),
'user_agent' => substr((string) $request->userAgent(), 0, 255),
]);
} catch (Throwable $exception) {
Log::warning('Failed to record operation log.', [
'error' => $exception->getMessage(),
]);
}
}
/**
* @return array<string, mixed>
*/
private function buildPayload(Request $request): array
{
$payload = $request->all();
if (empty($payload)) {
return [];
}
$redactKeys = array_map('strtolower', config('toolbox.operation_log.redact_keys', []));
$payload = $this->redactPayload($payload, $redactKeys);
$encoded = json_encode($payload, JSON_UNESCAPED_UNICODE);
if ($encoded === false) {
return ['_unserializable' => true];
}
$maxLength = (int) config('toolbox.operation_log.max_payload_length', 2000);
if (strlen($encoded) <= $maxLength) {
return $payload;
}
return [
'_truncated' => true,
'preview' => substr($encoded, 0, $maxLength),
];
}
/**
* @param array<string, mixed> $payload
* @param array<int, string> $redactKeys
* @return array<string, mixed>
*/
private function redactPayload(array $payload, array $redactKeys): array
{
$redacted = [];
foreach ($payload as $key => $value) {
$lowerKey = strtolower((string) $key);
if (in_array($lowerKey, $redactKeys, true)) {
$redacted[$key] = '[redacted]';
continue;
}
if (is_array($value)) {
$redacted[$key] = $this->redactPayload($value, $redactKeys);
continue;
}
$redacted[$key] = $value;
}
return $redacted;
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class IpUserMapping extends Model
{
use HasFactory;
protected $fillable = [
'ip_address',
'user_name',
'remark',
];
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class OperationLog extends Model
{
use HasFactory;
protected $fillable = [
'ip_address',
'user_label',
'method',
'path',
'route_name',
'status_code',
'duration_ms',
'request_payload',
'user_agent',
];
protected $casts = [
'request_payload' => 'array',
];
}

50
app/Support/IpAccess.php Normal file
View File

@@ -0,0 +1,50 @@
<?php
namespace App\Support;
class IpAccess
{
/**
* @return array<int, string>
*/
public static function adminIps(): array
{
return config('toolbox.admin_ips', []);
}
public static function isAdmin(?string $ip): bool
{
if (!is_string($ip) || $ip === '') {
return false;
}
$adminIps = self::adminIps();
if (empty($adminIps)) {
return false;
}
foreach ($adminIps as $pattern) {
if ($pattern === $ip) {
return true;
}
if (str_contains($pattern, '*') && self::matchWildcard($pattern, $ip)) {
return true;
}
}
return false;
}
private static function matchWildcard(string $pattern, string $ip): bool
{
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
return false;
}
$escaped = preg_quote($pattern, '#');
$regex = str_replace('\*', '[0-9.]*', $escaped);
return (bool) preg_match('#^' . $regex . '$#', $ip);
}
}

View File

@@ -13,12 +13,19 @@ return Application::configure(basePath: dirname(__DIR__))
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'admin.ip' => \App\Http\Middleware\AdminIpMiddleware::class,
]);
$middleware->appendToGroup('api', \App\Http\Middleware\OperationLogMiddleware::class);
// 为 API 路由添加 CSRF 豁免
$middleware->validateCsrfTokens(except: [
'api/jira/*',
'api/env/*',
'api/message-sync/*',
'api/message-dispatch/*'
'api/message-dispatch/*',
'api/admin/*',
]);
})
->withExceptions(function (Exceptions $exceptions): void {

19
config/toolbox.php Normal file
View File

@@ -0,0 +1,19 @@
<?php
return [
'admin_ips' => array_values(array_filter(array_map(
static fn(string $ip): string => trim($ip),
explode(',', (string) env('TOOLBOX_ADMIN_IPS', ''))
))),
'operation_log' => [
'methods' => ['POST', 'PUT', 'PATCH', 'DELETE'],
'max_payload_length' => 2000,
'redact_keys' => [
'content',
'password',
'token',
'authorization',
'api_token',
],
],
];

View File

@@ -0,0 +1,24 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('ip_user_mappings', function (Blueprint $table): void {
$table->id();
$table->string('ip_address', 64)->unique();
$table->string('user_name', 128);
$table->string('remark', 255)->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('ip_user_mappings');
}
};

View File

@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('operation_logs', function (Blueprint $table): void {
$table->id();
$table->string('ip_address', 64);
$table->string('user_label', 128)->nullable();
$table->string('method', 10);
$table->string('path', 255);
$table->string('route_name', 255)->nullable();
$table->unsignedSmallInteger('status_code');
$table->unsignedInteger('duration_ms')->default(0);
$table->json('request_payload')->nullable();
$table->string('user_agent', 255)->nullable();
$table->timestamps();
$table->index(['ip_address', 'created_at']);
$table->index(['user_label', 'created_at']);
});
}
public function down(): void
{
Schema::dropIfExists('operation_logs');
}
};

View File

@@ -1,6 +1,7 @@
<template>
<admin-layout
:page-title="pageTitle"
:is-admin="isAdmin"
@menu-change="handleMenuChange"
>
<!-- 环境管理页面 -->
@@ -15,6 +16,12 @@
ref="weeklyReport"
/>
<!-- SQL 生成页面 -->
<sql-generator
v-else-if="currentPage === 'sql-generator'"
ref="sqlGenerator"
/>
<!-- JIRA 工时查询页面 -->
<jira-worklog
v-else-if="currentPage === 'worklog'"
@@ -43,15 +50,10 @@
<system-settings v-else-if="currentPage === 'settings'" />
<!-- 操作日志页面 -->
<div v-else-if="currentPage === 'logs'" class="bg-white rounded-xl shadow-sm border border-gray-200 p-8">
<div class="text-center py-12">
<svg class="w-16 h-16 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
</svg>
<h3 class="text-lg font-medium text-gray-900 mb-2">操作日志</h3>
<p class="text-gray-500">此功能正在开发中...</p>
</div>
</div>
<operation-logs v-else-if="currentPage === 'logs'" :is-admin="isAdmin" :current-ip="currentIp" />
<!-- IP 用户映射页面 -->
<ip-user-mappings v-else-if="currentPage === 'ip-mappings'" />
</admin-layout>
</template>
@@ -59,11 +61,14 @@
import AdminLayout from './AdminLayout.vue';
import EnvManagement from '../env/EnvManagement.vue';
import WeeklyReport from '../jira/WeeklyReport.vue';
import SqlGenerator from '../tools/SqlGenerator.vue';
import JiraWorklog from '../jira/JiraWorklog.vue';
import MessageSync from '../message-sync/MessageSync.vue';
import EventConsumerSync from '../message-sync/EventConsumerSync.vue';
import MessageDispatch from '../message-sync/MessageDispatch.vue';
import SystemSettings from './SystemSettings.vue';
import OperationLogs from './OperationLogs.vue';
import IpUserMappings from './IpUserMappings.vue';
export default {
name: 'AdminDashboard',
@@ -71,38 +76,62 @@ export default {
AdminLayout,
EnvManagement,
WeeklyReport,
SqlGenerator,
JiraWorklog,
MessageSync,
EventConsumerSync,
MessageDispatch,
SystemSettings
SystemSettings,
OperationLogs,
IpUserMappings
},
data() {
return {
currentPage: 'env',
pageTitle: '环境配置管理'
pageTitle: '环境配置管理',
isAdmin: false,
currentIp: ''
}
},
mounted() {
console.log('AdminDashboard mounted');
// 根据 URL 路径设置初始页面
async mounted() {
await this.loadAdminMeta();
this.setCurrentPageFromPath();
},
methods: {
async loadAdminMeta() {
try {
const response = await fetch('/api/admin/meta');
const data = await response.json();
if (data.success) {
this.isAdmin = Boolean(data.data.is_admin);
this.currentIp = data.data.ip || '';
}
} catch (error) {
this.isAdmin = false;
this.currentIp = '';
}
},
handleMenuChange(menu) {
if (menu === 'ip-mappings' && !this.isAdmin) {
this.redirectToDefault();
return;
}
this.currentPage = menu;
// 更新页面标题
const titles = {
'env': '环境配置管理',
'weekly-report': '生成周报',
'sql-generator': '生成SQL',
'worklog': 'JIRA 工时查询',
'message-sync': '消息同步',
'event-consumer-sync': '事件消费者同步对比',
'message-dispatch': '消息分发异常查询',
'settings': '系统设置',
'logs': '操作日志'
'logs': '操作日志',
'ip-mappings': 'IP 用户映射'
};
this.pageTitle = titles[menu] || '环境配置管理';
@@ -114,6 +143,8 @@ export default {
if (path === '/') {
page = 'env';
} else if (path === '/sql-generator') {
page = 'sql-generator';
} else if (path === '/weekly-report') {
page = 'weekly-report';
} else if (path === '/worklog') {
@@ -128,10 +159,25 @@ export default {
page = 'settings';
} else if (path === '/logs') {
page = 'logs';
} else if (path === '/ip-mappings') {
page = 'ip-mappings';
}
if (page === 'ip-mappings' && !this.isAdmin) {
this.redirectToDefault();
return;
}
this.currentPage = page;
this.handleMenuChange(page);
},
redirectToDefault() {
this.currentPage = 'env';
this.pageTitle = '环境配置管理';
if (window.location.pathname !== '/') {
window.history.replaceState({}, '', '/');
}
}
}
}

View File

@@ -44,6 +44,30 @@
环境配置管理
</a>
<a
href="#"
@click.prevent="setActiveMenu('sql-generator')"
:class="[
'group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors duration-200',
activeMenu === 'sql-generator'
? 'bg-blue-50 text-blue-700 border-r-2 border-blue-700'
: 'text-gray-700 hover:bg-gray-50 hover:text-gray-900'
]"
>
<svg
:class="[
'mr-3 h-5 w-5 transition-colors duration-200',
activeMenu === 'sql-generator' ? 'text-blue-500' : 'text-gray-400 group-hover:text-gray-500'
]"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
</svg>
生成SQL
</a>
<!-- JIRA 相关菜单项 -->
<a
@@ -214,6 +238,31 @@
</svg>
操作日志
</a>
<a
href="#"
@click.prevent="setActiveMenu('ip-mappings')"
v-if="isAdmin"
:class="[
'group flex items-center px-3 py-2 text-sm font-medium rounded-lg transition-colors duration-200',
activeMenu === 'ip-mappings'
? 'bg-blue-50 text-blue-700 border-r-2 border-blue-700'
: 'text-gray-700 hover:bg-gray-50 hover:text-gray-900'
]"
>
<svg
:class="[
'mr-3 h-5 w-5 transition-colors duration-200',
activeMenu === 'ip-mappings' ? 'text-blue-500' : 'text-gray-400 group-hover:text-gray-500'
]"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
</svg>
IP 用户映射
</a>
</div>
<!-- 底部信息 -->
@@ -244,6 +293,10 @@ export default {
pageTitle: {
type: String,
default: '环境配置管理'
},
isAdmin: {
type: Boolean,
default: false
}
},
data() {
@@ -251,6 +304,11 @@ export default {
activeMenu: 'env'
}
},
watch: {
isAdmin() {
this.setActiveMenuFromPath();
}
},
mounted() {
// 根据 URL 路径设置初始菜单
this.setActiveMenuFromPath();
@@ -263,6 +321,10 @@ export default {
},
methods: {
setActiveMenu(menu) {
if (menu === 'ip-mappings' && !this.isAdmin) {
return;
}
this.activeMenu = menu;
// 更新 URL 路径
const path = menu === 'env' ? '/' : `/${menu}`;
@@ -276,6 +338,8 @@ export default {
if (path === '/') {
menu = 'env';
} else if (path === '/sql-generator') {
menu = 'sql-generator';
} else if (path === '/weekly-report') {
menu = 'weekly-report';
} else if (path === '/worklog') {
@@ -290,6 +354,12 @@ export default {
menu = 'settings';
} else if (path === '/logs') {
menu = 'logs';
} else if (path === '/ip-mappings') {
menu = 'ip-mappings';
}
if (menu === 'ip-mappings' && !this.isAdmin) {
menu = 'env';
}
this.activeMenu = menu;
@@ -314,9 +384,5 @@ export default {
transform: translateX(-100%);
transition: transform 0.3s ease-in-out;
}
.admin-layout .fixed.w-64.open {
transform: translateX(0);
}
}
</style>

View File

@@ -0,0 +1,342 @@
<template>
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-8">
<div class="flex items-start justify-between gap-4">
<div>
<h3 class="text-lg font-medium text-gray-900">IP 用户映射</h3>
<p class="text-gray-500 mt-1">维护 IP 与用户标识的对应关系</p>
</div>
<button
class="px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 disabled:opacity-50"
:disabled="loading"
@click="loadMappings"
>
{{ loading ? '加载中...' : '刷新' }}
</button>
</div>
<div class="mt-6 grid grid-cols-1 md:grid-cols-4 gap-4">
<input
v-model="newMapping.ip_address"
type="text"
class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="IP 地址"
/>
<input
v-model="newMapping.user_name"
type="text"
class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="用户标识"
/>
<input
v-model="newMapping.remark"
type="text"
class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="备注(可选)"
/>
<button
class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
:disabled="saving"
@click="createMapping"
>
{{ saving ? '保存中...' : '新增映射' }}
</button>
</div>
<div
v-if="unmappedIps.length"
class="mt-6 border border-amber-200 bg-amber-50 rounded-lg p-4"
>
<div class="flex items-center justify-between">
<div class="text-sm font-medium text-amber-700">待匹配 IP来自日志</div>
<div class="text-xs text-amber-600"> {{ unmappedIps.length }} </div>
</div>
<div class="mt-3 grid grid-cols-1 md:grid-cols-2 gap-2 max-h-64 overflow-auto">
<div
v-for="item in unmappedIps"
:key="item.ip_address"
class="flex items-center justify-between gap-3 bg-white border border-amber-100 rounded px-3 py-2 text-sm"
>
<div class="flex flex-col">
<span class="font-mono text-gray-800">{{ item.ip_address }}</span>
<span class="text-xs text-gray-500">
{{ item.logs_count }} 次日志 · 最近 {{ formatTime(item.last_seen_at) }}
</span>
</div>
<button
class="px-2 py-1 text-xs text-amber-700 bg-amber-100 rounded hover:bg-amber-200"
@click="fillIp(item.ip_address)"
>
填入
</button>
</div>
</div>
</div>
<div v-if="message" class="mt-4 text-sm text-green-700 bg-green-50 border border-green-200 rounded-md px-3 py-2">
{{ message }}
</div>
<div v-if="error" class="mt-4 text-sm text-red-700 bg-red-50 border border-red-200 rounded-md px-3 py-2">
{{ error }}
</div>
<div v-if="loading" class="mt-4 text-sm text-gray-400">加载中...</div>
<div v-else class="mt-4 overflow-x-auto border border-gray-200 rounded-lg">
<table class="min-w-full text-sm">
<thead class="bg-gray-50 text-gray-600">
<tr>
<th class="text-left px-4 py-3 font-medium">IP 地址</th>
<th class="text-left px-4 py-3 font-medium">用户标识</th>
<th class="text-left px-4 py-3 font-medium">备注</th>
<th class="text-left px-4 py-3 font-medium">操作</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-200">
<tr v-for="mapping in mappings" :key="mapping.id" class="text-gray-700">
<td class="px-4 py-3 font-mono">
<input
v-model="mapping.ip_address"
type="text"
class="w-full px-2 py-1 border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500"
/>
</td>
<td class="px-4 py-3">
<input
v-model="mapping.user_name"
type="text"
class="w-full px-2 py-1 border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500"
/>
</td>
<td class="px-4 py-3">
<input
v-model="mapping.remark"
type="text"
class="w-full px-2 py-1 border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500"
/>
</td>
<td class="px-4 py-3 whitespace-nowrap">
<div class="flex items-center gap-2">
<button
class="px-3 py-1 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
:disabled="mapping._saving"
@click="updateMapping(mapping)"
>
{{ mapping._saving ? '保存中...' : '保存' }}
</button>
<button
class="px-3 py-1 bg-red-50 text-red-700 rounded-md hover:bg-red-100 disabled:opacity-50"
:disabled="mapping._deleting"
@click="deleteMapping(mapping)"
>
{{ mapping._deleting ? '删除中...' : '删除' }}
</button>
</div>
</td>
</tr>
<tr v-if="mappings.length === 0">
<td colspan="4" class="px-4 py-6 text-center text-gray-400">暂无映射</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
export default {
name: 'IpUserMappings',
data() {
return {
mappings: [],
unmappedIps: [],
loading: false,
saving: false,
error: '',
message: '',
newMapping: {
ip_address: '',
user_name: '',
remark: ''
}
};
},
mounted() {
this.loadMappings();
},
methods: {
formatTime(value) {
if (!value) {
return '-';
}
return value.replace('T', ' ').replace('Z', '');
},
async parseJsonResponse(response) {
const contentType = response.headers.get('content-type') || '';
if (!contentType.includes('application/json')) {
const text = await response.text();
throw new Error(text || '响应不是JSON');
}
return response.json();
},
getErrorMessage(data, fallback) {
if (!data) {
return fallback;
}
if (data.message) {
return data.message;
}
if (data.errors && typeof data.errors === 'object') {
const firstKey = Object.keys(data.errors)[0];
const firstError = firstKey ? data.errors[firstKey]?.[0] : '';
if (firstError) {
return firstError;
}
}
return fallback;
},
fillIp(ip) {
this.newMapping.ip_address = ip;
},
async loadMappings() {
this.loading = true;
this.error = '';
this.message = '';
try {
const response = await fetch('/api/admin/ip-user-mappings', {
headers: {
Accept: 'application/json'
}
});
const data = await this.parseJsonResponse(response);
if (!response.ok) {
this.error = this.getErrorMessage(data, '加载失败');
return;
}
if (!data.success) {
this.error = data.message || '加载失败';
return;
}
this.mappings = (data.data.mappings || []).map((item) => ({
...item,
_saving: false,
_deleting: false
}));
this.unmappedIps = data.data.unmapped_ips || [];
} catch (error) {
this.error = error.message;
} finally {
this.loading = false;
}
},
async createMapping() {
this.saving = true;
this.error = '';
this.message = '';
try {
const response = await fetch('/api/admin/ip-user-mappings', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify(this.newMapping)
});
const data = await this.parseJsonResponse(response);
if (!response.ok) {
this.error = this.getErrorMessage(data, '创建失败');
return;
}
if (!data.success) {
this.error = data.message || '创建失败';
return;
}
this.message = '已新增映射';
this.newMapping = { ip_address: '', user_name: '', remark: '' };
await this.loadMappings();
} catch (error) {
this.error = error.message;
} finally {
this.saving = false;
}
},
async updateMapping(mapping) {
mapping._saving = true;
this.error = '';
this.message = '';
try {
const response = await fetch(`/api/admin/ip-user-mappings/${mapping.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
ip_address: mapping.ip_address,
user_name: mapping.user_name,
remark: mapping.remark
})
});
const data = await this.parseJsonResponse(response);
if (!response.ok) {
this.error = this.getErrorMessage(data, '更新失败');
return;
}
if (!data.success) {
this.error = data.message || '更新失败';
return;
}
this.message = '已更新映射';
} catch (error) {
this.error = error.message;
} finally {
mapping._saving = false;
}
},
async deleteMapping(mapping) {
mapping._deleting = true;
this.error = '';
this.message = '';
try {
const response = await fetch(`/api/admin/ip-user-mappings/${mapping.id}`, {
method: 'DELETE',
headers: {
Accept: 'application/json'
}
});
const data = await this.parseJsonResponse(response);
if (!response.ok) {
this.error = this.getErrorMessage(data, '删除失败');
return;
}
if (!data.success) {
this.error = data.message || '删除失败';
return;
}
this.message = '已删除映射';
await this.loadMappings();
} catch (error) {
this.error = error.message;
} finally {
mapping._deleting = false;
}
}
}
};
</script>

View File

@@ -0,0 +1,216 @@
<template>
<div class="space-y-6">
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-8">
<div class="flex items-start justify-between gap-4">
<div>
<h3 class="text-lg font-medium text-gray-900">操作日志</h3>
<p class="text-gray-500 mt-1">记录对系统产生影响的请求POST/PUT/PATCH/DELETE</p>
<p v-if="currentIp" class="text-xs text-gray-400 mt-1">当前 IP: {{ currentIp }}</p>
</div>
<button
class="px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 disabled:opacity-50"
:disabled="logsLoading"
@click="loadLogs"
>
{{ logsLoading ? '加载中...' : '刷新' }}
</button>
</div>
<div class="mt-6 flex flex-wrap items-center gap-3">
<input
v-model="filters.q"
type="text"
class="w-full md:w-64 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="搜索 IP / 用户 / 路径"
/>
<select
v-model="filters.method"
class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">全部方法</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="PATCH">PATCH</option>
<option value="DELETE">DELETE</option>
</select>
<select
v-model.number="logsPerPage"
class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option :value="20">20/</option>
<option :value="50">50/</option>
<option :value="100">100/</option>
</select>
<button
class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
:disabled="logsLoading"
@click="applyFilters"
>
查询
</button>
</div>
<div v-if="logsError" class="mt-4 text-sm text-red-700 bg-red-50 border border-red-200 rounded-md px-3 py-2">
{{ logsError }}
</div>
<div v-if="logsLoading" class="mt-4 text-sm text-gray-400">加载中...</div>
<div v-else class="mt-4">
<div class="overflow-x-auto border border-gray-200 rounded-lg">
<table class="min-w-full text-sm">
<thead class="bg-gray-50 text-gray-600">
<tr>
<th class="text-left px-4 py-3 font-medium">时间</th>
<th v-if="isAdmin" class="text-left px-4 py-3 font-medium">用户</th>
<th class="text-left px-4 py-3 font-medium">IP</th>
<th class="text-left px-4 py-3 font-medium">方法</th>
<th class="text-left px-4 py-3 font-medium">路径</th>
<th class="text-left px-4 py-3 font-medium">状态</th>
<th class="text-left px-4 py-3 font-medium">请求数据</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-200">
<tr v-for="log in logs" :key="log.id" class="text-gray-700">
<td class="px-4 py-3 whitespace-nowrap">{{ formatTime(log.created_at) }}</td>
<td v-if="isAdmin" class="px-4 py-3 whitespace-nowrap font-mono">{{ log.user_label || '-' }}</td>
<td class="px-4 py-3 whitespace-nowrap font-mono">{{ log.ip_address }}</td>
<td class="px-4 py-3 whitespace-nowrap font-mono">{{ log.method }}</td>
<td class="px-4 py-3 whitespace-nowrap">{{ log.path }}</td>
<td class="px-4 py-3 whitespace-nowrap">{{ log.status_code }}</td>
<td class="px-4 py-3">
<details v-if="hasPayload(log.request_payload)">
<summary class="cursor-pointer text-blue-600">查看</summary>
<pre class="mt-2 text-xs bg-gray-50 p-2 rounded whitespace-pre-wrap">{{ formatPayload(log.request_payload) }}</pre>
</details>
<span v-else>-</span>
</td>
</tr>
<tr v-if="logs.length === 0">
<td :colspan="logColumnCount" class="px-4 py-6 text-center text-gray-400">暂无记录</td>
</tr>
</tbody>
</table>
</div>
<div class="mt-4 flex items-center justify-between text-sm text-gray-500">
<div> {{ logsTotal }} </div>
<div class="flex items-center gap-2">
<button
class="px-3 py-1 bg-gray-100 rounded-md hover:bg-gray-200 disabled:opacity-50"
:disabled="logsPage <= 1"
@click="changePage(logsPage - 1)"
>
上一页
</button>
<div> {{ logsPage }} / {{ logsLastPage || 1 }} </div>
<button
class="px-3 py-1 bg-gray-100 rounded-md hover:bg-gray-200 disabled:opacity-50"
:disabled="logsPage >= logsLastPage"
@click="changePage(logsPage + 1)"
>
下一页
</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'OperationLogs',
props: {
isAdmin: {
type: Boolean,
default: false
},
currentIp: {
type: String,
default: ''
}
},
data() {
return {
logs: [],
logsLoading: false,
logsError: '',
logsPage: 1,
logsPerPage: 50,
logsTotal: 0,
logsLastPage: 1,
filters: {
q: '',
method: ''
}
};
},
computed: {
logColumnCount() {
return this.isAdmin ? 7 : 6;
}
},
mounted() {
this.loadLogs();
},
methods: {
formatTime(value) {
if (!value) {
return '-';
}
return value.replace('T', ' ').replace('Z', '');
},
hasPayload(payload) {
return payload && Object.keys(payload).length > 0;
},
formatPayload(payload) {
return JSON.stringify(payload, null, 2);
},
buildLogQuery() {
const params = new URLSearchParams();
params.set('page', String(this.logsPage));
params.set('per_page', String(this.logsPerPage));
if (this.filters.q) {
params.set('q', this.filters.q);
}
if (this.filters.method) {
params.set('method', this.filters.method);
}
return params.toString();
},
async loadLogs() {
this.logsLoading = true;
this.logsError = '';
try {
const response = await fetch(`/api/operation-logs?${this.buildLogQuery()}`);
const data = await response.json();
if (!data.success) {
this.logsError = data.message || '加载失败';
return;
}
const pagination = data.data.pagination || {};
this.logs = data.data.logs || [];
this.logsTotal = pagination.total || 0;
this.logsLastPage = pagination.last_page || 1;
this.logsPage = pagination.current_page || 1;
} catch (error) {
this.logsError = error.message;
} finally {
this.logsLoading = false;
}
},
applyFilters() {
this.logsPage = 1;
this.loadLogs();
},
changePage(page) {
this.logsPage = page;
this.loadLogs();
}
}
};
</script>

View File

@@ -0,0 +1,447 @@
<template>
<div class="sql-generator h-full flex flex-col p-4 box-border gap-4">
<div class="flex flex-col gap-4 lg:grid lg:grid-cols-2 lg:items-stretch lg:flex-1 min-h-0">
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex flex-col min-h-0">
<div class="flex items-center justify-between mb-3">
<h2 class="text-sm lg:text-base font-semibold text-gray-900 flex items-center">
<svg class="w-4 h-4 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
</svg>
生成SQL
</h2>
<span class="text-xs text-gray-500">选择功能后粘贴内容生成SQL</span>
</div>
<div class="flex flex-col gap-3 flex-1 min-h-0">
<div class="flex-shrink-0">
<label class="block text-xs font-medium text-gray-600 mb-2">功能选择</label>
<select
v-model="selectedTool"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm"
>
<option v-for="tool in toolOptions" :key="tool.value" :value="tool.value">
{{ tool.label }}
</option>
</select>
<p class="text-xs text-gray-500 mt-2">
{{ currentTool.description }}
</p>
</div>
<div class="flex flex-col flex-1 min-h-0">
<label class="block text-xs font-medium text-gray-600 mb-2">文本内容</label>
<textarea
v-model="inputText"
rows="8"
placeholder="示例: X0X60F 17141\nC01008446046, 11894"
class="w-full flex-1 min-h-[200px] px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm font-mono"
></textarea>
<div class="flex items-center justify-between mt-2">
<p class="text-xs text-gray-500">支持换行分隔符逗号 / 空格 / 制表符</p>
<div class="flex items-center space-x-2">
<button
@click="clearInput"
class="px-3 py-1.5 text-xs text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
type="button"
>
清空
</button>
<button
@click="generateSql"
:disabled="loading"
class="px-3 py-1.5 text-xs text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-60"
type="button"
>
<span v-if="loading">生成中...</span>
<span v-else>生成SQL</span>
</button>
</div>
</div>
</div>
</div>
</div>
<div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 flex flex-col min-h-0">
<div class="flex flex-col gap-4 h-full min-h-0">
<div>
<div class="flex items-center justify-between mb-2">
<h3 class="text-sm lg:text-base font-semibold text-gray-900">查询SQL</h3>
<button
@click="copyQuery"
:disabled="!querySql"
class="px-3 py-1.5 text-xs text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-60"
type="button"
>
复制查询SQL
</button>
</div>
<textarea
v-model="querySql"
readonly
ref="queryTextarea"
class="w-full min-h-[100px] px-3 py-2 border border-gray-200 rounded-lg text-sm font-mono bg-gray-50"
></textarea>
</div>
<div class="flex flex-col flex-1 min-h-0">
<div class="flex items-center justify-between mb-2">
<h3 class="text-sm lg:text-base font-semibold text-gray-900">生成结果</h3>
<div v-if="stats.total" class="text-xs text-gray-500">
{{ stats.total }} 更新 {{ stats.update }} 新增 {{ stats.insert }}
</div>
</div>
<textarea
v-model="outputSql"
readonly
ref="outputTextarea"
class="w-full flex-1 min-h-[200px] px-3 py-2 border border-gray-200 rounded-lg text-sm font-mono bg-gray-50"
></textarea>
<div class="flex items-center justify-between mt-2">
<p class="text-xs text-gray-400">结果仅用于复制执行请确认无误后使用</p>
<button
@click="copyOutput"
:disabled="!outputSql"
class="px-3 py-1.5 text-xs text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-60"
type="button"
>
复制结果
</button>
</div>
<div
v-if="copyStatus.message"
class="mt-2 text-xs"
:class="copyStatus.type === 'success' ? 'text-green-600' : 'text-red-600'"
>
{{ copyStatus.message }}
</div>
</div>
</div>
</div>
</div>
<div v-if="errors.length" class="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700">
<div class="font-medium mb-1">输入格式问题</div>
<ul class="list-disc list-inside space-y-0.5">
<li v-for="(error, index) in errors" :key="index">{{ error }}</li>
</ul>
</div>
<div v-if="warnings.length" class="bg-yellow-50 border border-yellow-200 rounded-lg p-3 text-sm text-yellow-800">
<div class="font-medium mb-1">发现重复 case_id</div>
<ul class="list-disc list-inside space-y-0.5">
<li v-for="(warning, index) in warnings" :key="index">{{ warning }}</li>
</ul>
</div>
</div>
</template>
<script>
export default {
name: 'SqlGenerator',
data() {
return {
selectedTool: 'ob-external-id',
inputText: '',
outputSql: '',
querySql: '',
loading: false,
errors: [],
warnings: [],
copyStatus: {
message: '',
type: 'success'
},
copyStatusTimer: null,
stats: {
total: 0,
update: 0,
insert: 0
},
toolOptions: [
{
value: 'ob-external-id',
label: 'OB外部ID',
description: '每行输入 case_id 与 ob_id系统会判断是否生成更新或插入 SQL。'
}
]
}
},
computed: {
currentTool() {
return this.toolOptions.find((tool) => tool.value === this.selectedTool) || this.toolOptions[0];
}
},
methods: {
clearInput() {
this.inputText = '';
this.outputSql = '';
this.querySql = '';
this.errors = [];
this.warnings = [];
this.resetCopyStatus();
this.resetStats();
},
resetStats() {
this.stats = {
total: 0,
update: 0,
insert: 0
};
},
parseObExternalIdInput() {
const lines = this.inputText.split(/\r?\n/);
const errors = [];
const duplicates = new Map();
const caseMap = new Map();
lines.forEach((line, index) => {
const trimmed = line.trim();
if (!trimmed) {
return;
}
const parts = trimmed.split(/[\s,]+/).filter(Boolean);
if (parts.length !== 2) {
errors.push(`${index + 1} 行格式不正确,请提供 case_id 与 ob_id 两列`);
return;
}
const [caseCode, obId] = parts;
if (!caseCode || !obId) {
errors.push(`${index + 1} 行缺少 case_id 或 ob_id`);
return;
}
const lineNumber = index + 1;
if (caseMap.has(caseCode)) {
const existing = caseMap.get(caseCode);
if (!duplicates.has(caseCode)) {
duplicates.set(caseCode, {
caseCode,
lineNumbers: [existing.lineNumber]
});
}
duplicates.get(caseCode).lineNumbers.push(lineNumber);
}
caseMap.set(caseCode, {
caseCode,
obId,
lineNumber
});
});
const pairs = Array.from(caseMap.values());
if (pairs.length === 0 && errors.length === 0) {
errors.push('请输入至少一行 case_id 与 ob_id。');
}
return {
pairs,
errors,
duplicates: Array.from(duplicates.values())
};
},
async generateSql() {
this.errors = [];
this.outputSql = '';
this.querySql = '';
this.warnings = [];
this.resetCopyStatus();
this.resetStats();
if (this.selectedTool === 'ob-external-id') {
await this.generateObExternalIdSql();
return;
}
this.errors = ['未识别的功能类型,请重新选择。'];
},
async generateObExternalIdSql() {
const { pairs, errors, duplicates } = this.parseObExternalIdInput();
this.warnings = this.buildDuplicateWarnings(duplicates);
if (errors.length) {
this.errors = errors;
return;
}
this.loading = true;
try {
const caseCodes = pairs.map((pair) => pair.caseCode);
this.querySql = this.buildCaseExtrasSelect(caseCodes);
const response = await fetch('/api/sql-generator/ob-external-id/check', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
},
body: JSON.stringify({
case_codes: caseCodes
})
});
const data = await response.json();
if (!response.ok || !data.success) {
this.errors = [data.message || '查询 case_extras 失败,请稍后重试。'];
return;
}
const existingCaseCodes = new Set(data.data.existing_case_codes || []);
const sqlLines = [];
pairs.forEach((pair) => {
const caseCode = this.escapeSqlValue(pair.caseCode);
const obId = this.escapeSqlValue(pair.obId);
if (existingCaseCodes.has(pair.caseCode)) {
sqlLines.push(
`update case_extras set value = '${obId}' where case_code = '${caseCode}' and source = 'ob' and field = 'OB Case ID'`
);
this.stats.update += 1;
} else {
sqlLines.push(
`insert into case_extras(case_code, source, field, value) VALUES ('${caseCode}', 'ob', 'OB Case ID', '${obId}')`
);
this.stats.insert += 1;
}
});
this.stats.total = sqlLines.length;
this.outputSql = sqlLines.join('\n');
} catch (error) {
this.errors = ['网络请求失败: ' + error.message];
} finally {
this.loading = false;
}
},
escapeSqlValue(value) {
return String(value).replace(/'/g, "''");
},
buildCaseExtrasSelect(caseCodes) {
if (!caseCodes.length) {
return '';
}
const inValues = caseCodes.map((caseCode) => `'${this.escapeSqlValue(caseCode)}'`).join(', ');
return `select * from case_extras where case_code in (${inValues})`;
},
buildDuplicateWarnings(duplicates) {
return duplicates.map((duplicate) => {
const lines = duplicate.lineNumbers.join('、');
return `case_id ${duplicate.caseCode} 重复出现在第 ${lines} 行,已以最后一行的 ob_id 为准。`;
});
},
resetCopyStatus() {
this.copyStatus = {
message: '',
type: 'success'
};
},
setCopyStatus(message, type) {
this.copyStatus = {
message,
type
};
window.clearTimeout(this.copyStatusTimer);
this.copyStatusTimer = window.setTimeout(() => {
this.resetCopyStatus();
}, 3000);
},
execCommandCopy(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
document.body.appendChild(textarea);
textarea.select();
let success = false;
try {
success = document.execCommand('copy');
} catch (error) {
success = false;
}
document.body.removeChild(textarea);
return success;
},
execCommandCopyFromRef(refName) {
const target = this.$refs[refName];
if (!target) {
return false;
}
target.focus();
target.select();
target.setSelectionRange(0, target.value.length);
let success = false;
try {
success = document.execCommand('copy');
} catch (error) {
success = false;
}
target.blur();
return success;
},
async copyToClipboard(text, fallbackMessage, refName) {
if (!text) {
return;
}
this.resetCopyStatus();
if (navigator.clipboard && window.isSecureContext) {
try {
await navigator.clipboard.writeText(text);
this.setCopyStatus('已复制到剪贴板。', 'success');
return;
} catch (error) {
// fallback to execCommand
}
}
const success = refName
? this.execCommandCopyFromRef(refName)
: this.execCommandCopy(text);
if (success) {
this.setCopyStatus('已复制到剪贴板。', 'success');
return;
}
this.setCopyStatus(fallbackMessage, 'error');
},
async copyOutput() {
await this.copyToClipboard(this.outputSql, '复制失败,请手动复制结果。', 'outputTextarea');
},
async copyQuery() {
await this.copyToClipboard(this.querySql, '复制失败请手动复制查询SQL。', 'queryTextarea');
}
}
}
</script>
<style scoped>
.sql-generator {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
</style>

View File

@@ -5,6 +5,10 @@ use App\Http\Controllers\EnvController;
use App\Http\Controllers\JiraController;
use App\Http\Controllers\MessageSyncController;
use App\Http\Controllers\MessageDispatchController;
use App\Http\Controllers\SqlGeneratorController;
use App\Http\Controllers\Admin\AdminMetaController;
use App\Http\Controllers\Admin\IpUserMappingController;
use App\Http\Controllers\Admin\OperationLogController;
// 环境管理API路由
Route::prefix('env')->group(function () {
@@ -21,6 +25,11 @@ Route::prefix('env')->group(function () {
Route::delete('/projects/{project}/envs/{env}', [EnvController::class, 'deleteEnv']);
});
// SQL 生成器 API 路由
Route::prefix('sql-generator')->group(function () {
Route::post('/ob-external-id/check', [SqlGeneratorController::class, 'checkObExternalId']);
});
// JIRA API路由
Route::prefix('jira')->group(function () {
Route::get('/config', [JiraController::class, 'getConfig']);
@@ -48,3 +57,17 @@ Route::prefix('message-dispatch')->group(function () {
Route::get('/abnormal', [MessageDispatchController::class, 'getAbnormalDispatches']);
Route::post('/batch-update', [MessageDispatchController::class, 'batchUpdateDispatch']);
});
// 操作日志(所有人可查看,用户名字段对非管理员隐藏)
Route::get('/operation-logs', [OperationLogController::class, 'index']);
// 管理员信息(不受白名单限制)
Route::get('/admin/meta', [AdminMetaController::class, 'show']);
// 管理员IP白名单限定的后台接口
Route::prefix('admin')->middleware('admin.ip')->group(function () {
Route::get('/ip-user-mappings', [IpUserMappingController::class, 'index']);
Route::post('/ip-user-mappings', [IpUserMappingController::class, 'store']);
Route::put('/ip-user-mappings/{mapping}', [IpUserMappingController::class, 'update']);
Route::delete('/ip-user-mappings/{mapping}', [IpUserMappingController::class, 'destroy']);
});

View File

@@ -8,6 +8,7 @@ Route::get('/', [AdminController::class, 'index'])->name('home');
// 前端路由 - 所有页面都通过admin框架显示
Route::get('/env', [AdminController::class, 'index'])->name('admin.env');
Route::get('/sql-generator', [AdminController::class, 'index'])->name('admin.sql-generator');
Route::get('/weekly-report', [AdminController::class, 'index'])->name('admin.weekly-report');
Route::get('/worklog', [AdminController::class, 'index'])->name('admin.worklog');
Route::get('/message-sync', [AdminController::class, 'index'])->name('admin.message-sync');
@@ -15,3 +16,4 @@ Route::get('/event-consumer-sync', [AdminController::class, 'index'])->name('adm
Route::get('/message-dispatch', [AdminController::class, 'index'])->name('admin.message-dispatch');
Route::get('/settings', [AdminController::class, 'index'])->name('admin.settings');
Route::get('/logs', [AdminController::class, 'index'])->name('admin.logs');
Route::get('/ip-mappings', [AdminController::class, 'index'])->name('admin.ip-mappings')->middleware('admin.ip');