功能:在系统设置中管理多个云数据库

This commit is contained in:
WuYongJie 2026-07-22 15:16:57 +08:00
parent af800b66f9
commit d9af0a0b7f
13 changed files with 642 additions and 217 deletions

View File

@ -6,190 +6,279 @@ use App\Models\Settings\DatabaseConnection;
use App\Utilities\SystemAccess;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Services\UpstreamOdbcConnection;
use Modules\EcommerceFinance\Services\UpstreamSourceRegistry;
use Modules\EcommerceFinance\Services\UpstreamStoredConfiguration;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
class Databases extends Controller
{
public function __construct()
{
$this->middleware(function ($request, $next) {
abort_unless(SystemAccess::canOpenSettings(), 403);
abort_unless(SystemAccess::isSuperAdmin(), 403);
return $next($request);
});
}
public function index()
public function index(UpstreamStoredConfiguration $storedConfiguration)
{
$defaultConnection = (string) config('database.default');
$systemDatabase = (array) config('database.connections.' . $defaultConnection, []);
return view('system_settings.databases.index', [
'connections' => DatabaseConnection::where('company_id', company_id())->orderBy('id')->get(),
'connections' => $storedConfiguration->editable()
? DatabaseConnection::query()
->where('company_id', UpstreamStoredConfiguration::SYSTEM_COMPANY_ID)
->orderBy('name')
->get()
: collect(),
'sourceLabels' => $this->sourceLabels(),
'systemDatabase' => [
'connection' => $defaultConnection,
'driver' => $systemDatabase['driver'] ?? $defaultConnection,
'host' => $systemDatabase['host'] ?? '本机文件',
'port' => $systemDatabase['port'] ?? null,
'database' => $systemDatabase['database'] ?? '',
],
'editable' => $storedConfiguration->editable(),
]);
}
public function create()
public function create(UpstreamStoredConfiguration $storedConfiguration)
{
return view('system_settings.databases.form', ['connection' => null]);
abort_unless($storedConfiguration->editable(), 403);
return view('system_settings.databases.form', [
'connection' => null,
'sourceLabels' => $this->sourceLabels(),
'values' => $this->defaultValues(),
]);
}
public function store(Request $request)
public function store(Request $request, UpstreamStoredConfiguration $storedConfiguration)
{
$data = $this->validateConnection($request);
$data['company_id'] = company_id();
$data['enabled'] = (bool) ($data['enabled'] ?? false);
abort_unless($storedConfiguration->editable(), 403);
DatabaseConnection::create($data);
$data = $this->validateConnection($request);
$connection = DatabaseConnection::create($this->attributes($data, null, $request));
$this->resetSource($connection->source_key, $storedConfiguration);
flash('数据库配置已新增。')->success();
return redirect()->route('system-settings.databases.index');
}
public function edit(int $id)
public function edit(int $connection, UpstreamStoredConfiguration $storedConfiguration)
{
abort_unless($storedConfiguration->editable(), 403);
$connection = $this->connection($connection);
return view('system_settings.databases.form', [
'connection' => $this->findConnection($id),
'connection' => $connection,
'sourceLabels' => $this->sourceLabels(),
'values' => $this->values($connection),
]);
}
public function update(int $id, Request $request)
public function update(int $connection, Request $request, UpstreamStoredConfiguration $storedConfiguration)
{
$connection = $this->findConnection($id);
abort_unless($storedConfiguration->editable(), 403);
$connection = $this->connection($connection);
$oldSource = $connection->source_key;
$data = $this->validateConnection($request, $connection);
$data['enabled'] = (bool) ($data['enabled'] ?? false);
$connection->update($this->attributes($data, $connection, $request));
if (empty($data['password'])) {
unset($data['password']);
}
$connection->update($data);
$this->resetSource($oldSource, $storedConfiguration);
$this->resetSource($connection->source_key, $storedConfiguration);
flash('数据库配置已修改。')->success();
return redirect()->route('system-settings.databases.index');
}
public function destroy(int $id)
public function destroy(int $connection, UpstreamStoredConfiguration $storedConfiguration)
{
$this->findConnection($id)->delete();
abort_unless($storedConfiguration->editable(), 403);
$connection = $this->connection($connection);
$source = $connection->source_key;
$connection->delete();
$this->resetSource($source, $storedConfiguration);
flash('数据库配置已删除。')->success();
return redirect()->route('system-settings.databases.index');
}
public function export()
public function test(int $connection, UpstreamStoredConfiguration $storedConfiguration)
{
$connections = DatabaseConnection::where('company_id', company_id())->orderBy('id')->get();
abort_unless($storedConfiguration->editable(), 403);
$connection = $this->connection($connection);
return response()->streamDownload(function () use ($connections) {
$stream = fopen('php://output', 'w');
fwrite($stream, "\xEF\xBB\xBF");
fputcsv($stream, ['name', 'driver', 'host', 'port', 'database_name', 'username', 'password', 'charset', 'enabled']);
foreach ($connections as $connection) {
fputcsv($stream, [
$connection->name,
$connection->driver,
$connection->host,
$connection->port,
$connection->database_name,
$connection->username,
'',
$connection->charset,
$connection->enabled ? 1 : 0,
]);
}
fclose($stream);
}, 'database-connections.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
public function import(Request $request)
{
$request->validate(['file' => ['required', 'file', 'mimes:csv,txt', 'max:5120']]);
$handle = fopen($request->file('file')->getRealPath(), 'r');
$header = fgetcsv($handle);
$header = array_map(fn ($value) => trim((string) $value, "\xEF\xBB\xBF \t\n\r\0\x0B"), $header ?: []);
$required = ['name', 'driver', 'database_name'];
if (array_diff($required, $header)) {
fclose($handle);
return back()->withErrors(['file' => '文件表头不正确,请先导出模板后填写。']);
try {
UpstreamOdbcConnection::probeConfiguration($this->odbcConfiguration($connection), $connection->name);
} catch (ServiceUnavailableHttpException) {
throw ValidationException::withMessages([
'connection' => '连接失败。请检查地址、端口、数据库、账号、网络白名单和本机 ODBC 驱动。',
]);
}
$count = 0;
DB::transaction(function () use ($handle, $header, &$count) {
while (($row = fgetcsv($handle)) !== false) {
if (count(array_filter($row, fn ($value) => trim((string) $value) !== '')) === 0) {
continue;
}
$row = array_pad($row, count($header), '');
$data = array_combine($header, array_slice($row, 0, count($header)));
$driver = in_array($data['driver'] ?? '', ['mysql', 'pgsql', 'sqlite', 'sqlsrv'], true)
? $data['driver']
: 'mysql';
$attributes = [
'driver' => $driver,
'host' => $data['host'] ?: null,
'port' => ($data['port'] ?? '') !== '' ? (int) $data['port'] : null,
'database_name' => trim((string) ($data['database_name'] ?? '')),
'username' => $data['username'] ?: null,
'charset' => $data['charset'] ?: 'utf8mb4',
'enabled' => filter_var($data['enabled'] ?? true, FILTER_VALIDATE_BOOL),
];
if (($data['password'] ?? '') !== '') {
$attributes['password'] = $data['password'];
}
if (trim((string) ($data['name'] ?? '')) === '' || $attributes['database_name'] === '') {
continue;
}
DatabaseConnection::updateOrCreate(
['company_id' => company_id(), 'name' => trim($data['name'])],
$attributes
);
$count++;
}
});
fclose($handle);
flash("已导入 {$count} 条数据库配置。")->success();
flash($connection->name . '连接成功,仅执行了 SELECT 1 只读测试。')->success();
return redirect()->route('system-settings.databases.index');
}
private function findConnection(int $id): DatabaseConnection
{
return DatabaseConnection::where('company_id', company_id())->findOrFail($id);
}
private function validateConnection(Request $request, ?DatabaseConnection $connection = null): array
{
$sourceKeys = array_keys($this->sourceLabels());
return $request->validate([
'name' => [
'required',
'string',
'max:191',
Rule::unique('system_database_connections', 'name')
->where(fn ($query) => $query->where('company_id', company_id()))
->where(fn ($query) => $query->where('company_id', UpstreamStoredConfiguration::SYSTEM_COMPANY_ID))
->ignore($connection?->id),
],
'driver' => ['required', Rule::in(['mysql', 'pgsql', 'sqlite', 'sqlsrv'])],
'host' => ['nullable', 'string', 'max:191'],
'port' => ['nullable', 'integer', 'between:1,65535'],
'database_name' => ['required', 'string', 'max:191'],
'username' => ['nullable', 'string', 'max:191'],
'password' => ['nullable', 'string', 'max:1000'],
'charset' => ['required', 'string', 'max:30'],
'source_key' => [
'nullable',
Rule::in($sourceKeys),
Rule::unique('system_database_connections', 'source_key')
->where(fn ($query) => $query->where('company_id', UpstreamStoredConfiguration::SYSTEM_COMPANY_ID))
->ignore($connection?->id),
],
'host' => ['required', 'string', 'max:191', 'not_regex:/[;\x00-\x1F]/'],
'port' => ['required', 'integer', 'between:1,65535'],
'database_name' => ['required', 'string', 'max:191', 'not_regex:/[;\x00-\x1F]/'],
'username' => ['required', 'string', 'max:191', 'not_regex:/[;\x00-\x1F]/'],
'password' => [$connection ? 'nullable' : 'required', 'string', 'max:1000'],
'odbc_driver' => ['required', 'string', 'max:128', 'not_regex:/[;{}\x00-\x1F]/'],
'tds_version' => ['required', 'regex:/^\d+(?:\.\d+)?$/', 'max:16'],
'connect_timeout' => ['required', 'integer', 'between:1,30'],
'query_timeout' => ['required', 'integer', 'between:1,120'],
'allowed_scopes' => ['nullable', 'string', 'max:4000'],
'enabled' => ['nullable', 'boolean'],
]);
}
private function attributes(array $data, ?DatabaseConnection $connection, Request $request): array
{
$attributes = [
'company_id' => UpstreamStoredConfiguration::SYSTEM_COMPANY_ID,
'source_key' => $data['source_key'] ?? null,
'name' => trim($data['name']),
'driver' => 'sqlsrv',
'host' => trim($data['host']),
'port' => (int) $data['port'],
'database_name' => trim($data['database_name']),
'username' => trim($data['username']),
'odbc_driver' => trim($data['odbc_driver']),
'tds_version' => trim($data['tds_version']),
'connect_timeout' => (int) $data['connect_timeout'],
'query_timeout' => (int) $data['query_timeout'],
'allowed_scopes' => $this->parseScopes((string) ($data['allowed_scopes'] ?? '')),
'charset' => 'UTF-8',
'enabled' => $request->boolean('enabled'),
];
if (! empty($data['password'])) {
$attributes['password'] = $data['password'];
}
return $attributes;
}
private function parseScopes(string $value): array
{
$scopes = array_values(array_unique(array_filter(array_map('trim', preg_split('/[,\r\n]+/', $value) ?: []))));
foreach ($scopes as $scope) {
if ($scope === '*' || preg_match('/^[a-z0-9_.-]+(?:\.\*)?$/i', $scope) !== 1) {
throw ValidationException::withMessages([
'allowed_scopes' => '数据范围只允许精确名称或“前缀.*”,不能使用全局 *。',
]);
}
}
return $scopes;
}
private function connection(int $id): DatabaseConnection
{
return DatabaseConnection::query()
->where('company_id', UpstreamStoredConfiguration::SYSTEM_COMPANY_ID)
->findOrFail($id);
}
private function sourceLabels(): array
{
return collect((array) config('upstreams.sources', []))
->mapWithKeys(fn (array $source, string $key) => [$key => $source['label'] ?? $key])
->all();
}
private function defaultValues(): array
{
return [
'name' => '',
'source_key' => '',
'enabled' => false,
'host' => '',
'port' => 1433,
'database_name' => '',
'username' => '',
'odbc_driver' => 'FreeTDS',
'tds_version' => '7.4',
'connect_timeout' => 5,
'query_timeout' => 15,
'allowed_scopes' => '',
];
}
private function values(DatabaseConnection $connection): array
{
return [
'name' => $connection->name,
'source_key' => $connection->source_key,
'enabled' => $connection->enabled,
'host' => $connection->host,
'port' => $connection->port,
'database_name' => $connection->database_name,
'username' => $connection->username,
'odbc_driver' => $connection->odbc_driver,
'tds_version' => $connection->tds_version,
'connect_timeout' => $connection->connect_timeout,
'query_timeout' => $connection->query_timeout,
'allowed_scopes' => implode(', ', $connection->allowed_scopes ?? []),
];
}
private function odbcConfiguration(DatabaseConnection $connection): array
{
return [
'host' => $connection->host,
'port' => $connection->port,
'database' => $connection->database_name,
'username' => $connection->username,
'password' => $connection->password,
'odbc_driver' => $connection->odbc_driver,
'tds_version' => $connection->tds_version,
'connect_timeout' => $connection->connect_timeout,
'query_timeout' => $connection->query_timeout,
];
}
private function resetSource(?string $source, UpstreamStoredConfiguration $storedConfiguration): void
{
if (! $source) {
return;
}
$storedConfiguration->forget($source);
UpstreamOdbcConnection::reset($source);
}
}

View File

@ -29,6 +29,10 @@ class Settings extends Component
['system-settings.sidebar.edit', '侧边栏管理', 'menu', '侧边栏 用户类型 指定管理员'],
];
if (SystemAccess::isSuperAdmin()) {
$items[] = ['system-settings.databases.index', '数据库管理', 'storage', '数据库 云数据库 上游 连接 测试'];
}
foreach ($items as $index => [$route, $title, $icon, $keywords]) {
if ($this->keyword && ! Str::contains(Str::lower($title . ' ' . $keywords), Str::lower($this->keyword))) {
continue;

View File

@ -10,6 +10,7 @@ class DatabaseConnection extends Model
protected $fillable = [
'company_id',
'source_key',
'name',
'driver',
'host',
@ -17,12 +18,18 @@ class DatabaseConnection extends Model
'database_name',
'username',
'password',
'odbc_driver',
'tds_version',
'connect_timeout',
'query_timeout',
'allowed_scopes',
'charset',
'enabled',
];
protected $casts = [
'password' => 'encrypted',
'allowed_scopes' => 'array',
'enabled' => 'boolean',
];

View File

@ -0,0 +1,37 @@
<?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::table('system_database_connections', function (Blueprint $table) {
$table->string('source_key', 64)->nullable()->after('company_id');
$table->string('odbc_driver', 128)->nullable()->after('password');
$table->string('tds_version', 16)->nullable()->after('odbc_driver');
$table->unsignedInteger('connect_timeout')->nullable()->after('tds_version');
$table->unsignedInteger('query_timeout')->nullable()->after('connect_timeout');
$table->text('allowed_scopes')->nullable()->after('query_timeout');
$table->unique(['company_id', 'source_key'], 'system_database_connections_source_unique');
});
}
public function down(): void
{
Schema::table('system_database_connections', function (Blueprint $table) {
$table->dropUnique('system_database_connections_source_unique');
$table->dropColumn([
'source_key',
'odbc_driver',
'tds_version',
'connect_timeout',
'query_timeout',
'allowed_scopes',
]);
});
}
};

View File

@ -24,15 +24,59 @@ class UpstreamOdbcConnection
}
public static function create(string $source): PDO
{
return self::connect($source, true);
}
public static function probe(string $source): void
{
$sources = app(UpstreamSourceRegistry::class);
$definition = $sources->definition($source);
if (! $sources->enabled($source)) {
self::probeConfiguration(
(array) $sources->value($source, 'connection', []),
$definition['label'],
$definition['key'],
);
}
public static function probeConfiguration(array $connection, string $label, string $source = 'custom'): void
{
$pdo = self::open($connection, $source, $label);
try {
$statement = $pdo->query('SELECT 1');
$statement->fetchColumn();
} catch (PDOException $exception) {
Log::warning('上游数据库只读连接探测失败。', [
'source' => $source,
'source_label' => $label,
'sql_state' => (string) $exception->getCode(),
'exception' => $exception::class,
]);
throw new ServiceUnavailableHttpException(60, '上游数据库连接探测失败,请检查配置。');
}
}
private static function connect(string $source, bool $requireEnabled): PDO
{
$sources = app(UpstreamSourceRegistry::class);
$definition = $sources->definition($source);
if ($requireEnabled && ! $sources->enabled($source)) {
throw new ServiceUnavailableHttpException(60, '该上游数据同步尚未启用,请联系管理员。');
}
$connection = (array) $sources->value($source, 'connection', []);
return self::open(
(array) $sources->value($source, 'connection', []),
$definition['key'],
$definition['label'],
);
}
private static function open(array $connection, string $source, string $label): PDO
{
$host = trim((string) ($connection['host'] ?? ''));
$port = min(max((int) ($connection['port'] ?? 1433), 1), 65535);
$db = trim((string) ($connection['database'] ?? ''));
@ -83,8 +127,8 @@ class UpstreamOdbcConnection
]);
} catch (PDOException $exception) {
Log::warning('上游数据库连接失败。', [
'source' => $definition['key'],
'source_label' => $definition['label'],
'source' => $source,
'source_label' => $label,
'sql_state' => (string) $exception->getCode(),
'exception' => $exception::class,
]);

View File

@ -24,16 +24,16 @@ class UpstreamQueryCache
private readonly string $label;
private readonly string $configKey;
private readonly UpstreamSourceRegistry $sources;
private ?array $lastReadState = null;
public function __construct(UpstreamSourceRegistry $sources, string $source)
{
$definition = $sources->definition($source);
$this->sources = $sources;
$this->source = $definition['key'];
$this->label = $definition['label'];
$this->configKey = $definition['config'];
}
public function sourceKey(): string
@ -43,9 +43,7 @@ class UpstreamQueryCache
public function setting(string $path, mixed $default = null): mixed
{
$suffix = trim($path, '.');
return config($this->configKey . ($suffix === '' ? '' : '.' . $suffix), $default);
return $this->sources->value($this->source, $path, $default);
}
/**

View File

@ -9,6 +9,11 @@ use InvalidArgumentException;
*/
class UpstreamSourceRegistry
{
public function __construct(
private readonly UpstreamStoredConfiguration $storedConfiguration,
) {
}
/**
* @return array{key:string,label:string,config:string}
*/
@ -44,8 +49,9 @@ class UpstreamSourceRegistry
$definition = $this->definition($source);
$suffix = trim($path, '.');
$key = $definition['config'] . ($suffix === '' ? '' : '.' . $suffix);
$configured = config($key, $default);
return config($key, $default);
return $this->storedConfiguration->value($definition['key'], $suffix, $configured);
}
public function enabled(string $source): bool

View File

@ -0,0 +1,75 @@
<?php
namespace Modules\EcommerceFinance\Services;
use App\Models\Settings\DatabaseConnection;
use Illuminate\Support\Facades\Schema;
/**
* 读取仅供本地开发使用的上游连接配置。
*
* 生产环境始终使用私有环境变量,避免网页配置覆盖服务器运行配置。
*/
class UpstreamStoredConfiguration
{
public const SYSTEM_COMPANY_ID = 0;
/** @var array<string, DatabaseConnection|null> */
private array $connections = [];
public function editable(): bool
{
return app()->environment(['local', 'development', 'testing']);
}
public function find(string $source): ?DatabaseConnection
{
if (! $this->editable()) {
return null;
}
if (array_key_exists($source, $this->connections)) {
return $this->connections[$source];
}
if (! Schema::hasTable('system_database_connections')) {
return $this->connections[$source] = null;
}
$this->connections[$source] = DatabaseConnection::query()
->where('company_id', self::SYSTEM_COMPANY_ID)
->where('source_key', $source)
->first();
return $this->connections[$source];
}
public function forget(string $source): void
{
unset($this->connections[$source]);
}
public function value(string $source, string $path, mixed $default = null): mixed
{
$connection = $this->find($source);
if (! $connection) {
return $default;
}
return match (trim($path, '.')) {
'enabled' => $connection->enabled,
'allowed_scopes' => $connection->allowed_scopes ?? [],
'connection.host' => $connection->host,
'connection.port' => $connection->port,
'connection.database' => $connection->database_name,
'connection.username' => $connection->username,
'connection.password' => $connection->password,
'connection.odbc_driver' => $connection->odbc_driver,
'connection.tds_version' => $connection->tds_version,
'connection.connect_timeout' => $connection->connect_timeout,
'connection.query_timeout' => $connection->query_timeout,
default => $default,
};
}
}

View File

@ -1,70 +1,77 @@
<x-layouts.admin>
<x-slot name="title">{{ $connection ? '修改数据库配置' : '新增数据库配置' }}</x-slot>
<x-slot name="title">{{ $connection ? '修改数据库' : '添加数据库' }}</x-slot>
<x-slot name="content">
<div class="my-6">
@include('system_settings.partials.navigation')
<form method="POST" action="{{ $connection ? route('system-settings.databases.update', $connection->id) : route('system-settings.databases.store') }}" class="max-w-4xl rounded-xl border border-gray-200 bg-white p-6 shadow-sm">
<form method="POST" action="{{ $connection ? route('system-settings.databases.update', $connection->id) : route('system-settings.databases.store') }}" class="max-w-4xl rounded-xl border border-gray-200 bg-white p-6">
@csrf
@if ($connection) @method('PATCH') @endif
@if ($errors->any())
<div class="mb-5 rounded-lg bg-red-50 px-4 py-3 text-sm text-red-700">
<div class="mb-5 rounded-lg bg-red-50 px-4 py-3 text-sm text-red-700" role="alert">
@foreach ($errors->all() as $error)<p>{{ $error }}</p>@endforeach
</div>
@endif
<div class="grid grid-cols-1 gap-5 sm:grid-cols-2">
<label class="block">
<label class="block sm:col-span-2">
<span class="text-sm font-semibold text-gray-700">配置名称 *</span>
<input name="name" value="{{ old('name', $connection?->name) }}" required maxlength="191" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2.5 text-sm focus:border-purple focus:ring-purple">
<input name="name" value="{{ old('name', $values['name']) }}" required maxlength="191" placeholder="例如:JianSun 测试库" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm placeholder-gray-500 focus:border-purple-700 focus:ring-purple-700">
</label>
<label class="block sm:col-span-2">
<span class="text-sm font-semibold text-gray-700">主机地址 *</span>
<input name="host" value="{{ old('host', $values['host']) }}" required maxlength="191" autocomplete="off" placeholder="数据库域名、IP 或本地隧道地址" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm placeholder-gray-500 focus:border-purple-700 focus:ring-purple-700">
</label>
<label class="block">
<span class="text-sm font-semibold text-gray-700">数据库类型 *</span>
<select name="driver" required class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2.5 text-sm focus:border-purple focus:ring-purple">
@foreach (['mysql' => 'MySQL', 'pgsql' => 'PostgreSQL', 'sqlite' => 'SQLite', 'sqlsrv' => 'SQL Server'] as $driver => $label)
<option value="{{ $driver }}" @selected(old('driver', $connection?->driver ?? 'mysql') === $driver)>{{ $label }}</option>
<span class="text-sm font-semibold text-gray-700">端口 *</span>
<input type="number" name="port" value="{{ old('port', $values['port']) }}" required min="1" max="65535" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-purple-700 focus:ring-purple-700">
</label>
<label class="block">
<span class="text-sm font-semibold text-gray-700">数据库名称 *</span>
<input name="database_name" value="{{ old('database_name', $values['database_name']) }}" required maxlength="191" autocomplete="off" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-purple-700 focus:ring-purple-700">
</label>
<label class="block">
<span class="text-sm font-semibold text-gray-700">只读账号 *</span>
<input name="username" value="{{ old('username', $values['username']) }}" required maxlength="191" autocomplete="off" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-purple-700 focus:ring-purple-700">
</label>
<label class="block">
<span class="text-sm font-semibold text-gray-700">密码 {{ $connection ? '' : '*' }}</span>
<input type="password" name="password" @required(! $connection) maxlength="1000" autocomplete="new-password" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-purple-700 focus:ring-purple-700">
<span class="mt-1 block text-xs text-gray-500">{{ $connection ? '留空表示保留原密码。' : '保存后不会回显。' }}</span>
</label>
<label class="block sm:col-span-2">
<span class="text-sm font-semibold text-gray-700">绑定业务来源</span>
<select name="source_key" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-purple-700 focus:ring-purple-700">
<option value="">不绑定,仅保存和测试</option>
@foreach ($sourceLabels as $key => $label)
<option value="{{ $key }}" @selected(old('source_key', $values['source_key']) === $key)>{{ $label }}</option>
@endforeach
</select>
</label>
<label class="block">
<span class="text-sm font-semibold text-gray-700">主机地址</span>
<input name="host" value="{{ old('host', $connection?->host) }}" maxlength="191" placeholder="127.0.0.1" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2.5 text-sm focus:border-purple focus:ring-purple">
</label>
<label class="block">
<span class="text-sm font-semibold text-gray-700">端口</span>
<input type="number" name="port" value="{{ old('port', $connection?->port) }}" min="1" max="65535" placeholder="3306" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2.5 text-sm focus:border-purple focus:ring-purple">
</label>
<label class="block">
<span class="text-sm font-semibold text-gray-700">数据库名称 / SQLite 路径 *</span>
<input name="database_name" value="{{ old('database_name', $connection?->database_name) }}" required maxlength="191" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2.5 text-sm focus:border-purple focus:ring-purple">
</label>
<label class="block">
<span class="text-sm font-semibold text-gray-700">字符集 *</span>
<input name="charset" value="{{ old('charset', $connection?->charset ?? 'utf8mb4') }}" required maxlength="30" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2.5 text-sm focus:border-purple focus:ring-purple">
</label>
<label class="block">
<span class="text-sm font-semibold text-gray-700">用户名</span>
<input name="username" value="{{ old('username', $connection?->username) }}" maxlength="191" autocomplete="off" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2.5 text-sm focus:border-purple focus:ring-purple">
</label>
<label class="block">
<span class="text-sm font-semibold text-gray-700">密码</span>
<input type="password" name="password" maxlength="1000" autocomplete="new-password" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2.5 text-sm focus:border-purple focus:ring-purple">
@if ($connection)<span class="mt-1 block text-xs text-gray-400">留空表示保留已加密保存的密码</span>@endif
</label>
<div class="flex items-end pb-2">
<input type="hidden" name="enabled" value="0">
<label class="inline-flex items-center gap-2 text-sm font-semibold text-gray-700">
<input type="checkbox" name="enabled" value="1" @checked((bool) old('enabled', $connection?->enabled ?? true)) class="rounded border-gray-300 text-purple focus:ring-purple">
启用配置
</label>
</div>
</div>
<div class="mt-7 flex justify-end gap-3 border-t border-gray-100 pt-5">
<a href="{{ route('system-settings.databases.index') }}" class="rounded-lg px-5 py-2.5 text-sm text-gray-600 hover:bg-gray-100">取消</a>
<button type="submit" class="rounded-lg bg-green px-5 py-2.5 text-sm text-white hover:bg-green-700">保存</button>
<details class="mt-6 rounded-lg border border-gray-200 px-4 py-3">
<summary class="cursor-pointer text-sm font-semibold text-gray-700">高级设置</summary>
<div class="mt-4 grid grid-cols-1 gap-5 sm:grid-cols-2">
<label class="block"><span class="text-sm font-semibold text-gray-700">ODBC 驱动</span><input name="odbc_driver" value="{{ old('odbc_driver', $values['odbc_driver']) }}" required maxlength="128" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-purple-700 focus:ring-purple-700"></label>
<label class="block"><span class="text-sm font-semibold text-gray-700">TDS 版本</span><input name="tds_version" value="{{ old('tds_version', $values['tds_version']) }}" required maxlength="16" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-purple-700 focus:ring-purple-700"></label>
<label class="block"><span class="text-sm font-semibold text-gray-700">连接超时(秒)</span><input type="number" name="connect_timeout" value="{{ old('connect_timeout', $values['connect_timeout']) }}" required min="1" max="30" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-purple-700 focus:ring-purple-700"></label>
<label class="block"><span class="text-sm font-semibold text-gray-700">查询超时(秒)</span><input type="number" name="query_timeout" value="{{ old('query_timeout', $values['query_timeout']) }}" required min="1" max="120" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-purple-700 focus:ring-purple-700"></label>
<label class="block sm:col-span-2"><span class="text-sm font-semibold text-gray-700">允许的数据范围</span><textarea name="allowed_scopes" rows="2" maxlength="4000" placeholder="绑定业务来源时填写,每行或逗号分隔" class="mt-1 w-full rounded-lg border border-gray-300 px-3 py-2 text-sm placeholder-gray-500 focus:border-purple-700 focus:ring-purple-700">{{ old('allowed_scopes', $values['allowed_scopes']) }}</textarea></label>
</div>
</details>
<div class="mt-6 flex items-center justify-between border-t border-gray-100 pt-5">
<div>
<input type="hidden" name="enabled" value="0">
<label class="inline-flex items-center gap-2 text-sm font-semibold text-gray-700"><input type="checkbox" name="enabled" value="1" @checked((bool) old('enabled', $values['enabled'])) class="rounded border-gray-300 text-purple-700 focus:ring-purple-700">启用</label>
</div>
<div class="flex gap-3">
<a href="{{ route('system-settings.databases.index') }}" class="rounded-lg px-5 py-2 text-sm font-semibold text-gray-600 hover:bg-gray-100">取消</a>
<button type="submit" class="rounded-lg bg-purple-700 px-5 py-2 text-sm font-semibold text-white hover:bg-purple-800">保存</button>
</div>
</div>
</form>
</div>

View File

@ -1,81 +1,78 @@
<x-layouts.admin>
<x-slot name="title">数据库配置管理</x-slot>
<x-slot name="title">数据库管理</x-slot>
<x-slot name="buttons">
<a href="{{ route('system-settings.databases.create') }}" class="inline-flex items-center gap-2 rounded-lg bg-green px-5 py-2 text-sm text-white hover:bg-green-700">
<span class="material-icons-outlined text-lg">add</span>新增配置
</a>
</x-slot>
@if ($editable)
<x-slot name="buttons">
<a href="{{ route('system-settings.databases.create') }}" class="inline-flex items-center gap-2 rounded-lg bg-purple-700 px-4 py-2 text-sm font-semibold text-white hover:bg-purple-800">
<span class="material-icons-outlined text-lg" aria-hidden="true">add</span>添加数据库
</a>
</x-slot>
@endif
<x-slot name="content">
<div class="my-6">
@include('system_settings.partials.navigation')
<div class="mb-5 rounded-lg border-l-4 border-purple bg-lilac-100 px-4 py-3 text-sm text-gray-700">
数据库密码加密保存,列表及导出文件均不会显示密码。导入时密码留空可保留已有密码。
</div>
@if ($errors->any())
<div class="mb-4 rounded-lg bg-red-50 px-4 py-3 text-sm text-red-700">
<div class="mb-5 rounded-lg bg-red-50 px-4 py-3 text-sm text-red-700" role="alert">
@foreach ($errors->all() as $error)<p>{{ $error }}</p>@endforeach
</div>
@endif
<div class="mb-5 flex flex-wrap items-end justify-between gap-4 rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
<form method="POST" action="{{ route('system-settings.databases.import') }}" enctype="multipart/form-data" class="flex flex-wrap items-end gap-3">
@csrf
<label class="block">
<span class="mb-1 block text-xs font-semibold text-gray-600">导入 CSV</span>
<input type="file" name="file" accept=".csv,.txt" required class="block max-w-xs text-sm text-gray-600">
</label>
<button type="submit" class="inline-flex h-10 items-center gap-2 rounded-lg bg-green px-4 text-sm text-white hover:bg-green-700">
<span class="material-icons-outlined text-lg">upload_file</span>导入
</button>
</form>
<a href="{{ route('system-settings.databases.export') }}" class="inline-flex h-10 items-center gap-2 rounded-lg border border-gray-300 px-4 text-sm text-gray-600 hover:bg-gray-50">
<span class="material-icons-outlined text-lg">download</span>导出 / 下载模板
</a>
<div class="mb-5 rounded-xl bg-purple-100 px-5 py-4 text-sm leading-6 text-gray-700">
<p class="font-semibold text-gray-900">当前系统数据库</p>
<p class="mt-1">
{{ strtoupper($systemDatabase['driver']) }} · {{ $systemDatabase['host'] }}{{ $systemDatabase['port'] ? ':' . $systemDatabase['port'] : '' }} · {{ $systemDatabase['database'] ?: $systemDatabase['connection'] }}
</p>
<p class="mt-1">用户、系统设置和下方所有数据库配置都统一保存在这个数据库中。系统库的启动连接由私有 <code>runtime/.env</code> 提供,页面不会显示密码。</p>
@if ($editable)
<p class="mt-1">下方可继续添加多个云数据库;连接测试只执行 <code>SELECT 1</code>。</p>
@else
<p class="mt-1">生产环境不允许在网页中修改数据库凭据。</p>
@endif
</div>
<div class="overflow-x-auto rounded-xl border border-gray-200 bg-white">
<table class="min-w-full divide-y divide-gray-200 text-sm">
<thead class="bg-gray-50 text-left text-gray-500">
<thead class="bg-purple-50 text-left text-gray-700">
<tr>
<th class="px-5 py-3">配置名称</th>
<th class="px-5 py-3">类型</th>
<th class="px-5 py-3">主机 / 端口</th>
<th class="px-5 py-3">数据库</th>
<th class="px-5 py-3">用户名</th>
<th class="px-5 py-3">状态</th>
<th class="px-5 py-3 text-right">操作</th>
<th class="px-5 py-3 font-semibold">名称</th>
<th class="px-5 py-3 font-semibold">地址</th>
<th class="px-5 py-3 font-semibold">数据库</th>
<th class="px-5 py-3 font-semibold">业务绑定</th>
<th class="px-5 py-3 font-semibold">状态</th>
<th class="px-5 py-3 text-right font-semibold">操作</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100">
@forelse ($connections as $connection)
<tr>
<td class="px-5 py-4 font-semibold text-gray-800">{{ $connection->name }}</td>
<td class="px-5 py-4 uppercase text-gray-600">{{ $connection->driver }}</td>
<td class="px-5 py-4 text-gray-600">{{ $connection->host ?: '-' }}{{ $connection->port ? ':' . $connection->port : '' }}</td>
<td class="px-5 py-4 font-semibold text-gray-900">{{ $connection->name }}</td>
<td class="px-5 py-4 text-gray-600">{{ $connection->host }}:{{ $connection->port }}</td>
<td class="px-5 py-4 text-gray-600">{{ $connection->database_name }}</td>
<td class="px-5 py-4 text-gray-600">{{ $connection->username ?: '-' }}</td>
<td class="px-5 py-4 text-gray-600">{{ $sourceLabels[$connection->source_key] ?? '未绑定' }}</td>
<td class="px-5 py-4">
<span @class([
'rounded-full px-2.5 py-1 text-xs font-semibold',
'inline-flex rounded-full px-2.5 py-1 text-xs font-semibold',
'bg-green-100 text-green-700' => $connection->enabled,
'bg-gray-100 text-gray-500' => ! $connection->enabled,
'bg-gray-100 text-gray-600' => ! $connection->enabled,
])>{{ $connection->enabled ? '启用' : '停用' }}</span>
</td>
<td class="px-5 py-4 text-right whitespace-nowrap">
<a href="{{ route('system-settings.databases.edit', $connection->id) }}" class="mr-4 text-purple hover:underline">修改</a>
<form method="POST" action="{{ route('system-settings.databases.destroy', $connection->id) }}" class="inline" onsubmit="return confirm('确定删除该数据库配置吗?')">
<form method="POST" action="{{ route('system-settings.databases.test', $connection->id) }}" class="inline">
@csrf
<button type="submit" class="font-semibold text-gray-600 hover:text-purple-700 hover:underline">测试</button>
</form>
<a href="{{ route('system-settings.databases.edit', $connection->id) }}" class="ml-4 font-semibold text-purple-700 hover:text-purple-800 hover:underline">修改</a>
<form method="POST" action="{{ route('system-settings.databases.destroy', $connection->id) }}" class="ml-4 inline" onsubmit="return confirm('确定删除这个数据库配置吗?')">
@csrf
@method('DELETE')
<button type="submit" class="text-red-600 hover:underline">删除</button>
<button type="submit" class="font-semibold text-red-600 hover:underline">删除</button>
</form>
</td>
</tr>
@empty
<tr><td colspan="7" class="px-5 py-12 text-center text-gray-400">暂无数据库配置</td></tr>
<tr><td colspan="6" class="px-5 py-12 text-center text-gray-500">还没有数据库配置,点击“添加数据库”开始。</td></tr>
@endforelse
</tbody>
</table>

View File

@ -1,15 +1,23 @@
<nav class="mb-6 flex flex-wrap items-center gap-3 rounded-xl border border-gray-200 bg-white p-3 shadow-sm" aria-label="系统设置">
@foreach ([
@php
$items = [
['system-settings.users.index', '用户管理', 'people'],
['system-settings.sidebar.edit', '侧边栏管理', 'menu'],
] as [$routeName, $label, $icon])
];
if (\App\Utilities\SystemAccess::isSuperAdmin()) {
$items[] = ['system-settings.databases.index', '数据库管理', 'storage'];
}
@endphp
@foreach ($items as [$routeName, $label, $icon])
@php $active = request()->routeIs(Str::beforeLast($routeName, '.') . '.*'); @endphp
<a
href="{{ route($routeName) }}"
@class([
'inline-flex items-center gap-2 rounded-lg px-4 py-2.5 text-sm font-semibold transition-colors',
'bg-purple text-white' => $active,
'text-gray-600 hover:bg-lilac-100 hover:text-purple' => ! $active,
'bg-purple-700 text-white' => $active,
'text-gray-600 hover:bg-purple-100 hover:text-purple-700' => ! $active,
])
@if ($active) aria-current="page" @endif
>

View File

@ -23,6 +23,13 @@ Route::group(['as' => 'system-settings.', 'prefix' => 'system-settings'], functi
Route::get('sidebar', 'SystemSettings\Sidebar@edit')->name('sidebar.edit');
Route::patch('sidebar', 'SystemSettings\Sidebar@update')->name('sidebar.update');
Route::get('databases', 'SystemSettings\Databases@index')->name('databases.index');
Route::get('databases/create', 'SystemSettings\Databases@create')->name('databases.create');
Route::post('databases', 'SystemSettings\Databases@store')->name('databases.store');
Route::get('databases/{connection}/edit', 'SystemSettings\Databases@edit')->name('databases.edit');
Route::patch('databases/{connection}', 'SystemSettings\Databases@update')->name('databases.update');
Route::delete('databases/{connection}', 'SystemSettings\Databases@destroy')->name('databases.destroy');
Route::post('databases/{connection}/test', 'SystemSettings\Databases@test')->name('databases.test');
});
Route::group(['as' => 'uploads.', 'prefix' => 'uploads'], function () {

View File

@ -0,0 +1,146 @@
<?php
namespace Tests\Feature\SystemSettings;
use App\Models\Auth\Permission;
use App\Models\Auth\Role;
use App\Models\Settings\DatabaseConnection;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Services\UpstreamSourceRegistry;
use Tests\Feature\FeatureTestCase;
class UpstreamDatabasesTest extends FeatureTestCase
{
protected function setUp(): void
{
parent::setUp();
$this->user->attachPermission(
Permission::where('name', 'read-admin-panel')->firstOrFail()
);
}
public function test_super_admin_can_add_multiple_encrypted_database_configurations(): void
{
$this->loginAs()
->post(route('system-settings.databases.store'), $this->payload([
'name' => 'JianSun 测试库',
'source_key' => 'jiansun',
'password' => 'first-secret',
]))
->assertRedirect(route('system-settings.databases.index'));
$this->post(route('system-settings.databases.store'), $this->payload([
'name' => '云数据库二号',
'source_key' => '',
'host' => '127.0.0.2',
'password' => 'second-secret',
]))->assertRedirect(route('system-settings.databases.index'));
$this->assertSame(2, DatabaseConnection::where('company_id', 0)->count());
$connection = DatabaseConnection::where('source_key', 'jiansun')->firstOrFail();
$this->assertSame('first-secret', $connection->password);
$this->assertNotSame(
'first-secret',
DB::table('system_database_connections')->where('id', $connection->id)->value('password')
);
$sources = app(UpstreamSourceRegistry::class);
$this->assertSame('127.0.0.1', $sources->value('jiansun', 'connection.host'));
$this->assertSame('first-secret', $sources->value('jiansun', 'connection.password'));
$this->get(route('system-settings.databases.index'))
->assertOk()
->assertSeeText('JianSun 测试库')
->assertSeeText('云数据库二号')
->assertDontSee('first-secret');
}
public function test_editing_without_password_preserves_existing_password(): void
{
$connection = $this->connection('original-secret');
$this->loginAs()
->patch(route('system-settings.databases.update', $connection->id), $this->payload([
'name' => $connection->name,
'password' => '',
'host' => '127.0.0.2',
]))
->assertRedirect(route('system-settings.databases.index'));
$connection->refresh();
$this->assertSame('original-secret', $connection->password);
$this->assertSame('127.0.0.2', $connection->host);
$this->get(route('system-settings.databases.edit', $connection->id))
->assertOk()
->assertDontSee('original-secret');
}
public function test_global_wildcard_scope_is_rejected(): void
{
$this->withExceptionHandling();
$this->loginAs()
->post(route('system-settings.databases.store'), $this->payload([
'allowed_scopes' => '*',
]))
->assertSessionHasErrors('allowed_scopes');
$this->assertDatabaseMissing('system_database_connections', ['name' => '测试云数据库']);
}
public function test_regular_admin_cannot_open_database_settings(): void
{
$this->user->roles()->sync([
Role::where('name', 'admin')->firstOrFail()->id,
]);
$this->withExceptionHandling();
$this->loginAs()
->get(route('system-settings.databases.index'))
->assertForbidden();
}
private function payload(array $overrides = []): array
{
return array_merge([
'name' => '测试云数据库',
'source_key' => '',
'host' => '127.0.0.1',
'port' => 1433,
'database_name' => 'test_finance',
'username' => 'readonly_user',
'password' => 'secret',
'odbc_driver' => 'FreeTDS',
'tds_version' => '7.4',
'connect_timeout' => 3,
'query_timeout' => 8,
'allowed_scopes' => 'supplier.options',
'enabled' => '1',
], $overrides);
}
private function connection(string $password): DatabaseConnection
{
return DatabaseConnection::create([
'company_id' => 0,
'source_key' => null,
'name' => '已有云数据库',
'driver' => 'sqlsrv',
'host' => '127.0.0.1',
'port' => 1433,
'database_name' => 'test_finance',
'username' => 'readonly_user',
'password' => $password,
'odbc_driver' => 'FreeTDS',
'tds_version' => '7.4',
'connect_timeout' => 3,
'query_timeout' => 8,
'allowed_scopes' => ['supplier.options'],
'charset' => 'UTF-8',
'enabled' => true,
]);
}
}