91 lines
2.6 KiB
PHP
91 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace Modules\DocumentManagement\Models;
|
|
|
|
use App\Models\User;
|
|
use App\Traits\HasPublicIdentifier;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Database\Eloquent\Relations\MorphTo;
|
|
|
|
class Document extends Model
|
|
{
|
|
use HasPublicIdentifier;
|
|
|
|
protected $fillable = [
|
|
'title', 'category', 'category_id', 'project_id', 'status', 'description',
|
|
'documentable_type', 'documentable_id',
|
|
'uploaded_by', 'current_file_path', 'current_file_name',
|
|
'mime_type', 'file_size', 'version_count',
|
|
];
|
|
|
|
public function documentable(): MorphTo
|
|
{
|
|
return $this->morphTo();
|
|
}
|
|
|
|
public function uploader(): BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class, 'uploaded_by')->withoutGlobalScope(\App\Scopes\TenantScope::class);
|
|
}
|
|
|
|
public function versions(): HasMany
|
|
{
|
|
return $this->hasMany(DocumentVersion::class)->orderByDesc('version_number');
|
|
}
|
|
|
|
public function category(): BelongsTo
|
|
{
|
|
return $this->belongsTo(DocumentCategory::class, 'category_id');
|
|
}
|
|
|
|
public function project(): BelongsTo
|
|
{
|
|
return $this->belongsTo(\Modules\ProjectManagement\Models\Project::class);
|
|
}
|
|
|
|
public function approvals(): HasMany
|
|
{
|
|
return $this->hasMany(DocumentApproval::class);
|
|
}
|
|
|
|
public function addVersion(string $filePath, string $fileName, string $mimeType, int $fileSize, ?int $uploadedBy = null, ?string $changeNotes = null): DocumentVersion
|
|
{
|
|
$nextVersion = $this->version_count + 1;
|
|
|
|
$version = $this->versions()->create([
|
|
'version_number' => $nextVersion,
|
|
'file_path' => $filePath,
|
|
'file_name' => $fileName,
|
|
'mime_type' => $mimeType,
|
|
'file_size' => $fileSize,
|
|
'uploaded_by' => $uploadedBy,
|
|
'change_notes' => $changeNotes,
|
|
]);
|
|
|
|
$this->update([
|
|
'current_file_path' => $filePath,
|
|
'current_file_name' => $fileName,
|
|
'mime_type' => $mimeType,
|
|
'file_size' => $fileSize,
|
|
'version_count' => $nextVersion,
|
|
]);
|
|
|
|
return $version;
|
|
}
|
|
|
|
public function getIsImageAttribute(): bool
|
|
{
|
|
return $this->mime_type && str_starts_with($this->mime_type, 'image/');
|
|
}
|
|
|
|
public function getFormattedSizeAttribute(): string
|
|
{
|
|
$bytes = $this->file_size;
|
|
if ($bytes >= 1048576) return round($bytes / 1048576, 1) . ' MB';
|
|
if ($bytes >= 1024) return round($bytes / 1024, 1) . ' KB';
|
|
return $bytes . ' B';
|
|
}
|
|
}
|