Compare commits
3 Commits
88e526cf6c
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 047e155238 | |||
| e42ce8b092 | |||
| 7b00887372 |
@@ -20,4 +20,50 @@ class FileHelper
|
||||
default => 'document'
|
||||
};
|
||||
}
|
||||
|
||||
public static function getFileIconClass($filename)
|
||||
{
|
||||
$fileType = self::getFileType($filename);
|
||||
|
||||
$classes = [
|
||||
'pdf' => 'text-red-500',
|
||||
'word' => 'text-blue-500',
|
||||
'excel' => 'text-green-500',
|
||||
'image' => 'text-yellow-500',
|
||||
'archive' => 'text-purple-500',
|
||||
'text' => 'text-gray-500',
|
||||
'powerpoint' => 'text-orange-500',
|
||||
'document' => 'text-gray-400'
|
||||
];
|
||||
|
||||
return $classes[$fileType] ?? 'text-gray-400';
|
||||
}
|
||||
|
||||
public static function getFileIconSvg($filename)
|
||||
{
|
||||
$fileType = self::getFileType($filename);
|
||||
$colorClass = self::getFileIconClass($filename);
|
||||
|
||||
$icons = [
|
||||
'pdf' => '<svg class="w-5 h-5 '.$colorClass.'" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm2 6a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7z" clip-rule="evenodd"/>
|
||||
</svg>',
|
||||
'word' => '<svg class="w-5 h-5 '.$colorClass.'" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm2 6a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7z" clip-rule="evenodd"/>
|
||||
</svg>',
|
||||
'excel' => '<svg class="w-5 h-5 '.$colorClass.'" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm2 6a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7z" clip-rule="evenodd"/>
|
||||
</svg>',
|
||||
'image' => '<svg class="w-5 h-5 '.$colorClass.'" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clip-rule="evenodd"/>
|
||||
</svg>',
|
||||
'archive' => '<svg class="w-5 h-5 '.$colorClass.'" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clip-rule="evenodd"/>
|
||||
</svg>'
|
||||
];
|
||||
|
||||
return $icons[$fileType] ?? '<svg class="w-5 h-5 '.$colorClass.'" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clip-rule="evenodd"/>
|
||||
</svg>';
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Helpers;
|
||||
|
||||
class ProjectNamingSchema
|
||||
{
|
||||
/**
|
||||
* Generate a project name based on ISO 19650 schema.
|
||||
*
|
||||
* @param array $fields Associative array of required and optional fields.
|
||||
* @return string Generated project name.
|
||||
*/
|
||||
public static function generate(array $fields): string
|
||||
{
|
||||
// Validate required fields
|
||||
$requiredFields = ['project', 'creator', 'volume', 'level', 'documentType', 'discipline', 'number'];
|
||||
foreach ($requiredFields as $field) {
|
||||
if (empty($fields[$field])) {
|
||||
throw new \InvalidArgumentException("The field '{$field}' is required.");
|
||||
}
|
||||
}
|
||||
|
||||
// Build the project name
|
||||
$projectName = [
|
||||
strtoupper($fields['project']),
|
||||
strtoupper($fields['creator']),
|
||||
strtoupper($fields['volume']),
|
||||
strtoupper($fields['level']),
|
||||
strtoupper($fields['documentType']),
|
||||
strtoupper($fields['discipline']),
|
||||
str_pad($fields['number'], 3, '0', STR_PAD_LEFT),
|
||||
];
|
||||
|
||||
// Add optional fields if provided
|
||||
if (!empty($fields['description'])) {
|
||||
$projectName[] = $fields['description'];
|
||||
}
|
||||
if (!empty($fields['status'])) {
|
||||
$projectName[] = strtoupper($fields['status']);
|
||||
}
|
||||
if (!empty($fields['revision'])) {
|
||||
$projectName[] = str_pad($fields['revision'], 4, '0', STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
return implode('-', $projectName);
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,8 @@ class DocumentController extends Controller
|
||||
|
||||
$document->url = Storage::url($document->file_path);
|
||||
|
||||
$document->load('user');
|
||||
|
||||
return view('documents.show', [
|
||||
'document' => $document,
|
||||
'versions' => $document->versions()->latest()->get(),
|
||||
@@ -108,7 +110,7 @@ class DocumentController extends Controller
|
||||
foreach ($request->file('files') as $file) {
|
||||
$document = $project->documents()->create([
|
||||
'name' => $file->getClientOriginalName(),
|
||||
'status' => 'pending'
|
||||
'status' => 0
|
||||
]);
|
||||
|
||||
$this->createVersion($document, $file);
|
||||
@@ -125,4 +127,331 @@ class DocumentController extends Controller
|
||||
|
||||
$document->update(['current_version_id' => $version->id]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Actualizar PDF con anotaciones, firmas y sellos
|
||||
*/
|
||||
public function updatePdf(Request $request, Document $document)
|
||||
{
|
||||
$this->authorize('update', $document);
|
||||
|
||||
$request->validate([
|
||||
'pdf_data' => 'required|string', // PDF modificado en base64
|
||||
'annotations' => 'sometimes|array',
|
||||
'signatures' => 'sometimes|array',
|
||||
'stamps' => 'sometimes|array',
|
||||
]);
|
||||
|
||||
try {
|
||||
// Procesar el PDF modificado
|
||||
$modifiedPdf = $this->processPdfData($request->pdf_data);
|
||||
|
||||
// Reemplazar el archivo original (sin crear nueva versión si no quieres)
|
||||
$this->replaceOriginalPdf($document, $modifiedPdf);
|
||||
|
||||
// Opcional: también crear una nueva versión para historial
|
||||
$newVersion = $this->createNewVersion($document, $modifiedPdf, $request->all());
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'PDF actualizado correctamente',
|
||||
'version_id' => $newVersion->id ?? null,
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
\Log::error('Error updating PDF: ' . $e->getMessage());
|
||||
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Error al actualizar el PDF: ' . $e->getMessage()
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Procesar datos del PDF en base64
|
||||
*/
|
||||
private function processPdfData($pdfData)
|
||||
{
|
||||
// Eliminar el prefijo data:application/pdf;base64, si existe
|
||||
$pdfData = preg_replace('/^data:application\/pdf;base64,/', '', $pdfData);
|
||||
|
||||
// Decodificar base64
|
||||
$pdfContent = base64_decode($pdfData);
|
||||
|
||||
if (!$pdfContent) {
|
||||
throw new \Exception('Datos PDF inválidos');
|
||||
}
|
||||
|
||||
return $pdfContent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Procesar PDF con anotaciones (método alternativo)
|
||||
*/
|
||||
private function processPdfWithAnnotations($document, $data)
|
||||
{
|
||||
// Aquí integrarías una librería PHP para PDF como spatie/pdf-to-image o setasign/fpdi
|
||||
// Por ahora, devolvemos el contenido del archivo original
|
||||
// En producción, implementarías la lógica de modificación
|
||||
|
||||
if ($document->currentVersion) {
|
||||
$filePath = $document->currentVersion->file_path;
|
||||
} else {
|
||||
$filePath = $document->getFirstMedia('documents')->getPath();
|
||||
}
|
||||
|
||||
if (!Storage::exists($filePath)) {
|
||||
throw new \Exception('Archivo PDF no encontrado');
|
||||
}
|
||||
|
||||
return Storage::get($filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reemplazar el PDF original
|
||||
*/
|
||||
private function replaceOriginalPdf($document, $pdfContent)
|
||||
{
|
||||
// Obtener la ruta del archivo original
|
||||
$filePath = $document->file_path;
|
||||
|
||||
// Si el documento usa media library
|
||||
if ($document->getFirstMedia('documents')) {
|
||||
$media = $document->getFirstMedia('documents');
|
||||
$media->update([
|
||||
'file_name' => $document->name . '.pdf',
|
||||
'size' => strlen($pdfContent),
|
||||
]);
|
||||
|
||||
// Reemplazar el archivo
|
||||
Storage::put($media->getPath(), $pdfContent);
|
||||
} else {
|
||||
// Si usas file_path directo
|
||||
Storage::put($filePath, $pdfContent);
|
||||
|
||||
// Actualizar metadata del documento
|
||||
$document->update([
|
||||
'file_size' => strlen($pdfContent),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Crear nueva versión del documento
|
||||
*/
|
||||
private function createNewVersion($document, $pdfContent, $data = [])
|
||||
{
|
||||
$versionNumber = $document->versions()->count() + 1;
|
||||
$fileName = "documents/{$document->id}/v{$versionNumber}.pdf";
|
||||
|
||||
// Guardar el nuevo PDF
|
||||
Storage::put($fileName, $pdfContent);
|
||||
|
||||
// Crear registro de versión
|
||||
$version = $document->versions()->create([
|
||||
'version_number' => $versionNumber,
|
||||
'file_path' => $fileName,
|
||||
'file_size' => strlen($pdfContent),
|
||||
'hash' => hash('sha256', $pdfContent),
|
||||
'created_by' => auth()->id(),
|
||||
'metadata' => [
|
||||
'annotations_count' => count($data['annotations'] ?? []),
|
||||
'signatures_count' => count($data['signatures'] ?? []),
|
||||
'stamps_count' => count($data['stamps'] ?? []),
|
||||
'edited_at' => now()->toISOString(),
|
||||
'edited_by' => auth()->user()->name
|
||||
]
|
||||
]);
|
||||
|
||||
return $version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Guardar metadatos de anotaciones
|
||||
*/
|
||||
private function saveAnnotationsMetadata($version, $data)
|
||||
{
|
||||
// Guardar anotaciones en la base de datos si es necesario
|
||||
if (!empty($data['annotations'])) {
|
||||
foreach ($data['annotations'] as $annotation) {
|
||||
$version->annotations()->create([
|
||||
'type' => $annotation['type'] ?? 'text',
|
||||
'content' => $annotation['content'] ?? '',
|
||||
'position' => $annotation['position'] ?? [],
|
||||
'page' => $annotation['page'] ?? 1,
|
||||
'created_by' => auth()->id()
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Subir firma
|
||||
*/
|
||||
public function uploadSignature(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'signature' => 'required|image|max:2048|mimes:png,jpg,jpeg'
|
||||
]);
|
||||
|
||||
try {
|
||||
$user = auth()->user();
|
||||
$path = $request->file('signature')->store("signatures/{$user->id}", 'public');
|
||||
|
||||
// Opcional: Guardar en base de datos
|
||||
$user->signatures()->create([
|
||||
'file_path' => $path,
|
||||
'file_name' => $request->file('signature')->getClientOriginalName()
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'path' => Storage::url($path),
|
||||
'filename' => basename($path)
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
\Log::error('Error uploading signature: ' . $e->getMessage());
|
||||
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Error al subir la firma'
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Subir sello
|
||||
*/
|
||||
public function uploadStamp(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'stamp' => 'required|image|max:2048|mimes:png,jpg,jpeg'
|
||||
]);
|
||||
|
||||
try {
|
||||
$user = auth()->user();
|
||||
$path = $request->file('stamp')->store("stamps/{$user->id}", 'public');
|
||||
|
||||
// Opcional: Guardar en base de datos
|
||||
$user->stamps()->create([
|
||||
'file_path' => $path,
|
||||
'file_name' => $request->file('stamp')->getClientOriginalName(),
|
||||
'type' => $request->type ?? 'custom'
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'path' => Storage::url($path),
|
||||
'filename' => basename($path)
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
\Log::error('Error uploading stamp: ' . $e->getMessage());
|
||||
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Error al subir el sello'
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtener firmas del usuario
|
||||
*/
|
||||
public function getSignatures()
|
||||
{
|
||||
$user = auth()->user();
|
||||
$signatures = $user->signatures()->get()->map(function($signature) {
|
||||
return [
|
||||
'id' => $signature->id,
|
||||
'url' => Storage::url($signature->file_path),
|
||||
'name' => $signature->file_name
|
||||
];
|
||||
});
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'signatures' => $signatures
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtener sellos del usuario
|
||||
*/
|
||||
public function getStamps()
|
||||
{
|
||||
$user = auth()->user();
|
||||
$stamps = $user->stamps()->get()->map(function($stamp) {
|
||||
return [
|
||||
'id' => $stamp->id,
|
||||
'url' => Storage::url($stamp->file_path),
|
||||
'name' => $stamp->file_name,
|
||||
'type' => $stamp->type
|
||||
];
|
||||
});
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'stamps' => $stamps
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Descargar documento
|
||||
*/
|
||||
public function download(Document $document, $versionId = null)
|
||||
{
|
||||
$this->authorize('view', $document);
|
||||
|
||||
$version = $versionId ?
|
||||
$document->versions()->findOrFail($versionId) :
|
||||
$document->currentVersion;
|
||||
|
||||
if (!$version || !Storage::exists($version->file_path)) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
return Storage::download($version->file_path, $document->name . '.pdf');
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtener el PDF actual para edición
|
||||
*/
|
||||
public function getPdfForEditing(Document $document)
|
||||
{
|
||||
$this->authorize('view', $document);
|
||||
|
||||
try {
|
||||
if ($document->getFirstMedia('documents')) {
|
||||
$filePath = $document->getFirstMedia('documents')->getPath();
|
||||
} else {
|
||||
$filePath = $document->file_path;
|
||||
}
|
||||
|
||||
if (!Storage::exists($filePath)) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$pdfContent = Storage::get($filePath);
|
||||
$base64Pdf = base64_encode($pdfContent);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'pdf_data' => $base64Pdf,
|
||||
'document_name' => $document->name
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
\Log::error('Error getting PDF for editing: ' . $e->getMessage());
|
||||
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Error al cargar el PDF'
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Category;
|
||||
use App\Models\Folder;
|
||||
use App\Models\Project;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||
@@ -11,7 +12,7 @@ use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class ProjectController extends Controller
|
||||
{
|
||||
use AuthorizesRequests; // ← Añadir este trait
|
||||
use AuthorizesRequests;
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
@@ -43,7 +44,7 @@ class ProjectController extends Controller
|
||||
'project' => $project,
|
||||
'categories' => Category::orderBy('name')->get(),
|
||||
'users' => User::where('id', '!=', auth()->id())->get(),
|
||||
'companies' => \App\Models\Company::all(), // Pass companies to the view
|
||||
'companies' => \App\Models\Company::all(), // Pass companies to the view,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -93,6 +94,12 @@ class ProjectController extends Controller
|
||||
if($request->has('categories')) {
|
||||
$project->categories()->sync($request->categories);
|
||||
}
|
||||
|
||||
Folder::create([
|
||||
'name' => 'Project',
|
||||
'project_id' => $project->id,
|
||||
'parent_id' => null,
|
||||
]);
|
||||
|
||||
return redirect()->route('projects.show', $project)->with('success', 'Proyecto creado exitosamente');
|
||||
|
||||
@@ -172,6 +179,9 @@ class ProjectController extends Controller
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*/
|
||||
public function __invoke(Project $project)
|
||||
{
|
||||
return view('projects.show', [
|
||||
|
||||
223
app/Http/Controllers/ProjectSettingsController.php
Normal file
223
app/Http/Controllers/ProjectSettingsController.php
Normal file
@@ -0,0 +1,223 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Project;
|
||||
use App\Models\ProjectCodingConfig;
|
||||
use App\Models\ProjectDocumentStatus;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ProjectSettingsController extends Controller
|
||||
{
|
||||
public function index(Project $project)
|
||||
{
|
||||
$this->authorize('update', $project);
|
||||
|
||||
//$project->load(['codingConfig', 'documentStatuses']);
|
||||
|
||||
return view('project-settings.index', compact('project'));
|
||||
}
|
||||
|
||||
public function updateCoding(Request $request, Project $project)
|
||||
{
|
||||
$this->authorize('update', $project);
|
||||
|
||||
$validated = $request->validate([
|
||||
'format' => 'required|string|max:255',
|
||||
'year_format' => 'required|in:Y,y,Yy,yy,Y-m,Y/m,y-m,y/m',
|
||||
'separator' => 'required|string|max:5',
|
||||
'sequence_length' => 'required|integer|min:1|max:10',
|
||||
'auto_generate' => 'boolean',
|
||||
'elements' => 'nullable|array',
|
||||
'reset_sequence' => 'boolean',
|
||||
]);
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
$codingConfig = $project->codingConfig ?: new ProjectCodingConfig();
|
||||
$codingConfig->project_id = $project->id;
|
||||
|
||||
$codingConfig->fill([
|
||||
'format' => $validated['format'],
|
||||
'year_format' => $validated['year_format'],
|
||||
'separator' => $validated['separator'],
|
||||
'sequence_length' => $validated['sequence_length'],
|
||||
'auto_generate' => $validated['auto_generate'] ?? false,
|
||||
'elements' => $validated['elements'] ?? [],
|
||||
]);
|
||||
|
||||
if ($request->boolean('reset_sequence')) {
|
||||
$codingConfig->next_sequence = 1;
|
||||
}
|
||||
|
||||
$codingConfig->save();
|
||||
|
||||
DB::commit();
|
||||
|
||||
return redirect()->route('project-settings.index', $project)
|
||||
->with('success', 'Configuración de codificación actualizada correctamente.');
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
return redirect()->back()
|
||||
->with('error', 'Error al actualizar la configuración: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function storeStatus(Request $request, Project $project)
|
||||
{
|
||||
$this->authorize('update', $project);
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:100',
|
||||
'color' => 'required|string|max:7',
|
||||
'text_color' => 'nullable|string|max:7',
|
||||
'description' => 'nullable|string|max:500',
|
||||
'allow_upload' => 'boolean',
|
||||
'allow_edit' => 'boolean',
|
||||
'allow_delete' => 'boolean',
|
||||
'requires_approval' => 'boolean',
|
||||
'is_default' => 'boolean',
|
||||
]);
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
// Si se marca como default, quitar el default de otros estados
|
||||
if ($validated['is_default'] ?? false) {
|
||||
$project->documentStatuses()->update(['is_default' => false]);
|
||||
}
|
||||
|
||||
$status = new ProjectDocumentStatus($validated);
|
||||
$status->project_id = $project->id;
|
||||
$status->slug = Str::slug($validated['name']);
|
||||
|
||||
// Verificar que el slug sea único
|
||||
$counter = 1;
|
||||
$originalSlug = $status->slug;
|
||||
while ($project->documentStatuses()->where('slug', $status->slug)->exists()) {
|
||||
$status->slug = $originalSlug . '-' . $counter;
|
||||
$counter++;
|
||||
}
|
||||
|
||||
$status->save();
|
||||
|
||||
DB::commit();
|
||||
|
||||
return redirect()->route('project-settings.index', $project)
|
||||
->with('success', 'Estado creado correctamente.');
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
return redirect()->back()
|
||||
->with('error', 'Error al crear el estado: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function updateStatus(Request $request, Project $project, ProjectDocumentStatus $status)
|
||||
{
|
||||
$this->authorize('update', $project);
|
||||
|
||||
if ($status->project_id !== $project->id) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:100',
|
||||
'color' => 'required|string|max:7',
|
||||
'text_color' => 'nullable|string|max:7',
|
||||
'description' => 'nullable|string|max:500',
|
||||
'allow_upload' => 'boolean',
|
||||
'allow_edit' => 'boolean',
|
||||
'allow_delete' => 'boolean',
|
||||
'requires_approval' => 'boolean',
|
||||
'is_default' => 'boolean',
|
||||
]);
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
// Si se marca como default, quitar el default de otros estados
|
||||
if ($validated['is_default'] ?? false) {
|
||||
$project->documentStatuses()
|
||||
->where('id', '!=', $status->id)
|
||||
->update(['is_default' => false]);
|
||||
}
|
||||
|
||||
$status->update($validated);
|
||||
|
||||
DB::commit();
|
||||
|
||||
return redirect()->route('project-settings.index', $project)
|
||||
->with('success', 'Estado actualizado correctamente.');
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
return redirect()->back()
|
||||
->with('error', 'Error al actualizar el estado: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function destroyStatus(Project $project, ProjectDocumentStatus $status)
|
||||
{
|
||||
$this->authorize('update', $project);
|
||||
|
||||
if ($status->project_id !== $project->id) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
// Verificar que no haya documentos con este estado
|
||||
if ($status->documents()->exists()) {
|
||||
return redirect()->back()
|
||||
->with('error', 'No se puede eliminar el estado porque hay documentos asociados.');
|
||||
}
|
||||
|
||||
// Si es el estado por defecto, establecer otro como default
|
||||
if ($status->is_default) {
|
||||
$newDefault = $project->documentStatuses()
|
||||
->where('id', '!=', $status->id)
|
||||
->first();
|
||||
|
||||
if ($newDefault) {
|
||||
$newDefault->update(['is_default' => true]);
|
||||
}
|
||||
}
|
||||
|
||||
$status->delete();
|
||||
|
||||
return redirect()->route('project-settings.index', $project)
|
||||
->with('success', 'Estado eliminado correctamente.');
|
||||
}
|
||||
|
||||
public function reorderStatuses(Request $request, Project $project)
|
||||
{
|
||||
$this->authorize('update', $project);
|
||||
|
||||
$request->validate([
|
||||
'order' => 'required|array',
|
||||
'order.*' => 'exists:project_document_statuses,id',
|
||||
]);
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
foreach ($request->order as $index => $statusId) {
|
||||
$status = ProjectDocumentStatus::find($statusId);
|
||||
if ($status && $status->project_id === $project->id) {
|
||||
$status->update(['order' => $index + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
|
||||
return response()->json(['success' => true]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
return response()->json(['error' => $e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
251
app/Livewire/CodeEdit.php
Normal file
251
app/Livewire/CodeEdit.php
Normal file
@@ -0,0 +1,251 @@
|
||||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use Livewire\Component;
|
||||
|
||||
class CodeEdit extends Component
|
||||
{
|
||||
public $componentId; // Nuevo: ID del componente padre
|
||||
public $name = '';
|
||||
public $codeInput = '';
|
||||
public $labelInput = '';
|
||||
public $maxLength = 3;
|
||||
public $documentTypes = [];
|
||||
public $sortBy = 'code';
|
||||
public $sortDirection = 'asc';
|
||||
|
||||
protected $rules = [
|
||||
'name' => 'required|string|min:2|max:50',
|
||||
'codeInput' => 'required|string',
|
||||
'labelInput' => 'required|string',
|
||||
'maxLength' => 'required|integer|min:2|max:12',
|
||||
];
|
||||
|
||||
public function mount($componentId, $initialName = '', $initialMaxLength = 3, $initialDocumentTypes = [])
|
||||
{
|
||||
$this->componentId = $componentId;
|
||||
$this->name = $initialName;
|
||||
$this->maxLength = $initialMaxLength;
|
||||
$this->documentTypes = $initialDocumentTypes;
|
||||
|
||||
// Guardar datos iniciales
|
||||
$this->initialData = [
|
||||
'name' => $initialName,
|
||||
'maxLength' => $initialMaxLength,
|
||||
'documentTypes' => $initialDocumentTypes
|
||||
];
|
||||
|
||||
// Disparar eventos iniciales
|
||||
$this->dispatch('nameUpdated',
|
||||
componentId: $this->componentId,
|
||||
data: [
|
||||
'name' => $this->name,
|
||||
]
|
||||
);
|
||||
|
||||
$this->dispatch('componentUpdated',
|
||||
componentId: $this->componentId,
|
||||
data: [
|
||||
'documentTypes' => $this->documentTypes,
|
||||
'maxLength' => $this->maxLength
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
public function updateName()
|
||||
{
|
||||
$this->validate([
|
||||
'name' => 'required|string|min:2|max:50',
|
||||
]);
|
||||
|
||||
$this->dispatch('nameUpdated',
|
||||
componentId: $this->componentId,
|
||||
data: [
|
||||
'name' => $this->name
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
public function updateMaxLength()
|
||||
{
|
||||
$this->validate([
|
||||
'maxLength' => 'integer|min:2|max:12',
|
||||
]);
|
||||
|
||||
if (strlen($this->codeInput) > $this->maxLength) {
|
||||
$this->codeInput = substr($this->codeInput, 0, $this->maxLength);
|
||||
}
|
||||
}
|
||||
|
||||
public function addField()
|
||||
{
|
||||
$this->validate([
|
||||
'codeInput' => "required|string|size:{$this->maxLength}",
|
||||
'labelInput' => 'required|string|min:1',
|
||||
], [
|
||||
'codeInput.size' => "El código debe tener exactamente {$this->maxLength} caracteres",
|
||||
]);
|
||||
|
||||
$this->documentTypes[] = [
|
||||
'code' => $this->codeInput,
|
||||
'label' => $this->labelInput,
|
||||
//'max_length' => $this->maxLength,
|
||||
];
|
||||
|
||||
$this->sortList();
|
||||
$this->reset(['codeInput', 'labelInput']);
|
||||
|
||||
$this->dispatch('componentUpdated',
|
||||
componentId: $this->componentId, // Cambiado aquí
|
||||
data: [
|
||||
'documentTypes' => $this->documentTypes,
|
||||
'maxLength' => $this->maxLength
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
public function addCode()
|
||||
{
|
||||
$this->validate([
|
||||
'codeInput' => "required|string|size:{$this->maxLength}",
|
||||
], [
|
||||
'codeInput.size' => "El código debe tener exactamente {$this->maxLength} caracteres",
|
||||
]);
|
||||
|
||||
$this->dispatch('focus-label-input');
|
||||
}
|
||||
|
||||
public function addLabel()
|
||||
{
|
||||
$this->validate([
|
||||
'labelInput' => 'required|string|min:1',
|
||||
]);
|
||||
|
||||
if (!empty($this->codeInput) && !empty($this->labelInput)) {
|
||||
$this->addField();
|
||||
}
|
||||
}
|
||||
|
||||
public function removeField($index)
|
||||
{
|
||||
if (isset($this->documentTypes[$index])) {
|
||||
unset($this->documentTypes[$index]);
|
||||
$this->documentTypes = array_values($this->documentTypes);
|
||||
|
||||
$this->dispatch('componentUpdated',
|
||||
componentId: $this->componentId, // Cambiado aquí
|
||||
data: [
|
||||
'documentTypes' => $this->documentTypes,
|
||||
'maxLength' => $this->maxLength
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function updatedMaxLength($value)
|
||||
{
|
||||
$this->validate([
|
||||
'maxLength' => 'integer|min:2|max:12',
|
||||
]);
|
||||
|
||||
if (strlen($this->codeInput) > $value) {
|
||||
$this->codeInput = substr($this->codeInput, 0, $value);
|
||||
}
|
||||
}
|
||||
|
||||
public function updatedCodeInput($value)
|
||||
{
|
||||
if (strlen($value) > $this->maxLength) {
|
||||
$this->codeInput = substr($value, 0, $this->maxLength);
|
||||
}
|
||||
|
||||
$this->codeInput = strtoupper($value);
|
||||
}
|
||||
|
||||
public function sortByCode()
|
||||
{
|
||||
if ($this->sortBy === 'code') {
|
||||
$this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
$this->sortBy = 'code';
|
||||
$this->sortDirection = 'asc';
|
||||
}
|
||||
$this->sortList();
|
||||
}
|
||||
|
||||
public function sortByLabel()
|
||||
{
|
||||
if ($this->sortBy === 'label') {
|
||||
$this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
$this->sortBy = 'label';
|
||||
$this->sortDirection = 'asc';
|
||||
}
|
||||
$this->sortList();
|
||||
}
|
||||
|
||||
private function sortList()
|
||||
{
|
||||
$direction = $this->sortDirection === 'asc' ? SORT_ASC : SORT_DESC;
|
||||
|
||||
if ($this->sortBy === 'code') {
|
||||
array_multisort(
|
||||
array_column($this->documentTypes, 'code'),
|
||||
$direction,
|
||||
SORT_STRING,
|
||||
$this->documentTypes
|
||||
);
|
||||
} else {
|
||||
array_multisort(
|
||||
array_column($this->documentTypes, 'label'),
|
||||
$direction,
|
||||
SORT_STRING,
|
||||
$this->documentTypes
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function getSortedDocumentTypesProperty()
|
||||
{
|
||||
$sorted = $this->documentTypes;
|
||||
$direction = $this->sortDirection === 'asc' ? SORT_ASC : SORT_DESC;
|
||||
|
||||
if ($this->sortBy === 'code') {
|
||||
array_multisort(
|
||||
array_column($sorted, 'code'),
|
||||
$direction,
|
||||
SORT_STRING,
|
||||
$sorted
|
||||
);
|
||||
} else {
|
||||
array_multisort(
|
||||
array_column($sorted, 'label'),
|
||||
$direction,
|
||||
SORT_STRING,
|
||||
$sorted
|
||||
);
|
||||
}
|
||||
|
||||
return $sorted;
|
||||
}
|
||||
|
||||
public function getTotalDocumentTypesProperty()
|
||||
{
|
||||
return count($this->documentTypes);
|
||||
}
|
||||
|
||||
public function getSortIcon($column)
|
||||
{
|
||||
if ($this->sortBy !== $column) {
|
||||
return 'sort';
|
||||
}
|
||||
|
||||
return $this->sortDirection === 'asc' ? 'sort-up' : 'sort-down';
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
return view('livewire.code-edit');
|
||||
}
|
||||
}
|
||||
273
app/Livewire/ProjectDocumentList.php
Normal file
273
app/Livewire/ProjectDocumentList.php
Normal file
@@ -0,0 +1,273 @@
|
||||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Models\Document;
|
||||
use Maatwebsite\Excel\Facades\Excel;
|
||||
use App\Exports\DocumentsExport;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Rappasoft\LaravelLivewireTables\DataTableComponent;
|
||||
use Rappasoft\LaravelLivewireTables\Views\Column;
|
||||
use Rappasoft\LaravelLivewireTables\Views\Filters\SelectFilter;
|
||||
use Rappasoft\LaravelLivewireTables\Views\Filters\TextFilter;
|
||||
|
||||
class ProjectDocumentList extends DataTableComponent
|
||||
{
|
||||
public $projectId;
|
||||
public $folderId = null;
|
||||
|
||||
protected $model = Document::class;
|
||||
|
||||
public function configure(): void
|
||||
{
|
||||
$this->setPrimaryKey('id')
|
||||
->setAdditionalSelects(['documents.id as id'])
|
||||
|
||||
/*->setConfigurableAreas([
|
||||
'toolbar-left-start' => ['includes.areas.toolbar-left-start', ['param1' => 'Default', 'param2' => ['param2' => 2]]],
|
||||
])*/
|
||||
->setPaginationEnabled()
|
||||
->setPaginationMethod('simple')
|
||||
->setPaginationVisibilityEnabled()
|
||||
|
||||
|
||||
//->setReorderEnabled()
|
||||
->setHideReorderColumnUnlessReorderingEnabled()
|
||||
->setSecondaryHeaderTrAttributes(function ($rows) {
|
||||
return ['class' => 'bg-gray-100'];
|
||||
})
|
||||
->setSecondaryHeaderTdAttributes(function (Column $column, $rows) {
|
||||
if ($column->isField('id')) {
|
||||
return ['class' => 'text-red-100'];
|
||||
}
|
||||
return ['default' => true];
|
||||
})
|
||||
->setFooterTrAttributes(function ($rows) {
|
||||
return ['class' => 'bg-gray-100'];
|
||||
})
|
||||
->setFooterTdAttributes(function (Column $column, $rows) {
|
||||
if ($column->isField('name')) {
|
||||
return ['class' => 'text-green-500'];
|
||||
}
|
||||
return ['default' => true];
|
||||
})
|
||||
->setHideBulkActionsWhenEmptyEnabled()
|
||||
->setUseHeaderAsFooterEnabled()
|
||||
|
||||
->setPaginationEnabled()
|
||||
->setPaginationVisibilityEnabled()
|
||||
//->setToolsDisabled()
|
||||
//->setToolBarDisabled()
|
||||
|
||||
// Configuración de paginación
|
||||
->setPerPage(25) // Número de elementos por página
|
||||
->setPerPageAccepted([10, 25, 50, 100]) // Opciones de elementos por página
|
||||
->setPaginationEnabled() // Asegurar que la paginación esté habilitada
|
||||
->setPaginationVisibilityStatus(true); // Hacer visible el paginador
|
||||
;
|
||||
}
|
||||
|
||||
public function mount($projectId = null, $folderId = null)
|
||||
{
|
||||
$this->projectId = $projectId;
|
||||
$this->folderId = $folderId;
|
||||
}
|
||||
|
||||
public function columns(): array
|
||||
{
|
||||
return [
|
||||
Column::make("Código", "code")
|
||||
->sortable()
|
||||
->searchable()
|
||||
->secondaryHeaderFilter('code') // Filtro para esta columna
|
||||
->format(
|
||||
fn($value, $row, Column $column) =>
|
||||
'<a href="'.route('documents.show', $row->id).'" target="_blank" class=" target="_blank" class="flex items-center hover:text-blue-600 transition-colors"">'.$value.'</a>'
|
||||
)->html(),
|
||||
|
||||
Column::make("Nombre", "name")
|
||||
->sortable()
|
||||
->searchable()
|
||||
->secondaryHeaderFilter('name') // Filtro para esta columna
|
||||
->format(
|
||||
fn($value, $row, Column $column) =>
|
||||
'<div class="flex items-center">
|
||||
<span class="mr-2 text-lg">
|
||||
'.\App\Helpers\FileHelper::getFileIconSvg($value).'
|
||||
</span>
|
||||
<a href="'.route('documents.show', $row->id).'"
|
||||
target="_blank"
|
||||
class=" target="_blank" class="flex items-center hover:text-blue-600 transition-colors"">
|
||||
'.$value.'
|
||||
</a>
|
||||
</div>'
|
||||
)->html(),
|
||||
|
||||
Column::make("Estado", "status")
|
||||
->sortable()
|
||||
->searchable()
|
||||
->secondaryHeaderFilter('status') // Filtro para esta columna
|
||||
->format(
|
||||
fn($value, $row, Column $column) =>
|
||||
'<span class="px-2 py-1 text-xs font-semibold rounded-full '.
|
||||
($value === 'active' ? 'bg-green-100 text-green-800' :
|
||||
($value === 'pending' ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800')).'">'.
|
||||
$value.'</span>'
|
||||
)->html(),
|
||||
|
||||
Column::make("Revisión", "revision")
|
||||
->sortable()
|
||||
->searchable(),
|
||||
|
||||
Column::make("Versión", "version")
|
||||
->sortable()
|
||||
->searchable(),
|
||||
|
||||
Column::make("Área", "area")
|
||||
->sortable()
|
||||
->searchable()
|
||||
->secondaryHeaderFilter('area'), // Filtro para esta columna
|
||||
|
||||
Column::make("Disciplina", "discipline")
|
||||
->sortable()
|
||||
->searchable()
|
||||
->secondaryHeaderFilter('discipline'), // Filtro para esta columna
|
||||
|
||||
Column::make("Tipo", "document_type")
|
||||
->sortable()
|
||||
->searchable()
|
||||
->secondaryHeaderFilter('type'), // Filtro para esta columna
|
||||
|
||||
Column::make("Fecha Entrada", "entry_date")
|
||||
->sortable()
|
||||
->searchable()
|
||||
->format(
|
||||
fn($value, $row, Column $column) =>
|
||||
$value ? \Carbon\Carbon::parse($value)->format('d/m/Y') : '-'
|
||||
),
|
||||
|
||||
Column::make("Actualizado", "updated_at")
|
||||
->sortable()
|
||||
->searchable()
|
||||
->format(
|
||||
fn($value, $row, Column $column) =>
|
||||
$value ? \Carbon\Carbon::parse($value)->diffForHumans() : '-'
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
public function filters(): array
|
||||
{
|
||||
return [
|
||||
TextFilter::make('Código', 'code') // Agregar clave 'code'
|
||||
->config([
|
||||
'placeholder' => 'Buscar por código',
|
||||
])
|
||||
->filter(function (Builder $builder, string $value) {
|
||||
$builder->where('documents.code', 'like', '%'.$value.'%');
|
||||
}),
|
||||
|
||||
TextFilter::make('Nombre', 'name') // Agregar clave 'name'
|
||||
->config([
|
||||
'placeholder' => 'Buscar por nombre',
|
||||
])
|
||||
->filter(function (Builder $builder, string $value) {
|
||||
$builder->where('documents.name', 'like', '%'.$value.'%');
|
||||
}),
|
||||
|
||||
SelectFilter::make('Estado', 'status') // Agregar clave 'status'
|
||||
->options([
|
||||
'' => 'Todos',
|
||||
'active' => 'Activo',
|
||||
'pending' => 'Pendiente',
|
||||
'inactive' => 'Inactivo',
|
||||
])
|
||||
->filter(function (Builder $builder, string $value) {
|
||||
if ($value) {
|
||||
$builder->where('documents.status', $value);
|
||||
}
|
||||
}),
|
||||
|
||||
SelectFilter::make('Disciplina', 'discipline') // Agregar clave 'discipline'
|
||||
->options(
|
||||
collect(['Estructural', 'Arquitectura', 'Eléctrica', 'Mecánica', 'Civil', 'Otros'])
|
||||
->prepend('Todas', '')
|
||||
->toArray()
|
||||
)
|
||||
->filter(function (Builder $builder, string $value) {
|
||||
if ($value) {
|
||||
$builder->where('documents.discipline', $value);
|
||||
}
|
||||
}),
|
||||
|
||||
SelectFilter::make('Area', 'area') // Agregar clave 'area'
|
||||
->options(
|
||||
collect(['Estructural', 'Arquitectura', 'Eléctrica', 'Mecánica', 'Civil', 'Otros'])
|
||||
->prepend('Todas', '')
|
||||
->toArray()
|
||||
)
|
||||
->filter(function (Builder $builder, string $value) {
|
||||
if ($value) {
|
||||
$builder->where('documents.area', $value);
|
||||
}
|
||||
}),
|
||||
|
||||
SelectFilter::make('Tipo', 'type') // Agregar clave 'document_type'
|
||||
->options(
|
||||
collect(['Estructural', 'Arquitectura', 'Eléctrica', 'Mecánica', 'Civil', 'Otros'])
|
||||
->prepend('Todas', '')
|
||||
->toArray()
|
||||
)
|
||||
->filter(function (Builder $builder, string $value) {
|
||||
if ($value) {
|
||||
$builder->where('documents.document_type', $value);
|
||||
}
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
public function builder(): Builder
|
||||
{
|
||||
$query = Document::query()->where('project_id', $this->projectId);
|
||||
|
||||
if ($this->folderId) {
|
||||
$query->where('folder_id', $this->folderId);
|
||||
} else {
|
||||
$query->whereNull('folder_id');
|
||||
}
|
||||
|
||||
return $query->with('user');
|
||||
}
|
||||
|
||||
public function bulkActions(): array
|
||||
{
|
||||
return [
|
||||
'activate' => 'Activar',
|
||||
'deactivate' => 'Desactivar',
|
||||
'export' => 'Exportar',
|
||||
];
|
||||
}
|
||||
|
||||
public function export()
|
||||
{
|
||||
$documents = $this->getSelected();
|
||||
|
||||
$this->clearSelected();
|
||||
|
||||
return Excel::download(new DocumentsExport($documents), 'documentos.xlsx');
|
||||
}
|
||||
|
||||
public function activate()
|
||||
{
|
||||
Document::whereIn('id', $this->getSelected())->update(['status' => 'active']);
|
||||
$this->clearSelected();
|
||||
$this->dispatch('documents-updated');
|
||||
}
|
||||
|
||||
public function deactivate()
|
||||
{
|
||||
Document::whereIn('id', $this->getSelected())->update(['status' => 'inactive']);
|
||||
$this->clearSelected();
|
||||
$this->dispatch('documents-updated');
|
||||
}
|
||||
}
|
||||
317
app/Livewire/ProjectDocumentStatusManager.php
Normal file
317
app/Livewire/ProjectDocumentStatusManager.php
Normal file
@@ -0,0 +1,317 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Livewire;
|
||||
|
||||
use Livewire\Component;
|
||||
use App\Models\Project;
|
||||
use App\Models\ProjectDocumentStatus;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ProjectDocumentStatusManager extends Component
|
||||
{
|
||||
public $project;
|
||||
public $statuses = [];
|
||||
public $showForm = false;
|
||||
|
||||
public $formData = [
|
||||
'id' => null,
|
||||
'name' => '',
|
||||
'color' => '#6b7280',
|
||||
'text_color' => '#ffffff',
|
||||
'description' => '',
|
||||
'allow_upload' => true,
|
||||
'allow_edit' => true,
|
||||
'allow_delete' => false,
|
||||
'requires_approval' => false,
|
||||
'is_default' => false,
|
||||
];
|
||||
|
||||
public $showDeleteModal = false;
|
||||
public $statusToDelete = null;
|
||||
public $orderedStatusIds = [];
|
||||
|
||||
protected $rules = [
|
||||
'formData.name' => 'required|string|min:2|max:100',
|
||||
'formData.color' => 'required|string|max:7',
|
||||
'formData.text_color' => 'nullable|string|max:7',
|
||||
'formData.description' => 'nullable|string|max:500',
|
||||
'formData.allow_upload' => 'boolean',
|
||||
'formData.allow_edit' => 'boolean',
|
||||
'formData.allow_delete' => 'boolean',
|
||||
'formData.requires_approval' => 'boolean',
|
||||
'formData.is_default' => 'boolean',
|
||||
];
|
||||
|
||||
public function mount(Project $project)
|
||||
{
|
||||
$this->project = $project;
|
||||
$this->loadStatuses();
|
||||
}
|
||||
|
||||
public function loadStatuses()
|
||||
{
|
||||
$this->statuses = $this->project->documentStatuses()
|
||||
->orderBy('order')
|
||||
->get()
|
||||
->toArray();
|
||||
|
||||
$this->statuses = [];
|
||||
|
||||
$this->orderedStatusIds = collect($this->statuses)->pluck('id')->toArray();
|
||||
}
|
||||
|
||||
public function openForm($statusId = null)
|
||||
{
|
||||
$this->resetForm();
|
||||
|
||||
if ($statusId) {
|
||||
$status = ProjectDocumentStatus::find($statusId);
|
||||
if ($status && $status->project_id === $this->project->id) {
|
||||
$this->formData = [
|
||||
'id' => $status->id,
|
||||
'name' => $status->name,
|
||||
'color' => $status->color,
|
||||
'text_color' => $status->text_color,
|
||||
'description' => $status->description,
|
||||
'allow_upload' => $status->allow_upload,
|
||||
'allow_edit' => $status->allow_edit,
|
||||
'allow_delete' => $status->allow_delete,
|
||||
'requires_approval' => $status->requires_approval,
|
||||
'is_default' => $status->is_default,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$this->showForm = true;
|
||||
}
|
||||
|
||||
public function closeForm()
|
||||
{
|
||||
$this->showForm = false;
|
||||
$this->resetForm();
|
||||
}
|
||||
|
||||
public function resetForm()
|
||||
{
|
||||
$this->formData = [
|
||||
'id' => null,
|
||||
'name' => '',
|
||||
'color' => '#6b7280',
|
||||
'text_color' => '#ffffff',
|
||||
'description' => '',
|
||||
'allow_upload' => true,
|
||||
'allow_edit' => true,
|
||||
'allow_delete' => false,
|
||||
'requires_approval' => false,
|
||||
'is_default' => false,
|
||||
];
|
||||
$this->resetErrorBag();
|
||||
}
|
||||
|
||||
public function saveStatus()
|
||||
{
|
||||
$this->validate();
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
// Si se marca como default, quitar el default de otros estados
|
||||
if ($this->formData['is_default']) {
|
||||
$this->project->documentStatuses()->update(['is_default' => false]);
|
||||
}
|
||||
|
||||
$data = [
|
||||
'name' => $this->formData['name'],
|
||||
'color' => $this->formData['color'],
|
||||
'text_color' => $this->formData['text_color'] ?: $this->calculateTextColor($this->formData['color']),
|
||||
'description' => $this->formData['description'],
|
||||
'allow_upload' => $this->formData['allow_upload'],
|
||||
'allow_edit' => $this->formData['allow_edit'],
|
||||
'allow_delete' => $this->formData['allow_delete'],
|
||||
'requires_approval' => $this->formData['requires_approval'],
|
||||
'is_default' => $this->formData['is_default'],
|
||||
];
|
||||
|
||||
if ($this->formData['id']) {
|
||||
// Editar estado existente
|
||||
$status = ProjectDocumentStatus::find($this->formData['id']);
|
||||
if ($status && $status->project_id === $this->project->id) {
|
||||
$status->update($data);
|
||||
}
|
||||
} else {
|
||||
// Crear nuevo estado
|
||||
$data['project_id'] = $this->project->id;
|
||||
$data['slug'] = $this->generateUniqueSlug($this->formData['name']);
|
||||
$data['order'] = $this->project->documentStatuses()->count();
|
||||
|
||||
ProjectDocumentStatus::create($data);
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
|
||||
$this->loadStatuses();
|
||||
$this->closeForm();
|
||||
|
||||
$this->dispatch('show-message', [
|
||||
'type' => 'success',
|
||||
'message' => $this->formData['id'] ? 'Estado actualizado correctamente.' : 'Estado creado correctamente.'
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
$this->dispatch('show-message', [
|
||||
'type' => 'error',
|
||||
'message' => 'Error al guardar: ' . $e->getMessage()
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function generateUniqueSlug($name)
|
||||
{
|
||||
$slug = Str::slug($name);
|
||||
$originalSlug = $slug;
|
||||
$counter = 1;
|
||||
|
||||
while ($this->project->documentStatuses()->where('slug', $slug)->exists()) {
|
||||
$slug = $originalSlug . '-' . $counter;
|
||||
$counter++;
|
||||
}
|
||||
|
||||
return $slug;
|
||||
}
|
||||
|
||||
private function calculateTextColor($backgroundColor)
|
||||
{
|
||||
// Convertir hex a RGB
|
||||
$hex = str_replace('#', '', $backgroundColor);
|
||||
if (strlen($hex) == 3) {
|
||||
$hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
|
||||
}
|
||||
|
||||
$r = hexdec(substr($hex, 0, 2));
|
||||
$g = hexdec(substr($hex, 2, 2));
|
||||
$b = hexdec(substr($hex, 4, 2));
|
||||
|
||||
// Calcular luminosidad
|
||||
$luminosity = (0.299 * $r + 0.587 * $g + 0.114 * $b) / 255;
|
||||
|
||||
return $luminosity > 0.5 ? '#000000' : '#ffffff';
|
||||
}
|
||||
|
||||
public function confirmDelete($statusId)
|
||||
{
|
||||
$this->statusToDelete = ProjectDocumentStatus::find($statusId);
|
||||
if ($this->statusToDelete && $this->statusToDelete->project_id === $this->project->id) {
|
||||
$this->showDeleteModal = true;
|
||||
}
|
||||
}
|
||||
|
||||
public function closeDeleteModal()
|
||||
{
|
||||
$this->showDeleteModal = false;
|
||||
$this->statusToDelete = null;
|
||||
}
|
||||
|
||||
public function deleteStatus()
|
||||
{
|
||||
if (!$this->statusToDelete) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Verificar que no haya documentos con este estado
|
||||
if ($this->statusToDelete->documents()->exists()) {
|
||||
$this->dispatch('show-message', [
|
||||
'type' => 'error',
|
||||
'message' => 'No se puede eliminar el estado porque hay documentos asociados.'
|
||||
]);
|
||||
$this->closeDeleteModal();
|
||||
return;
|
||||
}
|
||||
|
||||
// Si es el estado por defecto, establecer otro como default
|
||||
if ($this->statusToDelete->is_default) {
|
||||
$newDefault = $this->project->documentStatuses()
|
||||
->where('id', '!=', $this->statusToDelete->id)
|
||||
->first();
|
||||
|
||||
if ($newDefault) {
|
||||
$newDefault->update(['is_default' => true]);
|
||||
}
|
||||
}
|
||||
|
||||
$this->statusToDelete->delete();
|
||||
$this->loadStatuses();
|
||||
|
||||
$this->dispatch('show-message', [
|
||||
'type' => 'success',
|
||||
'message' => 'Estado eliminado correctamente.'
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$this->dispatch('show-message', [
|
||||
'type' => 'error',
|
||||
'message' => 'Error al eliminar: ' . $e->getMessage()
|
||||
]);
|
||||
}
|
||||
|
||||
$this->closeDeleteModal();
|
||||
}
|
||||
|
||||
public function updateOrder()
|
||||
{
|
||||
try {
|
||||
foreach ($this->orderedStatusIds as $index => $statusId) {
|
||||
$status = ProjectDocumentStatus::find($statusId);
|
||||
if ($status && $status->project_id === $this->project->id) {
|
||||
$status->update(['order' => $index]);
|
||||
}
|
||||
}
|
||||
|
||||
$this->loadStatuses();
|
||||
|
||||
$this->dispatch('show-message', [
|
||||
'type' => 'success',
|
||||
'message' => 'Orden actualizado correctamente.'
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$this->dispatch('show-message', [
|
||||
'type' => 'error',
|
||||
'message' => 'Error al actualizar el orden: ' . $e->getMessage()
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function moveUp($statusId)
|
||||
{
|
||||
$index = array_search($statusId, $this->orderedStatusIds);
|
||||
|
||||
if ($index > 0) {
|
||||
$temp = $this->orderedStatusIds[$index];
|
||||
$this->orderedStatusIds[$index] = $this->orderedStatusIds[$index - 1];
|
||||
$this->orderedStatusIds[$index - 1] = $temp;
|
||||
|
||||
$this->updateOrder();
|
||||
}
|
||||
}
|
||||
|
||||
public function moveDown($statusId)
|
||||
{
|
||||
$index = array_search($statusId, $this->orderedStatusIds);
|
||||
|
||||
if ($index < count($this->orderedStatusIds) - 1) {
|
||||
$temp = $this->orderedStatusIds[$index];
|
||||
$this->orderedStatusIds[$index] = $this->orderedStatusIds[$index + 1];
|
||||
$this->orderedStatusIds[$index + 1] = $temp;
|
||||
|
||||
$this->updateOrder();
|
||||
}
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
return view('livewire.project-document-status-manager');
|
||||
}
|
||||
}
|
||||
274
app/Livewire/ProjectNameCoder.php
Normal file
274
app/Livewire/ProjectNameCoder.php
Normal file
@@ -0,0 +1,274 @@
|
||||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use Livewire\Component;
|
||||
use App\Models\Project;
|
||||
use App\Models\ProjectCodingConfig;
|
||||
|
||||
class ProjectNameCoder extends Component
|
||||
{
|
||||
public $components = [];
|
||||
public $nextId = 1;
|
||||
public $project;
|
||||
|
||||
protected $listeners = [
|
||||
'nameUpdated' => 'headerLabelUpdate',
|
||||
'componentUpdated' => 'handleComponentUpdate',
|
||||
'removeComponent' => 'removeComponent'
|
||||
];
|
||||
|
||||
public function mount(Project $project)
|
||||
{
|
||||
// Inicializar con un componente vacío
|
||||
$this->project = $project;
|
||||
|
||||
if ($project->codingConfig) {
|
||||
$this->loadDatabaseConfiguration();
|
||||
} else {
|
||||
$this->addComponent();
|
||||
}
|
||||
}
|
||||
|
||||
private function loadDatabaseConfiguration()
|
||||
{
|
||||
// Buscar la configuración de codificación del proyecto
|
||||
$config = $this->project->codingConfig;
|
||||
|
||||
if ($config && isset($config->elements['components'])) {
|
||||
$this->components = $config->elements['components'];
|
||||
$this->nextId = count($this->components) + 1;
|
||||
|
||||
// Asegurar que cada componente tenga los campos necesarios
|
||||
foreach ($this->components as &$component) {
|
||||
$component['data'] = $component['data'] ?? [];
|
||||
$component['order'] = $component['order'] ?? 0;
|
||||
$component['headerLabel'] = $component['headerLabel'] ?? '';
|
||||
$component['documentTypes'] = $component['documentTypes'] ?? [];
|
||||
}
|
||||
} else {
|
||||
// Si no hay configuración, inicializar con un componente vacío
|
||||
$this->addComponent();
|
||||
}
|
||||
}
|
||||
|
||||
public function addComponent()
|
||||
{
|
||||
$id = $this->nextId++;
|
||||
$this->components[] = [
|
||||
'id' => $id,
|
||||
'data' => [],
|
||||
'order' => count($this->components),
|
||||
'headerLabel' => ''
|
||||
];
|
||||
}
|
||||
|
||||
public function removeComponent($componentId)
|
||||
{
|
||||
$this->components = array_filter($this->components, function($component) use ($componentId) {
|
||||
return $component['id'] != $componentId;
|
||||
});
|
||||
|
||||
// Reindexar el orden
|
||||
$this->reorderComponents();
|
||||
}
|
||||
|
||||
public function headerLabelUpdate($componentId, $data)
|
||||
{
|
||||
foreach ($this->components as &$component) {
|
||||
if ($component['id'] == $componentId) {
|
||||
$component['headerLabel'] = $data['name'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function handleComponentUpdate($componentId, $data)
|
||||
{
|
||||
foreach ($this->components as &$component) {
|
||||
if ($component['id'] == $componentId) {
|
||||
$component['data'] = $data;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function updateComponentOrder($orderedIds)
|
||||
{
|
||||
foreach ($orderedIds as $index => $id) {
|
||||
foreach ($this->components as &$component) {
|
||||
if ($component['id'] == $id) {
|
||||
$component['order'] = $index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Ordenar el array por el campo 'order'
|
||||
usort($this->components, function($a, $b) {
|
||||
return $a['order'] - $b['order'];
|
||||
});
|
||||
}
|
||||
|
||||
private function reorderComponents()
|
||||
{
|
||||
foreach ($this->components as $index => &$component) {
|
||||
$component['order'] = $index;
|
||||
}
|
||||
}
|
||||
|
||||
public function moveComponentUp($componentId)
|
||||
{
|
||||
$index = $this->findComponentIndex($componentId);
|
||||
|
||||
if ($index > 0) {
|
||||
// Intercambiar con el componente anterior
|
||||
$temp = $this->components[$index];
|
||||
$this->components[$index] = $this->components[$index - 1];
|
||||
$this->components[$index - 1] = $temp;
|
||||
|
||||
// Actualizar órdenes
|
||||
$this->reorderComponents();
|
||||
}
|
||||
}
|
||||
|
||||
public function moveComponentDown($componentId)
|
||||
{
|
||||
$index = $this->findComponentIndex($componentId);
|
||||
|
||||
if ($index < count($this->components) - 1) {
|
||||
// Intercambiar con el componente siguiente
|
||||
$temp = $this->components[$index];
|
||||
$this->components[$index] = $this->components[$index + 1];
|
||||
$this->components[$index + 1] = $temp;
|
||||
|
||||
// Actualizar órdenes
|
||||
$this->reorderComponents();
|
||||
}
|
||||
}
|
||||
|
||||
private function findComponentIndex($componentId)
|
||||
{
|
||||
foreach ($this->components as $index => $component) {
|
||||
if ($component['id'] == $componentId) {
|
||||
return $index;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public function getComponentsCountProperty()
|
||||
{
|
||||
return count($this->components);
|
||||
}
|
||||
|
||||
public function getTotalDocumentTypesProperty()
|
||||
{
|
||||
$total = 0;
|
||||
foreach ($this->components as $component) {
|
||||
if (isset($component['data']['documentTypes'])) {
|
||||
$total += count($component['data']['documentTypes']);
|
||||
}
|
||||
}
|
||||
return $total;
|
||||
}
|
||||
|
||||
public function saveConfiguration()
|
||||
{
|
||||
try {
|
||||
// Preparar la configuración completa
|
||||
$configData = [
|
||||
'components' => $this->components,
|
||||
'total_components' => $this->componentsCount,
|
||||
//'total_document_types' => $this->totalDocumentTypes,
|
||||
//'generated_format' => $this->generateFormatString(),
|
||||
//'last_updated' => now()->toDateTimeString(),
|
||||
];
|
||||
|
||||
// Buscar o crear la configuración de codificación
|
||||
$codingConfig = ProjectCodingConfig::firstOrNew(['project_id' => $this->project->id]);
|
||||
|
||||
// Actualizar los campos
|
||||
$codingConfig->fill([
|
||||
'elements' => $configData,
|
||||
'format' => $this->generateFormatString(),
|
||||
'auto_generate' => true,
|
||||
]);
|
||||
|
||||
$codingConfig->save();
|
||||
|
||||
// Emitir evento de éxito
|
||||
$this->dispatch('configurationSaved', [
|
||||
'message' => 'Configuración guardada exitosamente',
|
||||
'format' => $this->generateFormatString()
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
$this->dispatch('configurationError', [
|
||||
'message' => 'Error al guardar la configuración: ' . $e->getMessage()
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function autoSave()
|
||||
{
|
||||
// Auto-guardar cada 30 segundos de inactividad o cuando haya cambios importantes
|
||||
// Esto es opcional pero mejora la experiencia de usuario
|
||||
$this->dispatch('configurationAutoSaved');
|
||||
}
|
||||
|
||||
private function generateFormatString()
|
||||
{
|
||||
$formatParts = [];
|
||||
|
||||
// Agregar el código del proyecto
|
||||
$formatParts[] = $this->project->code ?? $this->project->reference ?? 'PROJ';
|
||||
|
||||
// Agregar cada componente
|
||||
foreach ($this->components as $component) {
|
||||
if (!empty($component['headerLabel'])) {
|
||||
$formatParts[] = '[' . strtoupper($component['headerLabel']) . ']';
|
||||
}
|
||||
}
|
||||
|
||||
// Agregar el nombre del documento
|
||||
$formatParts[] = '[DOCUMENT_NAME]';
|
||||
|
||||
return implode('-', $formatParts);
|
||||
}
|
||||
|
||||
public function getExampleCodeAttribute()
|
||||
{
|
||||
$exampleParts = [];
|
||||
|
||||
// Agregar el código del proyecto
|
||||
$exampleParts[] = $this->project->code ?? $this->project->reference ?? 'PROJ';
|
||||
|
||||
// Agregar cada componente con un valor de ejemplo
|
||||
foreach ($this->components as $component) {
|
||||
if (!empty($component['headerLabel'])) {
|
||||
$exampleParts[] = $this->getExampleForComponent($component);
|
||||
}
|
||||
}
|
||||
|
||||
// Agregar nombre de documento de ejemplo
|
||||
$exampleParts[] = 'Documento-Ejemplo';
|
||||
|
||||
return implode('-', $exampleParts);
|
||||
}
|
||||
|
||||
private function getExampleForComponent($component)
|
||||
{
|
||||
if (isset($component['data']['documentTypes']) && count($component['data']['documentTypes']) > 0) {
|
||||
// Tomar el primer tipo de documento como ejemplo
|
||||
$firstType = $component['data']['documentTypes'][0];
|
||||
return $firstType['code'] ?? $firstType['name'] ?? 'TIPO';
|
||||
}
|
||||
|
||||
return 'VALOR';
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
return view('livewire.project-name-coder');
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ use App\Models\Document;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
use App\Services\ProjectCodeService;
|
||||
|
||||
class ProjectShow extends Component
|
||||
{
|
||||
|
||||
@@ -31,10 +33,14 @@ class ProjectShow extends Component
|
||||
public $selectedFiles = []; // Archivos temporales en el modal
|
||||
public $uploadProgress = [];
|
||||
|
||||
protected $listeners = ['documents-updated' => '$refresh'];
|
||||
|
||||
protected ProjectCodeService $codeService;
|
||||
|
||||
public function mount(Project $project)
|
||||
{
|
||||
$this->project = $project->load('rootFolders');
|
||||
$this->project = $project;
|
||||
$this->project['javi'] = 'braña';
|
||||
$this->currentFolder = $this->project->rootFolders->first() ?? null;
|
||||
}
|
||||
|
||||
@@ -80,28 +86,6 @@ class ProjectShow extends Component
|
||||
$this->project->refresh();
|
||||
}
|
||||
|
||||
/*public function uploadFiles(): void
|
||||
{
|
||||
$this->validate([
|
||||
'files.*' => 'file|max:10240|mimes:pdf,docx,xlsx,jpg,png'
|
||||
]);
|
||||
dd($this->files);
|
||||
foreach ($this->files as $file) {
|
||||
Document::create([
|
||||
'name' => $file->getClientOriginalName(),
|
||||
'file_path' => $file->store("projects/{$this->project->id}/documents"),
|
||||
'project_id' => $this->project->id,
|
||||
'folder_id' => $this->currentFolder?->id
|
||||
]);
|
||||
}
|
||||
|
||||
$this->reset('files');
|
||||
if ($this->currentFolder) {
|
||||
$this->currentFolder->refresh(); // Recargar documentos
|
||||
}
|
||||
$this->reset('files');
|
||||
}*/
|
||||
|
||||
public function getDocumentsProperty()
|
||||
{
|
||||
return $this->currentFolder
|
||||
@@ -147,6 +131,13 @@ class ProjectShow extends Component
|
||||
$this->validate([
|
||||
'selectedFiles.*' => 'file|max:10240|mimes:pdf,docx,xlsx,jpg,png'
|
||||
]);
|
||||
|
||||
$isValid = app(ProjectCodeService::class)->validate($this->project, $files[0]->getClientOriginalName());
|
||||
if ($isValid) {
|
||||
echo "✅ Código válido\n";
|
||||
} else {
|
||||
echo "❌ Código inválido\n";
|
||||
}
|
||||
|
||||
$this->selectedFiles = array_merge($this->selectedFiles, $files);
|
||||
}
|
||||
@@ -158,20 +149,47 @@ class ProjectShow extends Component
|
||||
$this->selectedFiles = array_values($this->selectedFiles); // Reindexar array
|
||||
}
|
||||
|
||||
// Método para confirmar y guardar
|
||||
public function uploadFiles(): void
|
||||
{
|
||||
$validator = new ProjectCodeValidator($project->codingConfig);
|
||||
foreach ($this->selectedFiles 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
|
||||
]);
|
||||
//print_r($analizador);
|
||||
//$resultado1 = $analizador->analizarDocumento($file->getClientOriginalName());
|
||||
if ($validator->validate($file->getClientOriginalName())) {
|
||||
echo "✅ Código válido\n";
|
||||
} else {
|
||||
echo "❌ Código inválido\n";
|
||||
return;
|
||||
}
|
||||
|
||||
$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();
|
||||
}
|
||||
@@ -226,7 +244,8 @@ class ProjectShow extends Component
|
||||
'file_path' => $path,
|
||||
'project_id' => $this->project->id,
|
||||
'folder_id' => $this->currentFolder?->id,
|
||||
'user_id' => Auth::id()
|
||||
'user_id' => Auth::id(),
|
||||
'code' => $code,
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
@@ -247,4 +266,9 @@ class ProjectShow extends Component
|
||||
{
|
||||
return \App\Helpers\ProjectNamingSchema::generate($fields);
|
||||
}
|
||||
|
||||
public function sellectAllDocuments()
|
||||
{
|
||||
$this->selectedFiles = $this->documents->pluck('id')->toArray();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ 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
|
||||
{
|
||||
@@ -20,22 +22,63 @@ class Document extends Model
|
||||
'file_path',
|
||||
'project_id', // Asegurar que está en fillable
|
||||
'folder_id',
|
||||
'user_id',
|
||||
'issuer',
|
||||
'status',
|
||||
'revision',
|
||||
'version',
|
||||
'discipline',
|
||||
'document_type',
|
||||
'issuer',
|
||||
'entry_date',
|
||||
'current_version_id',
|
||||
'code',
|
||||
];
|
||||
|
||||
|
||||
public function versions() {
|
||||
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);
|
||||
@@ -44,17 +87,6 @@ class Document extends Model
|
||||
public function comments() {
|
||||
return $this->hasMany(Comment::class)->whereNull('parent_id');
|
||||
}
|
||||
|
||||
|
||||
public function createVersion($file)
|
||||
{
|
||||
return $this->versions()->create([
|
||||
'file_path' => $file->store("documents/{$this->id}/versions"),
|
||||
'hash' => hash_file('sha256', $file),
|
||||
'user_id' => auth()->id(),
|
||||
'version_number' => $this->versions()->count() + 1
|
||||
]);
|
||||
}
|
||||
|
||||
public function getCurrentVersionAttribute()
|
||||
{
|
||||
@@ -63,7 +95,7 @@ class Document extends Model
|
||||
|
||||
public function uploadVersion($file)
|
||||
{
|
||||
$this->versions()->create([
|
||||
$version = $this->versions()->create([
|
||||
'file_path' => $file->store("projects/{$this->id}/versions"),
|
||||
'hash' => hash_file('sha256', $file),
|
||||
'version' => $this->versions()->count() + 1,
|
||||
@@ -82,4 +114,9 @@ class Document extends Model
|
||||
->logUnguarded();
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,9 +2,320 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class DocumentVersion extends Model
|
||||
{
|
||||
//
|
||||
}
|
||||
use HasFactory;
|
||||
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $fillable = [
|
||||
'document_id',
|
||||
'file_path',
|
||||
'hash',
|
||||
'version',
|
||||
'user_id',
|
||||
'changes',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that should be cast.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
protected $casts = [
|
||||
'changes' => 'array',
|
||||
'version' => 'integer',
|
||||
'created_at' => 'datetime',
|
||||
'updated_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that should be appended to the model's array form.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $appends = [
|
||||
'file_url',
|
||||
'file_size_formatted',
|
||||
'created_at_formatted',
|
||||
];
|
||||
|
||||
/**
|
||||
* Boot function for model events
|
||||
*/
|
||||
protected static function boot()
|
||||
{
|
||||
parent::boot();
|
||||
|
||||
static::creating(function ($model) {
|
||||
// Asegurar que la versión sea incremental para el mismo documento
|
||||
if (empty($model->version)) {
|
||||
$lastVersion = self::where('document_id', $model->document_id)
|
||||
->max('version');
|
||||
$model->version = $lastVersion ? $lastVersion + 1 : 1;
|
||||
}
|
||||
});
|
||||
|
||||
static::deleting(function ($model) {
|
||||
// No eliminar el archivo físico si hay otras versiones que lo usan
|
||||
$sameFileCount = self::where('file_path', $model->file_path)
|
||||
->where('id', '!=', $model->id)
|
||||
->count();
|
||||
|
||||
if ($sameFileCount === 0 && Storage::exists($model->file_path)) {
|
||||
Storage::delete($model->file_path);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the document that owns the version.
|
||||
*/
|
||||
public function document(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Document::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the user who created the version.
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file URL for the version.
|
||||
*/
|
||||
public function getFileUrlAttribute(): string
|
||||
{
|
||||
return Storage::url($this->file_path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file size in a human-readable format.
|
||||
*/
|
||||
public function getFileSizeFormattedAttribute(): string
|
||||
{
|
||||
if (!Storage::exists($this->file_path)) {
|
||||
return '0 B';
|
||||
}
|
||||
|
||||
$bytes = Storage::size($this->file_path);
|
||||
|
||||
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
$index = 0;
|
||||
|
||||
while ($bytes >= 1024 && $index < count($units) - 1) {
|
||||
$bytes /= 1024;
|
||||
$index++;
|
||||
}
|
||||
|
||||
return round($bytes, 2) . ' ' . $units[$index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the actual file size in bytes.
|
||||
*/
|
||||
public function getFileSizeAttribute(): int
|
||||
{
|
||||
return Storage::exists($this->file_path) ? Storage::size($this->file_path) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get formatted created_at date.
|
||||
*/
|
||||
public function getCreatedAtFormattedAttribute(): string
|
||||
{
|
||||
return $this->created_at->format('d/m/Y H:i');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the version label (v1, v2, etc.)
|
||||
*/
|
||||
public function getVersionLabelAttribute(): string
|
||||
{
|
||||
return 'v' . $this->version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this is the current version of the document.
|
||||
*/
|
||||
public function getIsCurrentAttribute(): bool
|
||||
{
|
||||
return $this->document->current_version_id === $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get changes summary for display.
|
||||
*/
|
||||
public function getChangesSummaryAttribute(): string
|
||||
{
|
||||
if (empty($this->changes)) {
|
||||
return 'Sin cambios registrados';
|
||||
}
|
||||
|
||||
$changes = $this->changes;
|
||||
|
||||
if (is_array($changes)) {
|
||||
$summary = [];
|
||||
|
||||
if (isset($changes['annotations_count']) && $changes['annotations_count'] > 0) {
|
||||
$summary[] = $changes['annotations_count'] . ' anotación(es)';
|
||||
}
|
||||
|
||||
if (isset($changes['signatures_count']) && $changes['signatures_count'] > 0) {
|
||||
$summary[] = $changes['signatures_count'] . ' firma(s)';
|
||||
}
|
||||
|
||||
if (isset($changes['stamps_count']) && $changes['stamps_count'] > 0) {
|
||||
$summary[] = $changes['stamps_count'] . ' sello(s)';
|
||||
}
|
||||
|
||||
if (isset($changes['edited_by'])) {
|
||||
$summary[] = 'por ' . $changes['edited_by'];
|
||||
}
|
||||
|
||||
return implode(', ', $summary);
|
||||
}
|
||||
|
||||
return (string) $changes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope a query to only include versions of a specific document.
|
||||
*/
|
||||
public function scopeOfDocument($query, $documentId)
|
||||
{
|
||||
return $query->where('document_id', $documentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope a query to order versions by latest first.
|
||||
*/
|
||||
public function scopeLatestFirst($query)
|
||||
{
|
||||
return $query->orderBy('version', 'desc');
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope a query to order versions by oldest first.
|
||||
*/
|
||||
public function scopeOldestFirst($query)
|
||||
{
|
||||
return $query->orderBy('version', 'asc');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the previous version.
|
||||
*/
|
||||
public function getPreviousVersion(): ?self
|
||||
{
|
||||
return self::where('document_id', $this->document_id)
|
||||
->where('version', '<', $this->version)
|
||||
->orderBy('version', 'desc')
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the next version.
|
||||
*/
|
||||
public function getNextVersion(): ?self
|
||||
{
|
||||
return self::where('document_id', $this->document_id)
|
||||
->where('version', '>', $this->version)
|
||||
->orderBy('version', 'asc')
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file exists in storage.
|
||||
*/
|
||||
public function fileExists(): bool
|
||||
{
|
||||
return Storage::exists($this->file_path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get file content.
|
||||
*/
|
||||
public function getFileContent(): ?string
|
||||
{
|
||||
return $this->fileExists() ? Storage::get($this->file_path) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify file integrity using hash.
|
||||
*/
|
||||
public function verifyIntegrity(): bool
|
||||
{
|
||||
if (!$this->fileExists()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$currentHash = hash_file('sha256', Storage::path($this->file_path));
|
||||
return $currentHash === $this->hash;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new version from file content.
|
||||
*/
|
||||
public static function createFromContent(Document $document, string $content, array $changes = [], ?User $user = null): self
|
||||
{
|
||||
$user = $user ?: auth()->user();
|
||||
|
||||
// Calcular hash
|
||||
$hash = hash('sha256', $content);
|
||||
|
||||
// Determinar siguiente versión
|
||||
$lastVersion = self::where('document_id', $document->id)->max('version');
|
||||
$version = $lastVersion ? $lastVersion + 1 : 1;
|
||||
|
||||
// Guardar archivo
|
||||
$filePath = "documents/{$document->id}/versions/v{$version}.pdf";
|
||||
Storage::put($filePath, $content);
|
||||
|
||||
// Crear registro
|
||||
return self::create([
|
||||
'document_id' => $document->id,
|
||||
'file_path' => $filePath,
|
||||
'hash' => $hash,
|
||||
'version' => $version,
|
||||
'user_id' => $user->id,
|
||||
'changes' => $changes,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore this version as the current version.
|
||||
*/
|
||||
public function restoreAsCurrent(): bool
|
||||
{
|
||||
if (!$this->fileExists()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Crear una nueva versión idéntica a esta
|
||||
$content = $this->getFileContent();
|
||||
$newVersion = self::createFromContent(
|
||||
$this->document,
|
||||
$content,
|
||||
['restored_from' => 'v' . $this->version]
|
||||
);
|
||||
|
||||
// Actualizar documento para apuntar a la nueva versión
|
||||
$this->document->update([
|
||||
'current_version_id' => $newVersion->id
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -87,4 +87,109 @@ class Project extends Model
|
||||
{
|
||||
return $this->belongsTo(Company::class);
|
||||
}
|
||||
|
||||
// Agregar estas relaciones al modelo Project
|
||||
public function codingConfig()
|
||||
{
|
||||
return $this->hasOne(ProjectCodingConfig::class);
|
||||
}
|
||||
|
||||
public function documentStatuses()
|
||||
{
|
||||
//return $this->hasMany(ProjectDocumentStatus::class);
|
||||
}
|
||||
|
||||
public function defaultStatus()
|
||||
{
|
||||
//return $this->hasOne(ProjectDocumentStatus::class)->where('is_default', true);
|
||||
}
|
||||
|
||||
// Método para inicializar la configuración
|
||||
public function initializeSettings()
|
||||
{
|
||||
// Crear configuración de codificación si no existe
|
||||
if (!$this->codingConfig) {
|
||||
$this->codingConfig()->create([
|
||||
'format' => '[PROJECT]-[TYPE]-[YEAR]-[SEQUENCE]',
|
||||
'next_sequence' => 1,
|
||||
'year_format' => 'Y',
|
||||
'separator' => '-',
|
||||
'sequence_length' => 4,
|
||||
'auto_generate' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
// Crear estados predeterminados si no existen
|
||||
/*
|
||||
if ($this->documentStatuses()->count() === 0) {
|
||||
$defaultStatuses = [
|
||||
[
|
||||
'name' => 'Borrador',
|
||||
'slug' => 'draft',
|
||||
'color' => '#6b7280', // Gris
|
||||
'order' => 1,
|
||||
'is_default' => true,
|
||||
'allow_upload' => true,
|
||||
'allow_edit' => true,
|
||||
'allow_delete' => true,
|
||||
'requires_approval' => false,
|
||||
'description' => 'Documento en proceso de creación',
|
||||
],
|
||||
[
|
||||
'name' => 'En Revisión',
|
||||
'slug' => 'in_review',
|
||||
'color' => '#f59e0b', // Ámbar
|
||||
'order' => 2,
|
||||
'is_default' => false,
|
||||
'allow_upload' => false,
|
||||
'allow_edit' => false,
|
||||
'allow_delete' => false,
|
||||
'requires_approval' => true,
|
||||
'description' => 'Documento en proceso de revisión',
|
||||
],
|
||||
[
|
||||
'name' => 'Aprobado',
|
||||
'slug' => 'approved',
|
||||
'color' => '#10b981', // Verde
|
||||
'order' => 3,
|
||||
'is_default' => false,
|
||||
'allow_upload' => false,
|
||||
'allow_edit' => false,
|
||||
'allow_delete' => false,
|
||||
'requires_approval' => false,
|
||||
'description' => 'Documento aprobado',
|
||||
],
|
||||
[
|
||||
'name' => 'Rechazado',
|
||||
'slug' => 'rejected',
|
||||
'color' => '#ef4444', // Rojo
|
||||
'order' => 4,
|
||||
'is_default' => false,
|
||||
'allow_upload' => true,
|
||||
'allow_edit' => true,
|
||||
'allow_delete' => false,
|
||||
'requires_approval' => false,
|
||||
'description' => 'Documento rechazado',
|
||||
],
|
||||
[
|
||||
'name' => 'Archivado',
|
||||
'slug' => 'archived',
|
||||
'color' => '#8b5cf6', // Violeta
|
||||
'order' => 5,
|
||||
'is_default' => false,
|
||||
'allow_upload' => false,
|
||||
'allow_edit' => false,
|
||||
'allow_delete' => false,
|
||||
'requires_approval' => false,
|
||||
'description' => 'Documento archivado',
|
||||
],
|
||||
];
|
||||
|
||||
foreach ($defaultStatuses as $status) {
|
||||
//$this->documentStatuses()->create($status);
|
||||
}
|
||||
}*/
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
|
||||
107
app/Models/ProjectCodingConfig.php
Normal file
107
app/Models/ProjectCodingConfig.php
Normal file
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ProjectCodingConfig extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'project_id',
|
||||
'format',
|
||||
'elements',
|
||||
'next_sequence',
|
||||
'year_format',
|
||||
'separator',
|
||||
'sequence_length',
|
||||
'auto_generate'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'elements' => 'array',
|
||||
'auto_generate' => 'boolean',
|
||||
];
|
||||
|
||||
public function project()
|
||||
{
|
||||
return $this->belongsTo(Project::class);
|
||||
}
|
||||
|
||||
// Método para generar un código de documento
|
||||
public function generateCode($type = 'DOC', $year = null)
|
||||
{
|
||||
$code = $this->format;
|
||||
|
||||
// Reemplazar variables
|
||||
$replacements = [
|
||||
'[PROJECT]' => $this->project->code ?? 'PROJ',
|
||||
'[TYPE]' => $type,
|
||||
'[YEAR]' => $year ?? date($this->year_format),
|
||||
'[MONTH]' => date('m'),
|
||||
'[DAY]' => date('d'),
|
||||
'[SEQUENCE]' => str_pad($this->next_sequence, $this->sequence_length, '0', STR_PAD_LEFT),
|
||||
'[RANDOM]' => strtoupper(substr(md5(uniqid()), 0, 6)),
|
||||
];
|
||||
|
||||
// Si hay elementos personalizados, agregarlos
|
||||
if (is_array($this->elements)) {
|
||||
foreach ($this->elements as $key => $value) {
|
||||
$replacements["[{$key}]"] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$code = str_replace(array_keys($replacements), array_values($replacements), $code);
|
||||
|
||||
// Incrementar secuencia
|
||||
if (strpos($this->format, '[SEQUENCE]') !== false && $this->auto_generate) {
|
||||
$this->increment('next_sequence');
|
||||
}
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
// Método para obtener elementos disponibles
|
||||
public static function getAvailableElements()
|
||||
{
|
||||
return [
|
||||
'project' => [
|
||||
'label' => 'Código del Proyecto',
|
||||
'description' => 'Código único del proyecto',
|
||||
'variable' => '[PROJECT]',
|
||||
],
|
||||
'type' => [
|
||||
'label' => 'Tipo de Documento',
|
||||
'description' => 'Tipo de documento (DOC, IMG, PDF, etc.)',
|
||||
'variable' => '[TYPE]',
|
||||
],
|
||||
'year' => [
|
||||
'label' => 'Año',
|
||||
'description' => 'Año actual en formato configurable',
|
||||
'variable' => '[YEAR]',
|
||||
],
|
||||
'month' => [
|
||||
'label' => 'Mes',
|
||||
'description' => 'Mes actual (01-12)',
|
||||
'variable' => '[MONTH]',
|
||||
],
|
||||
'day' => [
|
||||
'label' => 'Día',
|
||||
'description' => 'Día actual (01-31)',
|
||||
'variable' => '[DAY]',
|
||||
],
|
||||
'sequence' => [
|
||||
'label' => 'Secuencia',
|
||||
'description' => 'Número secuencial autoincremental',
|
||||
'variable' => '[SEQUENCE]',
|
||||
],
|
||||
'random' => [
|
||||
'label' => 'Aleatorio',
|
||||
'description' => 'Cadena aleatoria de 6 caracteres',
|
||||
'variable' => '[RANDOM]',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,9 @@ use App\Livewire\PdfViewer;
|
||||
use App\Livewire\ProjectShow;
|
||||
use App\Livewire\Toolbar;
|
||||
use App\View\Components\Multiselect;
|
||||
use App\Services\ProjectCodeService;
|
||||
use App\Services\ProjectCodeValidator;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
@@ -21,7 +24,16 @@ class AppServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
//
|
||||
// Registrar el Service
|
||||
$this->app->singleton(ProjectCodeService::class, function ($app) {
|
||||
return new ProjectCodeService(new ProjectCodeValidator([]));
|
||||
});
|
||||
|
||||
// O si prefieres, registrar el validador por separado
|
||||
$this->app->bind(ProjectCodeValidator::class, function ($app, $params) {
|
||||
// $params[0] contendría los datos del proyecto
|
||||
return new ProjectCodeValidator($params[0] ?? []);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
80
app/Services/ProjectCodeService.php
Normal file
80
app/Services/ProjectCodeService.php
Normal file
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Project;
|
||||
use App\Services\ProjectCodeValidator;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
class ProjectCodeService
|
||||
{
|
||||
protected ProjectCodeValidator $validator;
|
||||
|
||||
public function __construct(ProjectCodeValidator $validator)
|
||||
{
|
||||
$this->validator = $validator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Crea un validador para un proyecto específico
|
||||
*/
|
||||
public function forProject(Project $project): ProjectCodeValidator
|
||||
{
|
||||
// Si es un modelo Eloquent, convertir a array
|
||||
//$projectData = $project instanceof Project ? $project->toArray() : $project;
|
||||
|
||||
return new ProjectCodeValidator($project);
|
||||
}
|
||||
|
||||
/**
|
||||
* Valida un código rápidamente
|
||||
*/
|
||||
public function validate(Project $project, string $code): bool
|
||||
{
|
||||
$validator = $this->forProject($project);
|
||||
return $validator->validate($code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Analiza un código y devuelve detalles
|
||||
*/
|
||||
public function analyze(Project $project, string $code): array
|
||||
{
|
||||
$validator = $this->forProject($project);
|
||||
return $validator->analyze($code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Genera un nuevo código para el proyecto
|
||||
*/
|
||||
public function generate(
|
||||
Project $project,
|
||||
array $components,
|
||||
string $documentName
|
||||
): string
|
||||
{
|
||||
$validator = $this->forProject($project);
|
||||
return $validator->generateCode($components, $documentName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene la configuración de codificación
|
||||
*/
|
||||
public function getConfiguration(Project $project): array
|
||||
{
|
||||
$validator = $this->forProject($project);
|
||||
|
||||
return [
|
||||
'format' => $validator->getFormat(),
|
||||
'reference' => $validator->getReference(),
|
||||
'separator' => $validator->getSeparator(),
|
||||
'sequence_length' => $validator->getSequenceLength(),
|
||||
'components' => [
|
||||
'maker' => $validator->getAllowedCodesForComponent('maker'),
|
||||
'system' => $validator->getAllowedCodesForComponent('system'),
|
||||
'discipline' => $validator->getAllowedCodesForComponent('discipline'),
|
||||
'document_type' => $validator->getAllowedCodesForComponent('document_type'),
|
||||
]
|
||||
];
|
||||
}
|
||||
}
|
||||
543
app/Services/ProjectCodeValidator.php
Normal file
543
app/Services/ProjectCodeValidator.php
Normal file
@@ -0,0 +1,543 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
class ProjectCodeValidator
|
||||
{
|
||||
private array $projectData;
|
||||
private array $components;
|
||||
private string $separator;
|
||||
private string $reference;
|
||||
private int $sequenceLength;
|
||||
|
||||
/**
|
||||
* Constructor de la clase
|
||||
*
|
||||
* @param array|string $project Los datos del proyecto (array o JSON string)
|
||||
* @throws InvalidArgumentException Si los datos no son válidos
|
||||
*/
|
||||
public function __construct($project)
|
||||
{
|
||||
//print_r($project);
|
||||
|
||||
// Convertir string JSON a array si es necesario
|
||||
if (is_string($project)) {
|
||||
$project = json_decode($project, true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new InvalidArgumentException('JSON inválido: ' . json_last_error_msg());
|
||||
}
|
||||
}
|
||||
|
||||
if (!is_array($project)) {
|
||||
throw new InvalidArgumentException('Los datos del proyecto deben ser un array o JSON string');
|
||||
}
|
||||
|
||||
$this->projectData = $project;
|
||||
// Validar que exista la configuración de codificación
|
||||
/*if (!isset($this->projectData['codingConfig'])) {
|
||||
throw new InvalidArgumentException('El proyecto no tiene configuración de codificación');
|
||||
}*/
|
||||
|
||||
$this->initializeConfiguration();
|
||||
}
|
||||
|
||||
/**
|
||||
* Inicializa la configuración a partir de los datos del proyecto
|
||||
*/
|
||||
private function initializeConfiguration(): void
|
||||
{
|
||||
$codingConfig = $this->projectData['codingConfig'];
|
||||
|
||||
// Obtener componentes ordenados por 'order'
|
||||
$this->components = $codingConfig['elements']['components'] ?? [];
|
||||
usort($this->components, fn($a, $b) => $a['order'] <=> $b['order']);
|
||||
|
||||
$this->separator = $codingConfig['separator'] ?? '-';
|
||||
$this->reference = $this->projectData['reference'] ?? '';
|
||||
$this->sequenceLength = $codingConfig['sequence_length'] ?? 4;
|
||||
}
|
||||
|
||||
/**
|
||||
* Valida si un código cumple con la configuración de codificación
|
||||
*
|
||||
* @param string $code El código a validar
|
||||
* @return bool True si el código es válido
|
||||
*/
|
||||
public function validate(string $code): bool
|
||||
{
|
||||
// Validación básica: número de partes
|
||||
$parts = explode($this->separator, $code);
|
||||
if (count($parts) !== 7) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Validar referencia (primera parte)
|
||||
if ($parts[0] !== $this->reference) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Validar cada componente (partes 2-6)
|
||||
for ($i = 1; $i <= 5; $i++) {
|
||||
if (!$this->validateComponent($i - 1, $parts[$i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// La parte 7 (DOCUMENT_NAME) no tiene validación específica
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Valida un componente específico del código
|
||||
*
|
||||
* @param int $componentIndex Índice del componente (0-4)
|
||||
* @param string $value Valor a validar
|
||||
* @return bool True si el valor es válido para el componente
|
||||
*/
|
||||
private function validateComponent(int $componentIndex, string $value): bool
|
||||
{
|
||||
if (!isset($this->components[$componentIndex])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$component = $this->components[$componentIndex];
|
||||
$headerLabel = $component['headerLabel'] ?? '';
|
||||
|
||||
// Validar longitud máxima
|
||||
$maxLength = $component['data']['maxLength'] ?? null;
|
||||
if ($maxLength && strlen($value) > $maxLength) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Validar según el tipo de componente
|
||||
if ($headerLabel === 'Version') {
|
||||
return $this->validateVersionComponent($value);
|
||||
}
|
||||
|
||||
// Validar contra códigos permitidos
|
||||
return $this->validateAgainstAllowedCodes($component, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Valida el componente de versión
|
||||
*
|
||||
* @param string $value Valor de la versión
|
||||
* @return bool True si es válido
|
||||
*/
|
||||
private function validateVersionComponent(string $value): bool
|
||||
{
|
||||
// La versión debe ser numérica
|
||||
if (!is_numeric($value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// La versión debe tener la longitud especificada
|
||||
if (strlen($value) !== $this->sequenceLength) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Valida un valor contra los códigos permitidos de un componente
|
||||
*
|
||||
* @param array $component Configuración del componente
|
||||
* @param string $value Valor a validar
|
||||
* @return bool True si el valor está en los códigos permitidos
|
||||
*/
|
||||
private function validateAgainstAllowedCodes(array $component, string $value): bool
|
||||
{
|
||||
$documentTypes = $component['data']['documentTypes'] ?? [];
|
||||
|
||||
if (empty($documentTypes)) {
|
||||
return true; // No hay restricciones de códigos
|
||||
}
|
||||
|
||||
$allowedCodes = array_column($documentTypes, 'code');
|
||||
return in_array($value, $allowedCodes, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Realiza un análisis detallado de un código
|
||||
*
|
||||
* @param string $code El código a analizar
|
||||
* @return array Array con información detallada de la validación
|
||||
*/
|
||||
public function analyze(string $code): array
|
||||
{
|
||||
$result = [
|
||||
'is_valid' => false,
|
||||
'code' => $code,
|
||||
'parts' => [],
|
||||
'errors' => [],
|
||||
'warnings' => []
|
||||
];
|
||||
|
||||
// Dividir en partes
|
||||
$parts = explode($this->separator, $code);
|
||||
|
||||
// Verificar número de partes
|
||||
$expectedParts = 7;
|
||||
if (count($parts) !== $expectedParts) {
|
||||
$result['errors'][] = sprintf(
|
||||
'El código debe tener %d partes separadas por "%s", tiene %d',
|
||||
$expectedParts,
|
||||
$this->separator,
|
||||
count($parts)
|
||||
);
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Nombres de los componentes según el orden esperado
|
||||
$componentNames = [
|
||||
'reference',
|
||||
'maker',
|
||||
'system',
|
||||
'discipline',
|
||||
'document_type',
|
||||
'version',
|
||||
'document_name'
|
||||
];
|
||||
|
||||
// Analizar cada parte
|
||||
foreach ($parts as $index => $value) {
|
||||
$analysis = $this->analyzePart($index, $value);
|
||||
$analysis['name'] = $componentNames[$index] ?? 'unknown';
|
||||
|
||||
$result['parts'][] = $analysis;
|
||||
|
||||
if (!$analysis['is_valid']) {
|
||||
$result['errors'][] = sprintf(
|
||||
'Parte %d (%s): %s',
|
||||
$index + 1,
|
||||
$componentNames[$index],
|
||||
$analysis['error'] ?? 'Error desconocido'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$result['is_valid'] = empty($result['errors']);
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Analiza una parte específica del código
|
||||
*
|
||||
* @param int $partIndex Índice de la parte (0-6)
|
||||
* @param string $value Valor de la parte
|
||||
* @return array Análisis detallado de la parte
|
||||
*/
|
||||
private function analyzePart(int $partIndex, string $value): array
|
||||
{
|
||||
$analysis = [
|
||||
'index' => $partIndex,
|
||||
'value' => $value,
|
||||
'is_valid' => true,
|
||||
'expected' => '',
|
||||
'error' => '',
|
||||
'notes' => []
|
||||
];
|
||||
|
||||
switch ($partIndex) {
|
||||
case 0: // Referencia
|
||||
$analysis['expected'] = $this->reference;
|
||||
if ($value !== $this->reference) {
|
||||
$analysis['is_valid'] = false;
|
||||
$analysis['error'] = sprintf(
|
||||
'Referencia incorrecta. Esperado: %s',
|
||||
$this->reference
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 1: // Maker (componente 0)
|
||||
case 2: // System (componente 1)
|
||||
case 3: // Discipline (componente 2)
|
||||
case 4: // Document Type (componente 3)
|
||||
$componentIndex = $partIndex - 1;
|
||||
if (isset($this->components[$componentIndex])) {
|
||||
$component = $this->components[$componentIndex];
|
||||
$analysis = array_merge($analysis, $this->analyzeComponent($component, $value));
|
||||
}
|
||||
break;
|
||||
|
||||
case 5: // Version (componente 4)
|
||||
if (isset($this->components[4])) {
|
||||
$component = $this->components[4];
|
||||
$analysis = array_merge($analysis, $this->analyzeComponent($component, $value));
|
||||
|
||||
// Información adicional para la versión
|
||||
$analysis['notes'][] = sprintf(
|
||||
'Longitud de secuencia: %d',
|
||||
$this->sequenceLength
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 6: // Document Name
|
||||
$analysis['notes'][] = 'Nombre del documento (sin restricciones específicas)';
|
||||
break;
|
||||
|
||||
default:
|
||||
$analysis['is_valid'] = false;
|
||||
$analysis['error'] = 'Índice de parte no válido';
|
||||
break;
|
||||
}
|
||||
|
||||
return $analysis;
|
||||
}
|
||||
|
||||
/**
|
||||
* Analiza un componente específico
|
||||
*
|
||||
* @param array $component Configuración del componente
|
||||
* @param string $value Valor a analizar
|
||||
* @return array Análisis del componente
|
||||
*/
|
||||
private function analyzeComponent(array $component, string $value): array
|
||||
{
|
||||
$result = [
|
||||
'is_valid' => true,
|
||||
'expected' => '',
|
||||
'error' => '',
|
||||
'notes' => []
|
||||
];
|
||||
|
||||
$headerLabel = $component['headerLabel'] ?? '';
|
||||
$maxLength = $component['data']['maxLength'] ?? null;
|
||||
$documentTypes = $component['data']['documentTypes'] ?? [];
|
||||
|
||||
// Validar longitud
|
||||
if ($maxLength && strlen($value) > $maxLength) {
|
||||
$result['is_valid'] = false;
|
||||
$result['error'] = sprintf(
|
||||
'Longitud máxima excedida: %d (actual: %d)',
|
||||
$maxLength,
|
||||
strlen($value)
|
||||
);
|
||||
}
|
||||
|
||||
// Validar tipo de componente
|
||||
if ($headerLabel === 'Version') {
|
||||
if (!is_numeric($value)) {
|
||||
$result['is_valid'] = false;
|
||||
$result['error'] = 'Debe ser numérico';
|
||||
} elseif (strlen($value) !== $this->sequenceLength) {
|
||||
$result['is_valid'] = false;
|
||||
$result['error'] = sprintf(
|
||||
'Longitud incorrecta. Esperado: %d, Actual: %d',
|
||||
$this->sequenceLength,
|
||||
strlen($value)
|
||||
);
|
||||
}
|
||||
|
||||
$result['expected'] = sprintf('Número de %d dígitos', $this->sequenceLength);
|
||||
} else {
|
||||
// Obtener códigos permitidos
|
||||
$allowedCodes = array_column($documentTypes, 'code');
|
||||
if (!empty($allowedCodes) && !in_array($value, $allowedCodes, true)) {
|
||||
$result['is_valid'] = false;
|
||||
$result['error'] = sprintf(
|
||||
'Código no permitido. Permitidos: %s',
|
||||
implode(', ', $allowedCodes)
|
||||
);
|
||||
}
|
||||
|
||||
$result['expected'] = $allowedCodes ? implode('|', $allowedCodes) : 'Sin restricciones';
|
||||
$result['notes'][] = sprintf('Componente: %s', $headerLabel);
|
||||
|
||||
// Agregar etiquetas de los códigos permitidos
|
||||
$labels = [];
|
||||
foreach ($documentTypes as $type) {
|
||||
if (isset($type['label'])) {
|
||||
$labels[] = sprintf('%s = %s', $type['code'], $type['label']);
|
||||
}
|
||||
}
|
||||
if (!empty($labels)) {
|
||||
$result['notes'][] = 'Significados: ' . implode(', ', $labels);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Genera un código válido basado en la configuración
|
||||
*
|
||||
* @param array $componentsValues Valores para cada componente
|
||||
* @param string $documentName Nombre del documento
|
||||
* @return string Código generado
|
||||
* @throws InvalidArgumentException Si los valores no son válidos
|
||||
*/
|
||||
public function generateCode(array $componentsValues, string $documentName): string
|
||||
{
|
||||
// Validar que tengamos valores para todos los componentes
|
||||
$requiredComponents = 5; // Maker, System, Discipline, Document Type, Version
|
||||
|
||||
if (count($componentsValues) < $requiredComponents) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf('Se requieren valores para %d componentes', $requiredComponents)
|
||||
);
|
||||
}
|
||||
|
||||
// Construir las partes del código
|
||||
$parts = [$this->reference];
|
||||
|
||||
// Agregar componentes validados
|
||||
for ($i = 0; $i < $requiredComponents; $i++) {
|
||||
$value = $componentsValues[$i];
|
||||
|
||||
if (!$this->validateComponent($i, $value)) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf('Valor inválido para componente %d: %s', $i, $value)
|
||||
);
|
||||
}
|
||||
|
||||
$parts[] = $value;
|
||||
}
|
||||
|
||||
// Agregar nombre del documento
|
||||
$parts[] = $this->sanitizeDocumentName($documentName);
|
||||
|
||||
return implode($this->separator, $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitiza el nombre del documento para usarlo en el código
|
||||
*
|
||||
* @param string $documentName Nombre del documento
|
||||
* @return string Nombre sanitizado
|
||||
*/
|
||||
private function sanitizeDocumentName(string $documentName): string
|
||||
{
|
||||
// Reemplazar caracteres no deseados
|
||||
$sanitized = preg_replace('/[^a-zA-Z0-9_-]/', '_', $documentName);
|
||||
|
||||
// Limitar longitud si es necesario
|
||||
return substr($sanitized, 0, 50);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene los códigos permitidos para un componente específico
|
||||
*
|
||||
* @param string $componentName Nombre del componente (maker, system, discipline, document_type)
|
||||
* @return array Array de códigos permitidos
|
||||
*/
|
||||
public function getAllowedCodesForComponent(string $componentName): array
|
||||
{
|
||||
$componentMap = [
|
||||
'maker' => 0,
|
||||
'system' => 1,
|
||||
'discipline' => 2,
|
||||
'document_type' => 3
|
||||
];
|
||||
|
||||
if (!isset($componentMap[$componentName])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$index = $componentMap[$componentName];
|
||||
if (!isset($this->components[$index])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$component = $this->components[$index];
|
||||
$documentTypes = $component['data']['documentTypes'] ?? [];
|
||||
|
||||
$result = [];
|
||||
foreach ($documentTypes as $type) {
|
||||
$result[] = [
|
||||
'code' => $type['code'],
|
||||
'label' => $type['label'] ?? $type['code'],
|
||||
'max_length' => $type['max_length'] ?? $component['data']['maxLength'] ?? null
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene el formato de codificación
|
||||
*
|
||||
* @return string Formato de codificación
|
||||
*/
|
||||
public function getFormat(): string
|
||||
{
|
||||
return $this->projectData['coding_config']['format'] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene la referencia del proyecto
|
||||
*
|
||||
* @return string Referencia del proyecto
|
||||
*/
|
||||
public function getReference(): string
|
||||
{
|
||||
return $this->reference;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene el separador usado en la codificación
|
||||
*
|
||||
* @return string Separador
|
||||
*/
|
||||
public function getSeparator(): string
|
||||
{
|
||||
return $this->separator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene la longitud de secuencia para la versión
|
||||
*
|
||||
* @return int Longitud de secuencia
|
||||
*/
|
||||
public function getSequenceLength(): int
|
||||
{
|
||||
return $this->sequenceLength;
|
||||
}
|
||||
}
|
||||
|
||||
// Ejemplo de uso:
|
||||
// Suponiendo que $projectDataVariable es la variable que contiene tus datos del proyecto
|
||||
/*
|
||||
$validator = new ProjectCodeValidator($projectDataVariable);
|
||||
|
||||
// Validar un código
|
||||
$codigo = "SOGOS0001-SOGOS-PV0-CV-DWG-0001-InformeTecnico";
|
||||
if ($validator->validate($codigo)) {
|
||||
echo "✅ Código válido\n";
|
||||
} else {
|
||||
echo "❌ Código inválido\n";
|
||||
}
|
||||
|
||||
// Analizar un código detalladamente
|
||||
$analisis = $validator->analyze($codigo);
|
||||
echo "Código analizado: " . $analisis['code'] . "\n";
|
||||
echo "Válido: " . ($analisis['is_valid'] ? 'Sí' : 'No') . "\n";
|
||||
|
||||
if (!$analisis['is_valid']) {
|
||||
echo "Errores:\n";
|
||||
foreach ($analisis['errors'] as $error) {
|
||||
echo "- $error\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Generar un código nuevo
|
||||
try {
|
||||
$componentes = ['SOGOS', 'PV0', 'CV', 'DWG', '0014'];
|
||||
$nuevoCodigo = $validator->generateCode($componentes, 'PlanosGenerales');
|
||||
echo "Código generado: $nuevoCodigo\n";
|
||||
} catch (InvalidArgumentException $e) {
|
||||
echo "Error al generar código: " . $e->getMessage() . "\n";
|
||||
}
|
||||
|
||||
// Obtener códigos permitidos para un componente
|
||||
$systemCodes = $validator->getAllowedCodesForComponent('system');
|
||||
echo "Códigos permitidos para System:\n";
|
||||
foreach ($systemCodes as $code) {
|
||||
echo "- {$code['code']}: {$code['label']}\n";
|
||||
}
|
||||
*/
|
||||
@@ -16,6 +16,7 @@
|
||||
"livewire/flux": "^2.1.1",
|
||||
"livewire/volt": "^1.7.0",
|
||||
"luvi-ui/laravel-luvi": "^0.6.0",
|
||||
"rappasoft/laravel-livewire-tables": "^3.7",
|
||||
"spatie/laravel-activitylog": "^4.10",
|
||||
"spatie/laravel-medialibrary": "^11.12",
|
||||
"spatie/laravel-permission": "^6.17",
|
||||
|
||||
233
composer.lock
generated
233
composer.lock
generated
@@ -4,8 +4,158 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "3dbc041e01a11822ed0b28f2eb838625",
|
||||
"content-hash": "066300d1440ecb28d9ef82afc2c057f2",
|
||||
"packages": [
|
||||
{
|
||||
"name": "blade-ui-kit/blade-heroicons",
|
||||
"version": "2.6.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/driesvints/blade-heroicons.git",
|
||||
"reference": "4553b2a1f6c76f0ac7f3bc0de4c0cfa06a097d19"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/driesvints/blade-heroicons/zipball/4553b2a1f6c76f0ac7f3bc0de4c0cfa06a097d19",
|
||||
"reference": "4553b2a1f6c76f0ac7f3bc0de4c0cfa06a097d19",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"blade-ui-kit/blade-icons": "^1.6",
|
||||
"illuminate/support": "^9.0|^10.0|^11.0|^12.0",
|
||||
"php": "^8.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"orchestra/testbench": "^7.0|^8.0|^9.0|^10.0",
|
||||
"phpunit/phpunit": "^9.0|^10.5|^11.0"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"laravel": {
|
||||
"providers": [
|
||||
"BladeUI\\Heroicons\\BladeHeroiconsServiceProvider"
|
||||
]
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"BladeUI\\Heroicons\\": "src"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Dries Vints",
|
||||
"homepage": "https://driesvints.com"
|
||||
}
|
||||
],
|
||||
"description": "A package to easily make use of Heroicons in your Laravel Blade views.",
|
||||
"homepage": "https://github.com/blade-ui-kit/blade-heroicons",
|
||||
"keywords": [
|
||||
"Heroicons",
|
||||
"blade",
|
||||
"laravel"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/driesvints/blade-heroicons/issues",
|
||||
"source": "https://github.com/driesvints/blade-heroicons/tree/2.6.0"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"url": "https://github.com/sponsors/driesvints",
|
||||
"type": "github"
|
||||
},
|
||||
{
|
||||
"url": "https://www.paypal.com/paypalme/driesvints",
|
||||
"type": "paypal"
|
||||
}
|
||||
],
|
||||
"time": "2025-02-13T20:53:33+00:00"
|
||||
},
|
||||
{
|
||||
"name": "blade-ui-kit/blade-icons",
|
||||
"version": "1.8.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/driesvints/blade-icons.git",
|
||||
"reference": "7b743f27476acb2ed04cb518213d78abe096e814"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/driesvints/blade-icons/zipball/7b743f27476acb2ed04cb518213d78abe096e814",
|
||||
"reference": "7b743f27476acb2ed04cb518213d78abe096e814",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"illuminate/contracts": "^8.0|^9.0|^10.0|^11.0|^12.0",
|
||||
"illuminate/filesystem": "^8.0|^9.0|^10.0|^11.0|^12.0",
|
||||
"illuminate/support": "^8.0|^9.0|^10.0|^11.0|^12.0",
|
||||
"illuminate/view": "^8.0|^9.0|^10.0|^11.0|^12.0",
|
||||
"php": "^7.4|^8.0",
|
||||
"symfony/console": "^5.3|^6.0|^7.0",
|
||||
"symfony/finder": "^5.3|^6.0|^7.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"mockery/mockery": "^1.5.1",
|
||||
"orchestra/testbench": "^6.0|^7.0|^8.0|^9.0|^10.0",
|
||||
"phpunit/phpunit": "^9.0|^10.5|^11.0"
|
||||
},
|
||||
"bin": [
|
||||
"bin/blade-icons-generate"
|
||||
],
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"laravel": {
|
||||
"providers": [
|
||||
"BladeUI\\Icons\\BladeIconsServiceProvider"
|
||||
]
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"files": [
|
||||
"src/helpers.php"
|
||||
],
|
||||
"psr-4": {
|
||||
"BladeUI\\Icons\\": "src"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Dries Vints",
|
||||
"homepage": "https://driesvints.com"
|
||||
}
|
||||
],
|
||||
"description": "A package to easily make use of icons in your Laravel Blade views.",
|
||||
"homepage": "https://github.com/blade-ui-kit/blade-icons",
|
||||
"keywords": [
|
||||
"blade",
|
||||
"icons",
|
||||
"laravel",
|
||||
"svg"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/blade-ui-kit/blade-icons/issues",
|
||||
"source": "https://github.com/blade-ui-kit/blade-icons"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"url": "https://github.com/sponsors/driesvints",
|
||||
"type": "github"
|
||||
},
|
||||
{
|
||||
"url": "https://www.paypal.com/paypalme/driesvints",
|
||||
"type": "paypal"
|
||||
}
|
||||
],
|
||||
"time": "2025-02-13T20:35:06+00:00"
|
||||
},
|
||||
{
|
||||
"name": "brick/math",
|
||||
"version": "0.12.3",
|
||||
@@ -3999,6 +4149,87 @@
|
||||
],
|
||||
"time": "2024-04-27T21:32:50+00:00"
|
||||
},
|
||||
{
|
||||
"name": "rappasoft/laravel-livewire-tables",
|
||||
"version": "v3.7.3",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/rappasoft/laravel-livewire-tables.git",
|
||||
"reference": "74beb4c2672e024000d41ecad8a17b4ab8c934bd"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/rappasoft/laravel-livewire-tables/zipball/74beb4c2672e024000d41ecad8a17b4ab8c934bd",
|
||||
"reference": "74beb4c2672e024000d41ecad8a17b4ab8c934bd",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"blade-ui-kit/blade-heroicons": "^2.1",
|
||||
"illuminate/contracts": "^10.0|^11.0|^12.0",
|
||||
"illuminate/support": "^10.0|^11.0|^12.0",
|
||||
"livewire/livewire": "^3.0|dev-main",
|
||||
"php": "^8.1|^8.2|^8.3|^8.4"
|
||||
},
|
||||
"require-dev": {
|
||||
"brianium/paratest": "^5.0|^6.0|^7.0|^8.0|^9.0",
|
||||
"ext-sqlite3": "*",
|
||||
"larastan/larastan": "^2.6|^3.0",
|
||||
"laravel/pint": "^1.10",
|
||||
"monolog/monolog": "*",
|
||||
"nunomaduro/collision": "^6.0|^7.0|^8.0|^9.0",
|
||||
"orchestra/testbench": "^7.0|^8.0|^9.0|^10.0",
|
||||
"phpunit/phpunit": "^9.0|^10.0|^11.0|^12.0"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"laravel": {
|
||||
"providers": [
|
||||
"Rappasoft\\LaravelLivewireTables\\LaravelLivewireTablesServiceProvider"
|
||||
]
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Rappasoft\\LaravelLivewireTables\\": "src"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Anthony Rappa",
|
||||
"email": "rappa819@gmail.com",
|
||||
"role": "Developer"
|
||||
},
|
||||
{
|
||||
"name": "Joe McElwee",
|
||||
"email": "joe@lowerrocklabs.com",
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"description": "A dynamic table component for Laravel Livewire",
|
||||
"homepage": "https://github.com/rappasoft/laravel-livewire-tables",
|
||||
"keywords": [
|
||||
"datatables",
|
||||
"laravel",
|
||||
"livewire",
|
||||
"rappasoft",
|
||||
"tables"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/rappasoft/laravel-livewire-tables/issues",
|
||||
"source": "https://github.com/rappasoft/laravel-livewire-tables/tree/v3.7.3"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"url": "https://github.com/rappasoft",
|
||||
"type": "github"
|
||||
}
|
||||
],
|
||||
"time": "2025-05-03T02:24:46+00:00"
|
||||
},
|
||||
{
|
||||
"name": "spatie/image",
|
||||
"version": "3.8.3",
|
||||
|
||||
@@ -13,10 +13,23 @@ return new class extends Migration
|
||||
{
|
||||
Schema::create('documents', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('code');
|
||||
$table->string('name');
|
||||
$table->enum('status', ['pending', 'in_review', 'approved', 'rejected'])->default('pending');
|
||||
|
||||
$table->foreignId('project_id')->constrained();
|
||||
$table->foreignId('folder_id')->nullable()->constrained();
|
||||
|
||||
$table->string('area', 2)->nullable();
|
||||
$table->string('discipline', 2)->nullable();
|
||||
$table->string('document_type', 3)->nullable();
|
||||
|
||||
$table->string('version')->nullable()->default("0");
|
||||
$table->string('revision')->nullable()->default("0");
|
||||
|
||||
$table->enum('status', [0, 1, 2, 3, 4])->default(0); //['pending', 'in_review', 'approved', 'rejected']
|
||||
|
||||
$table->string('issuer_id')->nullable();
|
||||
$table->date('entry_date')->nullable()->default(now());
|
||||
//$table->foreignId('current_version_id')->nullable()->constrained('document_versions');
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
@@ -15,11 +15,19 @@ return new class extends Migration
|
||||
$table->id();
|
||||
$table->foreignId('document_id')->constrained();
|
||||
$table->string('file_path');
|
||||
$table->string('hash');
|
||||
$table->string('hash'); // SHA256 hash for integrity verification
|
||||
$table->unsignedInteger('version')->default(1);
|
||||
$table->unsignedInteger('review')->default(0);
|
||||
$table->foreignId('user_id')->constrained();
|
||||
$table->text('changes')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
// Unique constraint to ensure one version per document
|
||||
$table->unique(['document_id', 'version', 'review']);
|
||||
|
||||
// Index for faster queries
|
||||
$table->index(['document_id', 'version']);
|
||||
$table->index('hash');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('documents', function (Blueprint $table) {
|
||||
$table->string('code')->before('name');
|
||||
$table->string('revision')->nullable();
|
||||
$table->string('version')->nullable();
|
||||
$table->string('discipline')->nullable();
|
||||
$table->string('document_type')->nullable();
|
||||
$table->string('issuer')->nullable();
|
||||
$table->date('entry_date')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('documents', function (Blueprint $table) {
|
||||
$table->dropColumn(['code', 'revision', 'version', 'discipline', 'document_type', 'issuer', 'entry_date']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('project_coding_configs', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('project_id')->constrained()->onDelete('cascade')->unique();
|
||||
$table->string('format')->default('[PROJECT]-[TYPE]-[YEAR]-[SEQUENCE]');
|
||||
$table->json('elements')->nullable(); // Elementos configurados del código
|
||||
$table->integer('next_sequence')->default(1);
|
||||
$table->string('year_format')->default('Y'); // Y, y, YY, yyyy
|
||||
$table->string('separator')->default('-');
|
||||
$table->integer('sequence_length')->default(4);
|
||||
$table->boolean('auto_generate')->default(true);
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('project_coding_configs');
|
||||
}
|
||||
};
|
||||
1156
package-lock.json
generated
1156
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -12,7 +12,9 @@
|
||||
"autoprefixer": "^10.4.20",
|
||||
"axios": "^1.7.4",
|
||||
"concurrently": "^9.0.1",
|
||||
"fabric": "^6.7.1",
|
||||
"laravel-vite-plugin": "^1.0",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"pdfjs-dist": "^5.2.133",
|
||||
"quill": "^2.0.3",
|
||||
"tailwindcss": "^4.0.7",
|
||||
|
||||
File diff suppressed because one or more lines are too long
16934
resources/js/pdfjs-5.2.133-dist/web/viewer.js
Normal file
16934
resources/js/pdfjs-5.2.133-dist/web/viewer.js
Normal file
File diff suppressed because one or more lines are too long
@@ -134,6 +134,45 @@
|
||||
{{ __('Create User') }}
|
||||
</flux:navlist.item>
|
||||
</flux:navlist.group>
|
||||
|
||||
<flux:separator />
|
||||
<!-- Sección de Empresas -->
|
||||
<flux:navlist.group :heading="__('Empresas')" expandable>
|
||||
<flux:navlist.item
|
||||
icon="building-office-2"
|
||||
:href="route('companies.index')"
|
||||
wire:navigate
|
||||
>
|
||||
{{ __('List companies') }}
|
||||
</flux:navlist.item>
|
||||
|
||||
<flux:navlist.item
|
||||
icon="building-office"
|
||||
:href="route('companies.create')"
|
||||
wire:navigate
|
||||
>
|
||||
{{ __('Create new company') }}
|
||||
</flux:navlist.item>
|
||||
</flux:navlist.group>
|
||||
|
||||
<flux:separator />
|
||||
<flux:navlist.group :heading="__('Projects')" expandable>
|
||||
<flux:navlist.item
|
||||
icon="folder"
|
||||
:href="route('projects.index')"
|
||||
wire:navigate
|
||||
>
|
||||
{{ __('List Projects') }}
|
||||
</flux:navlist.item>
|
||||
|
||||
<flux:navlist.item
|
||||
icon="plus"
|
||||
:href="route('projects.create')"
|
||||
wire:navigate
|
||||
>
|
||||
{{ __('Create Project') }}
|
||||
</flux:navlist.item>
|
||||
</flux:navlist.group>
|
||||
</flux:navlist>
|
||||
|
||||
@endpush
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
<x-layouts.app :title="__('Show document')">
|
||||
<div class="grid grid-cols-2 gap-x-4 h-screen bg-gray-100">
|
||||
<div class="grid grid-cols-2 gap-x-0 h-screen bg-gray-100">
|
||||
<!-- Zona izquierda - Visualizador de documentos -->
|
||||
<div class="bg-gray-100 relative">
|
||||
<div class="bg-gray-500 relative">
|
||||
<div id="outerContainer">
|
||||
|
||||
<div id="sidebarContainer">
|
||||
<div id="toolbarSidebar" class="toolbarHorizontalGroup">
|
||||
<div id="toolbarSidebarLeft">
|
||||
@@ -49,8 +48,6 @@
|
||||
|
||||
|
||||
<div id="mainContainer">
|
||||
|
||||
|
||||
<div class="toolbar">
|
||||
<div id="toolbarContainer">
|
||||
<div id="toolbarViewer" class="toolbarHorizontalGroup">
|
||||
@@ -704,7 +701,46 @@
|
||||
</div>
|
||||
|
||||
<!-- Zona derecha - Tabs de información -->
|
||||
<div x-data="{ activeTab: 'properties' }" class="flex flex-col bg-white">
|
||||
<div x-data="{
|
||||
activeTab: 'properties',
|
||||
// Estado para el treeview de versiones y revisiones
|
||||
openVersion: null,
|
||||
openRevision: {},
|
||||
|
||||
toggleVersion(versionNumber) {
|
||||
this.openVersion = this.openVersion === versionNumber ? null : versionNumber;
|
||||
},
|
||||
|
||||
toggleRevision(versionNumber, revisionNumber) {
|
||||
const key = `v${versionNumber}r${revisionNumber}`;
|
||||
this.openRevision[key] = !this.openRevision[key];
|
||||
// Para asegurar la reactividad
|
||||
this.openRevision = {...this.openRevision};
|
||||
},
|
||||
|
||||
// Función para cargar PDF en el visor
|
||||
loadPdfInViewer(pdfUrl) {
|
||||
if (pdfUrl) {
|
||||
// Usar PDFViewerApplication para cargar el nuevo PDF
|
||||
PDFViewerApplication.open(pdfUrl).then(() => {
|
||||
console.log('PDF cargado en el visor:', pdfUrl);
|
||||
|
||||
// Opcional: Mostrar un mensaje de éxito
|
||||
this.showNotification('PDF cargado en el visor', 'success');
|
||||
}).catch(error => {
|
||||
console.error('Error al cargar el PDF:', error);
|
||||
this.showNotification('Error al cargar el PDF', 'error');
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Función auxiliar para mostrar notificaciones
|
||||
showNotification(message, type = 'info') {
|
||||
// Puedes implementar un sistema de notificaciones toast aquí
|
||||
// Por ahora usamos alert para simplificar
|
||||
alert(message);
|
||||
}
|
||||
}" class="flex flex-col bg-white">
|
||||
<!-- Tabs de navegación -->
|
||||
<div class="border-b border-gray-200">
|
||||
<nav class="flex space-x-4 px-4 pt-2">
|
||||
@@ -752,20 +788,190 @@
|
||||
|
||||
<!-- Seguridad -->
|
||||
<div x-show="activeTab === 'security'" x-cloak>
|
||||
implementar
|
||||
Implementar
|
||||
</div>
|
||||
|
||||
<!-- Comentarios -->
|
||||
<div x-show="activeTab === 'comments'" x-cloak>
|
||||
|
||||
Implementar
|
||||
</div>
|
||||
|
||||
<!-- Historial -->
|
||||
<div x-show="activeTab === 'history'" x-cloak>
|
||||
<div class="space-y-4">
|
||||
@foreach($document->versions as $version)
|
||||
<x-version-item :version="$version" />
|
||||
<div class="space-y-2">
|
||||
@php
|
||||
// Agrupar las versiones por número de versión
|
||||
$groupedVersions = $document->versions->groupBy('version');
|
||||
@endphp
|
||||
|
||||
@foreach($groupedVersions as $versionNumber => $versions)
|
||||
<div class="border rounded-lg">
|
||||
<!-- Cabecera de la Versión (Rama principal) -->
|
||||
<div class="flex items-center justify-between p-4 bg-gray-50 cursor-pointer"
|
||||
@click="toggleVersion({{ $versionNumber }})">
|
||||
<div class="flex items-center space-x-3">
|
||||
<svg :class="{'rotate-90': openVersion === {{ $versionNumber }}}"
|
||||
class="w-4 h-4 transition-transform duration-200"
|
||||
fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
|
||||
</svg>
|
||||
<div class="flex items-center space-x-2">
|
||||
<svg class="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/>
|
||||
</svg>
|
||||
<span class="font-medium text-gray-800">
|
||||
Versión {{ $versionNumber }}
|
||||
</span>
|
||||
</div>
|
||||
<span class="text-sm text-gray-500 bg-gray-200 px-2 py-1 rounded-full">
|
||||
{{ $versions->count() }} revisión{{ $versions->count() > 1 ? 'es' : '' }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex items-center space-x-4">
|
||||
<span class="text-sm text-gray-500">
|
||||
{{ $versions->sortBy('created_at')->first()->created_at_formatted }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Contenido de la Versión - Revisiones como ramas hijas -->
|
||||
<div x-show="openVersion === {{ $versionNumber }}" class="border-t bg-white">
|
||||
<div class="space-y-0">
|
||||
@foreach($versions->sortByDesc('review') as $revisionIndex => $revision)
|
||||
<div class="border-b last:border-b-0">
|
||||
<!-- Cabecera de la Revisión (Rama hija) -->
|
||||
<div class="flex items-center justify-between p-4 pl-8 cursor-pointer hover:bg-gray-50"
|
||||
@click="toggleRevision({{ $versionNumber }}, {{ $revision->review }})">
|
||||
<div class="flex items-center space-x-3">
|
||||
<svg :class="{'rotate-90': openRevision['v{{ $versionNumber }}r{{ $revision->review }}']}"
|
||||
class="w-4 h-4 transition-transform duration-200"
|
||||
fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
|
||||
</svg>
|
||||
<div class="flex items-center space-x-2">
|
||||
<svg class="w-4 h-4 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
|
||||
</svg>
|
||||
<span class="font-medium text-gray-700">
|
||||
Revisión {{ $revision->review }}
|
||||
</span>
|
||||
@if($revision->review == 0)
|
||||
<span class="px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded-full">Original</span>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center space-x-4">
|
||||
<button @click.stop="loadPdfInViewer('{{ $revision->file_url }}')"
|
||||
class="inline-flex items-center px-3 py-1 text-sm bg-green-600 text-white rounded hover:bg-green-700"
|
||||
title="Cargar en visor PDF">
|
||||
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
|
||||
</svg>
|
||||
Cargar en Visor
|
||||
</button>
|
||||
<span class="text-sm text-gray-500">{{ $revision->created_at_formatted }}</span>
|
||||
<span class="text-sm text-gray-400">{{ $revision->file_size_formatted }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Detalles de la Revisión (Contenido expandible) -->
|
||||
<div x-show="openRevision['v{{ $versionNumber }}r{{ $revision->review }}']"
|
||||
class="bg-gray-50 border-t">
|
||||
<div class="p-4 pl-12 space-y-4">
|
||||
<!-- Información básica -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<x-property-item label="ID" :value="$revision->id" />
|
||||
<x-property-item label="Document ID" :value="$revision->document_id" />
|
||||
<x-property-item label="Usuario" :value="$revision->user->name ?? 'Usuario no disponible'" />
|
||||
</div>
|
||||
|
||||
<!-- Archivo -->
|
||||
<div>
|
||||
<div class="mb-2">
|
||||
<span class="block text-sm font-medium text-gray-700">Archivo</span>
|
||||
<div class="mt-1 flex items-center space-x-2">
|
||||
<x-property-item label="Ruta" :value="$revision->file_path" />
|
||||
<button @click="loadPdfInViewer('{{ $revision->file_url }}')"
|
||||
class="inline-flex items-center px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700">
|
||||
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
|
||||
</svg>
|
||||
Cargar en Visor
|
||||
</button>
|
||||
<a href="{{ $revision->file_url }}" target="_blank"
|
||||
class="inline-flex items-center px-3 py-1 text-sm bg-gray-600 text-white rounded hover:bg-gray-700">
|
||||
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
|
||||
</svg>
|
||||
Descargar
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Cambios -->
|
||||
<div>
|
||||
<span class="block text-sm font-medium text-gray-700 mb-2">Cambios realizados</span>
|
||||
@if(!empty($revision->changes) && count($revision->changes) > 0)
|
||||
<div class="bg-white rounded border p-3">
|
||||
<ul class="list-disc list-inside text-sm text-gray-600 space-y-1">
|
||||
@foreach($revision->changes as $change)
|
||||
<li class="hover:text-gray-800">{{ $change }}</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
</div>
|
||||
@else
|
||||
<div class="bg-white rounded border p-3 text-sm text-gray-500">
|
||||
No hay cambios registrados en esta revisión
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<!-- Fechas -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2 border-t">
|
||||
<x-property-item label="Fecha de creación" :value="$revision->created_at_formatted" />
|
||||
<x-property-item label="Última actualización"
|
||||
:value="$revision->updated_at ? \Carbon\Carbon::parse($revision->updated_at)->format('d/m/Y H:i') : 'N/A'" />
|
||||
</div>
|
||||
|
||||
<!-- Información adicional del usuario -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2 border-t">
|
||||
<div>
|
||||
<span class="block text-sm font-medium text-gray-700">Creado por</span>
|
||||
<div class="flex items-center space-x-2 mt-1">
|
||||
@if(isset($revision->user->avatar))
|
||||
<img src="{{ $revision->user->avatar }}" alt="{{ $revision->user->name }}" class="w-6 h-6 rounded-full">
|
||||
@else
|
||||
<div class="w-6 h-6 bg-gray-300 rounded-full flex items-center justify-center">
|
||||
<span class="text-xs text-gray-600">{{ substr($revision->user->name ?? 'U', 0, 1) }}</span>
|
||||
</div>
|
||||
@endif
|
||||
<span class="text-sm text-gray-600">{{ $revision->user->name ?? 'Usuario no disponible' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span class="block text-sm font-medium text-gray-700">Email</span>
|
||||
<span class="text-sm text-gray-600">{{ $revision->user->email ?? 'No disponible' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@endforeach
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@endforeach
|
||||
|
||||
@if($groupedVersions->isEmpty())
|
||||
<div class="text-center py-8 text-gray-500">
|
||||
<svg class="w-12 h-12 mx-auto text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
|
||||
</svg>
|
||||
<p class="mt-2">No hay historial de versiones disponible</p>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -778,46 +984,183 @@
|
||||
</div>
|
||||
|
||||
@push('scripts')
|
||||
<script>
|
||||
window.OptionKind = window.OptionKind || { VIEWER: 0, API: 1 };
|
||||
<script>
|
||||
var ae_post_url = "{{ route('documents.update-pdf', $document) }}";
|
||||
|
||||
window.OptionKind = window.OptionKind || { VIEWER: 0, API: 1 };
|
||||
|
||||
const PDF_URL = @json(Storage::url($document->file_path));
|
||||
console.log("PDF URL:", PDF_URL);
|
||||
const PDF_URL = @json(Storage::url($document->file_path));
|
||||
const SAVE_URL = "{{ route('documents.update-pdf', $document) }}";
|
||||
const CSRF_TOKEN = "{{ csrf_token() }}";
|
||||
|
||||
window.PDFViewerApplicationOptions = {
|
||||
defaultUrl: {
|
||||
value: encodeURI(PDF_URL),
|
||||
kind: OptionKind.VIEWER
|
||||
},
|
||||
cMapUrl: '/js/pdfjs-5.2.133-dist/web/cmaps/',
|
||||
cMapPacked: true
|
||||
};
|
||||
</script>
|
||||
console.log("PDF URL:", PDF_URL);
|
||||
|
||||
@vite([
|
||||
'resources/js/pdfjs-5.2.133-dist/build/pdf.mjs',
|
||||
'resources/js/pdfjs-5.2.133-dist/web/viewer.mjs',
|
||||
'resources/js/pdfjs-5.2.133-dist/web/viewer.css'
|
||||
])
|
||||
window.PDFViewerApplicationOptions = {
|
||||
defaultUrl: {
|
||||
value: encodeURI(PDF_URL),
|
||||
kind: OptionKind.VIEWER
|
||||
},
|
||||
cMapUrl: '/js/pdfjs-5.2.133-dist/web/cmaps/',
|
||||
cMapPacked: true
|
||||
};
|
||||
</script>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
PDFViewerApplication.initializedPromise.then(() => {
|
||||
// Pasar un OBJETO con { url: TU_URL }
|
||||
PDFViewerApplication.open({
|
||||
url: encodeURI(PDF_URL), // Propiedad requerida
|
||||
originalUrl: PDF_URL // Opcional (para mostrar en la UI)
|
||||
}).catch(error => {
|
||||
console.error('Error cargando PDF:', error);
|
||||
@vite([
|
||||
'resources/js/pdfjs-5.2.133-dist/build/pdf.mjs',
|
||||
'resources/js/pdfjs-5.2.133-dist/web/viewer.mjs',
|
||||
'resources/js/pdfjs-5.2.133-dist/web/viewer.css',
|
||||
'resources/js/pdfjs-5.2.133-dist/pdfjs-annotation-extension.js'
|
||||
])
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
PDFViewerApplication.initializedPromise.then(() => {
|
||||
// Pasar un OBJETO con { url: TU_URL }
|
||||
PDFViewerApplication.open({
|
||||
url: encodeURI(PDF_URL),
|
||||
originalUrl: PDF_URL
|
||||
}).then(() => {
|
||||
// Una vez cargado el PDF, configurar los event listeners para guardar
|
||||
setupSaveFunctionality();
|
||||
}).catch(error => {
|
||||
console.error('Error cargando PDF:', error);
|
||||
});
|
||||
});
|
||||
|
||||
function setupSaveFunctionality() {
|
||||
// Interceptar el botón de descarga para guardar con anotaciones
|
||||
const downloadButton = document.getElementById('downloadButton');
|
||||
if (downloadButton) {
|
||||
downloadButton.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
savePdfWithAnnotations();
|
||||
});
|
||||
}
|
||||
|
||||
// También puedes agregar un botón personalizado para guardar
|
||||
addCustomSaveButton();
|
||||
}
|
||||
|
||||
function addCustomSaveButton() {
|
||||
// Agregar botón de guardar personalizado en la toolbar
|
||||
const toolbarRight = document.getElementById('toolbarViewerRight');
|
||||
if (toolbarRight) {
|
||||
const saveButton = document.createElement('button');
|
||||
saveButton.id = 'saveWithAnnotations';
|
||||
saveButton.className = 'toolbarButton';
|
||||
saveButton.innerHTML = '<span>Guardar con anotaciones</span>';
|
||||
saveButton.title = 'Guardar PDF con anotaciones, firmas y stamps';
|
||||
saveButton.addEventListener('click', savePdfWithAnnotations);
|
||||
|
||||
// Insertar antes del botón de descarga
|
||||
const downloadBtn = document.getElementById('downloadButton');
|
||||
if (downloadBtn) {
|
||||
toolbarRight.insertBefore(saveButton, downloadBtn);
|
||||
} else {
|
||||
toolbarRight.appendChild(saveButton);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function savePdfWithAnnotations() {
|
||||
try {
|
||||
// Mostrar indicador de carga
|
||||
showLoading('Guardando PDF con anotaciones...');
|
||||
|
||||
// Obtener el PDF modificado con anotaciones
|
||||
const pdfDocument = PDFViewerApplication.pdfDocument;
|
||||
const data = await pdfDocument.saveDocument();
|
||||
const pdfData = await data.arrayBuffer();
|
||||
|
||||
// Convertir a base64
|
||||
const base64Pdf = arrayBufferToBase64(pdfData);
|
||||
|
||||
// Enviar al servidor
|
||||
const response = await fetch('{{ route("documents.update-pdf", $document) }}', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': '{{ csrf_token() }}'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
pdf_data: 'data:application/pdf;base64,' + base64Pdf,
|
||||
annotations: getCurrentAnnotations(), // Si quieres guardar metadatos
|
||||
signatures: getCurrentSignatures(),
|
||||
stamps: getCurrentStamps()
|
||||
})
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
hideLoading();
|
||||
|
||||
if (result.success) {
|
||||
showSuccess('PDF guardado correctamente con todas las anotaciones');
|
||||
} else {
|
||||
showError('Error al guardar: ' + result.message);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
hideLoading();
|
||||
console.error('Error saving PDF:', error);
|
||||
showError('Error al guardar el PDF');
|
||||
}
|
||||
}
|
||||
|
||||
function arrayBufferToBase64(buffer) {
|
||||
let binary = '';
|
||||
const bytes = new Uint8Array(buffer);
|
||||
const len = bytes.byteLength;
|
||||
for (let i = 0; i < len; i++) {
|
||||
binary += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
return window.btoa(binary);
|
||||
}
|
||||
|
||||
function getCurrentAnnotations() {
|
||||
// Obtener anotaciones actuales del visor
|
||||
// Esto depende de cómo la extensión almacena las anotaciones
|
||||
if (window.pdfAnnotationExtension) {
|
||||
return window.pdfAnnotationExtension.getAnnotations();
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function getCurrentSignatures() {
|
||||
// Obtener firmas actuales
|
||||
if (window.pdfAnnotationExtension) {
|
||||
return window.pdfAnnotationExtension.getSignatures();
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function getCurrentStamps() {
|
||||
// Obtener stamps actuales
|
||||
if (window.pdfAnnotationExtension) {
|
||||
return window.pdfAnnotationExtension.getStamps();
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function showLoading(message) {
|
||||
// Implementar un spinner o mensaje de carga
|
||||
console.log('Loading:', message);
|
||||
}
|
||||
|
||||
function hideLoading() {
|
||||
// Ocultar spinner
|
||||
console.log('Loading complete');
|
||||
}
|
||||
|
||||
function showSuccess(message) {
|
||||
alert(message); // Puedes usar un toast mejor
|
||||
}
|
||||
|
||||
function showError(message) {
|
||||
alert('Error: ' + message); // Puedes usar un toast mejor
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</script>
|
||||
<!-- ELIMINA EL SCRIPT versionTree() DE AQUÍ -->
|
||||
@endpush
|
||||
|
||||
</x-layouts.app>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
</x-layouts.app>
|
||||
@@ -1,331 +0,0 @@
|
||||
<x-layouts.app :title="__('Show document')">
|
||||
<div class="flex h-screen bg-gray-100"
|
||||
@resize.window.debounce="renderPage(currentPage)">
|
||||
|
||||
<!-- Zona izquierda - Visualizador de documentos -->
|
||||
<div class="w-1/2 bg-gray-800 p-4 relative">
|
||||
<!-- Loading State -->
|
||||
<template x-if="loading">
|
||||
<div class="absolute inset-0 bg-white bg-opacity-90 flex items-center justify-center">
|
||||
<div class="text-center">
|
||||
<svg class="animate-spin h-12 w-12 text-blue-500 mx-auto mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
<p class="text-gray-600">Cargando documento...</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Error State -->
|
||||
<template x-if="error">
|
||||
<div class="absolute inset-0 bg-red-50 flex items-center justify-center p-4">
|
||||
<div class="text-center text-red-600">
|
||||
<svg class="h-12 w-12 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
|
||||
</svg>
|
||||
<p x-text="error"></p>
|
||||
<p class="mt-2 text-sm">URL del documento: <span class="break-all" x-text="pdfUrl"></span></p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Controles del PDF -->
|
||||
<div class="flex items-center justify-between mb-4 bg-gray-700 p-2 rounded">
|
||||
<div class="flex items-center space-x-4 text-white">
|
||||
<button @click="previousPage" :disabled="currentPage <= 1" class="disabled:opacity-50">
|
||||
<x-icons icon="chevron-left" class="w-6 h-6" />
|
||||
</button>
|
||||
<span>Página <span x-text="currentPage"></span> de <span x-text="totalPages"></span></span>
|
||||
<button @click="nextPage" :disabled="currentPage >= totalPages" class="disabled:opacity-50">
|
||||
<x-icons icon="chevron-right" class="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="text-white">
|
||||
Zoom:
|
||||
<select x-model="scale" @change="renderPage(currentPage)" class="bg-gray-600 rounded px-2 py-1">
|
||||
<option value="0.25">25%</option>
|
||||
<option value="0.5">50%</option>
|
||||
<option value="0.75">75%</option>
|
||||
<option value="1">100%</option>
|
||||
<option value="1.5">150%</option>
|
||||
<option value="2">200%</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Canvas del PDF con comentarios -->
|
||||
<div class="flex-1 bg-white shadow-lg overflow-auto relative"
|
||||
id="pdf-container"
|
||||
@scroll.debounce="handleScroll">
|
||||
<div class="pdf-page-container" :style="`width: ${pageWidth}px`">
|
||||
<template x-for="(page, index) in renderedPages" :key="index">
|
||||
<div class="pdf-page">
|
||||
<canvas class="pdf-canvas"
|
||||
:id="`canvas-${page.pageNumber}`"></canvas>
|
||||
<div class="text-layer"
|
||||
:id="`text-layer-${page.pageNumber}`"></div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- Marcadores de comentarios existentes -->
|
||||
<template x-for="comment in comments" :key="comment.id">
|
||||
<div
|
||||
class="absolute w-4 h-4 bg-yellow-400 rounded-full cursor-pointer border-2 border-yellow-600"
|
||||
:style="`left: ${comment.x * 100}%; top: ${comment.y * 100}%;`"
|
||||
@click="scrollToComment(comment)"
|
||||
x-tooltip="'Ver comentario'"
|
||||
></div>
|
||||
</template>
|
||||
|
||||
<!-- Formulario flotante para nuevos comentarios -->
|
||||
<div
|
||||
class="absolute bg-white p-4 rounded-lg shadow-xl w-64"
|
||||
x-show="showCommentForm"
|
||||
:style="`top: ${clickY}px; left: ${clickX}px`"
|
||||
@click.outside="closeCommentForm"
|
||||
>
|
||||
<form @submit.prevent="submitComment">
|
||||
<textarea
|
||||
x-model="commentText"
|
||||
class="w-full mb-2 p-2 border rounded"
|
||||
placeholder="Escribe tu comentario..."
|
||||
rows="3"
|
||||
required
|
||||
></textarea>
|
||||
<button
|
||||
type="submit"
|
||||
class="btn btn-primary w-full flex items-center justify-center"
|
||||
>
|
||||
<x-icons icon="save" class="w-4 h-4 mr-2" /> Guardar
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Zona derecha - Tabs de información -->
|
||||
<div x-data="{ activeTab: 'properties' }" class="w-1/2 flex flex-col bg-white">
|
||||
<!-- Tabs de navegación -->
|
||||
<div class="border-b border-gray-200">
|
||||
<nav class="flex space-x-4 px-4 pt-2">
|
||||
<button @click="activeTab = 'properties'"
|
||||
:class="activeTab === 'properties' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'"
|
||||
class="py-4 px-1 border-b-2 font-medium">
|
||||
Propiedades
|
||||
</button>
|
||||
<button @click="activeTab = 'security'"
|
||||
:class="activeTab === 'security' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'"
|
||||
class="py-4 px-1 border-b-2 font-medium">
|
||||
Seguridad
|
||||
</button>
|
||||
<button @click="activeTab = 'comments'"
|
||||
:class="activeTab === 'comments' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'"
|
||||
class="py-4 px-1 border-b-2 font-medium">
|
||||
Comentarios
|
||||
</button>
|
||||
<button @click="activeTab = 'history'"
|
||||
:class="activeTab === 'history' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'"
|
||||
class="py-4 px-1 border-b-2 font-medium">
|
||||
Historial
|
||||
</button>
|
||||
<button @click="activeTab = 'relations'"
|
||||
:class="activeTab === 'relations' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'"
|
||||
class="py-4 px-1 border-b-2 font-medium">
|
||||
Relaciones
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<!-- Contenido de los tabs -->
|
||||
<div class="flex-1 overflow-y-auto p-4 space-y-6">
|
||||
<!-- Propiedades -->
|
||||
<div x-show="activeTab === 'properties'">
|
||||
<div class="space-y-4">
|
||||
<x-property-item label="Nombre" :value="$document->name" />
|
||||
<x-property-item label="Tipo" :value="$document->type" />
|
||||
<x-property-item label="Tamaño" :value="$document->size_for_humans" />
|
||||
<x-property-item label="Creado por" :value="Storage::url($document->file_path)" />
|
||||
<x-property-item label="Fecha creación" :value="$document->created_at->format('d/m/Y H:i')" />
|
||||
<x-property-item label="Última modificación" :value="$document->updated_at->format('d/m/Y H:i')" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Seguridad -->
|
||||
<div x-show="activeTab === 'security'" x-cloak>
|
||||
implementar
|
||||
</div>
|
||||
|
||||
<!-- Comentarios -->
|
||||
<div x-show="activeTab === 'comments'" x-cloak>
|
||||
<template x-for="comment in comments" :key="comment.id">
|
||||
<div class="p-4 mb-2 border rounded hover:bg-gray-50">
|
||||
<div class="text-sm text-gray-500"
|
||||
x-text="`Página ${comment.page} - ${new Date(comment.created_at).toLocaleString()}`"></div>
|
||||
<div x-text="comment.text" class="mt-1"></div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- Historial -->
|
||||
<div x-show="activeTab === 'history'" x-cloak>
|
||||
<div class="space-y-4">
|
||||
@foreach($document->versions as $version)
|
||||
<x-version-item :version="$version" />
|
||||
@endforeach
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Relaciones -->
|
||||
<div x-show="activeTab === 'relations'" x-cloak>
|
||||
implementar
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</x-layouts.app>
|
||||
|
||||
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
|
||||
<script>
|
||||
// Configuración del Visor PDF
|
||||
var currentPage = 1;
|
||||
var nextPage = 2;
|
||||
|
||||
const url = "{{ Storage::url($document->file_path) }}";
|
||||
let pdfDoc = null,
|
||||
pageNum = 1,
|
||||
pageRendering = false,
|
||||
pageNumPending = null,
|
||||
scale = 0.8,
|
||||
canvas = document.getElementById('pdf-canvas');
|
||||
ctx = canvas.getContext('2d');
|
||||
|
||||
function renderPage(num) {
|
||||
pageRendering = true;
|
||||
pdfDoc.getPage(num).then(function(page) {
|
||||
const viewport = page.getViewport({ scale: 1.5 });
|
||||
canvas.height = viewport.height;
|
||||
canvas.width = viewport.width;
|
||||
|
||||
const renderContext = {
|
||||
canvasContext: ctx,
|
||||
viewport: viewport
|
||||
};
|
||||
|
||||
page.render(renderContext).promise.then(() => {
|
||||
pageRendering = false;
|
||||
loadCommentsForPage(num);
|
||||
});
|
||||
|
||||
// Wait for rendering to finish
|
||||
renderTask.promise.then(function() {
|
||||
pageRendering = false;
|
||||
if (pageNumPending !== null) {
|
||||
// New page rendering is pending
|
||||
renderPage(pageNumPending);
|
||||
pageNumPending = null;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function handleCanvasClick(event) {
|
||||
const rect = event.target.getBoundingClientRect();
|
||||
this.clickX = event.clientX - rect.left;
|
||||
this.clickY = event.clientY - rect.top;
|
||||
this.showCommentForm = true;
|
||||
}
|
||||
|
||||
// Cargar PDF
|
||||
pdfjsLib.getDocument(url).promise.then(function(pdf) {
|
||||
pdfDoc = pdf;
|
||||
renderPage(pageNum);
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* If another page rendering in progress, waits until the rendering is
|
||||
* finised. Otherwise, executes rendering immediately.
|
||||
*/
|
||||
function queueRenderPage(num) {
|
||||
if (pageRendering) {
|
||||
pageNumPending = num;
|
||||
} else {
|
||||
renderPage(num);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays previous page.
|
||||
*/
|
||||
function onPrevPage() {
|
||||
if (pageNum <= 1) {
|
||||
return;
|
||||
}
|
||||
pageNum--;
|
||||
queueRenderPage(pageNum);
|
||||
}
|
||||
document.getElementById('prev').addEventListener('click', onPrevPage);
|
||||
|
||||
/**
|
||||
* Displays next page.
|
||||
*/
|
||||
function onNextPage() {
|
||||
if (pageNum >= pdfDoc.numPages) {
|
||||
return;
|
||||
}
|
||||
pageNum++;
|
||||
queueRenderPage(pageNum);
|
||||
}
|
||||
document.getElementById('next').addEventListener('click', onNextPage);
|
||||
|
||||
/**
|
||||
* Asynchronously downloads PDF.
|
||||
*/
|
||||
pdfjsLib.getDocument(url).promise.then(function(pdfDoc_) {
|
||||
pdfDoc = pdfDoc_;
|
||||
document.getElementById('page_count').textContent = pdfDoc.numPages;
|
||||
|
||||
// Initial/first page rendering
|
||||
renderPage(pageNum);
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.pdf-page-container {
|
||||
margin: 0 auto;
|
||||
padding: 20px 0;
|
||||
}
|
||||
|
||||
.pdf-page {
|
||||
position: relative;
|
||||
margin: 0 auto 20px;
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.text-layer {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
overflow: hidden;
|
||||
opacity: 0.2;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.text-layer span {
|
||||
color: transparent;
|
||||
position: absolute;
|
||||
white-space: pre;
|
||||
cursor: text;
|
||||
transform-origin: 0% 0%;
|
||||
}
|
||||
|
||||
.text-layer ::selection {
|
||||
background: rgba(0,0,255,0.2);
|
||||
}
|
||||
</style>
|
||||
55
resources/views/includes/areas/toolbar-left-start.blade.php
Normal file
55
resources/views/includes/areas/toolbar-left-start.blade.php
Normal file
@@ -0,0 +1,55 @@
|
||||
@aware(['component'])
|
||||
|
||||
<div class="w-full mb-4 md:w-auto md:mb-0">
|
||||
<div
|
||||
x-data="{ open: false }"
|
||||
@keydown.window.escape="open = false"
|
||||
x-on:click.away="open = false"
|
||||
class="relative z-10 inline-block w-full text-left md:w-auto"
|
||||
wire:key="my-dropdown-button-"
|
||||
>
|
||||
<div>
|
||||
<span class="rounded-md shadow-sm">
|
||||
<button
|
||||
x-on:click="open = !open"
|
||||
type="button"
|
||||
class="inline-flex justify-center w-full px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 dark:bg-gray-700 dark:text-white dark:border-gray-600 dark:hover:bg-gray-600"
|
||||
aria-haspopup="true"
|
||||
x-bind:aria-expanded="open"
|
||||
aria-expanded="true"
|
||||
>
|
||||
@lang('My Dropdown')
|
||||
|
||||
<svg class="w-5 h-5 ml-2 -mr-1" x-description="Heroicon name: chevron-down" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
x-cloak
|
||||
x-show="open"
|
||||
x-transition:enter="transition ease-out duration-100"
|
||||
x-transition:enter-start="transform opacity-0 scale-95"
|
||||
x-transition:enter-end="transform opacity-100 scale-100"
|
||||
x-transition:leave="transition ease-in duration-75"
|
||||
x-transition:leave-start="transform opacity-100 scale-100"
|
||||
x-transition:leave-end="transform opacity-0 scale-95"
|
||||
class="absolute right-0 z-50 w-full mt-2 origin-top-right bg-white divide-y divide-gray-100 rounded-md shadow-lg md:w-48 ring-1 ring-black ring-opacity-5 focus:outline-none"
|
||||
>
|
||||
<div class="bg-white rounded-md shadow-xs dark:bg-gray-700 dark:text-white">
|
||||
<div class="py-1" role="menu" aria-orientation="vertical">
|
||||
<button
|
||||
wire:key="my-dropdown-my-action-"
|
||||
type="button"
|
||||
class="flex items-center block w-full px-4 py-2 space-x-2 text-sm leading-5 text-gray-700 hover:bg-gray-100 hover:text-gray-900 focus:outline-none focus:bg-gray-100 focus:text-gray-900 dark:text-white dark:hover:bg-gray-600"
|
||||
role="menuitem"
|
||||
>
|
||||
<span>Dummy Action ({{ $param1 }})</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
102
resources/views/livewire/code-edit.blade.php
Normal file
102
resources/views/livewire/code-edit.blade.php
Normal file
@@ -0,0 +1,102 @@
|
||||
<div class="max-w-[280px] mx-auto">
|
||||
|
||||
<!-- Controles de configuración -->
|
||||
<div class="mb-4 p-1 bg-gray-50 rounded-lg flex items-center space-x-2 justify-left" style="width: 280px">
|
||||
<flux:input
|
||||
placeholder="Nombre"
|
||||
size="sm"
|
||||
style="width: 170px"
|
||||
wire:model="name"
|
||||
wire:change="updateName"
|
||||
wire:blur="updateName"
|
||||
/>
|
||||
<flux:input
|
||||
type="number"
|
||||
size="sm"
|
||||
style="width: 65px"
|
||||
wire:model="maxLength"
|
||||
wire:change="updateMaxLength"
|
||||
min="2"
|
||||
max="12"
|
||||
/>
|
||||
<flux:tooltip content="(2 - 12 caracteres)" position="right">
|
||||
<flux:button icon="information-circle" size="sm" variant="ghost" />
|
||||
</flux:tooltip>
|
||||
</div>
|
||||
|
||||
<!-- Inputs para agregar nuevos tipos -->
|
||||
<flux:input.group style="width: 255px">
|
||||
<!-- Selector de tamaño máximo -->
|
||||
|
||||
<!-- Input de código -->
|
||||
<flux:input
|
||||
placeholder="Código"
|
||||
size="sm"
|
||||
style="width: 80px"
|
||||
wire:model="codeInput"
|
||||
wire:keydown.enter="addCode"
|
||||
maxlength="{{ $maxLength }}"
|
||||
title="Máximo {{ $maxLength }} caracteres"
|
||||
/>
|
||||
|
||||
<!-- Input de label -->
|
||||
<flux:input
|
||||
placeholder="Label"
|
||||
size="sm"
|
||||
style="width: 180px"
|
||||
wire:model="labelInput"
|
||||
wire:keydown.enter="addLabel"
|
||||
x-ref="labelInput"
|
||||
/>
|
||||
|
||||
<!-- Botón agregar -->
|
||||
<flux:button
|
||||
icon="plus"
|
||||
size="sm"
|
||||
wire:click="addField"
|
||||
title="Agregar nuevo tipo"
|
||||
></flux:button>
|
||||
</flux:input.group>
|
||||
|
||||
<!-- Información de ayuda -->
|
||||
<div class="mt-1 text-xs text-gray-500">
|
||||
{{ __('Tamaño: ') . $maxLength . __(' caracteres.') }}
|
||||
@if($codeInput)
|
||||
<span class="ml-3">
|
||||
Longitud: {{ strlen($codeInput) }}/{{ $maxLength }}
|
||||
</span>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<!-- Lista de tipos de documento -->
|
||||
<div class="mt-3">
|
||||
@if($this->getTotalDocumentTypesProperty() > 0)
|
||||
<div class="text-sm font-medium text-gray-700 mb-2">
|
||||
Tipos de documento ({{ $this->getTotalDocumentTypesProperty() }})
|
||||
</div>
|
||||
<ul class="space-y-2">
|
||||
@foreach($documentTypes as $index => $documentType)
|
||||
<li class="flex items-center justify-between bg-white border border-gray-200 px-3 py-2 rounded-lg shadow-sm">
|
||||
<div class="flex items-center space-x-3">
|
||||
<span class="font-mono bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">
|
||||
{{ $documentType['code'] }}
|
||||
</span>
|
||||
<span class="text-gray-800">{{ $documentType['label'] }}</span>
|
||||
</div>
|
||||
<flux:button
|
||||
size="xs"
|
||||
variant="danger"
|
||||
icon="trash"
|
||||
wire:click="removeField({{ $index }})"
|
||||
title="Eliminar"
|
||||
></flux:button>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@else
|
||||
<div class="text-center py-4 text-gray-500 text-xs">
|
||||
No hay tipos de documento agregados
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
33
resources/views/livewire/project-document-filters.blade.php
Normal file
33
resources/views/livewire/project-document-filters.blade.php
Normal file
@@ -0,0 +1,33 @@
|
||||
<div class="flex flex-wrap items-center gap-4 p-4 bg-gray-50 rounded-lg mb-4">
|
||||
<div class="flex-1 min-w-[200px]">
|
||||
@include('livewire-tables::components.tools.filters.text-field', [
|
||||
'filter' => $this->getFilterByKey('code'),
|
||||
'placeholder' => 'Buscar código',
|
||||
])
|
||||
</div>
|
||||
|
||||
<div class="flex-1 min-w-[200px]">
|
||||
@include('livewire-tables::components.tools.filters.text-field', [
|
||||
'filter' => $this->getFilterByKey('name'),
|
||||
'placeholder' => 'Buscar nombre',
|
||||
])
|
||||
</div>
|
||||
|
||||
<div class="flex-1 min-w-[150px]">
|
||||
@include('livewire-tables::components.tools.filters.dropdown', [
|
||||
'filter' => $this->getFilterByKey('status'),
|
||||
])
|
||||
</div>
|
||||
|
||||
<div class="flex-1 min-w-[150px]">
|
||||
@include('livewire-tables::components.tools.filters.dropdown', [
|
||||
'filter' => $this->getFilterByKey('discipline'),
|
||||
])
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<button wire:click="clearFilters" class="px-3 py-2 text-sm text-gray-600 bg-white border border-gray-300 rounded hover:bg-gray-50">
|
||||
Limpiar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,348 @@
|
||||
<div class="max-w-full">
|
||||
<!-- Header -->
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<div>
|
||||
<h3 class="text-lg font-medium text-gray-900">Estados de Documentos</h3>
|
||||
<p class="text-sm text-gray-600">Configura los estados disponibles para los documentos de este proyecto</p>
|
||||
</div>
|
||||
|
||||
<button type="button"
|
||||
wire:click="openForm"
|
||||
class="btn btn-primary">
|
||||
<x-icons icon = "plus" class="w-4 h-4 mr-2" /> Nuevo Estado
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Lista de estados -->
|
||||
<div class="bg-white rounded-lg shadow overflow-hidden mb-6">
|
||||
@if(false)
|
||||
@if(count($statuses) > 0)
|
||||
<div class="divide-y divide-gray-200">
|
||||
@foreach($statuses as $status)
|
||||
<div class="p-4 hover:bg-gray-50 transition-colors"
|
||||
wire:key="status-{{ $status['id'] }}">
|
||||
<div class="flex items-center justify-between">
|
||||
<!-- Información del estado -->
|
||||
<div class="flex items-center space-x-4">
|
||||
<!-- Badge de color -->
|
||||
<div class="flex items-center">
|
||||
<div class="w-10 h-10 rounded-full border flex items-center justify-center"
|
||||
style="background-color: {{ $status['color'] }}; color: {{ $status['text_color'] }}"
|
||||
title="{{ $status['name'] }}">
|
||||
<span class="font-bold text-sm">
|
||||
{{ substr($status['name'], 0, 2) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Detalles -->
|
||||
<div>
|
||||
<div class="flex items-center space-x-2">
|
||||
<span class="font-medium text-gray-900">{{ $status['name'] }}</span>
|
||||
@if($status['is_default'])
|
||||
<span class="px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded-full">
|
||||
Por defecto
|
||||
</span>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
@if($status['description'])
|
||||
<p class="text-sm text-gray-600 mt-1">{{ $status['description'] }}</p>
|
||||
@endif
|
||||
|
||||
<!-- Permisos -->
|
||||
<div class="flex flex-wrap gap-2 mt-2">
|
||||
@if($status['allow_upload'])
|
||||
<span class="inline-flex items-center px-2 py-1 rounded text-xs bg-green-50 text-green-700">
|
||||
<x-icons icon = "upload" class="w-3 h-3 mr-1" /> Subir
|
||||
</span>
|
||||
@endif
|
||||
|
||||
@if($status['allow_edit'])
|
||||
<span class="inline-flex items-center px-2 py-1 rounded text-xs bg-blue-50 text-blue-700">
|
||||
<x-icons icon = "pencil" class="w-3 h-3 mr-1" /> Editar
|
||||
</span>
|
||||
@endif
|
||||
|
||||
@if($status['allow_delete'])
|
||||
<span class="inline-flex items-center px-2 py-1 rounded text-xs bg-red-50 text-red-700">
|
||||
<x-icons icon = "trash" class="w-3 h-3 mr-1" /> Eliminar
|
||||
</span>
|
||||
@endif
|
||||
|
||||
@if($status['requires_approval'])
|
||||
<span class="inline-flex items-center px-2 py-1 rounded text-xs bg-yellow-50 text-yellow-700">
|
||||
<x-icons icon = "shield-check" class="w-3 h-3 mr-1" /> Aprobación
|
||||
</span>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Acciones -->
|
||||
<div class="flex items-center space-x-2">
|
||||
<!-- Botones de orden -->
|
||||
<div class="flex space-x-1">
|
||||
<button type="button"
|
||||
wire:click="moveUp({{ $status['id'] }})"
|
||||
{{ $loop->first ? 'disabled' : '' }}
|
||||
class="p-1 {{ $loop->first ? 'text-gray-300 cursor-not-allowed' : 'text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded' }}"
|
||||
title="Mover hacia arriba">
|
||||
<x-icons icon = "arrow-up" class="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<button type="button"
|
||||
wire:click="moveDown({{ $status['id'] }})"
|
||||
{{ $loop->last ? 'disabled' : '' }}
|
||||
class="p-1 {{ $loop->last ? 'text-gray-300 cursor-not-allowed' : 'text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded' }}"
|
||||
title="Mover hacia abajo">
|
||||
<x-icons icon = "arrow-down" class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Botón editar -->
|
||||
<button type="button"
|
||||
wire:click="openForm({{ $status['id'] }})"
|
||||
class="p-1 text-yellow-600 hover:text-yellow-900 hover:bg-yellow-50 rounded"
|
||||
title="Editar estado">
|
||||
<x-icons icon = "pencil" class="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<!-- Botón eliminar -->
|
||||
@if(!$status['is_default'])
|
||||
<button type="button"
|
||||
wire:click="confirmDelete({{ $status['id'] }})"
|
||||
class="p-1 text-red-600 hover:text-red-900 hover:bg-red-50 rounded"
|
||||
title="Eliminar estado">
|
||||
<x-icons icon = "trash" class="w-4 h-4" />
|
||||
</button>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@endforeach
|
||||
</div>
|
||||
@else
|
||||
<div class="p-8 text-center text-gray-500">
|
||||
<x-icons icon = "document-text" class="w-12 h-12 mx-auto text-gray-300 mb-4" />
|
||||
<p class="mb-4">No hay estados configurados para este proyecto.</p>
|
||||
<button type="button"
|
||||
wire:click="openForm"
|
||||
class="btn btn-primary">
|
||||
<x-icons icon = "plus" class="w-4 h-4 mr-2" /> Crear primer estado
|
||||
</button>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<!-- Formulario para crear/editar estado -->
|
||||
<div x-data="{ showForm: @entangle('showForm') }"
|
||||
x-show="showForm"
|
||||
x-transition:enter="transition ease-out duration-300"
|
||||
x-transition:enter-start="opacity-0 transform scale-95"
|
||||
x-transition:enter-end="opacity-100 transform scale-100"
|
||||
x-transition:leave="transition ease-in duration-200"
|
||||
x-transition:leave-start="opacity-100 transform scale-100"
|
||||
x-transition:leave-end="opacity-0 transform scale-95"
|
||||
class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
|
||||
<div class="bg-white rounded-lg shadow-xl w-full max-w-md max-h-[90vh] overflow-y-auto">
|
||||
<!-- Header del modal -->
|
||||
<div class="border-b px-6 py-4">
|
||||
<h3 class="text-lg font-medium text-gray-900">
|
||||
{{ $formData['id'] ? 'Editar Estado' : 'Crear Nuevo Estado' }}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<!-- Formulario -->
|
||||
<form wire:submit.prevent="saveStatus" class="p-6">
|
||||
<!-- Nombre -->
|
||||
<div class="mb-4">
|
||||
<label for="name" class="block text-sm font-medium text-gray-700 mb-1">
|
||||
Nombre del Estado *
|
||||
</label>
|
||||
<input type="text"
|
||||
id="name"
|
||||
wire:model="formData.name"
|
||||
required
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
|
||||
@error('formData.name')
|
||||
<p class="mt-1 text-sm text-red-600">{{ $message }}</p>
|
||||
@enderror
|
||||
</div>
|
||||
|
||||
<!-- Colores -->
|
||||
<div class="grid grid-cols-2 gap-4 mb-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">
|
||||
Color de fondo
|
||||
</label>
|
||||
<div class="flex items-center space-x-2">
|
||||
<input type="color"
|
||||
wire:model="formData.color"
|
||||
class="w-10 h-10 p-1 border border-gray-300 rounded">
|
||||
<input type="text"
|
||||
wire:model="formData.color"
|
||||
maxlength="7"
|
||||
class="flex-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
|
||||
</div>
|
||||
@error('formData.color')
|
||||
<p class="mt-1 text-sm text-red-600">{{ $message }}</p>
|
||||
@enderror
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">
|
||||
Color del texto
|
||||
</label>
|
||||
<div class="flex items-center space-x-2">
|
||||
<input type="color"
|
||||
wire:model="formData.text_color"
|
||||
class="w-10 h-10 p-1 border border-gray-300 rounded">
|
||||
<input type="text"
|
||||
wire:model="formData.text_color"
|
||||
maxlength="7"
|
||||
class="flex-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
|
||||
</div>
|
||||
@error('formData.text_color')
|
||||
<p class="mt-1 text-sm text-red-600">{{ $message }}</p>
|
||||
@enderror
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Previsualización -->
|
||||
<div class="mb-4 p-3 bg-gray-50 rounded-lg">
|
||||
<p class="text-sm font-medium text-gray-700 mb-2">Previsualización:</p>
|
||||
<div class="flex items-center space-x-2">
|
||||
<span class="px-3 py-1 rounded-full text-sm font-medium"
|
||||
style="background-color: {{ $formData['color'] }}; color: {{ $formData['text_color'] ?: '#ffffff' }}">
|
||||
{{ $formData['name'] ?: 'Nombre del estado' }}
|
||||
</span>
|
||||
<span class="text-sm text-gray-500">(Esto es cómo se verá)</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Descripción -->
|
||||
<div class="mb-4">
|
||||
<label for="description" class="block text-sm font-medium text-gray-700 mb-1">
|
||||
Descripción
|
||||
</label>
|
||||
<textarea id="description"
|
||||
wire:model="formData.description"
|
||||
rows="3"
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></textarea>
|
||||
@error('formData.description')
|
||||
<p class="mt-1 text-sm text-red-600">{{ $message }}</p>
|
||||
@enderror
|
||||
</div>
|
||||
|
||||
<!-- Permisos -->
|
||||
<div class="mb-4">
|
||||
<p class="text-sm font-medium text-gray-700 mb-2">Permisos:</p>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<label class="flex items-center space-x-2">
|
||||
<input type="checkbox"
|
||||
wire:model="formData.allow_upload"
|
||||
class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
|
||||
<span class="text-sm text-gray-700">Permitir subida</span>
|
||||
</label>
|
||||
|
||||
<label class="flex items-center space-x-2">
|
||||
<input type="checkbox"
|
||||
wire:model="formData.allow_edit"
|
||||
class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
|
||||
<span class="text-sm text-gray-700">Permitir edición</span>
|
||||
</label>
|
||||
|
||||
<label class="flex items-center space-x-2">
|
||||
<input type="checkbox"
|
||||
wire:model="formData.allow_delete"
|
||||
class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
|
||||
<span class="text-sm text-gray-700">Permitir eliminación</span>
|
||||
</label>
|
||||
|
||||
<label class="flex items-center space-x-2">
|
||||
<input type="checkbox"
|
||||
wire:model="formData.requires_approval"
|
||||
class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
|
||||
<span class="text-sm text-gray-700">Requiere aprobación</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Estado por defecto -->
|
||||
<div class="mb-6">
|
||||
<label class="flex items-center space-x-2">
|
||||
<input type="checkbox"
|
||||
wire:model="formData.is_default"
|
||||
class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
|
||||
<span class="text-sm text-gray-700">Estado por defecto para nuevos documentos</span>
|
||||
</label>
|
||||
<p class="mt-1 text-sm text-gray-500">
|
||||
Solo puede haber un estado por defecto. Si marcas este, se desmarcará automáticamente el anterior.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Botones -->
|
||||
<div class="flex justify-end space-x-3">
|
||||
<button type="button"
|
||||
wire:click="closeForm"
|
||||
class="btn btn-secondary">
|
||||
Cancelar
|
||||
</button>
|
||||
<button type="submit"
|
||||
class="btn btn-primary">
|
||||
{{ $formData['id'] ? 'Actualizar Estado' : 'Crear Estado' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal de confirmación para eliminar -->
|
||||
<div x-data="{ showDeleteModal: @entangle('showDeleteModal') }"
|
||||
x-show="showDeleteModal"
|
||||
x-transition
|
||||
class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
|
||||
|
||||
<div class="bg-white rounded-lg shadow-xl w-full max-w-md">
|
||||
<div class="border-b px-6 py-4">
|
||||
<h3 class="text-lg font-medium text-gray-900">Confirmar eliminación</h3>
|
||||
</div>
|
||||
|
||||
<div class="p-6">
|
||||
<p class="text-gray-700 mb-4">
|
||||
¿Estás seguro de que deseas eliminar el estado
|
||||
<strong>"{{ $statusToDelete->name ?? '' }}"</strong>?
|
||||
</p>
|
||||
|
||||
@if($statusToDelete && $statusToDelete->documents()->exists())
|
||||
<div class="mb-4 p-3 bg-red-50 border border-red-200 rounded">
|
||||
<p class="text-sm text-red-700">
|
||||
<x-icons icon = "exclamation" class="w-4 h-4 inline mr-1" />
|
||||
No se puede eliminar porque hay documentos asociados a este estado.
|
||||
</p>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<div class="flex justify-end space-x-3">
|
||||
<button type="button"
|
||||
wire:click="closeDeleteModal"
|
||||
class="btn btn-secondary">
|
||||
Cancelar
|
||||
</button>
|
||||
|
||||
@if(!($statusToDelete && $statusToDelete->documents()->exists()))
|
||||
<button type="button"
|
||||
wire:click="deleteStatus"
|
||||
class="btn btn-danger">
|
||||
Eliminar Estado
|
||||
</button>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
264
resources/views/livewire/project-name-coder.blade.php
Normal file
264
resources/views/livewire/project-name-coder.blade.php
Normal file
@@ -0,0 +1,264 @@
|
||||
<div class="max-w-full">
|
||||
<!-- Header con contador y botón de agregar -->
|
||||
<div class="flex content-start justify-between mb-6">
|
||||
<div class="flex space-x-6 content-start">
|
||||
<h2 class="text-2xl font-bold text-gray-800">
|
||||
Codificación de los documentos del proyecto
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col items-end space-y-4">
|
||||
<div class="flex space-x-2">
|
||||
<button
|
||||
type="button"
|
||||
wire:click="addComponent"
|
||||
class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition-colors flex items-center space-x-2"
|
||||
>
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
|
||||
</svg>
|
||||
<span>Agregar Componente</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
wire:click="saveConfiguration"
|
||||
wire:loading.attr="disabled"
|
||||
class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors flex items-center space-x-2"
|
||||
>
|
||||
<svg class="w-4 h-4" wire:loading.remove wire:target="saveConfiguration" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
<svg class="w-4 h-4 animate-spin" wire:loading wire:target="saveConfiguration" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
|
||||
</svg>
|
||||
<span wire:loading.remove wire:target="saveConfiguration">Guardar</span>
|
||||
<span wire:loading wire:target="saveConfiguration">Guardando...</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Label con nombres de componentes -->
|
||||
<div class="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
|
||||
<div class="flex items-center space-x-2">
|
||||
<span class="text-sm font-medium text-blue-800">Código:</span>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span ><flux:badge color="green">{{ $project->reference}}</flux:badge>-</span>
|
||||
@foreach($components as $index => $component)
|
||||
<span class="inline-flex items-center px-3 py-1 rounded-md text-xs font-medium bg-white text-blue-700 border border-blue-200">
|
||||
{{ $component['headerLabel'] }}
|
||||
@if(isset($component['data']['documentTypes']) && count($component['data']['documentTypes']) > 0)
|
||||
<span class="ml-1 bg-blue-100 text-blue-800 px-1.5 py-0.5 rounded-full">
|
||||
{{ count($component['data']['documentTypes']) }}
|
||||
</span>
|
||||
@endif
|
||||
</span>
|
||||
@if(!$loop->last)
|
||||
<span class="text-blue-400">-</span>
|
||||
@endif
|
||||
@endforeach
|
||||
<span>- <flux:badge color="green">Document Name</flux:badge></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Contenedor horizontal para drag and drop -->
|
||||
<div
|
||||
x-data="{
|
||||
draggedComponent: null,
|
||||
init() {
|
||||
const container = this.$refs.componentsContainer;
|
||||
|
||||
if (container.children.length > 0) {
|
||||
// Inicializar Sortable para horizontal
|
||||
new Sortable(container, {
|
||||
animation: 150,
|
||||
ghostClass: 'bg-blue-50',
|
||||
chosenClass: 'bg-blue-100',
|
||||
dragClass: 'bg-blue-200',
|
||||
direction: 'horizontal',
|
||||
onStart: (evt) => {
|
||||
this.draggedComponent = evt.item.getAttribute('data-component-id');
|
||||
},
|
||||
onEnd: (evt) => {
|
||||
const orderedIds = Array.from(container.children).map(child => {
|
||||
return parseInt(child.getAttribute('data-component-id'));
|
||||
});
|
||||
|
||||
// Enviar el nuevo orden a Livewire
|
||||
this.$wire.updateComponentOrder(orderedIds);
|
||||
this.draggedComponent = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}"
|
||||
x-ref="componentsContainer"
|
||||
class="flex space-x-4 overflow-x-auto pb-4 min-h-80"
|
||||
>
|
||||
<!-- Lista de componentes en horizontal -->
|
||||
@foreach($components as $component)
|
||||
<div
|
||||
data-component-id="{{ $component['id'] }}"
|
||||
class="component-item bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md transition-shadow duration-200 flex-shrink-0 w-80"
|
||||
wire:key="component-{{ $component['id'] }}"
|
||||
>
|
||||
<!-- Header del componente -->
|
||||
<div class="flex justify-between items-center p-3 border-b border-gray-100 bg-gray-50 rounded-t-lg">
|
||||
<div class="flex items-center space-x-2">
|
||||
<!-- Handle para drag -->
|
||||
<!--
|
||||
<div class="cursor-move text-gray-400 hover:text-gray-600">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h16M4 16h16"></path>
|
||||
</svg>
|
||||
</div>
|
||||
-->
|
||||
<span class="text-xs font-medium text-gray-700">
|
||||
<span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-white text-blue-700 border border-blue-200">{{ $loop->iteration }}</span>
|
||||
{{ $component['headerLabel'] }}
|
||||
</span>
|
||||
|
||||
<!-- Contador de tipos en este componente -->
|
||||
@if(isset($component['data']['documentTypes']) && count($component['data']['documentTypes']) > 0)
|
||||
<span class="bg-blue-100 text-blue-800 text-xs px-1.5 py-0.5 rounded-full">
|
||||
{{ count($component['data']['documentTypes']) }}
|
||||
</span>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<div class="flex items-center space-x-1">
|
||||
<!-- Botones de orden -->
|
||||
@if(!$loop->first)
|
||||
<button
|
||||
type="button"
|
||||
wire:click="moveComponentUp({{ $component['id'] }})"
|
||||
title="Mover hacia arriba"
|
||||
class="p-1 text-blue-600 hover:text-blue-800 hover:bg-blue-100 rounded transition-colors"
|
||||
>
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
|
||||
</svg>
|
||||
</button>
|
||||
@else
|
||||
<div class="w-6"></div> <!-- Espacio para mantener alineación -->
|
||||
@endif
|
||||
|
||||
@if(!$loop->last)
|
||||
<button
|
||||
type="button"
|
||||
wire:click="moveComponentDown({{ $component['id'] }})"
|
||||
title="Mover hacia abajo"
|
||||
class="p-1 text-blue-600 hover:text-blue-800 hover:bg-blue-100 rounded transition-colors"
|
||||
>
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
|
||||
</svg>
|
||||
</button>
|
||||
@else
|
||||
<div class="w-6"></div> <!-- Espacio para mantener alineación -->
|
||||
@endif
|
||||
|
||||
<!-- Botón eliminar -->
|
||||
<button
|
||||
type="button"
|
||||
wire:click="removeComponent({{ $component['id'] }})"
|
||||
title="Eliminar este componente"
|
||||
class="p-1 text-red-600 hover:text-red-800 hover:bg-red-100 rounded transition-colors"
|
||||
>
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Componente hijo -->
|
||||
<div class="p-3">
|
||||
<livewire:code-edit
|
||||
:key="'document-manager-' . $component['id']"
|
||||
:component-id="$component['id']"
|
||||
:initial-name="$component['headerLabel']"
|
||||
:initial-max-length="$component['data']['maxLength'] ?? 3"
|
||||
:initial-document-types="$component['data']['documentTypes'] ?? []"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@endforeach
|
||||
</div>
|
||||
|
||||
<!-- Mensaje cuando no hay componentes -->
|
||||
@if($this->componentsCount === 0)
|
||||
<div class="text-center py-12 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
|
||||
<svg class="w-12 h-12 text-gray-400 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
|
||||
</svg>
|
||||
<p class="text-gray-500 mb-4">No hay componentes de tipos de documento</p>
|
||||
<button
|
||||
type="button"
|
||||
wire:click="addComponent"
|
||||
class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
Agregar el primer componente
|
||||
</button>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
|
||||
<!-- Incluir Sortable.js -->
|
||||
|
||||
|
||||
<style>
|
||||
.component-item {
|
||||
cursor: default;
|
||||
min-width: 320px;
|
||||
}
|
||||
|
||||
.component-item .cursor-move {
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
.component-item .cursor-move:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.sortable-ghost {
|
||||
opacity: 0.4;
|
||||
background-color: #dbeafe;
|
||||
}
|
||||
|
||||
.sortable-chosen {
|
||||
background-color: #eff6ff;
|
||||
transform: rotate(2deg);
|
||||
}
|
||||
|
||||
.sortable-drag {
|
||||
background-color: #dbeafe;
|
||||
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.overflow-x-auto {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: #cbd5e0 #f7fafc;
|
||||
}
|
||||
|
||||
.overflow-x-auto::-webkit-scrollbar {
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.overflow-x-auto::-webkit-scrollbar-track {
|
||||
background: #f7fafc;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.overflow-x-auto::-webkit-scrollbar-thumb {
|
||||
background: #cbd5e0;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.overflow-x-auto::-webkit-scrollbar-thumb:hover {
|
||||
background: #a0aec0;
|
||||
}
|
||||
</style>
|
||||
</div>
|
||||
@@ -1,506 +0,0 @@
|
||||
<div>
|
||||
<!-- Header y Breadcrumbs -->
|
||||
<div class="bg-white mb-6 flex content-start justify-between">
|
||||
<!-- User Info Left -->
|
||||
<div class="flex space-x-6 content-start">
|
||||
<!-- Icono -->
|
||||
<flux:icon.bolt class="w-24 h-24 shadow-lg object-cover border-1 border-gray-600"/>
|
||||
|
||||
<!-- Project Details -->
|
||||
<div class="flex flex-col content-start">
|
||||
<h1 class="text-2xl font-bold text-gray-700">
|
||||
{{ $project->name }}
|
||||
</h1>
|
||||
|
||||
<!-- Contact Info -->
|
||||
<div class="mt-2 ">
|
||||
<div class="flex items-center text-gray-600">
|
||||
<p class="text-sm text-gray-700">
|
||||
{{ $project->reference }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@if($project->phone)
|
||||
<div class="flex items-center text-gray-600">
|
||||
<svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/>
|
||||
</svg>
|
||||
<a href="tel:{{ $project->phone }}" class="hover:text-blue-600">
|
||||
{{ $project->phone }}
|
||||
</a>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Right Section -->
|
||||
<div class="flex flex-col items-end space-y-4">
|
||||
<!-- Navigation Toolbar -->
|
||||
<div class="flex space-x-2">
|
||||
<flux:button
|
||||
href="{{ route('projects.index') }}"
|
||||
icon:trailing="arrow-uturn-left"
|
||||
variant="ghost"
|
||||
>
|
||||
</flux:button>
|
||||
<flux:button
|
||||
href="{{ route('projects.index') }}"
|
||||
icon:trailing="chevron-left"
|
||||
variant="ghost"
|
||||
>
|
||||
</flux:button>
|
||||
<flux:button
|
||||
href="{{ route('projects.index') }}"
|
||||
icon:trailing="chevron-right"
|
||||
variant="ghost"
|
||||
>
|
||||
</flux:button>
|
||||
</div>
|
||||
|
||||
<!-- Status Badge -->
|
||||
<span class="px-4 py-2 w-30 rounded-lg text-sm text-center font-semibold
|
||||
{{ $project->is_active ? 'bg-green-600 text-white' : 'bg-red-100 text-red-800' }}">
|
||||
{{ $project->is_active ? 'Activo' : 'Inactivo' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div wire:loading wire:target="files" class="fixed top-0 right-0 p-4 bg-blue-100 text-blue-800">
|
||||
Subiendo archivos...
|
||||
</div>
|
||||
|
||||
|
||||
<!-- Contend: -->
|
||||
<div x-data="{ activeTab: 'info' }" class="bg-white rounded-lg shadow-md border-1">
|
||||
<!-- Tab Headers -->
|
||||
<div class="border-b border-gray-200">
|
||||
<nav class="flex space-x-8 px-6">
|
||||
<button @click="activeTab = 'info'"
|
||||
:class="activeTab === 'info' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'"
|
||||
class="py-4 px-1 border-b-2 font-medium">
|
||||
Project
|
||||
</button>
|
||||
|
||||
<button @click="activeTab = 'contacts'"
|
||||
:class="activeTab === 'contacts' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'"
|
||||
class="py-4 px-1 border-b-2 font-medium">
|
||||
Contactos
|
||||
</button>
|
||||
|
||||
<button @click="activeTab = 'documents'"
|
||||
:class="activeTab === 'documents' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'"
|
||||
class="py-4 px-1 border-b-2 font-medium">
|
||||
Documentos
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<!-- Tab Content -->
|
||||
<div class="p-6">
|
||||
<!-- Info Tab -->
|
||||
<div x-show="activeTab === 'info'">
|
||||
|
||||
<div class="flex flex-wrap gap-6">
|
||||
<!-- Columna Izquierda - Información -->
|
||||
<div class="w-full md:w-[calc(50%-12px)]">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="min-w-full divide-y divide-gray-200">
|
||||
<tbody class="bg-white divide-y divide-gray-200">
|
||||
@foreach(['name' => 'Nombre', 'last_name' => 'Apellido', 'email' => 'Email', 'phone' => 'Teléfono', 'created_at' => 'Fecha Registro'] as $field => $label)
|
||||
<tr>
|
||||
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ $label }}</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{{ $project->$field ?? 'N/A' }}
|
||||
</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Columna Derecha - Descripción del Proyecto -->
|
||||
<div class="w-full md:w-[calc(50%-12px)]"> <!-- 50% - gap/2 -->
|
||||
<div class="bg-white p-6 rounded-lg shadow-sm">
|
||||
<h3 class="whitespace-nowrap text-sm font-medium text-gray-900"">Descripción</h3>
|
||||
<div class="py-2 prose max-w-none text-gray-500">
|
||||
{!! $project->description ? $project->description : '<p class="text-gray-400">N/A</p>' !!}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Action Buttons -->
|
||||
<div class="mt-6 flex justify-end space-x-4">
|
||||
<a href="{{ route('projects.edit', $project) }}"
|
||||
class="w-[150px] px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg flex items-center justify-center">
|
||||
<svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/>
|
||||
</svg>
|
||||
Editar
|
||||
</a>
|
||||
|
||||
{{-- Formulario de Edición --}}
|
||||
<form method="POST" action="{{ route('projects.update', $project) }}">
|
||||
@csrf
|
||||
@method('PUT') <!-- Important! -->
|
||||
<button type="submit"
|
||||
class="w-[150px] px-4 py-2 bg-yellow-500 hover:bg-yellow-600 text-white rounded-lg flex items-center justify-center">
|
||||
<svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"/>
|
||||
</svg>
|
||||
{{ $project->is_active ? 'Desactivar' : 'Activar' }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{{-- Formulario de Eliminación --}}
|
||||
<form method="POST" action="{{ route('projects.destroy', $project) }}">
|
||||
@csrf
|
||||
@method('DELETE') <!-- Important! -->
|
||||
<button type="submit"
|
||||
onclick="return confirm('¿Estás seguro de querer eliminar este usuario?')"
|
||||
class="px-4 py-2 w-[150px] bg-red-600 hover:bg-red-700 text-white rounded-lg flex items-center justify-center">
|
||||
<svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
|
||||
</svg>
|
||||
Eliminar
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Contact Tab -->
|
||||
<div x-show="activeTab === 'contacts'" x-cloak>
|
||||
</div>
|
||||
|
||||
<!-- Permissions Tab -->
|
||||
<div x-show="activeTab === 'documents'" x-cloak>
|
||||
<!-- Contenedor principal con layout de explorador -->
|
||||
<div class="flex flex-col h-full">
|
||||
<!-- Barra de herramientas -->
|
||||
<div class="flex items-center justify-between p-2 bg-white border-b">
|
||||
<div class="flex items-center space-x-4">
|
||||
<!-- Botón Nueva Carpeta -->
|
||||
<button wire:click="showCreateFolderModal" class="flex items-center p-2 text-gray-600 hover:bg-gray-100 rounded">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 13h6m-3-3v6m-9 1V7a2 2 0 012-2h6l2 2h6a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2z" />
|
||||
</svg>
|
||||
<span class="text-sm">Nueva carpeta</span>
|
||||
</button>
|
||||
|
||||
<!-- Botón Subir Archivos (versión con button) -->
|
||||
<div class="relative">
|
||||
<button
|
||||
wire:click="openUploadModal"
|
||||
class="flex items-center p-2 text-gray-600 hover:bg-gray-100 rounded">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M12 16.5V9.75m0 0 3 3m-3-3-3 3M6.75 19.5a4.5 4.5 0 0 1-1.41-8.775 5.25 5.25 0 0 1 10.233-2.33 3 3 0 0 1 3.758 3.848A3.752 3.752 0 0 1 18 19.5H6.75Z" />
|
||||
</svg>
|
||||
<span class="text-sm">Subir archivos</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Contenido principal (treeview + documentos) -->
|
||||
<div class="flex flex-1 overflow-hidden">
|
||||
<!-- Treeview de Carpetas -->
|
||||
<div class="w-64 h-full overflow-y-auto border bg-white">
|
||||
<div class="">
|
||||
<ul class="space-y-1">
|
||||
@foreach($project->rootFolders as $folder)
|
||||
<x-folder-item
|
||||
:folder="$folder"
|
||||
:currentFolder="$currentFolder"
|
||||
:expandedFolders="$expandedFolders"
|
||||
wire:key="folder-{{ $folder->id }}"
|
||||
:itemsCount="$this->documents->count()"
|
||||
/>
|
||||
@endforeach
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Documentos -->
|
||||
<div class="flex-1 overflow-auto bg-white">
|
||||
<div class="p-2 bg-white border-b">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<nav class="flex space-x-2 text-sm">
|
||||
<a wire:click="currentFolder = null" class="flex cursor-pointer text-gray-600 hover:text-blue-600">
|
||||
<flux:icon.home class="w-4 h-4"/> Inicio
|
||||
</a>
|
||||
@foreach($this->breadcrumbs as $folder)
|
||||
<span class="text-gray-400">/</span>
|
||||
<a wire:click="selectFolder({{ $folder->id }})"
|
||||
class="cursor-pointer text-gray-600 hover:text-blue-600">
|
||||
{{ $folder->name }}
|
||||
</a>
|
||||
@endforeach
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="overflow-x-auto">
|
||||
<table id="listofdocuments" class="min-w-full divide-y divide-gray-200">
|
||||
<thead class="bg-gray-50 sticky top-0">
|
||||
<tr>
|
||||
<th class="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase">
|
||||
<div class="relative" x-data="{ open: false }">
|
||||
<button @click="open = !open" class="text-gray-700 hover:text-gray-900 focus:outline-none">
|
||||
Opciones
|
||||
</button>
|
||||
<div x-show="open" @click.away="open = false" class="absolute z-10 mt-2 bg-white border border-gray-300 rounded shadow-lg">
|
||||
<ul class="py-1">
|
||||
<template x-for="(column, index) in $store.columns.all" :key="index">
|
||||
<li class="px-4 py-2">
|
||||
<label class="inline-flex items-center">
|
||||
<input type="checkbox" class="form-checkbox" :checked="$store.columns.visible.includes(column)" @change="$store.columns.toggle(column)">
|
||||
<span class="ml-2" x-text="column"></span>
|
||||
</label>
|
||||
</li>
|
||||
</template>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
Nombre
|
||||
</div>
|
||||
</th>
|
||||
<template x-for="column in $store.columns.all" :key="column">
|
||||
<th class="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase" x-show="$store.columns.visible.includes(column)" x-text="column"></th>
|
||||
</template>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="bg-white divide-y divide-gray-200">
|
||||
@forelse($this->documents as $document)
|
||||
<tr class="hover:bg-gray-50">
|
||||
<td class="px-6 py-4 whitespace-nowrap">
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap">
|
||||
<div class="flex items-center">
|
||||
<a href="{{ route('documents.show', $document) }}"
|
||||
target="_blank"
|
||||
class="flex items-center hover:text-blue-600 transition-colors">
|
||||
@php
|
||||
$type = App\Helpers\FileHelper::getFileType($document->name);
|
||||
$iconComponent = "icons." . $type;
|
||||
$iconClass = [
|
||||
'pdf' => 'pdf text-red-500',
|
||||
'word' => 'word text-blue-500',
|
||||
'excel' => 'excel text-green-500',
|
||||
][$type] ?? 'document text-gray-400';
|
||||
@endphp
|
||||
<x-dynamic-component
|
||||
component="{{ $iconComponent }}"
|
||||
class="w-5 h-5 mr-2 {{ explode(' ', $iconClass)[1] }}"
|
||||
/>
|
||||
{{ $document->name }}
|
||||
</a>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Versiones')">
|
||||
{{ $document->versions_count }}
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Última Actualización')">
|
||||
{{ $document->updated_at->diffForHumans() }}
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Estado')">
|
||||
<x-status-badge :status="$document->status" />
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Revisión')">
|
||||
{{ $document->revision }}
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Disciplina')">
|
||||
{{ $document->discipline }}
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Tipo de Documento')">
|
||||
{{ $document->document_type }}
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Emisor')">
|
||||
{{ $document->issuer }}
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Fecha de Entrada')">
|
||||
{{ $document->entry_date }}
|
||||
</td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr>
|
||||
<td colspan="9" class="px-6 py-4 text-center text-gray-500">
|
||||
No se encontraron documentos en esta carpeta
|
||||
</td>
|
||||
</tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal para crear carpeta -->
|
||||
@if($showFolderModal)
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
|
||||
<div class="w-full max-w-md p-6 bg-white rounded-lg shadow-xl">
|
||||
<div class="mb-4">
|
||||
<h3 class="text-lg font-medium text-gray-900">Crear nueva carpeta</h3>
|
||||
<p class="mt-1 text-sm text-gray-500">Ingresa el nombre de la nueva carpeta</p>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<input
|
||||
type="text"
|
||||
wire:model="folderName"
|
||||
placeholder="Nombre de la carpeta"
|
||||
class="w-full p-2 border rounded focus:ring-blue-500 focus:border-blue-500"
|
||||
autofocus
|
||||
@keyup.enter="createFolder"
|
||||
>
|
||||
@error('folderName')
|
||||
<p class="mt-1 text-sm text-red-600">{{ $message }}</p>
|
||||
@enderror
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end space-x-3">
|
||||
<button
|
||||
wire:click="hideCreateFolderModal"
|
||||
class="px-4 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50">
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
wire:click="createFolder"
|
||||
class="px-4 py-2 text-sm text-white bg-blue-600 rounded-md hover:bg-blue-700">
|
||||
Crear carpeta
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<!-- Modal de subida -->
|
||||
@if($showUploadModal)
|
||||
<div
|
||||
x-data="{ isDragging: false }"
|
||||
x-on:drop.prevent="isDragging = false; $wire.selectFiles(Array.from($event.dataTransfer.files))"
|
||||
x-on:dragover.prevent="isDragging = true"
|
||||
x-on:dragleave.prevent="isDragging = false"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
|
||||
|
||||
<div class="w-full max-w-2xl p-6 bg-white rounded-lg shadow-xl">
|
||||
<div class="mb-4">
|
||||
<h3 class="text-lg font-medium text-gray-900">Subir archivos</h3>
|
||||
<p class="mt-1 text-sm text-gray-500">
|
||||
{{ $currentFolder ? "Carpeta destino: {$currentFolder->name}" : "Carpeta raíz del proyecto" }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Área de drag & drop -->
|
||||
<div
|
||||
x-on:click="$refs.fileInput.click()"
|
||||
:class="isDragging ? 'border-blue-500 bg-blue-50' : 'border-gray-300'"
|
||||
class="flex flex-col items-center justify-center p-8 border-2 border-dashed rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
|
||||
<input
|
||||
type="file"
|
||||
x-ref="fileInput"
|
||||
wire:model="selectedFiles"
|
||||
multiple
|
||||
class="hidden"
|
||||
wire:change="selectFiles($event.target.files)">
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-12 h-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
|
||||
</svg>
|
||||
|
||||
<div class="mt-4 text-center">
|
||||
<p class="font-medium text-gray-900">
|
||||
Arrastra archivos aquí o haz clic para seleccionar
|
||||
</p>
|
||||
<p class="text-sm text-gray-500">
|
||||
Formatos soportados: PDF, DOCX, XLSX, JPG, PNG (Máx. 10MB)
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Lista de archivos -->
|
||||
<div class="mt-4 max-h-64 overflow-y-auto">
|
||||
@if(count($selectedFiles) > 0)
|
||||
<ul class="space-y-2">
|
||||
@foreach($selectedFiles as $index => $file)
|
||||
<li class="flex items-center justify-between p-2 bg-gray-50 rounded">
|
||||
<div class="flex items-center truncate">
|
||||
<x-icons icon="document" class="w-4 h-4 mr-2 text-gray-400" />
|
||||
<span class="text-sm truncate">
|
||||
{{ $file->getClientOriginalName() }} <!-- Ahora funciona -->
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center space-x-2">
|
||||
<span class="text-xs text-gray-500">
|
||||
{{ number_format($file->getSize() / 1024, 2) }} KB
|
||||
</span>
|
||||
<button
|
||||
wire:click="removeFile({{ $index }})"
|
||||
type="button"
|
||||
class="p-1 text-gray-400 hover:text-red-600">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<!-- Footer del modal -->
|
||||
<div class="flex justify-end mt-6 space-x-3">
|
||||
<button
|
||||
wire:click="resetUpload"
|
||||
type="button"
|
||||
class="px-4 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50">
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
wire:click="uploadFiles"
|
||||
:disabled="!selectedFiles.length"
|
||||
class="px-4 py-2 text-sm text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed">
|
||||
Subir archivos ({{ count($selectedFiles) }})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
|
||||
<script>
|
||||
document.addEventListener('alpine:init', () => {
|
||||
Alpine.store('columns', {
|
||||
all: ['Versiones', 'Última Actualización', 'Estado', 'Revisión', 'Disciplina', 'Tipo de Documento', 'Emisor', 'Fecha de Entrada'],
|
||||
visible: ['Versiones', 'Última Actualización', 'Estado', 'Revisión', 'Disciplina', 'Tipo de Documento', 'Emisor', 'Fecha de Entrada'],
|
||||
toggle(column) {
|
||||
if (this.visible.includes(column)) {
|
||||
this.visible = this.visible.filter(c => c !== column);
|
||||
} else {
|
||||
this.visible.push(column);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<script>
|
||||
document.addEventListener('livewire:init', () => {
|
||||
Livewire.on('upload-progress', (name, progress) => {
|
||||
// Actualizar progreso en el frontend
|
||||
const progressBar = document.querySelector(`[data-file="${name}"] .progress-bar`);
|
||||
if (progressBar) {
|
||||
progressBar.style.width = `${progress}%`;
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
@@ -18,6 +18,9 @@
|
||||
<p class="text-sm text-gray-700">
|
||||
{{ $project->reference }}
|
||||
</p>
|
||||
<p class="mx-2">
|
||||
{{ $project['codingConfig'] }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@if($project->phone)
|
||||
@@ -60,8 +63,8 @@
|
||||
|
||||
<!-- Status Badge -->
|
||||
<span class="px-4 py-2 w-30 rounded-lg text-sm text-center font-semibold
|
||||
{{ $project->is_active ? 'bg-green-600 text-white' : 'bg-red-100 text-red-800' }}">
|
||||
{{ $project->is_active ? 'Activo' : 'Inactivo' }}
|
||||
{{ $project->status == "Activo" ? 'bg-green-600 text-white' : 'bg-red-100 text-red-800' }}">
|
||||
{{ /*$project->is_active ? 'Activo' : 'Inactivo'*/ $project->status}}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -73,7 +76,7 @@
|
||||
|
||||
|
||||
<!-- Contend: -->
|
||||
<div x-data="{ activeTab: 'info' }" class="bg-white rounded-lg shadow-md border-1">
|
||||
<div x-data="{ activeTab: 'documents' }" class="bg-white rounded-lg shadow-md border-1">
|
||||
<!-- Tab Headers -->
|
||||
<div class="border-b border-gray-200">
|
||||
<nav class="flex space-x-8 px-6">
|
||||
@@ -101,7 +104,6 @@
|
||||
<div class="p-6">
|
||||
<!-- Info Tab -->
|
||||
<div x-show="activeTab === 'info'">
|
||||
|
||||
<div class="flex flex-wrap gap-6">
|
||||
<!-- Columna Izquierda - Información -->
|
||||
<div class="w-full md:w-[calc(50%-12px)]">
|
||||
@@ -141,6 +143,12 @@
|
||||
Editar
|
||||
</a>
|
||||
|
||||
@can('update', $project)
|
||||
<a href="{{ route('project-settings.index', $project) }}" class="btn btn-primary">
|
||||
<x-icons icon="cog-6-tooth" class="w-4 h-4 mr-1" /> Configurar
|
||||
</a>
|
||||
@endcan
|
||||
|
||||
{{-- Formulario de Edición --}}
|
||||
<form method="POST" action="{{ route('projects.update', $project) }}">
|
||||
@csrf
|
||||
@@ -150,7 +158,7 @@
|
||||
<svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"/>
|
||||
</svg>
|
||||
{{ $project->is_active ? 'Desactivar' : 'Activar' }}
|
||||
{{ $project->status == "Activo" ? 'Desactivar' : 'Activar' }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
@@ -244,97 +252,11 @@
|
||||
</div>
|
||||
|
||||
<div class="overflow-x-auto">
|
||||
<table id="listofdocuments" class="min-w-full divide-y divide-gray-200">
|
||||
<thead class="bg-gray-50 sticky top-0">
|
||||
<tr>
|
||||
<th class="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="relative" x-data="{ open: false }">
|
||||
<flux:dropdown>
|
||||
<flux:button icon="ellipsis-horizontal" variant="subtle" size="sm"/>
|
||||
<flux:menu>
|
||||
<template x-for="(column, index) in $store.columns.all" :key="index">
|
||||
<li class="px-4 py-2">
|
||||
<label class="inline-flex items-center">
|
||||
<input type="checkbox" class="form-checkbox" :checked="$store.columns.visible.includes(column)" @change="$store.columns.toggle(column)">
|
||||
<span class="ml-2" x-text="column"></span>
|
||||
</label>
|
||||
</li>
|
||||
</template>
|
||||
</flux:menu>
|
||||
</flux:dropdown>
|
||||
</div>
|
||||
<span><flux:checkbox /></span>
|
||||
</div>
|
||||
</th>
|
||||
<th class="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase">
|
||||
NOMBRE
|
||||
</th>
|
||||
<template x-for="column in $store.columns.all" :key="column">
|
||||
<th class="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase" x-show="$store.columns.visible.includes(column)" x-text="column"></th>
|
||||
</template>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="bg-white divide-y divide-gray-200">
|
||||
@forelse($this->documents as $document)
|
||||
<tr class="hover:bg-gray-50">
|
||||
<td class="w-4"></td>
|
||||
<td class="px-6 py-4 whitespace-nowrap">
|
||||
<div class="flex items-center">
|
||||
<a href="{{ route('documents.show', $document) }}"
|
||||
target="_blank"
|
||||
class="flex items-center hover:text-blue-600 transition-colors">
|
||||
@php
|
||||
$type = App\Helpers\FileHelper::getFileType($document->name);
|
||||
$iconComponent = "icons." . $type;
|
||||
$iconClass = [
|
||||
'pdf' => 'pdf text-red-500',
|
||||
'word' => 'word text-blue-500',
|
||||
'excel' => 'excel text-green-500',
|
||||
][$type] ?? 'document text-gray-400';
|
||||
@endphp
|
||||
<x-dynamic-component
|
||||
component="{{ $iconComponent }}"
|
||||
class="w-5 h-5 mr-2 {{ explode(' ', $iconClass)[1] }}"
|
||||
/>
|
||||
{{ $document->name }}
|
||||
</a>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Versiones')">
|
||||
{{ $document->versions_count }}
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Última Actualización')">
|
||||
{{ $document->updated_at->diffForHumans() }}
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Estado')">
|
||||
<x-status-badge :status="$document->status" />
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Revisión')">
|
||||
{{ $document->revision }}
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Disciplina')">
|
||||
{{ $document->discipline }}
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Tipo de Documento')">
|
||||
{{ $document->document_type }}
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Emisor')">
|
||||
{{ $document->issuer }}
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap" x-show="$store.columns.visible.includes('Fecha de Entrada')">
|
||||
{{ $document->entry_date }}
|
||||
</td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr>
|
||||
<td colspan="9" class="px-6 py-4 text-center text-gray-500">
|
||||
No se encontraron documentos en esta carpeta
|
||||
</td>
|
||||
</tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
<livewire:project-document-list
|
||||
:project-id="$project->id"
|
||||
:folder-id="$currentFolder?->id"
|
||||
wire:key="document-table-{{ $currentFolder?->id ?? 'root' }}-{{ now()->timestamp }}"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -435,7 +357,7 @@
|
||||
<div class="flex items-center truncate">
|
||||
<x-icons icon="document" class="w-4 h-4 mr-2 text-gray-400" />
|
||||
<span class="text-sm truncate">
|
||||
{{ $file->getClientOriginalName() }} <!-- Ahora funciona -->
|
||||
{{ $file->getClientOriginalName() }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
||||
85
resources/views/project-settings/index.blade.php
Normal file
85
resources/views/project-settings/index.blade.php
Normal file
@@ -0,0 +1,85 @@
|
||||
|
||||
<x-layouts.app title="{{ 'Configuración del Proyecto - ' . $project->name }}"
|
||||
:showSidebar={{ $showSidebar }}>
|
||||
|
||||
<!-- Header -->
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold text-gray-900">Configuración del Proyecto</h2>
|
||||
<p class="text-gray-600">{{ $project->reference }} - {{ $project->name }}</p>
|
||||
</div>
|
||||
|
||||
<flux:button
|
||||
href="{{ route('projects.show', $project) }}"
|
||||
icon:trailing="arrow-uturn-left"
|
||||
variant="ghost"
|
||||
>
|
||||
Volver al Proyecto
|
||||
</flux:button>
|
||||
</div>
|
||||
|
||||
@if(session('success'))
|
||||
<div class="mb-4 p-4 bg-green-100 text-green-700 rounded-lg">
|
||||
{{ session('success') }}
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if(session('error'))
|
||||
<div class="mb-4 p-4 bg-red-100 text-red-700 rounded-lg">
|
||||
{{ session('error') }}
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<!-- Tabs de navegación -->
|
||||
<div x-data="{ activeTab: 'coding' }" class="bg-white rounded-lg shadow-md border-1">
|
||||
<div class="border-b border-gray-200 mb-6">
|
||||
<nav class="-mb-px flex space-x-8">
|
||||
<button @click="activeTab = 'coding'"
|
||||
:class="activeTab === 'coding' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'"
|
||||
class="py-4 px-1 border-b-2 font-medium">
|
||||
Codificación de Documentos
|
||||
</button>
|
||||
|
||||
<button @click="activeTab = 'statuses'"
|
||||
:class="activeTab === 'statuses' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'"
|
||||
class="py-4 px-1 border-b-2 font-medium">
|
||||
Estados de Documentos
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="p-6">
|
||||
<!-- Sección de Codificación -->
|
||||
<div x-show="activeTab === 'coding'">
|
||||
<div id="coding" class="mb-12">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h3 class="text-lg font-medium text-gray-900">Codificación de Documentos</h3>
|
||||
<div class="text-sm text-gray-500">
|
||||
Última actualización: {{ $project->codingConfig->updated_at->format('d/m/Y H:i') ?? 'No configurado' }}
|
||||
</div>
|
||||
</div>
|
||||
<livewire:project-name-coder
|
||||
:project="$project"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Sección de Estados -->
|
||||
<div x-show="activeTab === 'statuses'">
|
||||
<div id="statuses">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h3 class="text-lg font-medium text-gray-900">Estados de Documentos</h3>
|
||||
</div>
|
||||
|
||||
<div class="bg-white rounded-lg shadow overflow-hidden">
|
||||
<!-- Lista de estados existentes -->
|
||||
<div id="statuses-list" class="divide-y divide-gray-200">
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</x-layouts.app>
|
||||
@@ -0,0 +1,68 @@
|
||||
<div class="status-item p-4 flex items-center hover:bg-gray-50 transition-colors"
|
||||
data-status-id="{{ $status->id }}">
|
||||
<!-- Handle para drag & drop -->
|
||||
<div class="drag-handle cursor-move mr-3 text-gray-400 hover:text-gray-600">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h16M4 16h16" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<!-- Badge de color -->
|
||||
<div class="w-8 h-8 rounded-full mr-3 border"
|
||||
style="background-color: {{ $status->color }}; color: {{ $status->text_color }}"
|
||||
title="{{ $status->name }}">
|
||||
<div class="flex items-center justify-center h-full text-xs font-bold">
|
||||
{{ substr($status->name, 0, 2) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Información del estado -->
|
||||
<div class="flex-grow">
|
||||
<div class="flex items-center">
|
||||
<span class="font-medium text-gray-900">{{ $status->name }}</span>
|
||||
@if($status->is_default)
|
||||
<span class="ml-2 px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded-full">
|
||||
Por defecto
|
||||
</span>
|
||||
@endif
|
||||
</div>
|
||||
@if($status->description)
|
||||
<p class="text-sm text-gray-600 mt-1">{{ $status->description }}</p>
|
||||
@endif
|
||||
|
||||
<!-- Permisos -->
|
||||
<div class="flex items-center space-x-3 mt-2">
|
||||
@if($status->allow_upload)
|
||||
<span class="text-xs text-green-600">✓ Subir</span>
|
||||
@endif
|
||||
@if($status->allow_edit)
|
||||
<span class="text-xs text-blue-600">✓ Editar</span>
|
||||
@endif
|
||||
@if($status->allow_delete)
|
||||
<span class="text-xs text-red-600">✓ Eliminar</span>
|
||||
@endif
|
||||
@if($status->requires_approval)
|
||||
<span class="text-xs text-yellow-600">⚠ Aprobación</span>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Acciones -->
|
||||
<div class="flex items-center space-x-2">
|
||||
<button type="button"
|
||||
onclick="openStatusModal({{ json_encode($status) }})"
|
||||
class="text-yellow-600 hover:text-yellow-900"
|
||||
title="Editar">
|
||||
<x-icons.pencil class="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
@if(!$status->is_default && $status->documents_count == 0)
|
||||
<button type="button"
|
||||
onclick="openDeleteModal({{ json_encode($status) }})"
|
||||
class="text-red-600 hover:text-red-900"
|
||||
title="Eliminar">
|
||||
<x-icons.trash class="w-5 h-5" />
|
||||
</button>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
@@ -26,7 +26,7 @@
|
||||
class="text-green-500"/>
|
||||
</svg>
|
||||
<h1 class="text-3xl font-bold text-gray-800">
|
||||
{{ (isset($project) && $project->id) ? 'Editar Proyecto' : 'Nuevo Proyecto' }}
|
||||
{{ (isset($project) && $project->id) ? 'Editar Proyecto' : 'Nuevo Proyecto'}}
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
@@ -37,7 +37,6 @@
|
||||
Complete todos los campos obligatorios para registrar un nuevo usuario en el sistema.
|
||||
@endisset
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
@if(session('error'))
|
||||
@@ -87,18 +86,19 @@
|
||||
@enderror
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
|
||||
<!-- Referencia -->
|
||||
<tr>
|
||||
<td class="w-1/4 py-3 pr-4 align-top">
|
||||
<x-label for="reference" :value="__('Referencia')" />
|
||||
</td>
|
||||
<td class="py-3">
|
||||
<input type="text" name="reference" id="reference"
|
||||
<input type="text" name="reference" id="reference"
|
||||
value="{{ old('reference', $project->reference ?? '') }}"
|
||||
class="w-[250px] border-b-1 border-gray-300 focus:border-blue-500 focus:outline-none"
|
||||
maxlength="12"
|
||||
autofocus
|
||||
maxlength="12"
|
||||
autofocus
|
||||
wire:model.live="projectCode"
|
||||
required>
|
||||
<flux:tooltip content="Máximo: 12 caracteres" position="right">
|
||||
<flux:button icon="information-circle" size="sm" variant="ghost" />
|
||||
@@ -203,6 +203,43 @@
|
||||
<div class="bg-white py-6">
|
||||
<table class="w-full mb-8">
|
||||
<tbody>
|
||||
|
||||
<!-- Mapa para Coordenadas -->
|
||||
<tr>
|
||||
<td class="w-1/4 py-3 pr-4 align-top">
|
||||
<x-label :value="__('Seleccione Ubicación')" />
|
||||
</td>
|
||||
<td class="py-3">
|
||||
<div id="map" class="h-100 border-2 border-gray-200"></div>
|
||||
<div class="grid grid-cols-2 gap-4 mt-2">
|
||||
<div>
|
||||
<x-label for="latitude" :value="__('Latitud')" />
|
||||
<input type="number"
|
||||
id="latitude"
|
||||
name="latitude"
|
||||
value="{{ old('latitude') }}"
|
||||
step="any"
|
||||
class="border-b-1 border-gray-300 focus:border-blue-500 focus:outline-none">
|
||||
</div>
|
||||
<div>
|
||||
<x-label for="longitude" :value="__('Longitud')" />
|
||||
<input type="number"
|
||||
id="longitude"
|
||||
name="longitude"
|
||||
value="{{ old('longitude') }}"
|
||||
step="any"
|
||||
class="border-b-1 border-gray-300 focus:border-blue-500 focus:outline-none">
|
||||
</div>
|
||||
</div>
|
||||
@error('latitude')
|
||||
<p class="mt-2 text-sm text-red-600">{{ $message }}</p>
|
||||
@enderror
|
||||
@error('longitude')
|
||||
<p class="mt-2 text-sm text-red-600">{{ $message }}</p>
|
||||
@enderror
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Dirección -->
|
||||
<tr>
|
||||
<td class="w-1/4 py-3 pr-4 align-top">
|
||||
@@ -249,6 +286,7 @@
|
||||
|
||||
<div>
|
||||
<livewire:country-select :initialCountry="old('country')" />
|
||||
|
||||
@error('country')
|
||||
<p class="mt-2 text-sm text-red-600">{{ $message }}</p>
|
||||
@enderror
|
||||
@@ -256,42 +294,6 @@
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Mapa para Coordenadas -->
|
||||
<tr>
|
||||
<td class="w-1/4 py-3 pr-4 align-top">
|
||||
<x-label :value="__('Seleccione Ubicación')" />
|
||||
</td>
|
||||
<td class="py-3">
|
||||
<div id="map" class="h-80 border-2 border-gray-200"></div>
|
||||
<div class="grid grid-cols-2 gap-4 mt-2">
|
||||
<div>
|
||||
<x-label for="latitude" :value="__('Latitud')" />
|
||||
<input type="number"
|
||||
id="latitude"
|
||||
name="latitude"
|
||||
value="{{ old('latitude') }}"
|
||||
step="any"
|
||||
class="border-b-1 border-gray-300 focus:border-blue-500 focus:outline-none">
|
||||
</div>
|
||||
<div>
|
||||
<x-label for="longitude" :value="__('Longitud')" />
|
||||
<input type="number"
|
||||
id="longitude"
|
||||
name="longitude"
|
||||
value="{{ old('longitude') }}"
|
||||
step="any"
|
||||
class="border-b-1 border-gray-300 focus:border-blue-500 focus:outline-none">
|
||||
</div>
|
||||
</div>
|
||||
@error('latitude')
|
||||
<p class="mt-2 text-sm text-red-600">{{ $message }}</p>
|
||||
@enderror
|
||||
@error('longitude')
|
||||
<p class="mt-2 text-sm text-red-600">{{ $message }}</p>
|
||||
@enderror
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -476,6 +478,8 @@
|
||||
map.on('click', function(e) {
|
||||
updateInputs(e.latlng.lat, e.latlng.lng);
|
||||
updateMarker(e.latlng);
|
||||
// Realizar reverse geocoding
|
||||
reverseGeocode(e.latlng.lat, e.latlng.lng);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -506,6 +510,43 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Función para reverse geocoding
|
||||
function reverseGeocode(lat, lng) {
|
||||
// Usar Nominatim API de OpenStreetMap para reverse geocoding
|
||||
fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data && data.address) {
|
||||
// Actualizar dirección completa
|
||||
const address = data.display_name || '';
|
||||
document.getElementById('address').value = address;
|
||||
|
||||
// Actualizar código postal
|
||||
const postalCode = data.address.postcode || '';
|
||||
document.getElementById('postal_code').value = postalCode;
|
||||
|
||||
// Actualizar provincia
|
||||
const province = data.address.state || data.address.region || data.address.county || '';
|
||||
document.getElementById('province').value = province;
|
||||
|
||||
// Actualizar país
|
||||
const country = data.address.country || '';
|
||||
const countryInput = document.querySelector('input[name="country"]');
|
||||
if (countryInput) {
|
||||
countryInput.value = country;
|
||||
// Disparar evento change para que Livewire lo detecte
|
||||
countryInput.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}
|
||||
|
||||
// También puedes actualizar otros campos si están disponibles
|
||||
console.log('Datos de geocoding:', data.address);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error en reverse geocoding:', error);
|
||||
});
|
||||
}
|
||||
|
||||
// Inicializar el mapa
|
||||
window.onload = function() {
|
||||
initMap();
|
||||
|
||||
@@ -9,6 +9,7 @@ use App\Http\Controllers\ProfileController;
|
||||
use App\Http\Controllers\ProjectController;
|
||||
use App\Http\Controllers\RoleController;
|
||||
use App\Http\Controllers\UserController;
|
||||
use App\Http\Controllers\ProjectSettingsController;
|
||||
use App\Livewire\ProjectShow;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Livewire\Volt\Volt;
|
||||
@@ -56,6 +57,20 @@ Route::middleware(['auth', 'verified'])->group(function () {
|
||||
//Route::get('/projects/{project}', ProjectController::class)->name('projects.show');
|
||||
//Route::get('/projects/{project}', ProjectController::class)->name('projects.show')->middleware('can:view,project'); // Opcional: política de acceso
|
||||
Route::get('/projects/{project}', ProjectShow::class)->name('projects.show');
|
||||
|
||||
// Configuración de proyectos
|
||||
Route::prefix('projects/{project}/settings')->name('project-settings.')->group(function () {
|
||||
Route::get('/', [ProjectSettingsController::class, 'index'])->name('index');
|
||||
|
||||
// Codificación
|
||||
Route::put('/coding', [ProjectSettingsController::class, 'updateCoding'])->name('coding.update');
|
||||
|
||||
// Estados
|
||||
Route::post('/statuses', [ProjectSettingsController::class, 'storeStatus'])->name('statuses.store');
|
||||
Route::put('/statuses/{status}', [ProjectSettingsController::class, 'updateStatus'])->name('statuses.update');
|
||||
Route::delete('/statuses/{status}', [ProjectSettingsController::class, 'destroyStatus'])->name('statuses.destroy');
|
||||
Route::post('/statuses/reorder', [ProjectSettingsController::class, 'reorderStatuses'])->name('statuses.reorder');
|
||||
});
|
||||
|
||||
|
||||
// Documentos
|
||||
@@ -63,7 +78,9 @@ Route::middleware(['auth', 'verified'])->group(function () {
|
||||
Route::post('/documents/{document}', [DocumentController::class, 'show'])->name('documents.show');
|
||||
//Route::post('/documents/{document}/approve', [DocumentController::class, 'approve'])->name('documents.approve');
|
||||
//Route::post('/documents/{document}/comment', [DocumentController::class, 'addComment'])->name('documents.comment');
|
||||
|
||||
Route::post('/documents/{document}/update-pdf', [DocumentController::class, 'updatePdf'])->name('documents.update-pdf');
|
||||
Route::get('/documents/{document}/edit-pdf', [DocumentController::class, 'getPdfForEditing'])->name('documents.edit-pdf');
|
||||
|
||||
// Carpetas
|
||||
Route::prefix('folders')->group(function () {
|
||||
Route::put('/{folder}/move', [FolderController::class, 'move']);
|
||||
|
||||
Reference in New Issue
Block a user