KTVCentral/app/Observers/RoomObserver.php
allen.yan 00c4225987 202508201522
調整包帳記錄
包廂加入歌曲點歌
2025-08-20 15:26:05 +08:00

98 lines
2.7 KiB
PHP
Raw 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 ($room->wasChanged()) {
$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,
'api_token' => bin2hex(random_bytes(32)),
]);
}
}
}
/**
* 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);
}
/**
* 建立 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');
}
}