> */ #[Locked] public array $cells = []; /** * Values that were not saved, shown back in their cell with the error. * * @var array */ #[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 */ #[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 */ 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 $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 */ 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

{{ $this->heading() }}

@if ($readOnly)

{{ __('time.other_intro') }}

{{ __('time.approval.back_to_list') }}

@endif {{-- Banner when another week than the current one is shown --}}
@unless ($current)

{{ __($shownMonday->lt($currentMonday) ? 'time.sheet.off_week_past' : 'time.sheet.off_week_future', ['number' => $shownMonday->isoWeek()]) }}

{{ __('time.sheet.off_week_hint', ['number' => $currentMonday->isoWeek(), 'from' => $currentMonday->format('j.n.'), 'to' => $currentMonday->addDays(6)->format('j.n.Y')]) }}

@endunless
{{-- Toolbar --}}
$current, 'border-amber-600 ring-2 ring-amber-500/80' => ! $current, ])>

{{ $this->weekHeading() }}

$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')) }}
@if ($sheet->totalQuarters > 0 && ! $approved && $this->canApprove()) @elseif ($sheet->lastApproval !== null) @can('time.cancel-approval') @endcan @endif @unless ($readOnly) @endunless
@if (! $approved && $sheet->missingNotes !== []) @endif

{{ $approved ? __('time.sheet.approved_total') : __('time.sheet.unapproved_total') }} $approved, 'text-sky-800 dark:text-sky-300' => ! $approved])>{{ $this->clock($approved ? $sheet->totalQuarters : $sheet->unapprovedQuarters) }}

@if ($sheet->lastApproval !== null)

@endif @if ($sheet->totalQuarters > 0 && ! $approved && ! $this->canApprove())

{{ __('time.approval.management_approves') }}

@endif

{{ $statusMessage }}

{{-- Desktop: two cards with an air gap, wide tables that may scroll sideways --}} {{-- Phone: one day at a time --}}
@foreach ($sheet->days as $day) @endforeach
@foreach (['scheduled' => $sheet->scheduled, 'pinned' => $sheet->pinned] as $section => $groups)

{{ __('time.sheet.'.$section) }}

@if ($groups === [])

{{ __('time.sheet.'.$section.'_empty') }}

@endif @foreach ($groups as $customer) @php $color = new \App\Modules\Shared\Domain\ValueObjects\HexColor($customer->headerColor ?? '#374151'); @endphp

{{ $customer->name }}

    @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
  • #{{ $job->number }} {{ $job->name }}

    {{ $row->task->taskTitle }} @if ($editable)
    @if (($cell?->quarters ?? 0) > 0) @endif
    @error('cells.'.$taskId.'.'.$selectedDay)

    {{ $message }}

    @enderror @else

    @if ($row->task->isLocked())

    @endif
  • @endforeach @endforeach
@endforeach @if ($section === 'pinned' && ! $readOnly) @endif
@endforeach

@if ($showMonth)
{{ $this->monthLabel() }} {{ __('time.sheet.month_summary', ['total' => $this->clock($this->month->totalQuarters), 'billable' => $this->clock($this->month->billableQuarters), 'internal' => $this->clock($this->month->internalQuarters)]) }}
@endif {{-- Entry dialog: Escape and closing save --}} @php $entryRow = $entryTaskId === null ? null : $sheet->row($entryTaskId); @endphp

{{ __('time.sheet.entry_title') }}

@if ($entryRow !== null)

{{ $entryRow->task->customerName }} • {{ $entryRow->task->taskTitle }} • {{ $this->dayLabel($entryDay) }} ({{ $this->clock($entryRow->cell($entryDay)?->quarters ?? 0) }})

@endif
{{ __('time.sheet.billing_model') }}
@foreach (EntryBillingModel::cases() as $model) @endforeach

{{ __('time.sheet.billing_note_hint') }}

{{ __('time.sheet.internal_comment_hint') }}

@if ($entryRow !== null && Gate::allows('expenses.record')) {{ __('time.sheet.add_product') }} @endif {{ __('time.sheet.esc_saves') }}
{{-- Missing billing notes --}}

{{ __('time.sheet.missing_intro') }}

    @foreach ($sheet->missingNotes as $missing)
  • {{ $missing->customerName }} • #{{ $missing->jobNumber }} {{ $missing->taskTitle }} • {{ $this->dayLabel($missing->day) }} ({{ $this->clock($missing->quarters) }}) @unless ($readOnly) @endunless
  • @endforeach
{{-- Timer: cannot be closed while running --}}

@foreach (['h' => 'timer_hours', 'm' => 'timer_minutes', 's' => 'timer_seconds'] as $part => $label)
@endforeach

@unless ($readOnly) {{-- +/- Työmääräykset --}}

{{ __('time.sheet.manage_intro') }}

@if ($this->weekJobs() === [])

{{ __('time.sheet.manage_empty') }}

@endif @foreach ($this->weekJobs() as $item) @php $job = $item['job']; @endphp

{{ $item['customer'] }} • #{{ $job->number }} {{ $job->name }}

@if ($job->status->locksTime()) ✓ {{ __('time.sheet.already_done') }} @elseif (Gate::allows('jobs.manage')) @endif
    @foreach ($item['rows'] as $row)
  • {{ $row->task->taskTitle }} @if ($row->pinned) @elseif (! $row->task->isLocked()) @endif
  • @endforeach
@endforeach
{{-- + Lisää työ listalle --}}
@if (mb_strlen(trim($pinSearch)) >= 2)

{{ trans_choice('time.sheet.add_count', count($this->pinCandidates), ['count' => count($this->pinCandidates)]) }}

    @foreach ($this->pinCandidates as $task)
  • {{ $task->customerName }} • #{{ $task->jobNumber }} {{ $task->jobName }} – {{ $task->taskTitle }}
  • @endforeach
@endif

{{ __('time.sheet.clear_pins_question') }}

@endunless @can('time.cancel-approval')

{{ __('time.approval.cancel_question', ['week' => $this->weekHeading()]) }}

@endcan