fixe duploads and attachments

This commit is contained in:
Mark Gregory
2026-06-16 18:25:54 +01:00
parent c008fc67dc
commit bcd133e27a
4 changed files with 276 additions and 33 deletions
+146 -11
View File
@@ -6,11 +6,15 @@ namespace Modules\Helpdesk\Livewire;
use App\Models\User;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Livewire\Attributes\Validate;
use Livewire\Component;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Livewire\WithFileUploads;
use Modules\Helpdesk\Models\Category;
use Modules\Helpdesk\Models\KanbanBoard;
use Modules\Helpdesk\Models\Priority;
@@ -25,6 +29,8 @@ use Modules\Helpdesk\Services\WorkflowNotificationService;
final class TicketEdit extends Component
{
use WithFileUploads;
public Ticket $ticket;
#[Validate('nullable|integer')]
@@ -63,16 +69,22 @@ final class TicketEdit extends Component
#[Validate('nullable|date')]
public ?string $due_at = null;
/** @var array<int, int> */
#[Validate('array')]
public array $tag_ids = [];
/** @var array<int, TemporaryUploadedFile> */
#[Validate('array')]
public array $attachments = [];
/**
* Load the editable ticket state, including existing attachments and assignment.
*/
public function mount(Ticket $ticket): void
{
$this->authorize('update', $ticket);
$this->ticket = $ticket->fresh(['status', 'priority', 'category', 'project', 'team', 'agent', 'tags']) ?? $ticket;
$this->ticket = $this->freshTicket($ticket);
$this->company_id = $this->ticket->company_id;
$this->subject = $this->ticket->subject;
$this->body = $this->ticket->body;
@@ -88,12 +100,16 @@ final class TicketEdit extends Component
$this->tag_ids = $this->ticket->tags->pluck('id')->map(fn ($id): int => (int) $id)->all();
}
/**
* Save ticket edits, assignment and any newly uploaded ticket-level attachments.
*/
public function save(WorkflowNotificationService $workflow, SlaService $sla): mixed
{
$this->authorize('update', $this->ticket);
$this->validate();
$this->validate();
$this->validate([
'attachments.*' => 'file|max:'.config('helpdesk.max_upload_kb', 10240).'|mimes:'.implode(',', config('helpdesk.allowed_mimes', ['jpg', 'jpeg', 'png', 'pdf', 'txt', 'log', 'zip'])),
'tag_ids.*' => 'integer|exists:helpdesk_tags,id',
]);
@@ -117,19 +133,36 @@ final class TicketEdit extends Component
])->save();
$this->ticket->tags()->sync(array_values(array_unique(array_map('intval', $this->tag_ids))));
$this->storeTicketAttachments();
if ($status->is_closed) {
$sla->recordClosure($this->ticket);
}
$fresh = $this->ticket->fresh(['owner', 'agent', 'status', 'priority', 'category', 'project', 'team', 'product', 'tags']) ?? $this->ticket;
$fresh = $this->freshTicket($this->ticket);
$workflow->dispatch($fresh, $status->is_closed ? 'ticket.closed' : 'ticket.updated', Auth::user());
session()->flash('success', 'Ticket ' . $fresh->reference . ' has been updated.');
session()->flash('success', 'Ticket '.$fresh->reference.' has been updated.');
return redirect()->route('helpdesk.tickets.show', $fresh);
}
/**
* Remove an existing ticket-level attachment from storage and the database.
*/
public function removeAttachment(int $attachmentId): void
{
$this->authorize('update', $this->ticket);
$attachment = $this->ticket->attachments()->whereKey($attachmentId)->firstOrFail();
if (method_exists($attachment, 'deleteFile')) {
$attachment->deleteFile();
}
$attachment->delete();
$this->ticket = $this->freshTicket($this->ticket);
}
/**
* Clear the edit form, including Select2 and Flatpickr browser widgets.
@@ -153,6 +186,7 @@ final class TicketEdit extends Component
$this->agent_id = null;
$this->due_at = null;
$this->tag_ids = [];
$this->attachments = [];
$this->dispatch('helpdesk-form-cleared');
$this->dispatch('helpdesk-editor-reset', model: 'body');
@@ -170,12 +204,113 @@ final class TicketEdit extends Component
'projects' => Project::query()->whereNull('archived_at')->orderBy('title')->get(),
'products' => Product::query()->where('is_active', true)->orderBy('name')->get(),
'tags' => Tag::query()->orderBy('name')->get(),
'agents' => User::query()
->where(static function ($query): void {
$query->where('helpdesk_agent', true)->orWhere('helpdesk_admin', true);
})
->orderBy('name')
->get(['id', 'name', 'email']),
'agents' => $this->agentOptions(),
])->layout('layouts.app');
}
/**
* Return assignable users. Falls back to all tenant users when helpdesk flags/roles are absent.
*
* @return EloquentCollection<int, User>
*/
private function agentOptions(): EloquentCollection
{
return User::query()
->select(['id', 'name', 'email', 'company_id'])
->when($this->company_id !== null && Schema::hasColumn('users', 'company_id'), function ($query): void {
$query->where(function ($query): void {
$query->where('company_id', $this->company_id)
->orWhereNull('company_id');
});
})
->when(Schema::hasColumn('users', 'helpdesk_agent') || Schema::hasColumn('users', 'helpdesk_admin'), function ($query): void {
$query->where(function ($query): void {
if (Schema::hasColumn('users', 'helpdesk_agent')) {
$query->orWhere('helpdesk_agent', true);
}
if (Schema::hasColumn('users', 'helpdesk_admin')) {
$query->orWhere('helpdesk_admin', true);
}
if ($this->agent_id !== null) {
$query->orWhereKey($this->agent_id);
}
});
})
->orderBy('name')
->get();
}
private function freshTicket(Ticket $ticket): Ticket
{
return $ticket->fresh([
'owner',
'agent',
'status',
'priority',
'category',
'project',
'team',
'product',
'tags',
'attachments.user',
]) ?? $ticket;
}
/**
* Store ticket-level attachments in a schema-tolerant way.
*/
private function storeTicketAttachments(): void
{
if ($this->attachments === []) {
return;
}
foreach ($this->attachments as $upload) {
if (! $upload instanceof TemporaryUploadedFile) {
continue;
}
$path = $upload->store('helpdesk/tickets/'.$this->ticket->id, 'public');
$this->ticket->attachments()->create($this->attachmentPayload($upload, $path));
}
$this->attachments = [];
$this->ticket = $this->freshTicket($this->ticket);
}
/**
* Build attachment attributes using the columns available in the project migration.
*
* @return array<string, mixed>
*/
private function attachmentPayload(TemporaryUploadedFile $upload, string $path): array
{
$table = 'helpdesk_attachments';
$payload = [];
$columns = [
'user_id' => Auth::id(),
'uploaded_by_id' => Auth::id(),
'disk' => 'public',
'path' => $path,
'file_path' => $path,
'filename' => basename($path),
'file_name' => basename($path),
'original_name' => $upload->getClientOriginalName(),
'original_filename' => $upload->getClientOriginalName(),
'mime_type' => $upload->getMimeType(),
'mime' => $upload->getMimeType(),
'size' => $upload->getSize(),
'size_bytes' => $upload->getSize(),
];
foreach ($columns as $column => $value) {
if (Schema::hasColumn($table, $column)) {
$payload[$column] = $value;
}
}
return $payload;
}
}
+57 -3
View File
@@ -6,8 +6,10 @@ namespace Modules\Helpdesk\Livewire;
use App\Models\User;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema;
use Livewire\Attributes\Validate;
use Livewire\Component;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
@@ -41,6 +43,8 @@ final class TicketShow extends Component
public ?int $priority_id = null;
public ?int $agent_id = null;
public ?int $reply_parent_id = null;
public string $replyBody = '';
@@ -53,6 +57,7 @@ final class TicketShow extends Component
$this->ticket = $this->freshTicket($ticket);
$this->status_id = $this->ticket->status_id;
$this->priority_id = $this->ticket->priority_id;
$this->agent_id = $this->ticket->agent_id;
}
public function startReply(int $commentId): void
@@ -73,7 +78,7 @@ final class TicketShow extends Component
$this->validate([
'commentBody' => ['required', 'string', 'min:2'],
'attachments.*' => 'file|max:'.config('helpdesk.max_upload_kb').'|mimes:'.implode(',', config('helpdesk.allowed_mimes')),
'attachments.*' => 'file|max:'.config('helpdesk.max_upload_kb', 10240).'|mimes:'.implode(',', config('helpdesk.allowed_mimes', ['jpg', 'jpeg', 'png', 'pdf', 'txt', 'log', 'zip'])),
]);
$tickets->comment($this->ticket, Auth::user(), $this->commentBody, $this->internal, $this->attachments);
@@ -101,7 +106,6 @@ final class TicketShow extends Component
$this->dispatch('helpdesk-reply-added');
}
public function applyCannedResponse(CannedResponseRenderer $renderer): void
{
$this->authorize('comment', $this->ticket);
@@ -167,11 +171,27 @@ final class TicketShow extends Component
$this->dispatch('helpdesk-priority-updated');
}
public function updateAgent(WorkflowNotificationService $workflow): void
{
$this->authorize('update', $this->ticket);
$this->validate(['agent_id' => ['nullable', 'integer', 'exists:users,id']]);
$this->ticket->forceFill([
'agent_id' => $this->agent_id,
'last_activity_at' => now(),
])->save();
$this->ticket = $this->freshTicket($this->ticket);
$workflow->dispatch($this->ticket, 'ticket.updated', Auth::user());
$this->dispatch('helpdesk-agent-updated');
}
public function render(): View
{
return view('helpdesk::livewire.ticket-show', [
'statuses' => Status::query()->orderBy('sort_order')->get(),
'priorities' => Priority::query()->orderBy('sort_order')->get(),
'agents' => $this->agentOptions(),
'cannedResponses' => CannedResponse::query()->where('is_active', true)->orderBy('sort_order')->orderBy('name')->get(),
])->layout('layouts.app');
}
@@ -207,10 +227,44 @@ final class TicketShow extends Component
return $ticket;
}
/**
* Return assignable users. Falls back to all tenant users when helpdesk flags/roles are absent.
*
* @return EloquentCollection<int, User>
*/
private function agentOptions(): EloquentCollection
{
return User::query()
->select(['id', 'name', 'email', 'company_id'])
->when($this->ticket->company_id !== null && Schema::hasColumn('users', 'company_id'), function ($query): void {
$query->where(function ($query): void {
$query->where('company_id', $this->ticket->company_id)
->orWhereNull('company_id');
});
})
->when(Schema::hasColumn('users', 'helpdesk_agent') || Schema::hasColumn('users', 'helpdesk_admin'), function ($query): void {
$query->where(function ($query): void {
if (Schema::hasColumn('users', 'helpdesk_agent')) {
$query->orWhere('helpdesk_agent', true);
}
if (Schema::hasColumn('users', 'helpdesk_admin')) {
$query->orWhere('helpdesk_admin', true);
}
if ($this->agent_id !== null) {
$query->orWhereKey($this->agent_id);
}
});
})
->orderBy('name')
->get();
}
/**
* Build an unlimited nested comment tree from a flat eager-loaded collection.
*
* @param Collection<int|string, Collection<int, mixed>> $grouped
* @param Collection<int|string, Collection<int, mixed>> $grouped
* @return Collection<int, mixed>
*/
private function buildCommentTree(Collection $grouped, ?int $parentId = null): Collection
@@ -170,19 +170,19 @@
<div class="xl:col-span-2">
<label class="block text-sm font-semibold text-zinc-200" for="agent_id">Assigned agent</label>
<div class="mt-2" wire:ignore>
<div class="mt-2">
<select
id="agent_id"
data-helpdesk-select2
data-placeholder="Select option"
data-wire-model="agent_id"
wire:model.live="agent_id"
class="block w-full rounded-xl border-zinc-700 bg-zinc-950 text-zinc-100 shadow-sm focus:border-blue-500 focus:ring-blue-500"
data-dusk="ticket-edit-agent"
>
<option value="">Unassigned</option>
@foreach ($agents as $agent)
<option value="{{ $agent->id }}" @selected((string) $agent_id === (string) $agent->id)>{{ $agent->name }} · {{ $agent->email }}</option>
@endforeach
@forelse ($agents as $agent)
<option value="{{ $agent->id }}">{{ $agent->name }} · {{ $agent->email }}</option>
@empty
<option value="" disabled>No users available for assignment</option>
@endforelse
</select>
</div>
@@ -374,6 +374,42 @@
Uploading attachments...
</div>
<div class="mt-4 space-y-3">
<h3 class="text-sm font-semibold text-zinc-200">Existing attachments</h3>
@forelse ($ticket->attachments as $attachment)
<div class="flex flex-col gap-3 rounded-xl border border-zinc-700 bg-zinc-900 p-3 text-sm sm:flex-row sm:items-center sm:justify-between">
<a
href="{{ method_exists($attachment, 'url') ? $attachment->url() : Storage::disk($attachment->disk ?? 'public')->url($attachment->path ?? $attachment->file_path) }}"
target="_blank"
class="min-w-0 font-medium text-blue-300 hover:text-blue-200"
>
<i class="fa-regular fa-file mr-2" aria-hidden="true"></i>
{{ $attachment->original_name ?? $attachment->original_filename ?? $attachment->filename ?? $attachment->file_name ?? basename($attachment->path ?? $attachment->file_path ?? '') }}
</a>
<button
type="button"
wire:click="removeAttachment({{ $attachment->id }})"
wire:confirm="Remove this attachment?"
class="inline-flex items-center justify-center rounded-lg bg-red-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-red-700"
>
Remove
</button>
</div>
@empty
<div class="rounded-xl border border-dashed border-zinc-700 bg-zinc-900 px-4 py-3 text-sm text-zinc-400">
No ticket-level attachments are currently saved.
</div>
@endforelse
</div>
@if ($attachments !== [])
<div class="mt-4 rounded-xl border border-blue-500/30 bg-blue-500/10 px-4 py-3 text-sm text-blue-100">
{{ count($attachments) }} new attachment(s) selected. Save the ticket to attach them.
</div>
@endif
@error('attachments')
<p class="mt-3 text-sm text-red-500">{{ $message }}</p>
@enderror
@@ -37,19 +37,21 @@
</div>
</article>
@if ($ticket->attachments->isNotEmpty())
<div class="rounded-2xl border border-zinc-200 bg-white p-6 shadow-sm dark:border-zinc-700 dark:bg-zinc-900">
<h2 class="mb-4 text-base font-semibold text-zinc-900 dark:text-white">Ticket attachments</h2>
<div class="grid gap-3 sm:grid-cols-2">
@foreach ($ticket->attachments as $attachment)
<a href="{{ $attachment->url() }}" target="_blank" class="rounded-xl border border-zinc-200 p-3 text-sm hover:bg-zinc-50 dark:border-zinc-700 dark:hover:bg-zinc-800">
<div class="font-medium text-zinc-900 dark:text-zinc-100">{{ $attachment->original_name }}</div>
<div class="text-xs text-zinc-500">{{ Number::fileSize($attachment->size) }}</div>
</a>
@endforeach
</div>
<div class="rounded-2xl border border-zinc-200 bg-white p-6 shadow-sm dark:border-zinc-700 dark:bg-zinc-900">
<h2 class="mb-4 text-base font-semibold text-zinc-900 dark:text-white">Ticket attachments</h2>
<div class="grid gap-3 sm:grid-cols-2">
@forelse ($ticket->attachments as $attachment)
<a href="{{ method_exists($attachment, 'url') ? $attachment->url() : Storage::disk($attachment->disk ?? 'public')->url($attachment->path ?? $attachment->file_path) }}" target="_blank" class="rounded-xl border border-zinc-200 p-3 text-sm hover:bg-zinc-50 dark:border-zinc-700 dark:hover:bg-zinc-800">
<div class="font-medium text-zinc-900 dark:text-zinc-100">{{ $attachment->original_name ?? $attachment->original_filename ?? $attachment->filename ?? $attachment->file_name ?? basename($attachment->path ?? $attachment->file_path ?? '') }}</div>
<div class="text-xs text-zinc-500">{{ Number::fileSize($attachment->size ?? $attachment->size_bytes ?? 0) }}</div>
</a>
@empty
<div class="rounded-xl border border-dashed border-zinc-300 p-4 text-sm text-zinc-500 dark:border-zinc-700">
No ticket-level attachments are currently saved.
</div>
@endforelse
</div>
@endif
</div>
<section class="space-y-4">
<h2 class="text-lg font-semibold text-zinc-900 dark:text-white">Conversation</h2>
@@ -184,6 +186,22 @@
@can('update', $ticket)
<div class="rounded-2xl border border-zinc-200 bg-white p-5 shadow-sm dark:border-zinc-700 dark:bg-zinc-900">
<h2 class="mb-4 text-base font-semibold text-zinc-900 dark:text-white">Agent actions</h2>
<label class="mb-2 block text-sm font-medium text-zinc-700 dark:text-zinc-200" for="show_agent_id">Assigned agent</label>
<select
id="show_agent_id"
wire:model.live="agent_id"
class="block w-full rounded-lg border border-zinc-300 bg-white p-2 text-sm dark:border-zinc-700 dark:bg-zinc-950"
data-dusk="ticket-show-agent"
>
<option value="">Unassigned</option>
@forelse ($agents as $agent)
<option value="{{ $agent->id }}">{{ $agent->name }} · {{ $agent->email }}</option>
@empty
<option value="" disabled>No users available for assignment</option>
@endforelse
</select>
<flux:button dusk="update-agent" wire:click="updateAgent" class="mt-4 mb-5 w-full !bg-emerald-600 !text-white hover:!bg-emerald-700 focus:!ring-emerald-400/60" variant="primary" icon="user">Update assigned agent</flux:button>
<flux:select wire:model="status_id" label="Status">
@foreach ($statuses as $status)
<option value="{{ $status->id }}">{{ $status->name }}</option>