- 创建 TerminalSyncService 服务类 - 实现配置快照生成(包含终端、知识库、提示词) - 创建 SyncTerminalConfigJob 异步任务 - 实现重试机制(最多3次,指数退避) - 创建 SyncConfigAction(单个和批量同步) - 在终端列表页添加同步状态列 - 在终端详情页添加同步历史展示 - 支持同步状态追踪(pending/syncing/synced/failed)
113 lines
2.9 KiB
PHP
113 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Terminal;
|
|
use App\Models\TerminalSyncLog;
|
|
use App\Jobs\SyncTerminalConfigJob;
|
|
|
|
/**
|
|
* 终端配置同步服务
|
|
*/
|
|
class TerminalSyncService
|
|
{
|
|
/**
|
|
* 同步终端配置
|
|
*
|
|
* @param Terminal $terminal
|
|
* @return TerminalSyncLog
|
|
*/
|
|
public function syncConfiguration(Terminal $terminal): TerminalSyncLog
|
|
{
|
|
// 创建同步日志记录
|
|
$log = TerminalSyncLog::create([
|
|
'terminal_id' => $terminal->id,
|
|
'status' => 'pending',
|
|
'config_snapshot' => $this->getConfigSnapshot($terminal),
|
|
]);
|
|
|
|
// 触发异步同步任务
|
|
dispatch(new SyncTerminalConfigJob($terminal, $log));
|
|
|
|
return $log;
|
|
}
|
|
|
|
/**
|
|
* 获取终端配置快照
|
|
*
|
|
* @param Terminal $terminal
|
|
* @return array
|
|
*/
|
|
public function getConfigSnapshot(Terminal $terminal): array
|
|
{
|
|
// 加载关联数据
|
|
$terminal->load(['knowledgeBases', 'prompt']);
|
|
|
|
return [
|
|
'terminal' => [
|
|
'id' => $terminal->id,
|
|
'name' => $terminal->name,
|
|
'code' => $terminal->code,
|
|
'ip_address' => $terminal->ip_address,
|
|
'station_id' => $terminal->station_id,
|
|
'diagram_url' => $terminal->diagram_url,
|
|
'display_config' => $terminal->display_config,
|
|
],
|
|
'knowledge_bases' => $terminal->knowledgeBases->map(function ($kb) {
|
|
return [
|
|
'id' => $kb->id,
|
|
'name' => $kb->name,
|
|
'priority' => $kb->pivot->priority,
|
|
];
|
|
})->toArray(),
|
|
'prompt' => $terminal->prompt ? [
|
|
'prompt_template' => $terminal->prompt->prompt_template,
|
|
'variables' => $terminal->prompt->variables,
|
|
] : null,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* 更新同步状态
|
|
*
|
|
* @param TerminalSyncLog $log
|
|
* @param string $status
|
|
* @param string|null $errorMessage
|
|
* @return void
|
|
*/
|
|
public function updateSyncStatus(TerminalSyncLog $log, string $status, ?string $errorMessage = null): void
|
|
{
|
|
$data = ['status' => $status];
|
|
|
|
if ($status === 'synced') {
|
|
$data['synced_at'] = now();
|
|
}
|
|
|
|
if ($errorMessage) {
|
|
$data['error_message'] = $errorMessage;
|
|
}
|
|
|
|
$log->update($data);
|
|
}
|
|
|
|
/**
|
|
* 批量同步终端配置
|
|
*
|
|
* @param array $terminalIds
|
|
* @return array
|
|
*/
|
|
public function batchSync(array $terminalIds): array
|
|
{
|
|
$logs = [];
|
|
|
|
foreach ($terminalIds as $terminalId) {
|
|
$terminal = Terminal::find($terminalId);
|
|
if ($terminal) {
|
|
$logs[] = $this->syncConfiguration($terminal);
|
|
}
|
|
}
|
|
|
|
return $logs;
|
|
}
|
|
}
|