107 lines
2.2 KiB
PHP
107 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class DocumentAccessLog extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $fillable = [
|
|
'document_id',
|
|
'document_version_id',
|
|
'action',
|
|
'user_id',
|
|
'ip_address',
|
|
'user_agent',
|
|
'accessed_at',
|
|
];
|
|
|
|
protected $casts = [
|
|
'accessed_at' => 'datetime',
|
|
];
|
|
|
|
// ==================== Relationships ====================
|
|
|
|
/**
|
|
* Get the document this log belongs to
|
|
*/
|
|
public function document()
|
|
{
|
|
return $this->belongsTo(Document::class);
|
|
}
|
|
|
|
/**
|
|
* Get the document version accessed
|
|
*/
|
|
public function version()
|
|
{
|
|
return $this->belongsTo(DocumentVersion::class, 'document_version_id');
|
|
}
|
|
|
|
/**
|
|
* Get the user who accessed (null if anonymous)
|
|
*/
|
|
public function user()
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
|
|
// ==================== Helper Methods ====================
|
|
|
|
/**
|
|
* Get action label in Chinese
|
|
*/
|
|
public function getActionLabel(): string
|
|
{
|
|
return match($this->action) {
|
|
'view' => '檢視',
|
|
'download' => '下載',
|
|
default => '未知',
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Get user display name (anonymous if no user)
|
|
*/
|
|
public function getUserDisplay(): string
|
|
{
|
|
return $this->user ? $this->user->name : '匿名訪客';
|
|
}
|
|
|
|
/**
|
|
* Get browser from user agent
|
|
*/
|
|
public function getBrowser(): string
|
|
{
|
|
if (!$this->user_agent) {
|
|
return '未知';
|
|
}
|
|
|
|
if (str_contains($this->user_agent, 'Chrome')) {
|
|
return 'Chrome';
|
|
}
|
|
if (str_contains($this->user_agent, 'Safari')) {
|
|
return 'Safari';
|
|
}
|
|
if (str_contains($this->user_agent, 'Firefox')) {
|
|
return 'Firefox';
|
|
}
|
|
if (str_contains($this->user_agent, 'Edge')) {
|
|
return 'Edge';
|
|
}
|
|
|
|
return '未知';
|
|
}
|
|
|
|
/**
|
|
* Check if access was by authenticated user
|
|
*/
|
|
public function isAuthenticated(): bool
|
|
{
|
|
return $this->user_id !== null;
|
|
}
|
|
}
|