Files
Nexora/app/Models/Document.php

123 lines
3.0 KiB
PHP

<?php
namespace App\Models;
use App\Events\DocumentVersionUpdated;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Document extends Model
{
use LogsActivity;
protected static $logAttributes = ['name', 'status'];
protected static $logOnlyDirty = true;
protected $fillable = [
'name',
'file_path',
'project_id', // Asegurar que está en fillable
'folder_id',
'issuer',
'status',
'revision',
'version',
'discipline',
'document_type',
'entry_date',
'current_version_id',
'code',
];
protected static function booted()
{
static::created(function ($document) {
if (request()->hasFile('file')) {
$file = request()->file('file');
$document->createVersion($file);
}
});
}
/**
* Get all versions of the document.
*/
public function versions(): HasMany
{
return $this->hasMany(DocumentVersion::class);
}
/**
* Get the current version of the document.
*/
public function currentVersion(): BelongsTo
{
return $this->belongsTo(DocumentVersion::class, 'current_version_id');
}
/**
* Get the latest version of the document.
*/
public function getLatestVersionAttribute()
{
return $this->versions()->latestFirst()->first();
}
/**
* Create a new version from file content.
*/
public function createVersion(string $content, array $changes = [], ?User $user = null): DocumentVersion
{
$version = DocumentVersion::createFromContent($this, $content, $changes, $user);
// Update current version pointer
$this->update(['current_version_id' => $version->id]);
return $version;
}
public function approvals() {
return $this->hasMany(Approval::class);
}
public function comments() {
return $this->hasMany(Comment::class)->whereNull('parent_id');
}
public function getCurrentVersionAttribute()
{
return $this->versions()->latest()->first();
}
public function uploadVersion($file)
{
$version = $this->versions()->create([
'file_path' => $file->store("projects/{$this->id}/versions"),
'hash' => hash_file('sha256', $file),
'version' => $this->versions()->count() + 1,
'user_id' => auth()->id()
]);
event(new DocumentVersionUpdated($this));
return $version;
}
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logExcept(['current_version_id'])
->logUnguarded();
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}