Files
Nexora/app/Livewire/ProjectShow.php

260 lines
7.9 KiB
PHP

<?php
namespace App\Livewire;
use Livewire\Component;
use Livewire\Attributes\Title;
use Livewire\WithFileUploads;
use App\Models\Project;
use App\Models\Folder;
use App\Models\Document;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
use App\Helpers\DocumentIdentifier;
class ProjectShow extends Component
{
use WithFileUploads;
protected $middleware = ['auth']; // Añade esto
public Project $project;
public ?Folder $currentFolder = null;
public $expandedFolders = [];
public $files = [];
public $folderName = '';
public $selectedFolderId = null;
public $showFolderModal = false;
public $showUploadModal = false;
public $tempFiles = [];
public $selectedFiles = []; // Archivos temporales en el modal
public $uploadProgress = [];
protected $listeners = ['documents-updated' => '$refresh'];
public function mount(Project $project)
{
$this->project = $project->load('rootFolders');
$this->currentFolder = $this->project->rootFolders->first() ?? null;
}
public function selectFolder($folderId)
{
$this->selectedFolderId = $folderId;
$this->currentFolder = Folder::with('children')->find($folderId);
}
public function toggleFolder($folderId): void
{
if (in_array($folderId, $this->expandedFolders)) {
$this->expandedFolders = array_diff($this->expandedFolders, [$folderId]);
} else {
$this->expandedFolders[] = $folderId;
}
}
public function createFolder(): void
{
$this->validate([
'folderName' => [
'required',
'max:255',
Rule::unique('folders', 'name')->where(function ($query) {
return $query->where('project_id', $this->project->id)
->where('parent_id', $this->currentFolder?->id);
})
]
]);
Folder::create([
'name' => $this->folderName,
'project_id' => $this->project->id,
'parent_id' => $this->currentFolder?->id,
]);
$this->hideCreateFolderModal();
$this->reset('folderName');
$this->project->load('rootFolders'); // Recargar carpetas raíz
if ($this->currentFolder) {
$this->currentFolder->load('children'); // Recargar hijos si está en una subcarpeta
}
$this->project->refresh();
}
public function getDocumentsProperty()
{
return $this->currentFolder
? $this->currentFolder->documents()->with('versions')->get()
: Document::whereNull('folder_id')->where('project_id', $this->project->id)->with('versions')->get();
}
public function getBreadcrumbsProperty()
{
if (!$this->currentFolder) return collect();
$breadcrumbs = collect();
$folder = $this->currentFolder;
while ($folder) {
$breadcrumbs->prepend($folder);
$folder = $folder->parent;
}
return $breadcrumbs;
}
public function showCreateFolderModal()
{
$this->folderName = '';
$this->showFolderModal = true;
}
public function hideCreateFolderModal()
{
$this->showFolderModal = false;
}
// Método para abrir el modal
public function openUploadModal(): void
{
$this->showUploadModal = true;
}
// Método para manejar archivos seleccionados
public function selectFiles($files): void
{
$this->validate([
'selectedFiles.*' => 'file|max:10240|mimes:pdf,docx,xlsx,jpg,png'
]);
$this->selectedFiles = array_merge($this->selectedFiles, $files);
}
// Método para eliminar un archivo de la lista
public function removeFile($index): void
{
unset($this->selectedFiles[$index]);
$this->selectedFiles = array_values($this->selectedFiles); // Reindexar array
}
public function uploadFiles(): void
{
foreach ($this->selectedFiles as $file) {
//$analizador = analizarDocumento();
//print_r($analizador);
//$resultado1 = $analizador->analizarDocumento($file->getClientOriginalName());
$code = $this->project->reference;
// Buscar si ya existe un documento con el mismo nombre en el mismo proyecto y carpeta
$existingDocument = Document::where('project_id', $this->project->id)
->where('folder_id', $this->currentFolder?->id)
->where('name', $file->getClientOriginalName())
->first();
if ($existingDocument) {
// Si existe, crear una nueva versión/revisión
$existingDocument->createVersion($file);
} else {
// Si no existe, crear el documento con revisión 0
$document = Document::create([
'name' => $file->getClientOriginalName(),
'file_path' => $file->store("projects/{$this->project->id}/documents"),
'project_id' => $this->project->id,
'folder_id' => $this->currentFolder?->id,
'issuer_id' => Auth::id(),
'code' => $code,
'entry_date' => now(),
'revision' => 0, // Revisión inicial
]);
$document->createVersion($file);
}
}
$this->resetUpload();
$this->project->refresh();
}
// Método para procesar los archivos
protected function processFiles(): void
{
foreach ($this->files as $file) {
Document::create([
'name' => $file->getClientOriginalName(),
'file_path' => $file->store("projects/{$this->project->id}/documents"),
'project_id' => $this->project->id, // Asegurar que se envía
'folder_id' => $this->currentFolder?->id,
//'user_id' => Auth::id(),
//'status' => 'active' // Añadir si tu modelo lo requiere
]);
}
}
// Método para resetear
public function resetUpload(): void
{
$this->reset(['selectedFiles', 'showUploadModal', 'uploadProgress']);
}
#[On('upload-progress')]
public function updateProgress($name, $progress)
{
$this->uploadProgress[$name] = $progress;
}
public function addFiles($files)
{
$this->validate([
'selectedFiles.*' => 'file|max:10240|mimes:pdf,docx,xlsx,jpg,png'
]);
$this->selectedFiles = array_merge($this->selectedFiles, $files);
}
public function startUpload()
{
foreach ($this->selectedFiles as $file) {
try {
$path = $file->store(
"projects/{$this->project->id}/".($this->currentFolder ? "folders/{$this->currentFolder->id}" : ""),
'public'
);
Document::create([
'name' => $file->getClientOriginalName(),
'file_path' => $path,
'project_id' => $this->project->id,
'folder_id' => $this->currentFolder?->id,
'user_id' => Auth::id(),
'code' => $code,
]);
} catch (\Exception $e) {
$this->addError('upload', "Error subiendo {$file->getClientOriginalName()}: {$e->getMessage()}");
}
}
$this->resetUpload();
$this->project->refresh();
}
public function render()
{
return view('livewire.project.show');
}
public function generateProjectCode(array $fields): string
{
return \App\Helpers\ProjectNamingSchema::generate($fields);
}
public function sellectAllDocuments()
{
$this->selectedFiles = $this->documents->pluck('id')->toArray();
}
}