Files
Toiminnanohjaus/app/Modules/TimeTracking/Presentation/Livewire/⚡week.blade.php
T
2026-11-30 06:56:14 +02:00

1228 lines
64 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
use App\Modules\Customers\Application\UseCases\ChangeCustomerHeaderColor;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\DTOs\BookableTask;
use App\Modules\Jobs\Application\UseCases\ChangeJobStatus;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Shared\Domain\Exceptions\InvalidHexColor;
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
use App\Modules\TimeTracking\Application\DTOs\MonthSummary;
use App\Modules\TimeTracking\Application\DTOs\TimesheetJobGroup;
use App\Modules\TimeTracking\Application\DTOs\TimesheetTaskRow;
use App\Modules\TimeTracking\Application\DTOs\TimesheetWeek;
use App\Modules\TimeTracking\Application\UseCases\AddTaskHours;
use App\Modules\TimeTracking\Application\UseCases\ApproveWeek;
use App\Modules\TimeTracking\Application\UseCases\CancelWeekApproval;
use App\Modules\TimeTracking\Application\UseCases\DescribeTimeEntry;
use App\Modules\TimeTracking\Application\UseCases\PinTimesheetTasks;
use App\Modules\TimeTracking\Application\UseCases\SetDayHours;
use App\Modules\TimeTracking\Domain\Enums\EntryBillingModel;
use App\Modules\TimeTracking\Domain\Exceptions\BillingNotesMissing;
use App\Modules\TimeTracking\Domain\Exceptions\DailyHoursExceeded;
use App\Modules\TimeTracking\Domain\Exceptions\InvalidWorkedHours;
use App\Modules\TimeTracking\Domain\Exceptions\TimeApproved;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
use App\Modules\Users\Application\Contracts\Clock;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Domain\Enums\Role;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Url;
use Livewire\Component;
/**
* The weekly time sheet (docs/ui-timesheet.md): "Aikataulutettu" (tasks
* scheduled for the week and tasks with hours) and "Lukitut työt" (tasks
* the user pinned), each grouped customer A–Ö → job → task. A cell takes
* HH:MM, decimal hours or minutes and has ±15 min buttons; the entry
* dialog holds the laskutusperuste, billing note and internal comment.
* The timer for today runs in the browser. The week is approved at once,
* and only when every entry has a billing note. On a phone one day is
* shown at a time. Management may open another user's week
* (?kayttaja=ID) to read, approve or cancel approval.
*/
new class extends Component
{
public const string ENTRY_DIALOG = 'entry-dialog';
public const string MISSING_DIALOG = 'missing-notes-dialog';
/**
* The Monday of the week shown (Y-m-d). Read from the URL on mount and
* then changed only by showWeek(), so the browser cannot set it.
*/
#[Locked]
#[Url(as: 'viikko', except: '')]
public string $week = '';
/**
* Another user's id from the URL, for management; '' is the signed-in user.
*/
#[Locked]
#[Url(as: 'kayttaja', except: '')]
public string $user = '';
#[Locked]
public int $viewedUserId = 0;
#[Locked]
public string $viewedUserName = '';
/**
* Stored hours as shown (H:MM), by task id and day.
*
* @var array<int|string, array<string, string>>
*/
#[Locked]
public array $cells = [];
/**
* Values that were not saved, shown back in their cell with the error.
*
* @var array<string, string>
*/
#[Locked]
public array $rejected = [];
/**
* The day shown on phones; changed only by selectDay().
*/
#[Locked]
public string $selectedDay = '';
#[Locked]
public string $today = '';
public bool $showMonth = false;
public string $pinSearch = '';
#[Locked]
public ?int $entryTaskId = null;
#[Locked]
public string $entryDay = '';
public string $entryBillingModel = '';
public string $entryNote = '';
public string $entryComment = '';
public string $statusMessage = '';
public string $errorMessage = '';
public function mount(Clock $clock): void
{
$this->authorize('time.use');
$this->viewedUserId = (int) auth()->id();
if ($this->user !== '' && (int) $this->user !== $this->viewedUserId) {
$this->authorize('time.approve-others');
$summary = ctype_digit($this->user) ? app(UserAccountQueries::class)->findSummary((int) $this->user) : null;
abort_if($summary === null, 404);
$this->viewedUserId = $summary->id;
$this->viewedUserName = $summary->name;
} else {
$this->user = '';
}
$this->today = $clock->today()->format('Y-m-d');
$this->week = $this->mondayOf($this->week !== '' ? $this->week : $this->today);
$this->selectedDay = in_array($this->today, $this->sheet->days, true) ? $this->today : $this->week;
$this->loadCells();
}
#[Computed]
public function sheet(): TimesheetWeek
{
return app(TimeEntryQueries::class)->timesheet($this->viewedUserId, $this->week);
}
#[Computed]
public function month(): MonthSummary
{
return app(TimeEntryQueries::class)->monthSummary($this->viewedUserId, CarbonImmutable::parse($this->week)->addDays(3)->format('Y-m'));
}
/**
* Whether management is looking at someone else's week: nothing can be typed then.
*/
public function isReadOnly(): bool
{
return $this->viewedUserId !== (int) auth()->id();
}
public function isCurrentWeek(): bool
{
return $this->week === $this->mondayOf($this->today);
}
public function canApprove(): bool
{
return Gate::allows('time.approve', $this->viewedUserId);
}
/**
* @return list<BookableTask>
*/
#[Computed]
public function pinCandidates(): array
{
$term = trim($this->pinSearch);
if (mb_strlen($term) < 2) {
return [];
}
$pinned = array_map(fn (TimesheetTaskRow $row): int => $row->task->taskId, array_filter($this->sheet->rows(), fn (TimesheetTaskRow $row): bool => $row->pinned));
return array_values(array_filter(
app(TaskQueries::class)->searchBookableTasks($term, $this->isSubcontractor() ? (int) auth()->id() : null),
fn (BookableTask $task): bool => ! $task->isLocked() && ! in_array($task->taskId, $pinned, true),
));
}
/**
* The jobs of the week for "+/- Työmääräykset".
*
* @return list<TimesheetJobGroup>
*/
public function weekJobs(): array
{
$jobs = [];
foreach ([...$this->sheet->scheduled, ...$this->sheet->pinned] as $customer) {
foreach ($customer->jobs as $job) {
$jobs[$job->jobId] ??= ['job' => $job, 'customer' => $customer->name, 'color' => $customer->headerColor, 'rows' => []];
$jobs[$job->jobId]['rows'] = [...$jobs[$job->jobId]['rows'], ...$job->rows];
}
}
return array_values($jobs);
}
public function saveCell(int $taskId, string $day, string $value): void
{
try {
$quarters = WorkedHours::parseFlexible($value)?->quarters ?? 0;
} catch (InvalidWorkedHours) {
$this->rejectCell($taskId, $day, $value, __('time.errors.invalid_hours'));
return;
}
$this->storeCell($taskId, $day, $quarters, $value);
}
/**
* The −15 min / +15 min buttons.
*/
public function adjustCell(int $taskId, string $day, int $delta): void
{
$row = $this->sheet->row($taskId);
$current = $row?->cell($day)?->quarters ?? 0;
$this->storeCell($taskId, $day, max(0, $current + ($delta > 0 ? 1 : -1)), null);
}
public function openEntry(int $taskId, string $day): void
{
$row = $this->sheet->row($taskId);
$cell = $row?->cell($day);
if ($row === null || ! in_array($day, $this->sheet->days, true)) {
return;
}
if ($cell === null) {
$this->statusMessage = __('time.sheet.entry_needs_hours');
return;
}
$this->resetErrorBag('entryNote');
$this->entryTaskId = $taskId;
$this->entryDay = $day;
$this->entryBillingModel = ($cell->billingModel ?? $row->defaultBillingModel())->value;
$this->entryNote = (string) $cell->billingNote;
$this->entryComment = (string) $cell->internalComment;
$this->js("document.getElementById('".self::MISSING_DIALOG."').close(); document.getElementById('".self::ENTRY_DIALOG."').showModal()");
}
/**
* "Tallenna", Escape or closing the entry dialog.
*/
public function saveEntry(DescribeTimeEntry $describe): void
{
$this->authorize('time.use');
$row = $this->entryTaskId === null ? null : $this->sheet->row($this->entryTaskId);
if ($this->isReadOnly() || $row === null || $row->task->isLocked() || $row->cell($this->entryDay)?->approved !== false) {
$this->js("document.getElementById('".self::ENTRY_DIALOG."').close()");
return;
}
$this->authorize('time.book', $row->task->jobId);
$model = EntryBillingModel::tryFrom($this->entryBillingModel);
try {
$describe->execute(
(int) auth()->id(),
$row->task->taskId,
$this->entryDay,
$model === $row->defaultBillingModel() && $row->cell($this->entryDay)?->billingModel === null ? null : $model,
mb_substr($this->entryNote, 0, 2000),
mb_substr($this->entryComment, 0, 2000),
);
} catch (DomainException) {
$this->errorMessage = __('time.errors.approved');
return;
}
unset($this->sheet);
$this->statusMessage = __('time.sheet.entry_saved', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($this->entryDay)]);
$this->entryTaskId = null;
$this->js("document.getElementById('".self::ENTRY_DIALOG."').close()");
}
/**
* "Pysäytä ja tallenna" of the timer: the time rounded to the nearest
* quarter hour, at least 15 minutes, on today's cell.
*/
public function saveTimer(int $taskId, int $seconds, string $note, AddTaskHours $addHours): void
{
$row = $this->sheet->row($taskId);
if ($this->isReadOnly() || $row === null || ! in_array($this->today, $this->sheet->days, true)) {
return;
}
$this->authorize('time.book', $row->task->jobId);
$quarters = max(1, (int) round($seconds / 900));
try {
$addHours->execute((int) auth()->id(), $taskId, $this->today, WorkedHours::formatQuarters(min($quarters, WorkedHours::MAX_QUARTERS)), trim($note) === '' ? null : mb_substr(trim($note), 0, 2000));
} catch (DomainException $exception) {
$this->errorMessage = $row->task->taskTitle.': '.$this->domainMessage($exception);
return;
}
unset($this->sheet, $this->month);
$this->loadCells();
$this->statusMessage = __('time.sheet.timer_saved', ['time' => WorkedHours::formatClock($quarters), 'task' => $row->task->taskTitle]);
}
public function approveWeek(ApproveWeek $approveWeek): void
{
$this->authorize('time.approve', $this->viewedUserId);
try {
$count = $approveWeek->execute($this->viewedUserId, $this->week, (int) auth()->id());
} catch (BillingNotesMissing) {
unset($this->sheet);
$this->js("document.getElementById('".self::MISSING_DIALOG."').showModal()");
return;
}
unset($this->sheet);
$this->loadCells();
$this->rejected = [];
$this->resetErrorBag();
$this->errorMessage = '';
$this->statusMessage = $count === 0
? __('time.approval.nothing_to_approve')
: __('time.approval.approved', ['week' => $this->weekHeading()]);
}
public function confirmCancelApproval(): void
{
$this->authorize('time.cancel-approval');
$this->js("document.getElementById('cancel-approval-dialog').showModal()");
}
public function cancelApproval(CancelWeekApproval $cancelApproval): void
{
$this->authorize('time.cancel-approval');
$cancelApproval->execute($this->viewedUserId, $this->week);
unset($this->sheet);
$this->loadCells();
$this->statusMessage = __('time.approval.cancelled', ['week' => $this->weekHeading()]);
$this->js("document.getElementById('cancel-approval-dialog').close(); document.getElementById('week-heading').focus()");
}
/**
* @param list<int> $taskIds
*/
public function pinTasks(array $taskIds, PinTimesheetTasks $pins): void
{
$this->authorize('time.use');
if ($this->isReadOnly()) {
return;
}
$taskIds = array_values(array_filter(array_map('intval', $taskIds), fn (int $id): bool => $id > 0));
$tasks = app(TaskQueries::class)->bookableTasks($taskIds);
foreach ($tasks as $task) {
if (Gate::denies('time.book', $task->jobId)) {
return;
}
}
try {
$pins->pin((int) auth()->id(), array_map(fn (BookableTask $task): int => $task->taskId, $tasks));
} catch (DomainException) {
$this->errorMessage = __('time.sheet.cannot_pin');
return;
}
unset($this->sheet, $this->pinCandidates);
$this->loadCells();
$this->statusMessage = count($tasks) === 1
? __('time.sheet.pinned_task', ['task' => $tasks[0]->taskTitle])
: __('time.sheet.pinned_job', ['job' => $tasks[0]->jobNumber ?? '']);
}
/**
* "★ Kiinnitä työ": every open task of the job shown on the sheet.
*/
public function pinJob(int $jobId, PinTimesheetTasks $pins): void
{
$taskIds = [];
foreach ($this->sheet->rows() as $row) {
if ($row->task->jobId === $jobId && ! $row->task->isLocked() && ! $row->pinned) {
$taskIds[] = $row->task->taskId;
}
}
if ($taskIds !== []) {
$this->pinTasks($taskIds, $pins);
}
}
public function unpinTask(int $taskId, PinTimesheetTasks $pins): void
{
$this->authorize('time.use');
if ($this->isReadOnly()) {
return;
}
$row = $this->sheet->row($taskId);
$pins->unpin((int) auth()->id(), $taskId);
unset($this->sheet, $this->pinCandidates);
$this->loadCells();
$this->statusMessage = __('time.sheet.unpinned', ['task' => $row->task->taskTitle ?? '']);
}
public function clearPins(PinTimesheetTasks $pins): void
{
$this->authorize('time.use');
if ($this->isReadOnly()) {
return;
}
$count = $pins->unpinAll((int) auth()->id());
unset($this->sheet);
$this->loadCells();
$this->statusMessage = trans_choice('time.sheet.pins_cleared', $count, ['count' => $count]);
$this->js("document.getElementById('clear-pins-dialog').close(); document.getElementById('week-heading').focus()");
}
/**
* "Merkitse valmiiksi" in +/- Työmääräykset.
*/
public function markJobDone(int $jobId, ChangeJobStatus $changeStatus): void
{
$this->authorize('jobs.manage');
$job = collect($this->weekJobs())->first(fn (array $job): bool => $job['job']->jobId === $jobId);
if ($job === null || $job['job']->status->locksTime()) {
return;
}
try {
$changeStatus->execute($jobId, JobStatus::Done, (int) auth()->id());
} catch (CustomerJobNotFound) {
return;
}
unset($this->sheet);
$this->loadCells();
$this->statusMessage = __('time.sheet.marked_done', ['job' => $job['job']->number.' '.$job['job']->name]);
}
public function setCustomerColor(int $customerId, ?string $color, ChangeCustomerHeaderColor $changeColor): void
{
$this->authorize('customers.use');
$name = collect($this->sheet->rows())->first(fn (TimesheetTaskRow $row): bool => $row->task->customerId === $customerId)?->task->customerName ?? '';
try {
$changeColor->execute($customerId, $color);
} catch (InvalidHexColor|CustomerNotFound) {
$this->errorMessage = __('time.sheet.invalid_color');
return;
}
unset($this->sheet);
$this->statusMessage = __('time.sheet.color_saved', ['customer' => $name]);
}
public function selectDay(string $day): void
{
if (in_array($day, $this->sheet->days, true)) {
$this->selectedDay = $day;
}
}
public function showWeek(string $which): void
{
$this->week = match ($which) {
'previous' => CarbonImmutable::parse($this->week)->subWeek()->toDateString(),
'next' => CarbonImmutable::parse($this->week)->addWeek()->toDateString(),
default => $this->mondayOf($this->today),
};
unset($this->sheet, $this->month);
$this->selectedDay = $this->isCurrentWeek() ? $this->today : $this->week;
$this->statusMessage = $this->weekHeading();
$this->errorMessage = '';
$this->resetErrorBag();
$this->rejected = [];
$this->loadCells();
}
public function weekHeading(): string
{
$monday = CarbonImmutable::parse($this->week);
return __('time.week_heading', [
'number' => $monday->isoWeek(),
'from' => $monday->format('j.n.'),
'to' => $monday->addDays(6)->format('j.n.Y'),
]);
}
public function dayLabel(string $day): string
{
$date = CarbonImmutable::parse($day);
return __('time.days')[$date->dayOfWeekIso - 1].' '.$date->format('j.n.');
}
/**
* @return array<string, string>
*/
public function dayLabels(): array
{
return collect($this->sheet->days)->mapWithKeys(fn (string $day): array => [$day => $this->dayLabel($day)])->all();
}
public function clock(int $quarters): string
{
return WorkedHours::formatClock($quarters);
}
public function monthLabel(): string
{
$date = CarbonImmutable::createFromFormat('!Y-m', $this->month->month) ?: CarbonImmutable::now();
return ucfirst(__('time.sheet.months')[$date->month - 1]).' '.$date->year;
}
public function isSubcontractor(): bool
{
return auth()->user()?->role === Role::Subcontractor;
}
public function heading(): string
{
return $this->isReadOnly() ? __('time.other_title', ['name' => $this->viewedUserName]) : __('time.title');
}
public function render(): mixed
{
return $this->view()->title($this->heading());
}
private function storeCell(int $taskId, string $day, int $quarters, ?string $typed): void
{
$this->authorize('time.use');
$row = $this->sheet->row($taskId);
if ($this->isReadOnly() || $row === null || ! in_array($day, $this->sheet->days, true)) {
return;
}
$this->authorize('time.book', $row->task->jobId);
$this->resetErrorBag("cells.{$taskId}.{$day}");
unset($this->rejected["{$taskId}.{$day}"]);
$this->errorMessage = '';
try {
app(SetDayHours::class)->execute((int) auth()->id(), $taskId, $day, $quarters === 0 ? '' : WorkedHours::formatQuarters(min($quarters, WorkedHours::MAX_QUARTERS + 1)));
} catch (DomainException $exception) {
$this->rejectCell($taskId, $day, $typed ?? WorkedHours::formatClock($quarters), $this->domainMessage($exception));
return;
}
unset($this->sheet, $this->month);
$this->loadCells();
$this->statusMessage = $quarters === 0
? __('time.removed', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($day)])
: __('time.sheet.saved', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($day), 'hours' => WorkedHours::formatClock($quarters)]);
}
private function rejectCell(int $taskId, string $day, string $value, string $message): void
{
$title = $this->sheet->row($taskId)->task->taskTitle ?? '';
$this->addError("cells.{$taskId}.{$day}", $message);
$this->errorMessage = $title.', '.$this->dayLabel($day).': '.$message;
$this->rejected["{$taskId}.{$day}"] = $value;
}
private function domainMessage(DomainException $exception): string
{
return __(match (true) {
$exception instanceof InvalidWorkedHours => 'time.errors.invalid_hours',
$exception instanceof DailyHoursExceeded => 'time.errors.day_full',
$exception instanceof TimeLocked => 'time.errors.locked',
$exception instanceof TimeApproved => 'time.errors.approved',
default => 'time.errors.not_found',
});
}
private function loadCells(): void
{
$cells = [];
foreach ($this->sheet->rows() as $row) {
foreach ($this->sheet->days as $day) {
$cells[$row->task->taskId][$day] = WorkedHours::formatClock($row->cell($day)?->quarters ?? 0);
}
}
$this->cells = $cells;
}
private function mondayOf(string $date): string
{
try {
return CarbonImmutable::parse($date)->startOfWeek()->toDateString();
} catch (\Throwable) {
return CarbonImmutable::now()->startOfWeek()->toDateString();
}
}
};
?>
@php
$sheet = $this->sheet;
$readOnly = $this->isReadOnly();
$current = $this->isCurrentWeek();
$today = $current ? $today : null;
$labels = $this->dayLabels();
$approved = $sheet->isApproved();
$currentMonday = CarbonImmutable::parse($this->today)->startOfWeek();
$shownMonday = CarbonImmutable::parse($week);
$userKey = (int) auth()->id();
@endphp
<div
class="mx-auto max-w-[1680px] space-y-3 px-2 py-4 sm:px-5"
x-data="{
storageKey: 'timesheet-timer-{{ $userKey }}',
timer: { taskId: null, title: '', customer: '', job: '', running: false, startedAt: null, elapsed: 0, note: '', editing: false, h: 0, m: 0, s: 0 },
now: Date.now(),
tick: null,
init() {
try {
const saved = JSON.parse(localStorage.getItem(this.storageKey) || 'null');
if (saved && saved.taskId) { Object.assign(this.timer, saved, { editing: false }); }
} catch (e) {}
this.tick = setInterval(() => { this.now = Date.now(); }, 1000);
},
persist() {
try { localStorage.setItem(this.storageKey, JSON.stringify(this.timer)); } catch (e) {}
},
seconds() {
return Math.floor(this.timer.elapsed + (this.timer.running && this.timer.startedAt ? (this.now - this.timer.startedAt) / 1000 : 0));
},
formatted() {
const t = this.seconds();
const pad = (v) => String(v).padStart(2, '0');
return pad(Math.floor(t / 3600)) + ':' + pad(Math.floor((t % 3600) / 60)) + ':' + pad(t % 60);
},
commitLabel() {
const q = Math.max(1, Math.round(this.seconds() / 900));
return '+' + Math.floor(q / 4) + ':' + String((q % 4) * 15).padStart(2, '0');
},
openTimer(taskId, title, customer, job) {
if (this.timer.taskId !== taskId && ! this.timer.running && this.seconds() === 0) {
Object.assign(this.timer, { taskId, title, customer, job, elapsed: 0, startedAt: null, note: '' });
}
document.getElementById('timer-dialog').showModal();
},
start() {
if (this.timer.editing) { this.applyEdit(); }
this.timer.running = true;
this.timer.startedAt = Date.now();
this.persist();
},
pause() {
this.timer.elapsed = this.seconds();
this.timer.running = false;
this.timer.startedAt = null;
this.persist();
},
reset() {
Object.assign(this.timer, { running: false, startedAt: null, elapsed: 0, editing: false, note: '' });
this.persist();
},
edit() {
this.pause();
const t = this.seconds();
Object.assign(this.timer, { editing: true, h: Math.floor(t / 3600), m: Math.floor((t % 3600) / 60), s: t % 60 });
},
applyEdit() {
const v = (x, max) => Math.max(0, Math.min(max, parseInt(x, 10) || 0));
this.timer.elapsed = v(this.timer.h, 23) * 3600 + v(this.timer.m, 59) * 60 + v(this.timer.s, 59);
this.timer.editing = false;
this.persist();
},
stopAndSave() {
if (this.timer.editing) { this.applyEdit(); }
const seconds = this.seconds();
const taskId = this.timer.taskId;
const note = this.timer.note;
this.reset();
this.timer.taskId = null;
this.persist();
document.getElementById('timer-dialog').close();
if (taskId && seconds > 0) { $wire.saveTimer(taskId, seconds, note); }
},
}"
>
<h1 class="sr-only">{{ $this->heading() }}</h1>
@if ($readOnly)
<div class="card space-y-1 text-sm">
<p>{{ __('time.other_intro') }}</p>
<p><x-link :href="route('time.approvals')" navigate class="text-sm underline">{{ __('time.approval.back_to_list') }}</x-link></p>
</div>
@endif
{{-- Banner when another week than the current one is shown --}}
<div role="status" aria-live="polite">
@unless ($current)
<div class="flex flex-wrap items-center justify-between gap-3 rounded-xl border-2 border-amber-600 bg-amber-50 px-4 py-2.5 text-amber-950 shadow-lg dark:border-amber-500 dark:bg-amber-950/90 dark:text-amber-100">
<div class="flex items-center gap-3">
<span class="flex size-8 shrink-0 items-center justify-center rounded-lg border border-amber-500/50 bg-amber-200/60 dark:bg-amber-500/20" aria-hidden="true">
<x-icon name="exclamation-triangle" class="size-5" />
</span>
<div>
<p class="text-sm font-semibold">{{ __($shownMonday->lt($currentMonday) ? 'time.sheet.off_week_past' : 'time.sheet.off_week_future', ['number' => $shownMonday->isoWeek()]) }}</p>
<p class="text-xs">{{ __('time.sheet.off_week_hint', ['number' => $currentMonday->isoWeek(), 'from' => $currentMonday->format('j.n.'), 'to' => $currentMonday->addDays(6)->format('j.n.Y')]) }}</p>
</div>
</div>
<button type="button" wire:click="showWeek('this')" class="min-h-6 shrink-0 rounded-lg bg-amber-600 px-3.5 py-1.5 text-xs font-semibold text-zinc-950 shadow hover:bg-amber-500 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-800 dark:focus-visible:outline-amber-200">
{{ __('time.sheet.back_to_current', ['number' => $currentMonday->isoWeek()]) }}
</button>
</div>
@endunless
</div>
{{-- Toolbar --}}
<section aria-labelledby="week-heading" @class([
'rounded-xl border bg-white px-3.5 py-3 shadow-md transition-all dark:bg-[#16160e]',
'border-slate-300 dark:border-[#36393f]' => $current,
'border-amber-600 ring-2 ring-amber-500/80' => ! $current,
])>
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex flex-wrap items-center gap-3">
<div>
<div class="flex items-center gap-2">
<h2 id="week-heading" tabindex="-1" class="text-base font-bold tracking-tight focus:outline-none sm:text-lg">{{ $this->weekHeading() }}</h2>
<span @class([
'rounded-full border px-2 py-0.5 text-[11px] font-semibold',
'border-indigo-400/40 bg-indigo-100 text-indigo-900 dark:bg-indigo-500/20 dark:text-indigo-100' => $current,
'border-amber-500/50 bg-amber-100 text-amber-900 dark:bg-amber-500/20 dark:text-amber-100' => ! $current,
])>{{ $current ? __('time.sheet.current_week') : ($shownMonday->lt($currentMonday) ? __('time.sheet.past_week') : __('time.sheet.future_week')) }}</span>
</div>
<label class="mt-0.5 inline-flex cursor-pointer items-center gap-1.5 text-xs select-none">
<input type="checkbox" wire:model.live="showMonth" class="size-4 rounded border-zinc-500 text-indigo-600 dark:bg-[#1b1d20]" />
<span>{{ __('time.sheet.month_view') }}</span>
</label>
</div>
<nav aria-label="{{ __('time.sheet.navigator') }}" class="inline-flex items-center overflow-hidden rounded-lg border border-slate-300 bg-slate-100 dark:border-[#3c4047] dark:bg-[#282a2e]">
<button type="button" wire:click="showWeek('previous')" aria-label="{{ __('time.previous_week') }}" class="flex min-h-8 items-center px-2.5 transition hover:bg-indigo-500/20 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">
<x-icon name="chevron-left" class="size-4" aria-hidden="true" />
</button>
<button type="button" wire:click="showWeek('this')" class="flex min-h-8 items-center gap-2 border-x border-inherit px-3 text-xs font-medium focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">
<x-icon name="calendar" class="size-3.5" aria-hidden="true" />
<span><span class="sr-only">{{ __('time.this_week') }}: </span>{{ $shownMonday->format('j.n.Y') }}</span>
</button>
<button type="button" wire:click="showWeek('next')" aria-label="{{ __('time.next_week') }}" class="flex min-h-8 items-center px-2.5 transition hover:bg-indigo-500/20 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">
<x-icon name="chevron-right" class="size-4" aria-hidden="true" />
</button>
</nav>
<div class="flex flex-wrap items-center gap-2">
@if ($sheet->totalQuarters > 0 && ! $approved && $this->canApprove())
<button type="button" wire:click="approveWeek" class="flex min-h-8 items-center gap-1.5 rounded-lg border border-indigo-500 bg-indigo-700 px-3 text-xs font-semibold text-white shadow-sm transition hover:bg-indigo-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">
<x-icon name="check" class="size-3.5" aria-hidden="true" />{{ __('time.approval.approve_week') }}
</button>
@elseif ($sheet->lastApproval !== null)
@can('time.cancel-approval')
<button type="button" wire:click="confirmCancelApproval" class="flex min-h-8 items-center gap-1.5 rounded-lg border border-emerald-600/50 bg-emerald-50 px-3 text-xs font-semibold text-emerald-900 transition hover:bg-emerald-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:bg-emerald-600/20 dark:text-emerald-100 dark:focus-visible:outline-primary-300">
<x-icon name="arrow-uturn-left" class="size-3.5" aria-hidden="true" />{{ __('time.approval.cancel') }}
</button>
@endcan
@endif
@unless ($readOnly)
<button
type="button"
x-on:click="document.getElementById('clear-pins-dialog').showModal()"
@disabled($sheet->pinnedTaskCount() === 0)
class="flex min-h-8 items-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 text-xs font-medium text-slate-800 transition hover:bg-rose-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 disabled:opacity-40 dark:border-[#3c4047] dark:bg-[#282a2e] dark:text-zinc-100 dark:hover:bg-rose-500/20 dark:focus-visible:outline-primary-300"
>
<x-icon name="x-mark" class="size-3.5 text-rose-700 dark:text-rose-300" aria-hidden="true" />{{ __('time.sheet.clear_pins') }}
</button>
<button
type="button"
id="open-manage"
x-on:click="document.getElementById('manage-dialog').showModal()"
class="flex min-h-8 items-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 text-xs font-medium text-slate-800 transition hover:bg-slate-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:border-[#3c4047] dark:bg-[#282a2e] dark:text-zinc-100 dark:hover:bg-[#32353b] dark:focus-visible:outline-primary-300"
>{{ __('time.sheet.manage') }}</button>
@endunless
</div>
</div>
<div class="flex flex-wrap items-center gap-3 text-xs">
<button
type="button"
x-show="timer.taskId !== null && (timer.running || seconds() > 0)"
x-cloak
x-on:click="document.getElementById('timer-dialog').showModal()"
class="flex min-h-8 items-center gap-2 rounded-lg bg-emerald-700 px-2.5 text-xs font-medium text-white shadow transition hover:bg-emerald-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300"
>
<span class="size-2 rounded-full bg-white" x-bind:class="timer.running && 'animate-ping'" aria-hidden="true"></span>
<span class="sr-only">{{ __('time.sheet.timer') }}:</span>
<span class="max-w-[140px] truncate" x-text="timer.title"></span>
<span class="font-mono font-semibold" x-text="formatted()"></span>
</button>
@if (! $approved && $sheet->missingNotes !== [])
<button
type="button"
x-on:click="document.getElementById('missing-notes-dialog').showModal()"
class="flex min-h-8 items-center gap-1.5 rounded-lg border border-amber-600/60 bg-amber-50 px-2.5 font-medium text-amber-900 transition hover:bg-amber-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:bg-amber-500/15 dark:text-amber-100 dark:focus-visible:outline-primary-300"
>
<span class="size-2 rounded-full bg-amber-500" aria-hidden="true"></span>
{{ trans_choice('time.sheet.missing_notes', count($sheet->missingNotes), ['count' => count($sheet->missingNotes)]) }}
</button>
@endif
<p class="flex items-center gap-1.5">
<span>{{ $approved ? __('time.sheet.approved_total') : __('time.sheet.unapproved_total') }}</span>
<span @class(['font-mono text-sm font-bold', 'text-emerald-800 dark:text-emerald-300' => $approved, 'text-sky-800 dark:text-sky-300' => ! $approved])>{{ $this->clock($approved ? $sheet->totalQuarters : $sheet->unapprovedQuarters) }}</span>
</p>
</div>
</div>
@if ($sheet->lastApproval !== null)
<p class="mt-2 inline-flex items-center gap-1 text-xs">
<x-icon name="check-circle" class="size-4" aria-hidden="true" />
{{ __('time.approval.approved_by', ['date' => CarbonImmutable::parse($sheet->lastApproval->approvedAt)->format('j.n.Y H:i'), 'name' => $sheet->lastApproval->approverName]) }}
</p>
@endif
@if ($sheet->totalQuarters > 0 && ! $approved && ! $this->canApprove())
<p class="mt-2 text-xs">{{ __('time.approval.management_approves') }}</p>
@endif
</section>
<p role="status" aria-live="polite" class="min-h-5 text-sm">{{ $statusMessage }}</p>
<p role="alert" class="text-sm font-medium text-red-700 dark:text-red-200">{{ $errorMessage }}</p>
{{-- Desktop: two cards with an air gap, wide tables that may scroll sideways --}}
<div class="hidden overflow-x-auto pb-2 lg:block" tabindex="0" role="region" aria-label="{{ __('time.table_caption') }}">
<div class="min-w-[1260px] space-y-6">
<x-time.sheet-section section="scheduled" collapsible :groups="$sheet->scheduled" :days="$sheet->days" :today="$today" :read-only="$readOnly" :cells="$cells" :rejected="$rejected" :labels="$labels" />
<x-time.sheet-section section="pinned" :groups="$sheet->pinned" :days="$sheet->days" :today="$today" :read-only="$readOnly" :cells="$cells" :rejected="$rejected" :labels="$labels" />
</div>
</div>
{{-- Phone: one day at a time --}}
<div class="space-y-4 lg:hidden">
<div role="group" aria-label="{{ __('time.choose_day') }}" class="grid grid-cols-4 gap-2 sm:grid-cols-7">
@foreach ($sheet->days as $day)
<button
type="button"
wire:click="selectDay('{{ $day }}')"
aria-pressed="{{ $day === $selectedDay ? 'true' : 'false' }}"
aria-label="{{ __('time.day_button', ['day' => $this->dayLabel($day), 'hours' => $this->clock($sheet->dayTotals[$day])]) }}"
@class([
'rounded-md border px-2 py-2 text-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300',
'border-primary-700 bg-primary-700 font-semibold text-white' => $day === $selectedDay,
'border-zinc-300 bg-white text-zinc-900 dark:border-zinc-600 dark:bg-zinc-900 dark:text-zinc-100' => $day !== $selectedDay,
])
>
<span class="block">{{ $this->dayLabel($day) }}</span>
<span class="block text-xs">{{ $this->clock($sheet->dayTotals[$day]) }}</span>
</button>
@endforeach
</div>
@foreach (['scheduled' => $sheet->scheduled, 'pinned' => $sheet->pinned] as $section => $groups)
<section aria-labelledby="m-{{ $section }}-heading" class="card space-y-3 p-3">
<h2 id="m-{{ $section }}-heading" class="text-sm font-bold tracking-wider uppercase">{{ __('time.sheet.'.$section) }}</h2>
@if ($groups === [])
<p class="text-sm">{{ __('time.sheet.'.$section.'_empty') }}</p>
@endif
@foreach ($groups as $customer)
@php
$color = new \App\Modules\Shared\Domain\ValueObjects\HexColor($customer->headerColor ?? '#374151');
@endphp
<div class="overflow-hidden rounded-lg border border-zinc-200 dark:border-zinc-700">
<p style="background-color: {{ $color->value }}; color: {{ $color->textColor() }}" class="px-3 py-1.5 text-xs font-bold">{{ $customer->name }}</p>
<ul class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($customer->jobs as $job)
@foreach ($job->rows as $row)
@php
$taskId = $row->task->taskId;
$cell = $row->cell($selectedDay);
$editable = ! $readOnly && ! $row->task->isLocked() && ! ($cell?->approved ?? false);
$fieldId = 'mcell-'.$section.'-'.$taskId.'-'.$selectedDay;
@endphp
<li wire:key="m-{{ $section }}-{{ $taskId }}" class="space-y-2 p-3 text-sm">
<p class="text-xs">#{{ $job->number }} {{ $job->name }}</p>
<x-link :href="route('time.task', $taskId)" navigate class="font-medium break-words">{{ $row->task->taskTitle }}</x-link>
@if ($editable)
<label for="{{ $fieldId }}" class="block text-xs font-medium">{{ __('time.sheet.cell', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($selectedDay)]) }}</label>
<div class="flex items-center gap-2">
<button type="button" wire:click="adjustCell({{ $taskId }}, '{{ $selectedDay }}', -1)" @disabled(($cell?->quarters ?? 0) === 0) aria-label="{{ __('time.sheet.minus', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($selectedDay)]) }}" class="flex size-10 items-center justify-center rounded border border-zinc-400 text-lg font-bold focus-visible:outline-2 focus-visible:outline-primary-600 disabled:opacity-40 dark:border-zinc-500 dark:focus-visible:outline-primary-300">−</button>
<input
id="{{ $fieldId }}"
type="text"
inputmode="decimal"
autocomplete="off"
value="{{ $rejected[$taskId.'.'.$selectedDay] ?? ($cells[$taskId][$selectedDay] ?? '0:00') }}"
wire:change="saveCell({{ $taskId }}, '{{ $selectedDay }}', $event.target.value)"
@error('cells.'.$taskId.'.'.$selectedDay) aria-invalid="true" aria-describedby="{{ $fieldId }}-error" @enderror
class="h-10 w-20 rounded-md border border-zinc-400 bg-white px-2 text-center font-mono text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:focus-visible:outline-primary-300"
/>
<button type="button" wire:click="adjustCell({{ $taskId }}, '{{ $selectedDay }}', 1)" aria-label="{{ __('time.sheet.plus', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($selectedDay)]) }}" class="flex size-10 items-center justify-center rounded border border-zinc-400 text-lg font-bold focus-visible:outline-2 focus-visible:outline-primary-600 dark:border-zinc-500 dark:focus-visible:outline-primary-300">+</button>
@if (($cell?->quarters ?? 0) > 0)
<button type="button" wire:click="openEntry({{ $taskId }}, '{{ $selectedDay }}')" aria-label="{{ __('time.sheet.note_button', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($selectedDay)]) }} {{ $cell?->hasBillingNote() ? __('time.sheet.note_filled') : __('time.sheet.note_missing') }}" class="flex size-10 items-center justify-center rounded border border-zinc-400 focus-visible:outline-2 focus-visible:outline-primary-600 dark:border-zinc-500 dark:focus-visible:outline-primary-300">
<x-icon name="pencil-square" class="size-5" aria-hidden="true" />
</button>
@endif
</div>
@error('cells.'.$taskId.'.'.$selectedDay)
<p id="{{ $fieldId }}-error" class="text-xs text-red-700 dark:text-red-200">{{ $message }}</p>
@enderror
@else
<p class="inline-flex items-center gap-1">
@if ($row->task->isLocked())
<x-icon name="lock-closed" class="size-4" aria-hidden="true" /> {{ __('time.locked') }} –
@elseif ($cell?->approved)
<x-icon name="check-circle" class="size-4" aria-hidden="true" /> {{ __('time.approval.cell_approved') }} –
@endif
{{ $this->clock($cell?->quarters ?? 0) }}
</p>
@endif
</li>
@endforeach
@endforeach
</ul>
</div>
@endforeach
@if ($section === 'pinned' && ! $readOnly)
<x-button subtle color="black" sm :text="__('time.sheet.add_to_list')" x-on:click="document.getElementById('add-to-list-dialog').showModal()" />
@endif
</section>
@endforeach
</div>
<p class="inline-flex items-center gap-2 rounded-lg bg-primary-50 px-3 py-2 text-sm font-semibold text-primary-900 dark:bg-primary-950 dark:text-primary-100"><x-icon name="clock" class="size-4" aria-hidden="true" />{{ __('time.week_total', ['hours' => $this->clock($sheet->totalQuarters)]) }}</p>
@if ($showMonth)
<section aria-label="{{ __('time.sheet.month_view') }}" class="flex flex-wrap items-center justify-between gap-4 rounded-xl border border-slate-300 bg-white p-4 text-xs shadow-md dark:border-[#36393f] dark:bg-[#16160e]">
<div class="flex flex-wrap items-center gap-3">
<span class="rounded-lg border border-indigo-500/40 bg-indigo-100 px-2.5 py-1 font-semibold text-indigo-900 dark:bg-indigo-500/20 dark:text-indigo-100">{{ $this->monthLabel() }}</span>
<span>{{ __('time.sheet.month_summary', ['total' => $this->clock($this->month->totalQuarters), 'billable' => $this->clock($this->month->billableQuarters), 'internal' => $this->clock($this->month->internalQuarters)]) }}</span>
</div>
<button type="button" wire:click="$set('showMonth', false)" class="min-h-6 text-xs underline focus-visible:outline-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">{{ __('time.sheet.hide_month') }}</button>
</section>
@endif
{{-- Entry dialog: Escape and closing save --}}
<dialog
id="entry-dialog"
aria-labelledby="entry-dialog-title"
wire:ignore.self
x-on:cancel.prevent="$wire.saveEntry()"
class="m-auto w-[calc(100%-1rem)] max-w-lg rounded-2xl border border-slate-300 bg-white p-0 text-slate-900 shadow-2xl backdrop:bg-black/75 dark:border-[#3c4047] dark:bg-[#1a1c20] dark:text-zinc-100"
>
@php
$entryRow = $entryTaskId === null ? null : $sheet->row($entryTaskId);
@endphp
<form wire:submit="saveEntry" class="space-y-4 p-5">
<div class="flex items-start justify-between gap-3">
<div>
<h2 id="entry-dialog-title" class="text-base font-bold">{{ __('time.sheet.entry_title') }}</h2>
@if ($entryRow !== null)
<p class="text-xs">
<span class="font-semibold">{{ $entryRow->task->customerName }}</span> •
{{ $entryRow->task->taskTitle }} •
<span class="font-semibold">{{ $this->dayLabel($entryDay) }}</span>
(<span class="font-mono font-bold">{{ $this->clock($entryRow->cell($entryDay)?->quarters ?? 0) }}</span>)
</p>
@endif
</div>
<button type="button" wire:click="saveEntry" aria-label="{{ __('layout.close') }}" class="inline-flex size-8 items-center justify-center rounded-lg hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-primary-600 dark:hover:bg-white/10 dark:focus-visible:outline-primary-300">
<x-icon name="x-mark" class="size-5" aria-hidden="true" />
</button>
</div>
<fieldset class="space-y-2">
<legend class="text-xs font-semibold">{{ __('time.sheet.billing_model') }}</legend>
<div class="grid gap-2 sm:grid-cols-3">
@foreach (EntryBillingModel::cases() as $model)
<label class="flex cursor-pointer flex-col gap-1 rounded-lg border border-slate-300 p-2.5 text-xs has-checked:border-indigo-600 has-checked:bg-indigo-50 has-focus-visible:outline-2 has-focus-visible:outline-primary-600 dark:border-[#3c4047] dark:has-checked:border-indigo-400 dark:has-checked:bg-indigo-500/15 dark:has-focus-visible:outline-primary-300">
<span class="flex items-center gap-2 font-semibold">
<input type="radio" name="entry-billing-model" value="{{ $model->value }}" wire:model="entryBillingModel" class="size-4 text-indigo-600 focus:outline-none dark:bg-[#1b1d20]" />
<span aria-hidden="true">{{ $model->symbol() }}</span>
{{ __('time.sheet.models.'.$model->value) }}
</span>
<span>{{ __('time.sheet.model_hints.'.$model->value) }}</span>
</label>
@endforeach
</div>
</fieldset>
<div>
<label for="entry-note" class="block text-xs font-semibold">{{ __('time.sheet.billing_note') }}</label>
<textarea id="entry-note" rows="3" maxlength="2000" wire:model="entryNote" aria-describedby="entry-note-hint" class="mt-1 w-full rounded-lg border border-slate-400 bg-white p-2.5 text-sm text-slate-900 focus-visible:outline-2 focus-visible:outline-primary-600 dark:border-[#5a5e66] dark:bg-[#24262a] dark:text-white dark:focus-visible:outline-primary-300"></textarea>
<p id="entry-note-hint" class="mt-1 text-[11px]">{{ __('time.sheet.billing_note_hint') }}</p>
</div>
<div>
<label for="entry-comment" class="block text-xs font-semibold">{{ __('time.sheet.internal_comment') }}</label>
<textarea id="entry-comment" rows="2" maxlength="2000" wire:model="entryComment" aria-describedby="entry-comment-hint" class="mt-1 w-full rounded-lg border border-slate-400 bg-white p-2.5 text-sm text-slate-900 focus-visible:outline-2 focus-visible:outline-primary-600 dark:border-[#5a5e66] dark:bg-[#24262a] dark:text-white dark:focus-visible:outline-primary-300"></textarea>
<p id="entry-comment-hint" class="mt-1 text-[11px]">{{ __('time.sheet.internal_comment_hint') }}</p>
</div>
<div class="flex flex-wrap items-center justify-between gap-3 border-t border-slate-200 pt-3 dark:border-[#36393f]">
<div class="flex items-center gap-3">
@if ($entryRow !== null && Gate::allows('expenses.record'))
<x-link :href="route('expenses.create', $entryRow->task->jobId)" navigate class="text-xs">{{ __('time.sheet.add_product') }}</x-link>
@endif
<span class="text-[11px]">{{ __('time.sheet.esc_saves') }}</span>
</div>
<x-button submit icon="check" :text="__('time.sheet.save_entry')" />
</div>
</form>
</dialog>
{{-- Missing billing notes --}}
<x-work-dialog id="missing-notes-dialog" :title="__('time.sheet.missing_title')" width="max-w-2xl">
<div class="space-y-3 p-5 text-sm">
<p>{{ __('time.sheet.missing_intro') }}</p>
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-200 dark:divide-zinc-700 dark:border-zinc-700">
@foreach ($sheet->missingNotes as $missing)
<li wire:key="missing-{{ $missing->taskId }}-{{ $missing->day }}" class="flex flex-wrap items-center justify-between gap-2 p-3">
<span>
<span class="font-semibold">{{ $missing->customerName }}</span> • #{{ $missing->jobNumber }} {{ $missing->taskTitle }} •
{{ $this->dayLabel($missing->day) }} (<span class="font-mono">{{ $this->clock($missing->quarters) }}</span>)
</span>
@unless ($readOnly)
<x-button
sm
wire:click="openEntry({{ $missing->taskId }}, '{{ $missing->day }}')"
:text="__('time.sheet.fill_note').' →'"
:aria-label="__('time.sheet.fill_note_label', ['task' => $missing->taskTitle, 'day' => $this->dayLabel($missing->day)])"
/>
@endunless
</li>
@endforeach
</ul>
</div>
<x-slot:footer>
<span></span>
<x-button subtle color="black" :text="__('layout.close')" x-on:click="$el.closest('dialog').close()" />
</x-slot:footer>
</x-work-dialog>
{{-- Timer: cannot be closed while running --}}
<x-work-dialog id="timer-dialog" :title="__('time.sheet.timer')" width="max-w-md" locked="timer.running">
<div class="space-y-4 p-5 text-center">
<p x-show="timer.running" x-cloak class="inline-flex items-center gap-1.5 rounded-full border border-amber-500/50 bg-amber-100 px-2.5 py-0.5 text-[11px] font-semibold text-amber-900 dark:bg-amber-500/20 dark:text-amber-100">
<x-icon name="lock-closed" class="size-3.5" aria-hidden="true" />{{ __('time.sheet.timer_locked') }}
</p>
<div>
<p class="text-[11px] font-semibold tracking-wider uppercase" x-text="timer.customer"></p>
<p class="text-xs font-medium" x-text="timer.job"></p>
<p class="mt-1 text-sm font-bold text-indigo-800 dark:text-indigo-200" x-text="timer.title"></p>
</div>
<p x-show="! timer.editing" class="font-mono text-4xl font-bold tracking-wider" x-text="formatted()" aria-live="off"></p>
<div x-show="timer.editing" x-cloak class="flex items-end justify-center gap-2">
@foreach (['h' => 'timer_hours', 'm' => 'timer_minutes', 's' => 'timer_seconds'] as $part => $label)
<div>
<label for="timer-{{ $part }}" class="block text-[11px] font-semibold">{{ __('time.sheet.'.$label) }}</label>
<input id="timer-{{ $part }}" type="number" min="0" max="{{ $part === 'h' ? 23 : 59 }}" x-model.number="timer.{{ $part }}" class="w-16 rounded-md border border-slate-400 bg-white px-2 py-1 text-center font-mono text-lg dark:border-[#5a5e66] dark:bg-[#24262a]" />
</div>
@endforeach
<x-button sm :text="__('time.sheet.timer_apply')" x-on:click="applyEdit()" />
</div>
<button type="button" x-show="! timer.editing" x-on:click="edit()" class="min-h-6 text-xs underline focus-visible:outline-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">{{ __('time.sheet.timer_edit') }}</button>
<p class="text-xs" role="status" x-text="timer.running ? @js(__('time.sheet.timer_state_running')) : (timer.editing ? @js(__('time.sheet.timer_state_edit')) : @js(__('time.sheet.timer_state_idle')))"></p>
<div class="text-left">
<label for="timer-note" class="block text-xs font-semibold">{{ __('time.sheet.timer_note') }}</label>
<input id="timer-note" type="text" maxlength="2000" x-model="timer.note" x-on:change="persist()" class="mt-1 w-full rounded-lg border border-slate-400 bg-white px-2.5 py-1.5 text-sm dark:border-[#5a5e66] dark:bg-[#24262a]" />
</div>
<div class="flex flex-wrap justify-center gap-2">
<x-button sm icon="play" :text="__('time.sheet.timer_start')" x-on:click="start()" x-bind:disabled="timer.running" />
<x-button sm subtle color="black" icon="pause" :text="__('time.sheet.timer_pause')" x-on:click="pause()" x-bind:disabled="! timer.running" />
<x-button sm subtle color="black" :text="__('time.sheet.timer_reset')" x-on:click="reset()" />
<button type="button" x-on:click="stopAndSave()" x-bind:disabled="seconds() === 0" class="inline-flex min-h-8 items-center gap-1.5 rounded-lg bg-emerald-700 px-3 text-xs font-semibold text-white hover:bg-emerald-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 disabled:opacity-40 dark:focus-visible:outline-primary-300">
<x-icon name="stop" class="size-4" aria-hidden="true" />
<span>{{ __('time.sheet.timer_stop') }} (<span x-text="commitLabel()"></span>)</span>
</button>
</div>
</div>
</x-work-dialog>
@unless ($readOnly)
{{-- +/- Työmääräykset --}}
<x-work-dialog id="manage-dialog" :title="__('time.sheet.manage_title')" width="max-w-2xl">
<div class="space-y-3 p-5">
<p class="text-xs">{{ __('time.sheet.manage_intro') }}</p>
@if ($this->weekJobs() === [])
<p class="text-sm">{{ __('time.sheet.manage_empty') }}</p>
@endif
@foreach ($this->weekJobs() as $item)
@php
$job = $item['job'];
@endphp
<div wire:key="manage-job-{{ $job->jobId }}" class="space-y-2 rounded-xl border border-slate-200 bg-slate-50 p-3 dark:border-[#383c44] dark:bg-[#25272c]">
<div class="flex flex-wrap items-center justify-between gap-2">
<p class="flex flex-wrap items-center gap-2 text-xs">
<span class="size-3 rounded-full" style="background-color: {{ $item['color'] ?? '#374151' }}" aria-hidden="true"></span>
<span class="font-bold">{{ $item['customer'] }}</span> •
<span class="font-mono">#{{ $job->number }}</span>
<span class="font-semibold">{{ $job->name }}</span>
</p>
@if ($job->status->locksTime())
<span class="rounded-lg border border-emerald-600/50 bg-emerald-50 px-2.5 py-1 text-[11px] font-semibold text-emerald-900 dark:bg-emerald-600/20 dark:text-emerald-100">✓ {{ __('time.sheet.already_done') }}</span>
@elseif (Gate::allows('jobs.manage'))
<button type="button" wire:click="markJobDone({{ $job->jobId }})" aria-label="{{ __('time.sheet.mark_done_label', ['job' => $job->number.' '.$job->name]) }}" class="min-h-6 rounded-lg border border-slate-300 bg-white px-2.5 text-[11px] font-semibold transition hover:bg-emerald-50 focus-visible:outline-2 focus-visible:outline-primary-600 dark:border-[#3c4047] dark:bg-[#1a1c20] dark:hover:bg-emerald-500/20 dark:focus-visible:outline-primary-300">{{ __('time.sheet.mark_done') }}</button>
@endif
</div>
<ul class="divide-y divide-slate-200 pl-5 dark:divide-zinc-700/40">
@foreach ($item['rows'] as $row)
<li class="flex items-center justify-between gap-2 py-1.5 text-xs">
<span>{{ $row->task->taskTitle }}</span>
@if ($row->pinned)
<button type="button" wire:click="unpinTask({{ $row->task->taskId }})" aria-label="{{ __('time.sheet.unpin_task_label', ['task' => $row->task->taskTitle]) }}" class="min-h-6 rounded-md border border-amber-600/50 bg-amber-100 px-2.5 text-[11px] font-semibold text-amber-900 dark:bg-amber-500/20 dark:text-amber-100">{{ __('time.sheet.pin_toggle_off') }}</button>
@elseif (! $row->task->isLocked())
<button type="button" wire:click="pinTasks([{{ $row->task->taskId }}])" aria-label="{{ __('time.sheet.pin_task_label', ['task' => $row->task->taskTitle]) }}" class="min-h-6 rounded-md border border-indigo-500/50 bg-indigo-100 px-2.5 text-[11px] font-semibold text-indigo-900 dark:bg-indigo-600/20 dark:text-indigo-100">{{ __('time.sheet.pin_toggle_on') }}</button>
@endif
</li>
@endforeach
</ul>
</div>
@endforeach
</div>
<x-slot:footer>
<span></span>
<x-button :text="__('layout.close')" x-on:click="$el.closest('dialog').close()" />
</x-slot:footer>
</x-work-dialog>
{{-- + Lisää työ listalle --}}
<x-work-dialog id="add-to-list-dialog" :title="__('time.sheet.add_title')" width="max-w-2xl">
<div class="space-y-3 p-5">
<x-input id="pin-search" wire:model.live.debounce.300ms="pinSearch" type="search" icon="magnifying-glass" :label="__('time.sheet.add_search')" :hint="__('time.sheet.add_hint')" autocomplete="off" />
@if (mb_strlen(trim($pinSearch)) >= 2)
<p role="status" aria-live="polite" class="text-sm">{{ trans_choice('time.sheet.add_count', count($this->pinCandidates), ['count' => count($this->pinCandidates)]) }}</p>
<ul class="space-y-1">
@foreach ($this->pinCandidates as $task)
<li wire:key="pin-candidate-{{ $task->taskId }}" class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-slate-200 p-2 text-xs dark:border-[#383c44]">
<span><span class="font-bold">{{ $task->customerName }}</span> • <span class="font-mono">#{{ $task->jobNumber }}</span> {{ $task->jobName }} – {{ $task->taskTitle }}</span>
<x-button sm wire:click="pinTasks([{{ $task->taskId }}])" :text="__('time.sheet.add_pin')" :aria-label="__('time.sheet.add_pin_label', ['task' => $task->label()])" />
</li>
@endforeach
</ul>
@endif
</div>
<x-slot:footer>
<span></span>
<x-button :text="__('time.sheet.done')" x-on:click="$el.closest('dialog').close()" />
</x-slot:footer>
</x-work-dialog>
<x-confirm-dialog id="clear-pins-dialog" :title="__('time.sheet.clear_pins_title')">
<p>{{ __('time.sheet.clear_pins_question') }}</p>
<x-slot:actions>
<x-button wire:click="clearPins" color="red" icon="x-mark" :text="__('time.sheet.clear_pins_confirm')" />
</x-slot:actions>
</x-confirm-dialog>
@endunless
@can('time.cancel-approval')
<x-confirm-dialog id="cancel-approval-dialog" :title="__('time.approval.cancel_title')">
<p>{{ __('time.approval.cancel_question', ['week' => $this->weekHeading()]) }}</p>
<x-slot:actions>
<x-button wire:click="cancelApproval" color="red" icon="arrow-uturn-left" :text="__('time.approval.cancel')" />
</x-slot:actions>
</x-confirm-dialog>
@endcan
<x-color-picker />
</div>