phases one of time logged now with log display

This commit is contained in:
Mark Gregory
2026-06-22 14:22:58 +01:00
parent bc213e0c6e
commit 0159a638f6
6 changed files with 195 additions and 175 deletions
+29 -58
View File
@@ -5,8 +5,8 @@ namespace Modules\Helpdesk\Livewire;
use Carbon\Carbon;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\ValidationException;
use Livewire\Component;
use Modules\Helpdesk\Models\Ticket;
@@ -25,7 +25,7 @@ class TicketTimer extends Component
public int $elapsedSeconds = 0;
/**
* Mount the ticket timer component.
* Mount the ticket timer and load any active database-backed timer.
*/
public function mount(Ticket $ticket): void
{
@@ -34,7 +34,7 @@ class TicketTimer extends Component
}
/**
* Start a user-specific timer for this ticket.
* Start a database-backed timer for the current authenticated user.
*
* @throws \Illuminate\Validation\ValidationException
*/
@@ -42,23 +42,16 @@ class TicketTimer extends Component
{
$user = $this->authenticatedUser();
Gate::authorize('update', $this->ticket);
if ($this->activeUserTimerQuery($user)->exists()) {
throw ValidationException::withMessages([
'timer' => 'You already have a running timer. End it before starting another one.',
]);
}
if ($this->activeAnyTicketTimerQuery($user)->exists()) {
throw ValidationException::withMessages([
'timer' => 'You already have a running timer on another ticket. End it before starting another one.',
'timer' => 'You already have a running timer.',
]);
}
$startedAt = Carbon::now();
TicketTimeLog::query()->create([
try {
$timer = TicketTimeLog::query()->create([
'ticket_id' => $this->ticket->getKey(),
'user_id' => $user->getAuthIdentifier(),
'minutes' => 0,
@@ -68,25 +61,28 @@ class TicketTimer extends Component
'ended_at' => null,
'logged_at' => $startedAt,
]);
} catch (QueryException $exception) {
throw ValidationException::withMessages([
'timer' => 'You already have a running timer.',
]);
}
$this->activeTimer = $timer->fresh();
$this->elapsedSeconds = 0;
$this->description = '';
$this->message = 'Timer started.';
$this->refreshActiveTimer();
$this->dispatch('timer-started');
}
/**
* End the active user timer and add the elapsed time to the ticket.
* End the current user's active timer and persist seconds/minutes.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function endTimer(): void
{
$user = $this->authenticatedUser();
Gate::authorize('update', $this->ticket);
$timer = $this->activeUserTimerQuery($user)->first();
if (! $timer instanceof TicketTimeLog) {
@@ -108,7 +104,14 @@ class TicketTimer extends Component
'logged_at' => $endedAt,
])->save();
$this->updateTicketTimeSpentFromSeconds();
$totalSeconds = (int) TicketTimeLog::query()
->where('ticket_id', $this->ticket->getKey())
->whereNotNull('ended_at')
->sum('seconds');
$this->ticket->forceFill([
'time_spent_minutes' => (int) ceil($totalSeconds / 60),
])->save();
$this->activeTimer = null;
$this->elapsedSeconds = 0;
@@ -119,15 +122,15 @@ class TicketTimer extends Component
}
/**
* Render the ticket timer view.
* Render the timer view.
*/
public function render(): mixed
public function render()
{
return view('helpdesk::livewire.ticket-timer');
}
/**
* Refresh the active timer from the database.
* Refresh the active timer state from the database.
*/
private function refreshActiveTimer(): void
{
@@ -142,7 +145,7 @@ class TicketTimer extends Component
$this->activeTimer = $this->activeUserTimerQuery($user)->first();
$this->elapsedSeconds = $this->activeTimer instanceof TicketTimeLog
? (int) $this->activeTimer->started_at->diffInSeconds(Carbon::now())
? $this->activeTimer->started_at->diffInSeconds(Carbon::now())
: 0;
}
@@ -157,38 +160,6 @@ class TicketTimer extends Component
->whereNull('ended_at');
}
/**
* Build the active timer query for the authenticated user across all tickets.
*/
private function activeAnyTicketTimerQuery(Authenticatable $user): Builder
{
return TicketTimeLog::query()
->where('user_id', $user->getAuthIdentifier())
->whereNull('ended_at');
}
/**
* Update the ticket's rounded minute total using stored seconds.
*/
private function updateTicketTimeSpentFromSeconds(): void
{
$totalSeconds = (int) TicketTimeLog::query()
->where('ticket_id', $this->ticket->getKey())
->whereNotNull('ended_at')
->sum('seconds');
if ($totalSeconds === 0) {
$totalSeconds = (int) TicketTimeLog::query()
->where('ticket_id', $this->ticket->getKey())
->whereNotNull('ended_at')
->sum('minutes') * 60;
}
$this->ticket->forceFill([
'time_spent_minutes' => (int) ceil($totalSeconds / 60),
])->save();
}
/**
* Return the authenticated user or fail validation cleanly.
*
@@ -200,7 +171,7 @@ class TicketTimer extends Component
if (! $user instanceof Authenticatable) {
throw ValidationException::withMessages([
'timer' => 'You must be signed in to use the ticket timer.',
'timer' => 'You must be logged in to use the timer.',
]);
}
@@ -208,12 +179,12 @@ class TicketTimer extends Component
}
/**
* Return a safe note for the timer.
* Return the safe timer description.
*/
private function normalisedDescription(): string
{
$description = trim($this->description);
return $description !== '' ? $description : 'Work timer';
return $description !== '' ? $description : 'Timer entry';
}
}
@@ -1,5 +1,5 @@
@php
use Illuminate\Support\Str;
use Illuminate\Support\Str;use Modules\Helpdesk\Models\TicketTimeLog;
$currentUser = auth()->user();
$currentCompany = $currentUser?->company;
@@ -8,7 +8,11 @@
Str::lower((string) ($currentCompany?->slug ?? '')) === 'mpba-limited' ||
Str::contains(Str::lower((string) ($currentCompany?->name ?? '')), 'mpba');
$visibleCommentCount = $ticket->comments->count();
$ticketTimeLogs = collect($ticket->timeLogs ?? []);
$ticketTimeLogs = TicketTimeLog::query()
->with('user')
->where('ticket_id', $ticket->getKey())
->orderByDesc('started_at')
->get();
@endphp
<div data-dusk="helpdesk-ticket-show" dusk="helpdesk-ticket-show" class="hd-helpdesk-surface space-y-4">
@@ -126,8 +130,10 @@
<div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
<div class="min-w-0">
<p class="text-xs font-black uppercase tracking-[0.18em] text-blue-200">Add files</p>
<p class="mt-1 truncate text-xs font-semibold text-slate-200" data-helpdesk-file-label>
<p class="text-xs font-black uppercase tracking-[0.18em] text-blue-200">Add
files</p>
<p class="mt-1 truncate text-xs font-semibold text-slate-200"
data-helpdesk-file-label>
No files selected</p>
</div>
@@ -356,8 +362,10 @@
);
@endphp
<script type="application/json" id="helpdesk-canned-response-bodies">@json($cannedResponseBodies)</script>
<script type="application/json" id="helpdesk-canned-response-names">@json($cannedResponseNames)</script>
<script type="application/json"
id="helpdesk-canned-response-bodies">@json($cannedResponseBodies)</script>
<script type="application/json"
id="helpdesk-canned-response-names">@json($cannedResponseNames)</script>
@if ($cannedResponses->isNotEmpty())
<div class="grid gap-3 md:grid-cols-[1fr_auto]">
@@ -402,17 +410,23 @@
<div class="mb-2 flex flex-wrap gap-2"
data-helpdesk-html-toolbar="ticket-comment-body-editor">
<button type="button" data-helpdesk-command="bold"
class="rounded-lg border px-2 py-1 text-xs font-black">B</button>
class="rounded-lg border px-2 py-1 text-xs font-black">B
</button>
<button type="button" data-helpdesk-command="italic"
class="rounded-lg border px-2 py-1 text-xs italic">I</button>
class="rounded-lg border px-2 py-1 text-xs italic">I
</button>
<button type="button" data-helpdesk-command="underline"
class="rounded-lg border px-2 py-1 text-xs underline">U</button>
class="rounded-lg border px-2 py-1 text-xs underline">U
</button>
<button type="button" data-helpdesk-command="insertUnorderedList"
class="rounded-lg border px-2 py-1 text-xs">List</button>
class="rounded-lg border px-2 py-1 text-xs">List
</button>
<button type="button" data-helpdesk-block="blockquote"
class="rounded-lg border px-2 py-1 text-xs">Quote</button>
class="rounded-lg border px-2 py-1 text-xs">Quote
</button>
<button type="button" data-helpdesk-block="code"
class="rounded-lg border px-2 py-1 text-xs">Code</button>
class="rounded-lg border px-2 py-1 text-xs">Code
</button>
</div>
<div id="ticket-comment-body-editor" dusk="ticket-comment-editor" contenteditable="true"
@@ -421,7 +435,8 @@
class="prose block min-h-[12rem] w-full max-w-none rounded-xl border border-zinc-300 bg-white p-4 text-sm leading-6 text-zinc-900 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-zinc-700 dark:bg-zinc-950 dark:text-zinc-100 dark:prose-invert">
{!! $oldCommentBody !!}</div>
<textarea dusk="comment-body" data-dusk="comment-body" id="ticket-comment-body" name="commentBody" required
<textarea dusk="comment-body" data-dusk="comment-body" id="ticket-comment-body"
name="commentBody" required
class="sr-only" tabindex="-1" aria-hidden="true">{{ $oldCommentBody }}</textarea>
</div>
@@ -430,7 +445,8 @@
class="rounded-xl border border-zinc-200 bg-zinc-50 p-3 dark:border-zinc-700 dark:bg-zinc-950">
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div class="min-w-0">
<label class="block text-xs font-bold text-zinc-700 dark:text-zinc-200">Attach files to
<label class="block text-xs font-bold text-zinc-700 dark:text-zinc-200">Attach files
to
this reply</label>
<p class="mt-1 truncate text-xs font-semibold text-zinc-500 dark:text-zinc-400"
data-helpdesk-file-label>No files selected</p>
@@ -936,7 +952,9 @@
@if ($ticket->checklistItems->isNotEmpty())
<div
class="rounded-xl border border-zinc-200 bg-white p-4 shadow-sm dark:border-zinc-700 dark:bg-zinc-900">
@php($completedChecks = $ticket->checklistItems->where('is_completed', true)->count())
@php
$completedChecks = $ticket->checklistItems->where('is_completed', true)->count();
@endphp
<div class="-mx-4 -mt-4 mb-4 rounded-t-xl bg-amber-600 px-4 py-4 text-white">
<div class="flex items-center justify-between gap-3">
@@ -1013,7 +1031,8 @@
</span>
<div class="min-w-0">
<h2 class="text-lg font-black uppercase tracking-wide">Ticket controls</h2>
<p class="text-xs font-semibold text-indigo-100">Log time, assignment, status and priority
<p class="text-xs font-semibold text-indigo-100">Log time, assignment, status and
priority
</p>
</div>
</div>
@@ -1072,7 +1091,9 @@
data-dusk="ticket-show-agent">
<option value="" @selected($agent_id === null)>Unassigned</option>
@forelse ($agents as $agent)
<option value="{{ $agent->id }}" @selected((int) $agent_id === (int) $agent->id)>{{ $agent->name }} ·
<option
value="{{ $agent->id }}" @selected((int) $agent_id === (int) $agent->id)>{{ $agent->name }}
·
{{ $agent->email }}</option>
@empty
<option value="" disabled>No users available for assignment</option>
@@ -1100,7 +1121,8 @@
class="hd-select block min-h-10 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-xs font-semibold text-zinc-900 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:border-zinc-700 dark:bg-zinc-950 dark:text-zinc-100"
data-dusk="ticket-show-status">
@foreach ($statuses as $status)
<option value="{{ $status->id }}" @selected((int) $status_id === (int) $status->id)>{{ $status->name }}
<option
value="{{ $status->id }}" @selected((int) $status_id === (int) $status->id)>{{ $status->name }}
</option>
@endforeach
</select>
@@ -1126,7 +1148,8 @@
class="hd-select block w-full rounded-lg border border-zinc-300 bg-white p-2 text-xs font-semibold text-zinc-900 shadow-sm focus:border-amber-500 focus:ring-amber-500 dark:border-zinc-700 dark:bg-zinc-950 dark:text-zinc-100"
data-dusk="ticket-show-priority">
@foreach ($priorities as $priority)
<option value="{{ $priority->id }}" @selected((int) $priority_id === (int) $priority->id)>{{ $priority->name }}
<option
value="{{ $priority->id }}" @selected((int) $priority_id === (int) $priority->id)>{{ $priority->name }}
</option>
@endforeach
</select>
@@ -1181,9 +1204,11 @@
{{ $timeLog->logged_at?->format('d M Y H:i') ?? $timeLog->created_at?->format('d M Y H:i') }}
</p>
</div>
@php
$timeLogSeconds = (int) ($timeLog->seconds ?? ((int) $timeLog->minutes * 60));
@endphp
<span class="shrink-0 rounded-lg bg-emerald-600 px-3 py-1.5 text-xs font-black text-white">
{{ $timeLog->minutes }}m
{{ gmdate('H:i:s', $timeLogSeconds) }}
</span>
</div>
</div>
@@ -55,6 +55,7 @@
}
}"
x-init="start()"
x-on:timer-started.window="start()"
x-on:timer-ended.window="stop(); elapsedSeconds = 0"
x-on:livewire:navigating.window="stop()"
class="rounded-xl bg-emerald-700 px-3 py-2 text-right text-white shadow-sm"
@@ -1,4 +1,3 @@
@php use Modules\Helpdesk\Livewire\TicketTimer; @endphp
@can('update', $ticket)
@livewire(TicketTimer::class, ['ticket' => $ticket], key('helpdesk-ticket-timer-'.$ticket->getKey()))
@livewire('Modules\\Helpdesk\\Livewire\\TicketTimer', ['ticket' => $ticket], key('helpdesk-ticket-timer-'.$ticket->getKey()))
@endcan
@@ -1 +0,0 @@
@livewire(\Modules\Helpdesk\Livewire\TicketTimer::class, ['ticket' => $ticket], key('helpdesk-ticket-timer-'.$ticket->getKey()))
@@ -0,0 +1,25 @@
<?php
namespace Modules\Helpdesk\Tests\Feature;
use Tests\TestCase;
class TicketTimerStartDisplayFilesTest extends TestCase
{
/**
* The component must hydrate the active timer immediately after start so the running card displays.
*/
public function test_start_timer_refreshes_running_display_state(): void
{
$component = (string) file_get_contents(base_path('Modules/Helpdesk/Livewire/TicketTimer.php'));
$view = (string) file_get_contents(base_path('Modules/Helpdesk/resources/views/livewire/ticket-timer.blade.php'));
$this->assertStringContainsString('$this->activeTimer = $timer->fresh();', $component);
$this->assertStringContainsString('$this->elapsedSeconds = 0;', $component);
$this->assertStringContainsString("dispatch('timer-started')", $component);
$this->assertStringContainsString('$hasRunningTimer = $activeTimer && $activeTimer->ended_at === null;', $view);
$this->assertStringContainsString('data-helpdesk-running-timer', $view);
$this->assertStringContainsString('x-on:timer-started.window', $view);
$this->assertStringNotContainsString('wire:ignore', $view);
}
}