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 Carbon\Carbon;
use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Livewire\Component; use Livewire\Component;
use Modules\Helpdesk\Models\Ticket; use Modules\Helpdesk\Models\Ticket;
@@ -25,7 +25,7 @@ class TicketTimer extends Component
public int $elapsedSeconds = 0; 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 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 * @throws \Illuminate\Validation\ValidationException
*/ */
@@ -42,23 +42,16 @@ class TicketTimer extends Component
{ {
$user = $this->authenticatedUser(); $user = $this->authenticatedUser();
Gate::authorize('update', $this->ticket);
if ($this->activeUserTimerQuery($user)->exists()) { if ($this->activeUserTimerQuery($user)->exists()) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
'timer' => 'You already have a running timer. End it before starting another one.', 'timer' => 'You already have a running timer.',
]);
}
if ($this->activeAnyTicketTimerQuery($user)->exists()) {
throw ValidationException::withMessages([
'timer' => 'You already have a running timer on another ticket. End it before starting another one.',
]); ]);
} }
$startedAt = Carbon::now(); $startedAt = Carbon::now();
TicketTimeLog::query()->create([ try {
$timer = TicketTimeLog::query()->create([
'ticket_id' => $this->ticket->getKey(), 'ticket_id' => $this->ticket->getKey(),
'user_id' => $user->getAuthIdentifier(), 'user_id' => $user->getAuthIdentifier(),
'minutes' => 0, 'minutes' => 0,
@@ -68,25 +61,28 @@ class TicketTimer extends Component
'ended_at' => null, 'ended_at' => null,
'logged_at' => $startedAt, '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->description = '';
$this->message = 'Timer started.'; $this->message = 'Timer started.';
$this->refreshActiveTimer();
$this->dispatch('timer-started'); $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 * @throws \Illuminate\Validation\ValidationException
*/ */
public function endTimer(): void public function endTimer(): void
{ {
$user = $this->authenticatedUser(); $user = $this->authenticatedUser();
Gate::authorize('update', $this->ticket);
$timer = $this->activeUserTimerQuery($user)->first(); $timer = $this->activeUserTimerQuery($user)->first();
if (! $timer instanceof TicketTimeLog) { if (! $timer instanceof TicketTimeLog) {
@@ -108,7 +104,14 @@ class TicketTimer extends Component
'logged_at' => $endedAt, 'logged_at' => $endedAt,
])->save(); ])->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->activeTimer = null;
$this->elapsedSeconds = 0; $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'); 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 private function refreshActiveTimer(): void
{ {
@@ -142,7 +145,7 @@ class TicketTimer extends Component
$this->activeTimer = $this->activeUserTimerQuery($user)->first(); $this->activeTimer = $this->activeUserTimerQuery($user)->first();
$this->elapsedSeconds = $this->activeTimer instanceof TicketTimeLog $this->elapsedSeconds = $this->activeTimer instanceof TicketTimeLog
? (int) $this->activeTimer->started_at->diffInSeconds(Carbon::now()) ? $this->activeTimer->started_at->diffInSeconds(Carbon::now())
: 0; : 0;
} }
@@ -157,38 +160,6 @@ class TicketTimer extends Component
->whereNull('ended_at'); ->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. * Return the authenticated user or fail validation cleanly.
* *
@@ -200,7 +171,7 @@ class TicketTimer extends Component
if (! $user instanceof Authenticatable) { if (! $user instanceof Authenticatable) {
throw ValidationException::withMessages([ 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 private function normalisedDescription(): string
{ {
$description = trim($this->description); $description = trim($this->description);
return $description !== '' ? $description : 'Work timer'; return $description !== '' ? $description : 'Timer entry';
} }
} }
@@ -1,5 +1,5 @@
@php @php
use Illuminate\Support\Str; use Illuminate\Support\Str;use Modules\Helpdesk\Models\TicketTimeLog;
$currentUser = auth()->user(); $currentUser = auth()->user();
$currentCompany = $currentUser?->company; $currentCompany = $currentUser?->company;
@@ -8,7 +8,11 @@
Str::lower((string) ($currentCompany?->slug ?? '')) === 'mpba-limited' || Str::lower((string) ($currentCompany?->slug ?? '')) === 'mpba-limited' ||
Str::contains(Str::lower((string) ($currentCompany?->name ?? '')), 'mpba'); Str::contains(Str::lower((string) ($currentCompany?->name ?? '')), 'mpba');
$visibleCommentCount = $ticket->comments->count(); $visibleCommentCount = $ticket->comments->count();
$ticketTimeLogs = collect($ticket->timeLogs ?? []); $ticketTimeLogs = TicketTimeLog::query()
->with('user')
->where('ticket_id', $ticket->getKey())
->orderByDesc('started_at')
->get();
@endphp @endphp
<div data-dusk="helpdesk-ticket-show" dusk="helpdesk-ticket-show" class="hd-helpdesk-surface space-y-4"> <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="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
<div class="min-w-0"> <div class="min-w-0">
<p class="text-xs font-black uppercase tracking-[0.18em] text-blue-200">Add files</p> <p class="text-xs font-black uppercase tracking-[0.18em] text-blue-200">Add
<p class="mt-1 truncate text-xs font-semibold text-slate-200" data-helpdesk-file-label> files</p>
<p class="mt-1 truncate text-xs font-semibold text-slate-200"
data-helpdesk-file-label>
No files selected</p> No files selected</p>
</div> </div>
@@ -356,8 +362,10 @@
); );
@endphp @endphp
<script type="application/json" id="helpdesk-canned-response-bodies">@json($cannedResponseBodies)</script> <script type="application/json"
<script type="application/json" id="helpdesk-canned-response-names">@json($cannedResponseNames)</script> id="helpdesk-canned-response-bodies">@json($cannedResponseBodies)</script>
<script type="application/json"
id="helpdesk-canned-response-names">@json($cannedResponseNames)</script>
@if ($cannedResponses->isNotEmpty()) @if ($cannedResponses->isNotEmpty())
<div class="grid gap-3 md:grid-cols-[1fr_auto]"> <div class="grid gap-3 md:grid-cols-[1fr_auto]">
@@ -402,17 +410,23 @@
<div class="mb-2 flex flex-wrap gap-2" <div class="mb-2 flex flex-wrap gap-2"
data-helpdesk-html-toolbar="ticket-comment-body-editor"> data-helpdesk-html-toolbar="ticket-comment-body-editor">
<button type="button" data-helpdesk-command="bold" <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" <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" <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" <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" <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" <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>
<div id="ticket-comment-body-editor" dusk="ticket-comment-editor" contenteditable="true" <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"> 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> {!! $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> class="sr-only" tabindex="-1" aria-hidden="true">{{ $oldCommentBody }}</textarea>
</div> </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"> 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="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div class="min-w-0"> <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> this reply</label>
<p class="mt-1 truncate text-xs font-semibold text-zinc-500 dark:text-zinc-400" <p class="mt-1 truncate text-xs font-semibold text-zinc-500 dark:text-zinc-400"
data-helpdesk-file-label>No files selected</p> data-helpdesk-file-label>No files selected</p>
@@ -475,7 +491,7 @@
</form> </form>
<script> <script>
document.addEventListener('click', function(event) { document.addEventListener('click', function (event) {
const insertButton = event.target.closest('[data-insert-canned-response]'); const insertButton = event.target.closest('[data-insert-canned-response]');
if (insertButton) { if (insertButton) {
@@ -566,7 +582,7 @@
} }
}); });
document.addEventListener('submit', function(event) { document.addEventListener('submit', function (event) {
const form = event.target.closest('[data-helpdesk-comment-form]'); const form = event.target.closest('[data-helpdesk-comment-form]');
if (!form) { if (!form) {
@@ -578,7 +594,7 @@
}); });
}); });
document.addEventListener('input', function(event) { document.addEventListener('input', function (event) {
const richEditor = event.target.closest('[data-helpdesk-rich-editor]'); const richEditor = event.target.closest('[data-helpdesk-rich-editor]');
if (richEditor) { if (richEditor) {
@@ -766,7 +782,7 @@
return span.innerHTML; return span.innerHTML;
} }
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('[data-helpdesk-rich-editor]').forEach((editor) => syncRichEditor(editor)); document.querySelectorAll('[data-helpdesk-rich-editor]').forEach((editor) => syncRichEditor(editor));
updateCommentToggleButtons(); updateCommentToggleButtons();
}); });
@@ -936,7 +952,9 @@
@if ($ticket->checklistItems->isNotEmpty()) @if ($ticket->checklistItems->isNotEmpty())
<div <div
class="rounded-xl border border-zinc-200 bg-white p-4 shadow-sm dark:border-zinc-700 dark:bg-zinc-900"> 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="-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"> <div class="flex items-center justify-between gap-3">
@@ -1013,7 +1031,8 @@
</span> </span>
<div class="min-w-0"> <div class="min-w-0">
<h2 class="text-lg font-black uppercase tracking-wide">Ticket controls</h2> <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> </p>
</div> </div>
</div> </div>
@@ -1072,7 +1091,9 @@
data-dusk="ticket-show-agent"> data-dusk="ticket-show-agent">
<option value="" @selected($agent_id === null)>Unassigned</option> <option value="" @selected($agent_id === null)>Unassigned</option>
@forelse ($agents as $agent) @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> {{ $agent->email }}</option>
@empty @empty
<option value="" disabled>No users available for assignment</option> <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" 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"> data-dusk="ticket-show-status">
@foreach ($statuses as $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> </option>
@endforeach @endforeach
</select> </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" 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"> data-dusk="ticket-show-priority">
@foreach ($priorities as $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> </option>
@endforeach @endforeach
</select> </select>
@@ -1181,9 +1204,11 @@
{{ $timeLog->logged_at?->format('d M Y H:i') ?? $timeLog->created_at?->format('d M Y H:i') }} {{ $timeLog->logged_at?->format('d M Y H:i') ?? $timeLog->created_at?->format('d M Y H:i') }}
</p> </p>
</div> </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"> <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> </span>
</div> </div>
</div> </div>
@@ -55,6 +55,7 @@
} }
}" }"
x-init="start()" x-init="start()"
x-on:timer-started.window="start()"
x-on:timer-ended.window="stop(); elapsedSeconds = 0" x-on:timer-ended.window="stop(); elapsedSeconds = 0"
x-on:livewire:navigating.window="stop()" x-on:livewire:navigating.window="stop()"
class="rounded-xl bg-emerald-700 px-3 py-2 text-right text-white shadow-sm" 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) @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 @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);
}
}