KTVCentral/app/Observers/RoomObserver.php
allen.yan 9721325bbb 202508221007
修正updated_at 不寫記錄
2025-08-22 10:07:50 +08:00

105 lines
2.9 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Observers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Arr;
use App\Models\Room;
use App\Models\RoomStatusLog;
class RoomObserver
{
/**
* Handle the Room "created" event.
*/
public function created(Room $room): void
{
// 建立初始 log
$this->createStatusLog($room);
}
/**
* Handle the Room "updated" event.
*/
public function updated(Room $room): void
{
// 如果有變動才記錄
if ($this->hasChangesExcept($room, ['updated_at'])) {
$this->createStatusLog($room);
}
if ($room->isDirty('status')) {
$now = now();
// 找到最後一筆未結束 session
$lastSession = $room->sessions()->whereNull('ended_at')->latest('started_at')->first();
if ($lastSession) {
// 結束上一筆 session
$lastSession->update([
'status' => $room->status->value,
'ended_at' => $now,
]);
}
// 如果狀態是 active 或 maintain開新 session
if (in_array($room->status->value, ['active', 'maintain'])) {
$mode = $room->status->value === 'active' ? 'normal' : 'test';
$room->sessions()->create([
'mode' => $mode,
'status' => $room->status->value,
'started_at' => $now,
]);
}
}
}
/**
* Handle the Room "deleted" event.
*/
public function deleted(Room $room): void
{
$message = sprintf(
"%s:%s%s (%s:%s) 已刪除",
$room->branch->name,
$room->type->value,
$room->name,
$room->internal_ip,
$room->port
);
$this->createStatusLog($room,$message);
}
protected function hasChangesExcept($model, array $except = ['updated_at']): bool
{
$changes = $model->getChanges();
foreach ($except as $key) {
unset($changes[$key]);
}
return !empty($changes);
}
/**
* 建立 RoomStatusLog
*/
private function createStatusLog(Room $room,$log_message =null): void
{
$message=($log_message !=null)?$log_message:$room->log_message ?? '';
RoomStatusLog::create([
'branch_id' => $room->branch->id,
'room_id' => $room->id,
'user_id' => Auth::id() ?? 0,
'is_online' => $room->is_online,
'status' => $room->status,
'started_at' => $room->started_at,
'ended_at' => $room->ended_at,
'message' => $message,
'source' => $this->getSource($room),
]);
}
private function getSource(Room $room): string
{
return app()->runningInConsole() ? 'system' : ($room->log_source ?? 'manual');
}
}